aboutsummaryrefslogtreecommitdiff
path: root/src/Savestate.cpp
blob: 546c16e033cbe1893de442b3b97bcdd91c058a8a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/*
    Copyright 2016-2022 melonDS team

    This file is part of melonDS.

    melonDS 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, either version 3 of the License, or (at your option)
    any later version.

    melonDS 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. See the GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with melonDS. If not, see http://www.gnu.org/licenses/.
*/

#include <stdio.h>
#include <cassert>
#include <cstring>
#include "Savestate.h"
#include "Platform.h"

using Platform::Log;
using Platform::LogLevel;

static const char* SAVESTATE_MAGIC = "MELN";

/*
    Savestate format

    header:
    00 - magic MELN
    04 - version major
    06 - version minor
    08 - length
    0C - reserved (should be game serial later!)

    section header:
    00 - section magic
    04 - section length
    08 - reserved
    0C - reserved

    Implementation details

    version difference:
    * different major means savestate file is incompatible
    * different minor means adjustments may have to be made
*/

Savestate::Savestate(void *buffer, u32 size, bool save) :
    Error(false),
    Saving(save),
    CurSection(NO_SECTION),
    buffer(static_cast<u8 *>(buffer)),
    buffer_offset(0),
    buffer_length(size),
    buffer_owned(false),
    finished(false)
{
    if (Saving)
    {
        WriteSavestateHeader();
    }
    else
    {
        // Ensure that the file starts with "MELN"
        u32 read_magic = 0;
        Var32(&read_magic);

        if (read_magic != *((u32*)SAVESTATE_MAGIC))
        {
            Log(LogLevel::Error, "savestate: expected magic number %#08x (%s), got %#08x\n",
                *((u32*)SAVESTATE_MAGIC),
                SAVESTATE_MAGIC,
                read_magic
            );
            Error = true;
            return;
        }

        u16 major = 0;
        Var16(&major);
        if (major != SAVESTATE_MAJOR)
        {
            Log(LogLevel::Error, "savestate: bad version major %d, expecting %d\n", major, SAVESTATE_MAJOR);
            Error = true;
            return;
        }

        u16 minor = 0;
        Var16(&minor);
        if (minor > SAVESTATE_MINOR)
        {
            Log(LogLevel::Error, "savestate: state from the future, %d > %d\n", minor, SAVESTATE_MINOR);
            Error = true;
            return;
        }

        u32 read_length = 0;
        Var32(&read_length);
        if (read_length != buffer_length)
        {
            Log(LogLevel::Error, "savestate: expected a length of %d, got %d\n", buffer_length, read_length);
            Error = true;
            return;
        }

        // The next 4 bytes are reserved
        buffer_offset += 4;
    }
}


Savestate::Savestate(u32 initial_size) :
    Error(false),
    Saving(true), // Can't load from an empty buffer
    CurSection(NO_SECTION),
    buffer(nullptr),
    buffer_offset(0),
    buffer_length(initial_size),
    buffer_owned(true),
    finished(false)
{
    buffer = static_cast<u8 *>(malloc(buffer_length));

    if (buffer == nullptr)
    {
        Log(LogLevel::Error, "savestate: failed to allocate %d bytes\n", buffer_length);
        Error = true;
        return;
    }

    WriteSavestateHeader();
}

Savestate::~Savestate()
{
    if (Saving && !finished && !buffer_owned && !Error)
    { // If we haven't finished saving, and there hasn't been an error...
        Finish();
        // No need to close the active section for an owned buffer,
        // it's about to be thrown out.
    }

    if (buffer_owned)
    {
        free(buffer);
    }
}

void Savestate::Section(const char* magic)
{
    if (Error || finished) return;

    if (Saving)
    {
        // Go back to the current section's header and write the length
        CloseCurrentSection();

        CurSection = buffer_offset;

        // Write the new section's magic number
        VarArray((void*)magic, 4);

        // The next 4 bytes are the length, which we'll come back to later.
        u32 zero = 0;
        Var32(&zero);

        // The 8 bytes afterward are reserved, so we skip them.
        Var32(&zero);
        Var32(&zero);
    }
    else
    {
        u32 section_offset = FindSection(magic);

        if (section_offset != NO_SECTION)
        {
            buffer_offset = section_offset;
        }
        else
        {
            Log(LogLevel::Error, "savestate: section %s not found. blarg\n", magic);
            Error = true;
        }
    }
}

void Savestate::Bool32(bool* var)
{
    // for compatibility
    if (Saving)
    {
        u32 val = *var;
        Var32(&val);
    }
    else
    {
        u32 val;
        Var32(&val);
        *var = val != 0;
    }
}

