aboutsummaryrefslogtreecommitdiff
path: root/src/frontend/Util_ROM.cpp
blob: 065b319857f6f6ebf7a19c661e9f1072cff8716a (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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
/*
    Copyright 2016-2020 Arisotura

    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 <string.h>

#include "FrontendUtil.h"
#include "Config.h"
#include "SharedConfig.h"
#include "Platform.h"

#include "NDS.h"
#include "DSi.h"
#include "GBACart.h"

#include "AREngine.h"


namespace Frontend
{

char ROMPath     [ROMSlot_MAX][1024];
char SRAMPath    [ROMSlot_MAX][1024];
char PrevSRAMPath[ROMSlot_MAX][1024]; // for savestate 'undo load'

bool SavestateLoaded;

ARCodeFile* CheatFile;
bool CheatsOn;


void Init_ROM()
{
    SavestateLoaded = false;

    memset(ROMPath[ROMSlot_NDS], 0, 1024);
    memset(ROMPath[ROMSlot_GBA], 0, 1024);
    memset(SRAMPath[ROMSlot_NDS], 0, 1024);
    memset(SRAMPath[ROMSlot_GBA], 0, 1024);
    memset(PrevSRAMPath[ROMSlot_NDS], 0, 1024);
    memset(PrevSRAMPath[ROMSlot_GBA], 0, 1024);

    CheatFile = nullptr;
    CheatsOn = false;
}

void DeInit_ROM()
{
    if (CheatFile)
    {
        delete CheatFile;
        CheatFile = nullptr;
    }
}

// TODO: currently, when failing to load a ROM for whatever reason, we attempt
// to revert to the previous state and resume execution; this may not be a very
// good thing, depending on what state the core was left in.
// should we do a better state revert (via the savestate system)? completely stop?

void SetupSRAMPath(int slot)
{
    strncpy(SRAMPath[slot], ROMPath[slot], 1023);
    SRAMPath[slot][1023] = '\0';
    strncpy(SRAMPath[slot] + strlen(ROMPath[slot]) - 3, "sav", 3);
}

int VerifyDSBIOS()
{
    FILE* f;
    long len;

    f = Platform::OpenLocalFile(Config::BIOS9Path, "rb");
    if (!f) return Load_BIOS9Missing;

    fseek(f, 0, SEEK_END);
    len = ftell(f);
    if (len != 0x1000)
    {
        fclose(f);
        return Load_BIOS9Bad;
    }

    fclose(f);

    f = Platform::OpenLocalFile(Config::BIOS7Path, "rb");
    if (!f) return Load_BIOS7Missing;

    fseek(f, 0, SEEK_END);
    len = ftell(f);
    if (len != 0x4000)
    {
        fclose(f);
        return Load_BIOS7Bad;
    }

    fclose(f);

    return Load_OK;
}

int VerifyDSiBIOS()
{
    FILE* f;
    long len;

    // TODO: check the first 32 bytes

    f = Platform::OpenLocalFile(Config::DSiBIOS9Path, "rb");
    if (!f) return Load_DSiBIOS9Missing;

    fseek(f, 0, SEEK_END);
    len = ftell(f);
    if (len != 0x10000)
    {
        fclose(f);
        return Load_DSiBIOS9Bad;
    }

    fclose(f);

    f = Platform::OpenLocalFile(Config::DSiBIOS7Path, "rb");
    if (!f) return Load_DSiBIOS7Missing;

    fseek(f, 0, SEEK_END);
    len = ftell(f);
    if (len != 0x10000)
    {
        fclose(f);
        return Load_DSiBIOS7Bad;
    }

    fclose(f);

    return Load_OK;
}

int VerifyDSFirmware()
{
    FILE* f;
    long len;

    f = Platform::OpenLocalFile(Config::FirmwarePath, "rb");
    if (!f) return Load_FirmwareMissing;

    fseek(f, 0, SEEK_END);
    len = ftell(f);
    if (len == 0x20000)
    {
        // 128KB firmware, not bootable
        fclose(f);
        return Load_FirmwareNotBootable;
    }
    else if (len != 0x40000 && len != 0x80000)
    {
        fclose(f);
        return Load_FirmwareBad;
    }

    fclose(f);

    return Load_OK;
}

int VerifyDSiFirmware()
{
    FILE* f;
    long len;

    f = Platform::OpenLocalFile(Config::DSiFirmwarePath, "rb");
    if (!f) return Load_FirmwareMissing;

    fseek(f, 0, SEEK_END);
    len = ftell(f);
    if (len != 0x20000)
    {
        // not 128KB
        // TODO: check whether those work
        fclose(f);
        return Load_FirmwareBad;
    }

    fclose(f);

    return Load_OK;
}

int SetupDSiNAND()
{
    FILE* f;
    long len;

    f = Platform::OpenLocalFile(Config::DSiNANDPath, "r+b");
    if (!f) return Load_DSiNANDMissing;

    // TODO: some basic checks
    // check that it has the nocash footer, and all

    DSi::SDMMCFile = f;

    if (Config::DSiSDEnable)
    {
        f = Platform::OpenLocalFile(Config::DSiSDPath, "r+b");
        if (f)
            DSi::SDIOFile = f;
        else
            DSi::SDIOFile = Platform::OpenLocalFile(Config::DSiSDPath, "w+b");
    }

    return Load_OK;
}

void LoadCheats()
{
    if (CheatFile)
    {
        delete CheatFile;
        CheatFile = nullptr;
    }

    char filename[1024];
    if (ROMPath[ROMSlot_NDS][0] != '\0')
    {
        strncpy(filename, ROMPath[ROMSlot_NDS], 1023);
        filename[1023] = '\0';
        strncpy(filename + strlen(ROMPath[ROMSlot_NDS]) - 3, "mch", 3);
    }
    else
    {
        strncpy(filename, "firmware.mch", 1023);
    }

    // TODO: check for error (malformed cheat file, ...)
    CheatFile = new ARCodeFile(filename);

    AREngine::SetCodeFile(CheatsOn ? CheatFile : nullptr);
}

int LoadBIOS()
{
    DSi::CloseDSiNAND();

    int res;

    res = VerifyDSBIOS();
    if (res != Load_OK) return res;

    if (Config::ConsoleType == 1)
    {
        res = VerifyDSiBIOS();
        if (res != Load_OK) return res;

        res = VerifyDSiFirmware();
        if (res != Load_OK) return res;

        res = SetupDSiNAND();
        if (res != Load_OK) return res;
    }
    else
    {
        res = VerifyDSFirmware();
        if (res != Load_OK) return res;
    }

    // TODO:
    // original code in the libui frontend called NDS::LoadGBAROM() if needed
    // should this be carried over here?
    // is that behavior consistent with that of LoadROM() below?

    ROMPath[ROMSlot_NDS][0] = '\0';
    SRAMPath[ROMSlot_NDS][0] = '\0';

    NDS::SetConsoleType(Config::ConsoleType);
    NDS::LoadBIOS();

    SavestateLoaded = false;

    LoadCheats();

    return Load_OK;
}

int LoadROM(const char* file, int slot)
{
    DSi::CloseDSiNAND();

    int res;
    bool directboot = Config::DirectBoot != 0;

    if (Config::ConsoleType == 1 && slot == 1)
    {
        // cannot load a GBA ROM into a DSi
        return Load_ROMLoadError;
    }

    res = VerifyDSBIOS();
    if (res != Load_OK) return res;

    if (Config::ConsoleType == 1)
    {
        res = VerifyDSiBIOS();
        if (res != Load_OK) return res;

        res = VerifyDSiFirmware();
        if (res != Load_OK) return res;

        res = SetupDSiNAND();
        if (res != Load_OK) return res;

        GBACart::Eject();
        ROMPath[ROMSlot_GBA][0] = '\0';
    }
    else
    {
        res = VerifyDSFirmware();
        if (res != Load_OK)
        {
            if (res == Load_FirmwareNotBootable)
                directboot = true;
            else
                return res;
        }
    }

    char oldpath[1024];
    char oldsram[1024];
    strncpy(oldpath, ROMPath[slot], 1024);
    strncpy(oldsram, SRAMPath[slot], 1024);

    strncpy(ROMPath[slot], file, 1023);
    ROMPath[slot][1023] = '\0';

    SetupSRAMPath(0);
    SetupSRAMPath(1);

    NDS::SetConsoleType(Config::ConsoleType);

    if (slot == ROMSlot_NDS && NDS::LoadROM(ROMPath[slot], SRAMPath[slot], directboot))
    {
        SavestateLoaded = false;

        LoadCheats();

        // Reload the inserted GBA cartridge (if any)
        // TODO: report failure there??
        if (ROMPath[ROMSlot_GBA][0] != '\0') NDS::LoadGBAROM(ROMPath[ROMSlot_GBA], SRAMPath[ROMSlot_GBA]);

        strncpy(PrevSRAMPath[slot], SRAMPath[slot], 1024); // safety
        return Load_OK;
    }
    else if (slot == ROMSlot_GBA && NDS::LoadGBAROM(ROMPath[slot], SRAMPath[slot]))
    {
        SavestateLoaded = false; // checkme??

        strncpy(PrevSRAMPath[slot], SRAMPath[slot], 1024); // safety
        return Load_OK;
    }
    else
    {
        strncpy(ROMPath[slot], oldpath, 1024);
        strncpy(SRAMPath[slot], oldsram, 1024);
        return Load_ROMLoadError;
    }
}

void UnloadROM(int slot)
{
    if (slot == ROMSlot_NDS)
    {
        // TODO!
    }
    else if (slot == ROMSlot_GBA)
    {
        GBACart::Eject();
    }

    ROMPath[slot][0] = '\0';

    DSi::CloseDSiNAND();
}

int Reset()
{
    DSi::CloseDSiNAND();

    int res;
    bool directboot = Config::DirectBoot != 0;

    res = VerifyDSBIOS();
    if (res != Load_OK) return res;

    if (Config::ConsoleType == 1)
    {
        res = VerifyDSiBIOS();
        if (res != Load_OK) return res;

        res = VerifyDSiFirmware();
        if (res != Load_OK) return res;

        res = SetupDSiNAND();
        if (res != Load_OK) return res;

        GBACart::Eject();
        ROMPath[ROMSlot_GBA][0] = '\0';
    }
    else
    {
        res = VerifyDSFirmware();
        if (res != Load_OK)
        {
            if (res == Load_FirmwareNotBootable)
                directboot = true;
            else
                return res;
        }
    }

    SavestateLoaded = false;

    NDS::SetConsoleType(Config::ConsoleType);

    if (ROMPath[ROMSlot_NDS][0] == '\0')
    {
        NDS::LoadBIOS();
    }
    else
    {
        SetupSRAMPath(0);
        if (!NDS::LoadROM(ROMPath[ROMSlot_NDS], SRAMPath[ROMSlot_NDS], directboot))
            return Load_ROMLoadError;
    }

    if (ROMPath[ROMSlot_GBA][0] != '\0')
    {
        SetupSRAMPath(1);
        if (!NDS::LoadGBAROM(ROMPath[ROMSlot_GBA], SRAMPath[ROMSlot_GBA]))
            return Load_ROMLoadError;
    }

    LoadCheats();

    return Load_OK;
}


// SAVESTATE TODO
// * configurable paths. not everyone wants their ROM directory to be polluted, I guess.

void GetSavestateName(int slot, char* filename, int len)
{
    int pos;

    if (ROMPath[ROMSlot_NDS][0] == '\0') // running firmware, no ROM
    {
        strcpy(filename, "firmware");
        pos = 8;
    }
    else
    {
        int l = strlen(ROMPath[ROMSlot_NDS]);
        pos = l;
        while (ROMPath[ROMSlot_NDS][pos] != '.' && pos > 0) pos--;
        if (pos == 0) pos = l;

        // avoid buffer overflow. shoddy
        if (pos > len-5) pos = len-5;

        strncpy(&filename[0], ROMPath[ROMSlot_NDS], pos);
    }
    strcpy(&filename[pos], ".ml");
    filename[pos+3] = '0'+slot;
    filename[pos+4] = '\0';
}

bool SavestateExists(int slot)
{
    char ssfile[1024];
    GetSavestateName(slot, ssfile, 1024);
    return Platform::FileExists(ssfile);
}

bool LoadState(const char* filename)
{
    u32 oldGBACartCRC = GBACart::CartCRC;

    // backup
    Savestate* backup = new Savestate("timewarp.mln", true);
    NDS::DoSavestate(backup);
    delete backup;

    bool failed = false;

    Savestate* state = new Savestate(filename, false);
    if (state->Error)
    {
        delete state;

        //uiMsgBoxError(MainWindow, "Error", "Could not load savestate file.");

        // current state might be crapoed, so restore from sane backup
        state = new Savestate("timewarp.mln", false);
        failed = true;
    }

    NDS::DoSavestate(state);
    delete state;

    if (!failed)
    {
        if (Config::SavestateRelocSRAM && ROMPath[ROMSlot_NDS][0]!='\0')
        {
            strncpy(PrevSRAMPath[ROMSlot_NDS], SRAMPath[0], 1024);

            strncpy(SRAMPath[ROMSlot_NDS], filename, 1019);
            int len = strlen(SRAMPath[ROMSlot_NDS]);
            strcpy(&SRAMPath[ROMSlot_NDS][len], ".sav");
            SRAMPath[ROMSlot_NDS][len+4] = '\0';

            NDS::RelocateSave(SRAMPath[ROMSlot_NDS], false);
        }

        bool loadedPartialGBAROM = false;

        // in case we have a GBA cart inserted, and the GBA ROM changes
        // due to having loaded a save state, we do not want to reload
        // the previous cartridge on reset, or commit writes to any
        // loaded save file. therefore, their paths are "nulled".
        if (GBACart::CartInserted && GBACart::CartCRC != oldGBACartCRC)
        {
            ROMPath[ROMSlot_GBA][0] = '\0';
            SRAMPath[ROMSlot_GBA][0] = '\0';
            loadedPartialGBAROM = true;
        }

        // TODO forward this to user in a meaningful way!!
        /*char msg[64];
        if (slot > 0) sprintf(msg, "State loaded from slot %d%s",
                        slot, loadedPartialGBAROM ? " (GBA ROM header only)" : "");
        else          sprintf(msg, "State loaded from file%s",
                        loadedPartialGBAROM ? " (GBA ROM header only)" : "");
        OSD::AddMessage(0, msg);*/

        SavestateLoaded = true;
    }

    return !failed;
}

