diff --git a/CHANGES b/CHANGES index 09dc94684..f75e7505b 100644 --- a/CHANGES +++ b/CHANGES @@ -3,6 +3,7 @@ Bugfixes: - GBA Memory: Fix misaligned BIOS reads - GBA BIOS: Fix MidiKey2Freq BIOS reads - GBA BIOS: Fix invalid CpuSet not setting BIOS prefetch + - GB MBC: Fix SRAM dangling pointer with RTC games 0.5.1: (2016-10-05) Bugfixes: diff --git a/src/gb/gb.c b/src/gb/gb.c index 89b92a254..ff7953bfd 100644 --- a/src/gb/gb.c +++ b/src/gb/gb.c @@ -120,7 +120,7 @@ bool GBLoadSave(struct GB* gb, struct VFile* vf) { static void GBSramDeinit(struct GB* gb) { if (gb->sramVf) { gb->sramVf->unmap(gb->sramVf, gb->memory.sram, gb->sramSize); - if (gb->memory.mbcType == GB_MBC3_RTC) { + if (gb->memory.mbcType == GB_MBC3_RTC && gb->sramVf == gb->sramRealVf) { GBMBCRTCWrite(gb); } gb->sramVf = NULL; @@ -192,7 +192,7 @@ void GBResizeSram(struct GB* gb, size_t size) { void GBSramClean(struct GB* gb, uint32_t frameCount) { // TODO: Share with GBASavedataClean - if (!gb->sramVf) { + if (!gb->sramVf || gb->sramVf != gb->sramRealVf) { return; } if (gb->sramDirty & GB_SRAM_DIRT_NEW) { diff --git a/src/gb/mbc.c b/src/gb/mbc.c index acd84ce07..c1961341c 100644 --- a/src/gb/mbc.c +++ b/src/gb/mbc.c @@ -671,6 +671,15 @@ void GBMBCRTCWrite(struct GB* gb) { STORE_32LE(gb->memory.rtcRegs[4], 0, &rtcBuffer.latchedDaysHi); STORE_64LE(rtcLastLatch, 0, &rtcBuffer.unixTime); + if (vf->size(vf) == gb->sramSize) { + // Writing past the end of the file can invalidate the file mapping + vf->unmap(vf, gb->memory.sram, gb->sramSize); + gb->memory.sram = NULL; + } vf->seek(vf, gb->sramSize, SEEK_SET); vf->write(vf, &rtcBuffer, sizeof(rtcBuffer)); + if (!gb->memory.sram) { + gb->memory.sram = vf->map(vf, gb->sramSize, MAP_WRITE); + GBMBCSwitchSramBank(gb, gb->memory.sramCurrentBank); + } }