void Savestate::VarArray(void* data, u32 len)
{
    if (Error || finished) return;

    assert(buffer_offset <= buffer_length);

    if (Saving)
    {
        if (buffer_offset + len > buffer_length)
        { // If writing the given data would take us past the buffer's end...
            Log(LogLevel::Warn, "savestate: %u-byte write would exceed %u-byte savestate buffer\n", len, buffer_length);

            if (!(buffer_owned && Resize(buffer_length * 2 + len)))
            { // If we're not allowed to resize this buffer, or if we are but failed...
                Log(LogLevel::Error, "savestate: Failed to write %d bytes to savestate\n", len);
                Error = true;
                return;
            }
            // The buffer's length is doubled, plus however much memory is needed for this write.
            // This way we can write the data and reduce the chance of needing to resize again.
        }

        memcpy(buffer + buffer_offset, data, len);
    }
    else
    {
        if (buffer_offset + len > buffer_length)
        { // If reading the requested amount of data would take us past the buffer's edge...
            Log(LogLevel::Error, "savestate: %u-byte read would exceed %u-byte savestate buffer\n", len, buffer_length);
            Error = true;
            return;

            // Can't realloc here.
            // Not only do we not own the buffer pointer (when loading a state),
            // but we can't magically make the desired data appear.
        }

        memcpy(data, buffer + buffer_offset, len);
    }

    buffer_offset += len;
}

void Savestate::Finish()
{
    if (Error || finished) return;
    CloseCurrentSection();
    WriteStateLength();
    finished = true;
}

void Savestate::Rewind(bool save)
{
    Error = false;
    Saving = save;
    CurSection = NO_SECTION;

    buffer_offset = 0;
    finished = false;
}

void Savestate::CloseCurrentSection()
{
    if (CurSection != NO_SECTION && !finished)
    { // If we're in the middle of writing a section...

        // Go back to the section's header
        // Get the length of the section we've written thus far
        u32 section_length = buffer_offset - CurSection;

        // Write the length in the section's header
        // (specifically the first 4 bytes after the magic number)
        memcpy(buffer + CurSection + 4, &section_length, sizeof(section_length));

        CurSection = NO_SECTION;
    }
}

bool Savestate::Resize(u32 new_length)
{
    if (!buffer_owned)
    { // If we're not allowed to resize this buffer...
        Log(LogLevel::Error, "savestate: Buffer is externally-owned, cannot resize it\n");
        return false;
    }

    u32 old_length = buffer_length;
    void* resized = realloc(buffer, new_length);
    if (!resized)
    { // If the buffer couldn't be expanded...
        Log(LogLevel::Error, "savestate: Failed to resize owned savestate buffer from %dB to %dB\n", old_length, new_length);
        return false;
    }

    u32 length_diff = new_length - old_length;
    buffer = static_cast<u8 *>(resized);
    buffer_length = new_length;

    Log(LogLevel::Debug, "savestate: Expanded %uB savestate buffer to %uB\n", old_length, new_length);
    // Zero out the newly-allocated memory (to ensure we don't introduce a security hole)
    memset(buffer + old_length, 0, length_diff);
    return true;
}

void Savestate::WriteSavestateHeader()
{
    // The magic number
    VarArray((void *) SAVESTATE_MAGIC, 4);

    // The major and minor versions
    u16 major = SAVESTATE_MAJOR;
    Var16(&major);

    u16 minor = SAVESTATE_MINOR;
    Var16(&minor);

    // The next 4 bytes are the file's length, which will be filled in at the end
    u32 zero = 0;
    Var32(&zero);

    // The following 4 bytes are reserved
    Var32(&zero);
}

void Savestate::WriteStateLength()
{
    // Not to be confused with the buffer length.
    // The buffer might not be full,
    // so we don't want to write out the extra stuff.
    u32 state_length = buffer_offset;

    // Write the length in the header
    memcpy(buffer + 0x08, &state_length, sizeof(state_length));
}

u32 Savestate::FindSection(const char* magic) const
{
    if (!magic) return NO_SECTION;

    // Start looking at the savestate's beginning, right after its global header
    // (we can't start from the current offset because then we'd lose the ability to rearrange sections)

    for (u32 offset = 0x10; offset < buffer_length;)
    { // Until we've found the desired section...

        // Get this section's magic number
        char read_magic[4] = {0};
        memcpy(read_magic, buffer + offset, sizeof(read_magic));

        if (memcmp(read_magic, magic, sizeof(read_magic)) == 0)
        { // If this is the right section...
            return offset + 16; // ...return the offset of the first byte of the section after the header
        }

        // Haven't found our section yet. Let's move on to the next one.

        u32 section_length_offset = offset + sizeof(read_magic);
        if (section_length_offset >= buffer_length)
        { // If trying to read the section length would take us past the file's end...
            break;
        }

        // First we need to find out how big this section is...
        u32 section_length = 0;
        memcpy(&section_length, buffer + section_length_offset, sizeof(section_length));

        // ...then skip it. (The section length includes the 16-byte header.)
        offset += section_length;
    }

    // We've reached the end of the file without finding the requested section...
    Log(LogLevel::Error, "savestate: section %s not found. blarg\n", magic);
    return NO_SECTION;
}