OpenTTD
oldloader.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
10 #include "../stdafx.h"
11 #include "../debug.h"
12 #include "../strings_type.h"
13 #include "../string_func.h"
14 #include "../settings_type.h"
15 #include "../fileio_func.h"
16 
17 #include "table/strings.h"
18 
19 #include "saveload_internal.h"
20 #include "oldloader.h"
21 
22 #include <exception>
23 
24 #include "../safeguards.h"
25 
26 static const int TTO_HEADER_SIZE = 41;
27 static const int TTD_HEADER_SIZE = 49;
28 
29 uint32 _bump_assert_value;
30 
31 static inline OldChunkType GetOldChunkType(OldChunkType type) {return (OldChunkType)GB(type, 0, 4);}
32 static inline OldChunkType GetOldChunkVarType(OldChunkType type) {return (OldChunkType)(GB(type, 8, 8) << 8);}
33 static inline OldChunkType GetOldChunkFileType(OldChunkType type) {return (OldChunkType)(GB(type, 16, 8) << 16);}
34 
35 static inline byte CalcOldVarLen(OldChunkType type)
36 {
37  static const byte type_mem_size[] = {0, 1, 1, 2, 2, 4, 4, 8};
38  byte length = GB(type, 8, 8);
39  assert(length != 0 && length < lengthof(type_mem_size));
40  return type_mem_size[length];
41 }
42 
49 {
50  /* To avoid slow reads, we read BUFFER_SIZE of bytes per time
51  and just return a byte per time */
52  if (ls->buffer_cur >= ls->buffer_count) {
53 
54  /* Read some new bytes from the file */
55  int count = (int)fread(ls->buffer, 1, BUFFER_SIZE, ls->file);
56 
57  /* We tried to read, but there is nothing in the file anymore.. */
58  if (count == 0) {
59  DEBUG(oldloader, 0, "Read past end of file, loading failed");
60  throw std::exception();
61  }
62 
63  ls->buffer_count = count;
64  ls->buffer_cur = 0;
65  }
66 
67  return ls->buffer[ls->buffer_cur++];
68 }
69 
76 {
77  /* Old savegames have a nice compression algorithm (RLE)
78  which means that we have a chunk, which starts with a length
79  byte. If that byte is negative, we have to repeat the next byte
80  that many times ( + 1). Else, we need to read that amount of bytes.
81  Works pretty well if you have many zeros behind each other */
82 
83  if (ls->chunk_size == 0) {
84  /* Read new chunk */
85  int8 new_byte = ReadByteFromFile(ls);
86 
87  if (new_byte < 0) {
88  /* Repeat next char for new_byte times */
89  ls->decoding = true;
90  ls->decode_char = ReadByteFromFile(ls);
91  ls->chunk_size = -new_byte + 1;
92  } else {
93  ls->decoding = false;
94  ls->chunk_size = new_byte + 1;
95  }
96  }
97 
98  ls->total_read++;
99  ls->chunk_size--;
100 
101  return ls->decoding ? ls->decode_char : ReadByteFromFile(ls);
102 }
103 
109 bool LoadChunk(LoadgameState *ls, void *base, const OldChunks *chunks)
110 {
111  byte *base_ptr = (byte*)base;
112 
113  for (const OldChunks *chunk = chunks; chunk->type != OC_END; chunk++) {
114  if (((chunk->type & OC_TTD) && _savegame_type == SGT_TTO) ||
115  ((chunk->type & OC_TTO) && _savegame_type != SGT_TTO)) {
116  /* TTD(P)-only chunk, but TTO savegame || TTO-only chunk, but TTD/TTDP savegame */
117  continue;
118  }
119 
120  byte *ptr = (byte*)chunk->ptr;
121  if (chunk->type & OC_DEREFERENCE_POINTER) ptr = *(byte**)ptr;
122 
123  for (uint i = 0; i < chunk->amount; i++) {
124  /* Handle simple types */
125  if (GetOldChunkType(chunk->type) != 0) {
126  switch (GetOldChunkType(chunk->type)) {
127  /* Just read the byte and forget about it */
128  case OC_NULL: ReadByte(ls); break;
129 
130  case OC_CHUNK:
131  /* Call function, with 'i' as parameter to tell which item we
132  * are going to read */
133  if (!chunk->proc(ls, i)) return false;
134  break;
135 
136  case OC_ASSERT:
137  DEBUG(oldloader, 4, "Assert point: 0x%X / 0x%X", ls->total_read, chunk->offset + _bump_assert_value);
138  if (ls->total_read != chunk->offset + _bump_assert_value) throw std::exception();
139  default: break;
140  }
141  } else {
142  uint64 res = 0;
143 
144  /* Reading from the file: bits 16 to 23 have the FILE type */
145  switch (GetOldChunkFileType(chunk->type)) {
146  case OC_FILE_I8: res = (int8)ReadByte(ls); break;
147  case OC_FILE_U8: res = ReadByte(ls); break;
148  case OC_FILE_I16: res = (int16)ReadUint16(ls); break;
149  case OC_FILE_U16: res = ReadUint16(ls); break;
150  case OC_FILE_I32: res = (int32)ReadUint32(ls); break;
151  case OC_FILE_U32: res = ReadUint32(ls); break;
152  default: NOT_REACHED();
153  }
154 
155  /* When both pointers are nullptr, we are just skipping data */
156  if (base_ptr == nullptr && chunk->ptr == nullptr) continue;
157 
158  /* Writing to the var: bits 8 to 15 have the VAR type */
159  if (chunk->ptr == nullptr) ptr = base_ptr + chunk->offset;
160 
161  /* Write the data */
162  switch (GetOldChunkVarType(chunk->type)) {
163  case OC_VAR_I8: *(int8 *)ptr = GB(res, 0, 8); break;
164  case OC_VAR_U8: *(uint8 *)ptr = GB(res, 0, 8); break;
165  case OC_VAR_I16:*(int16 *)ptr = GB(res, 0, 16); break;
166  case OC_VAR_U16:*(uint16*)ptr = GB(res, 0, 16); break;
167  case OC_VAR_I32:*(int32 *)ptr = res; break;
168  case OC_VAR_U32:*(uint32*)ptr = res; break;
169  case OC_VAR_I64:*(int64 *)ptr = res; break;
170  case OC_VAR_U64:*(uint64*)ptr = res; break;
171  default: NOT_REACHED();
172  }
173 
174  /* Increase pointer base for arrays when looping */
175  if (chunk->amount > 1 && chunk->ptr != nullptr) ptr += CalcOldVarLen(chunk->type);
176  }
177  }
178  }
179 
180  return true;
181 }
182 
188 static void InitLoading(LoadgameState *ls)
189 {
190  ls->chunk_size = 0;
191  ls->total_read = 0;
192 
193  ls->decoding = false;
194  ls->decode_char = 0;
195 
196  ls->buffer_cur = 0;
197  ls->buffer_count = 0;
198  memset(ls->buffer, 0, BUFFER_SIZE);
199 
200  _bump_assert_value = 0;
201 
202  _settings_game.construction.freeform_edges = false; // disable so we can convert map array (SetTileType is still used)
203 }
204 
212 static bool VerifyOldNameChecksum(char *title, uint len)
213 {
214  uint16 sum = 0;
215  for (uint i = 0; i < len - 2; i++) {
216  sum += title[i];
217  sum = ROL(sum, 1);
218  }
219 
220  sum ^= 0xAAAA; // computed checksum
221 
222  uint16 sum2 = title[len - 2]; // checksum in file
223  SB(sum2, 8, 8, title[len - 1]);
224 
225  return sum == sum2;
226 }
227 
228 static inline bool CheckOldSavegameType(FILE *f, char *temp, const char *last, uint len)
229 {
230  assert(last - temp + 1 >= (int)len);
231 
232  if (fread(temp, 1, len, f) != len) {
233  temp[0] = '\0'; // if reading failed, make the name empty
234  return false;
235  }
236 
237  bool ret = VerifyOldNameChecksum(temp, len);
238  temp[len - 2] = '\0'; // name is null-terminated in savegame, but it's better to be sure
239  str_validate(temp, last);
240 
241  return ret;
242 }
243 
244 static SavegameType DetermineOldSavegameType(FILE *f, char *title, const char *last)
245 {
246  assert_compile(TTD_HEADER_SIZE >= TTO_HEADER_SIZE);
247  char temp[TTD_HEADER_SIZE] = "Unknown";
248 
249  SavegameType type = SGT_TTO;
250 
251  /* Can't fseek to 0 as in tar files that is not correct */
252  long pos = ftell(f);
253  if (pos >= 0 && !CheckOldSavegameType(f, temp, lastof(temp), TTO_HEADER_SIZE)) {
254  type = SGT_TTD;
255  if (fseek(f, pos, SEEK_SET) < 0 || !CheckOldSavegameType(f, temp, lastof(temp), TTD_HEADER_SIZE)) {
256  type = SGT_INVALID;
257  }
258  }
259 
260  if (title != nullptr) {
261  switch (type) {
262  case SGT_TTO: title = strecpy(title, "(TTO) ", last); break;
263  case SGT_TTD: title = strecpy(title, "(TTD) ", last); break;
264  default: title = strecpy(title, "(broken) ", last); break;
265  }
266  strecpy(title, temp, last);
267  }
268 
269  return type;
270 }
271 
272 typedef bool LoadOldMainProc(LoadgameState *ls);
273 
274 bool LoadOldSaveGame(const char *file)
275 {
276  LoadgameState ls;
277 
278  DEBUG(oldloader, 3, "Trying to load a TTD(Patch) savegame");
279 
280  InitLoading(&ls);
281 
282  /* Open file */
283  ls.file = FioFOpenFile(file, "rb", NO_DIRECTORY);
284 
285  if (ls.file == nullptr) {
286  DEBUG(oldloader, 0, "Cannot open file '%s'", file);
287  return false;
288  }
289 
290  SavegameType type = DetermineOldSavegameType(ls.file, nullptr, nullptr);
291 
292  LoadOldMainProc *proc = nullptr;
293 
294  switch (type) {
295  case SGT_TTO: proc = &LoadTTOMain; break;
296  case SGT_TTD: proc = &LoadTTDMain; break;
297  default: break;
298  }
299 
300  _savegame_type = type;
301 
302  bool game_loaded;
303  try {
304  game_loaded = proc != nullptr && proc(&ls);
305  } catch (...) {
306  game_loaded = false;
307  }
308 
309  if (!game_loaded) {
310  SetSaveLoadError(STR_GAME_SAVELOAD_ERROR_DATA_INTEGRITY_CHECK_FAILED);
311  fclose(ls.file);
312  return false;
313  }
314 
316 
317  return true;
318 }
319 
320 void GetOldSaveGameName(const char *file, char *title, const char *last)
321 {
322  FILE *f = FioFOpenFile(file, "rb", NO_DIRECTORY);
323 
324  if (f == nullptr) {
325  *title = '\0';
326  return;
327  }
328 
329  DetermineOldSavegameType(f, title, last);
330 
331  fclose(f);
332 }
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:79
static T ROL(const T x, const uint8 n)
ROtate x Left by n.
-//- TTO (default is neither of these)
Definition: oldloader.h:43
OldChunkType
Definition: oldloader.h:35
chunk is valid ONLY for TTD savegames
Definition: oldloader.h:42
TTD savegame (can be detected incorrectly)
Definition: saveload.h:331
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:48
SavegameType
Types of save games.
Definition: saveload.h:330
static T SB(T &x, const uint8 s, const uint8 n, const U d)
Set n bits in x starting at bit s to d.
static bool VerifyOldNameChecksum(char *title, uint len)
Verifies the title has a valid checksum.
Definition: oldloader.cpp:212
OldChunkType type
Type of field.
Definition: oldloader.h:87
bool freeform_edges
allow terraforming the tiles at the map edges
static void InitLoading(LoadgameState *ls)
Initialize some data before reading.
Definition: oldloader.cpp:188
TTO savegame.
Definition: saveload.h:335
void str_validate(char *str, const char *last, StringValidationSettings settings)
Scans the string for valid characters and if it finds invalid ones, replaces them with a question mar...
Definition: string.cpp:194
byte ReadByte(LoadgameState *ls)
Reads a byte from the buffer and decompress if needed.
Definition: oldloader.cpp:75
A game paused for saving/loading.
Definition: openttd.h:58
FILE * FioFOpenFile(const char *filename, const char *mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
Definition: fileio.cpp:463
A path without any base directory.
Definition: fileio_type.h:125
SavegameType _savegame_type
type of savegame we are loading
Definition: saveload.cpp:57
void SetSaveLoadError(StringID str)
Set the error message from outside of the actual loading/saving of the game (AfterLoadGame and friend...
Definition: saveload.cpp:2424
bool LoadChunk(LoadgameState *ls, void *base, const OldChunks *chunks)
Loads a chunk from the old savegame.
Definition: oldloader.cpp:109
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:40
Declarations of strctures and function used in loader of old savegames.
PauseMode _pause_mode
The current pause mode.
Definition: gfx.cpp:47
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:35
broken savegame (used internally)
Definition: saveload.h:336
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: depend.cpp:66
End of the whole chunk, all 32 bits set to zero.
Definition: oldloader.h:79
ConstructionSettings construction
construction of things in-game
Declaration of functions used in more save/load files.
static byte ReadByteFromFile(LoadgameState *ls)
Reads a byte from a file (do not call yourself, use ReadByte())
Definition: oldloader.cpp:48
Dereference the pointer once before writing to it, so we do not have to use big static arrays...
Definition: oldloader.h:77