bool SaveState(const char* filename)
{
    Savestate* state = new Savestate(filename, true);
    if (state->Error)
    {
        delete state;
        return false;
    }
    else
    {
        NDS::DoSavestate(state);
        delete state;

        if (Config::SavestateRelocSRAM && ROMPath[ROMSlot_NDS][0]!='\0')
        {
            strncpy(SRAMPath[ROMSlot_NDS], filename, 1019);
            int len = strlen(SRAMPath[ROMSlot_NDS]);
            strcpy(&SRAMPath[ROMSlot_NDS][len], ".sav");
            SRAMPath[ROMSlot_NDS][len+4] = '\0';

            NDS::RelocateSave(SRAMPath[ROMSlot_NDS], true);
        }
    }

    return true;
}

void UndoStateLoad()
{
    if (!SavestateLoaded) return;

    // pray that this works
    // what do we do if it doesn't???
    // but it should work.
    Savestate* backup = new Savestate("timewarp.mln", false);
    NDS::DoSavestate(backup);
    delete backup;

    if (ROMPath[ROMSlot_NDS][0]!='\0')
    {
        strncpy(SRAMPath[ROMSlot_NDS], PrevSRAMPath[ROMSlot_NDS], 1024);
        NDS::RelocateSave(SRAMPath[ROMSlot_NDS], false);
    }
}

int ImportSRAM(const char* filename)
{
    FILE* file = fopen(filename, "rb");
    fseek(file, 0, SEEK_END);
    u32 size = ftell(file);
    u8* importData = new u8[size];
    rewind(file);
    fread(importData, size, 1, file);
    fclose(file);

    int diff = NDS::ImportSRAM(importData, size);
    delete[] importData;
    return diff;
}

void EnableCheats(bool enable)
{
    CheatsOn = enable;
    if (CheatFile)
        AREngine::SetCodeFile(CheatsOn ? CheatFile : nullptr);
}

}