diff --git a/src/gb/gb.c b/src/gb/gb.c index 748720bcb..ba1f33571 100644 --- a/src/gb/gb.c +++ b/src/gb/gb.c @@ -44,6 +44,7 @@ static void GBInit(struct LR35902Core* cpu, struct LR35902Component* component) gb->timer.p = gb; gb->romVf = 0; + gb->sramVf = 0; gb->pristineRom = 0; gb->pristineRomSize = 0; @@ -72,6 +73,12 @@ bool GBLoadROM(struct GB* gb, struct VFile* vf, struct VFile* sav, const char* f gb->activeFile = fname; gb->memory.romSize = gb->pristineRomSize; gb->romCrc32 = doCrc32(gb->memory.rom, gb->memory.romSize); + gb->sramVf = sav; + if (sav) { + gb->memory.sram = sav->map(sav, 0x8000, MAP_WRITE); + } else { + gb->memory.sram = anonymousMemoryMap(0x8000); + } return true; // TODO: error check } @@ -93,6 +100,13 @@ void GBUnloadROM(struct GB* gb) { gb->pristineRom = 0; gb->romVf = 0; } + + if (gb->sramVf) { + gb->sramVf->unmap(gb->sramVf, gb->memory.sram, 0x8000); + } else if (gb->memory.sram) { + mappedMemoryFree(gb->memory.sram, 0x8000); + } + gb->memory.sram = 0; } void GBDestroy(struct GB* gb) { @@ -209,7 +223,6 @@ void GBSetInterrupts(struct LR35902Core* cpu, bool enable) { } void GBHalt(struct LR35902Core* cpu) { - struct GB* gb = (struct GB*) cpu->master; cpu->cycles = cpu->nextEvent; cpu->halted = true; } diff --git a/src/gb/gb.h b/src/gb/gb.h index 9a72daa69..9bf449637 100644 --- a/src/gb/gb.h +++ b/src/gb/gb.h @@ -50,6 +50,7 @@ struct GB { size_t yankedRomSize; uint32_t romCrc32; struct VFile* romVf; + struct VFile* sramVf; const char* activeFile; }; diff --git a/src/gb/memory.c b/src/gb/memory.c index 04fa03598..1338b865f 100644 --- a/src/gb/memory.c +++ b/src/gb/memory.c @@ -57,9 +57,6 @@ void GBMemoryDeinit(struct GB* gb) { if (gb->memory.rom) { mappedMemoryFree(gb->memory.rom, gb->memory.romSize); } - if (gb->memory.sram) { - mappedMemoryFree(gb->memory.sram, 0x8000); - } } void GBMemoryReset(struct GB* gb) { @@ -70,7 +67,6 @@ void GBMemoryReset(struct GB* gb) { gb->memory.wramBank = &gb->memory.wram[GB_SIZE_WORKING_RAM_BANK0]; gb->memory.romBank = &gb->memory.rom[GB_SIZE_CART_BANK0]; gb->memory.currentBank = 1; - gb->memory.sram = anonymousMemoryMap(0x8000); // TODO: Persist gb->memory.sramCurrentBank = 0; memset(&gb->video.oam, 0, sizeof(gb->video.oam));