From adf773f1ed272f31ae34e2613d20ec796b651bf8 Mon Sep 17 00:00:00 2001 From: GriffinR Date: Thu, 28 Oct 2021 22:54:41 -0400 Subject: [PATCH] Document remainder of save.c --- common_syms/save.txt | 6 +- include/load_save.h | 4 +- include/save.h | 129 ++++----- src/berry_blender.c | 4 +- src/berry_crush.c | 4 +- src/dodrio_berry_picking.c | 4 +- src/ereader_helpers.c | 4 +- src/hall_of_fame.c | 12 +- src/intro.c | 2 +- src/load_save.c | 4 +- src/pokemon_jump.c | 4 +- src/record_mixing.c | 10 +- src/recorded_battle.c | 16 +- src/reload_save.c | 2 +- src/save.c | 544 +++++++++++++++++++++---------------- src/save_failed_screen.c | 6 +- src/start_menu.c | 18 +- src/trade.c | 19 +- 18 files changed, 428 insertions(+), 364 deletions(-) diff --git a/common_syms/save.txt b/common_syms/save.txt index 190a65840..131031d50 100644 --- a/common_syms/save.txt +++ b/common_syms/save.txt @@ -3,11 +3,11 @@ gLastSaveCounter gLastKnownGoodSector gDamagedSaveSectors gSaveCounter -gFastSaveSection -gUnknown_03006208 +gReadWriteSector +gIncrementalSectorId gSaveUnusedVar gSaveFileStatus gGameContinueCallback -gRamSaveSectionLocations +gRamSaveSectorLocations gSaveUnusedVar2 gSaveAttemptStatus diff --git a/include/load_save.h b/include/load_save.h index 2f4a9ace6..14a979b45 100644 --- a/include/load_save.h +++ b/include/load_save.h @@ -24,8 +24,8 @@ void SavePlayerParty(void); void LoadPlayerParty(void); void SaveObjectEvents(void); void LoadObjectEvents(void); -void SaveSerializedGame(void); -void LoadSerializedGame(void); +void CopyPartyAndObjectsToSave(void); +void CopyPartyAndObjectsFromSave(void); void LoadPlayerBag(void); void SavePlayerBag(void); void ApplyNewEncryptionKeyToHword(u16 *hWord, u32 newKey); diff --git a/include/save.h b/include/save.h index 406e2e492..be7961136 100644 --- a/include/save.h +++ b/include/save.h @@ -1,43 +1,43 @@ #ifndef GUARD_SAVE_H #define GUARD_SAVE_H -struct SaveSectionLocation -{ - void *data; - u16 size; -}; - -struct SaveSection -{ - u8 data[0xFF4]; - u16 id; - u16 checksum; - u32 security; - u32 counter; -}; // size is 0x1000 - -// headless save section? -struct UnkSaveSection -{ - u8 data[0xFF4]; - u32 security; -}; // size is 0xFF8 - -struct SaveSectionOffsets -{ - u16 toAdd; - u16 size; -}; - -// Each 4 KiB flash sector contains 3968 bytes of actual data followed by a 128 byte footer +// Each 4 KiB flash sector contains 3968 bytes of actual data followed by a 128 byte footer. +// Only 12 bytes of the footer are used. #define SECTOR_DATA_SIZE 3968 #define SECTOR_FOOTER_SIZE 128 #define SECTOR_SIZE (SECTOR_DATA_SIZE + SECTOR_FOOTER_SIZE) #define NUM_SAVE_SLOTS 2 -#define UNKNOWN_CHECK_VALUE 0x8012025 -#define SPECIAL_SECTION_SENTINEL 0xB39D +// If the sector's security field is not this value then the sector is either invalid or empty. +#define SECTOR_SECURITY_NUM 0x8012025 + +#define SPECIAL_SECTOR_SENTINEL 0xB39D + +#define SECTOR_ID_SAVEBLOCK2 0 +#define SECTOR_ID_SAVEBLOCK1_START 1 +#define SECTOR_ID_SAVEBLOCK1_END 4 +#define SECTOR_ID_PKMN_STORAGE_START 5 +#define SECTOR_ID_PKMN_STORAGE_END 13 +#define NUM_SECTORS_PER_SLOT 14 +// Save Slot 1: 0-13; Save Slot 2: 14-27 +#define SECTOR_ID_HOF_1 28 +#define SECTOR_ID_HOF_2 29 +#define SECTOR_ID_TRAINER_HILL 30 +#define SECTOR_ID_RECORDED_BATTLE 31 +#define SECTORS_COUNT 32 + +#define NUM_HOF_SECTORS 2 + +#define SAVE_STATUS_EMPTY 0 +#define SAVE_STATUS_OK 1 +#define SAVE_STATUS_CORRUPT 2 +#define SAVE_STATUS_NO_FLASH 4 +#define SAVE_STATUS_ERROR 0xFF + +// Special sector id value for certain save functions to +// indicate that no specific sector should be used. +#define FULL_SAVE_SLOT 0xFFFF // SetDamagedSectorBits states enum @@ -51,7 +51,7 @@ enum enum { SAVE_NORMAL, - SAVE_LINK, + SAVE_LINK, // Link / Battle Frontier //EREADER_SAVE, // deprecated in Emerald SAVE_LINK2, // unknown 2nd link save SAVE_HALL_OF_FAME, @@ -59,54 +59,55 @@ enum SAVE_HALL_OF_FAME_ERASE_BEFORE // unused }; -#define SECTOR_ID_SAVEBLOCK2 0 -#define SECTOR_ID_SAVEBLOCK1_START 1 -#define SECTOR_ID_SAVEBLOCK1_END 4 -#define SECTOR_ID_PKMN_STORAGE_START 5 -#define SECTOR_ID_PKMN_STORAGE_END 13 -#define NUM_SECTORS_PER_SLOT 14 -// Save Slot 1: 0-13; Save Slot 2: 14-27 -#define SECTOR_ID_HOF_1 28 -#define SECTOR_ID_HOF_2 29 -#define SECTOR_ID_TRAINER_HILL 30 -#define SECTOR_ID_RECORDED_BATTLE 31 -#define SECTORS_COUNT 32 +// A save sector location holds a pointer to the data for a particular sector +// and the size of that data. Size cannot be greater than SECTOR_DATA_SIZE. +struct SaveSectorLocation +{ + void *data; + u16 size; +}; -#define SAVE_STATUS_EMPTY 0 -#define SAVE_STATUS_OK 1 -#define SAVE_STATUS_CORRUPT 2 -#define SAVE_STATUS_NO_FLASH 4 -#define SAVE_STATUS_ERROR 0xFF +struct SaveSector +{ + u8 data[SECTOR_DATA_SIZE]; + u8 unused[SECTOR_FOOTER_SIZE - 12]; // Unused portion of the footer + u16 id; + u16 checksum; + u32 security; + u32 counter; +}; // size is SECTOR_SIZE (0x1000) + +#define SECTOR_SECURITY_OFFSET offsetof(struct SaveSector, security) +#define SECTOR_COUNTER_OFFSET offsetof(struct SaveSector, counter) extern u16 gLastWrittenSector; extern u32 gLastSaveCounter; extern u16 gLastKnownGoodSector; extern u32 gDamagedSaveSectors; extern u32 gSaveCounter; -extern struct SaveSection *gFastSaveSection; -extern u16 gUnknown_03006208; +extern struct SaveSector *gFastSaveSector; +extern u16 gIncrementalSectorId; extern u16 gSaveFileStatus; extern void (*gGameContinueCallback)(void); -extern struct SaveSectionLocation gRamSaveSectionLocations[]; -extern u16 gUnknown_03006294; +extern struct SaveSectorLocation gRamSaveSectorLocations[]; -extern struct SaveSection gSaveDataBuffer; +extern struct SaveSector gSaveDataBuffer; void ClearSaveData(void); void Save_ResetSaveCounters(void); u8 HandleSavingData(u8 saveType); u8 TrySavingData(u8 saveType); -bool8 sub_8153380(void); -bool8 sub_81533AC(void); -bool8 sub_81533E0(void); -bool8 sub_8153408(void); -bool8 FullSaveGame(void); -bool8 CheckSaveFile(void); -u8 Save_LoadGameData(u8 saveType); +bool8 LinkFullSave_Init(void); +bool8 LinkFullSave_WriteSector(void); +bool8 LinkFullSave_ReplaceLastSector(void); +bool8 LinkFullSave_SetLastSectorSecurity(void); +bool8 WriteSaveBlock2(void); +bool8 WriteSaveBlock1Sector(void); +u8 LoadGameSave(u8 saveType); u16 GetSaveBlocksPointersBaseOffset(void); -u32 TryReadSpecialSaveSection(u8 sector, u8* dst); -u32 TryWriteSpecialSaveSection(u8 sector, u8* src); -void Task_LinkSave(u8 taskId); +u32 TryReadSpecialSaveSector(u8 sector, u8* dst); +u32 TryWriteSpecialSaveSector(u8 sector, u8* src); +void Task_LinkFullSave(u8 taskId); // save_failed_screen.c void DoSaveFailedScreen(u8 saveType); diff --git a/src/berry_blender.c b/src/berry_blender.c index 65008dae0..3ef2c4239 100644 --- a/src/berry_blender.c +++ b/src/berry_blender.c @@ -2785,7 +2785,7 @@ static bool8 LinkPlayAgainHandleSaving(void) } break; case 2: - FullSaveGame(); + WriteSaveBlock2(); sBerryBlender->linkPlayAgainState++; sBerryBlender->framesToWait = 0; break; @@ -2799,7 +2799,7 @@ static bool8 LinkPlayAgainHandleSaving(void) case 4: if (IsLinkTaskFinished()) { - if (CheckSaveFile()) + if (WriteSaveBlock1Sector()) { sBerryBlender->linkPlayAgainState = 5; } diff --git a/src/berry_crush.c b/src/berry_crush.c index 8ac6bb312..ca70e05e0 100755 --- a/src/berry_crush.c +++ b/src/berry_crush.c @@ -3244,10 +3244,10 @@ static u32 Cmd_SaveGame(struct BerryCrushGame *game, u8 *args) DrawDialogueFrame(0, 0); AddTextPrinterParameterized2(0, FONT_NORMAL, gText_SavingDontTurnOffPower, 0, 0, 2, 1, 3); CopyWindowToVram(0, 3); - CreateTask(Task_LinkSave, 0); + CreateTask(Task_LinkFullSave, 0); break; case 3: - if (FuncIsActiveTask(Task_LinkSave)) + if (FuncIsActiveTask(Task_LinkFullSave)) return 0; break; case 4: diff --git a/src/dodrio_berry_picking.c b/src/dodrio_berry_picking.c index 838e8ed94..8e226312a 100644 --- a/src/dodrio_berry_picking.c +++ b/src/dodrio_berry_picking.c @@ -5035,12 +5035,12 @@ static void Msg_SavingDontTurnOff(void) case 2: if (!IsDma3ManagerBusyWithBgCopy()) { - CreateTask(Task_LinkSave, 0); + CreateTask(Task_LinkFullSave, 0); sGfx->state++; } break; case 3: - if (!FuncIsActiveTask(Task_LinkSave)) + if (!FuncIsActiveTask(Task_LinkFullSave)) sGfx->state++; break; default: diff --git a/src/ereader_helpers.c b/src/ereader_helpers.c index 9a93707d8..0de87602e 100755 --- a/src/ereader_helpers.c +++ b/src/ereader_helpers.c @@ -481,7 +481,7 @@ static bool32 TryWriteTrainerHill_Internal(struct EReaderTrainerHillSet * hillSe } hillTag->checksum = CalcByteArraySum((u8 *)hillTag->floors, NUM_TRAINER_HILL_FLOORS * sizeof(struct TrHillFloor)); - if (TryWriteSpecialSaveSection(SECTOR_ID_TRAINER_HILL, (u8 *)hillTag) != SAVE_STATUS_OK) + if (TryWriteSpecialSaveSector(SECTOR_ID_TRAINER_HILL, (u8 *)hillTag) != SAVE_STATUS_OK) return FALSE; return TRUE; @@ -497,7 +497,7 @@ bool32 TryWriteTrainerHill(struct EReaderTrainerHillSet * hillSet) static bool32 TryReadTrainerHill_Internal(struct EReaderTrainerHillSet * dest, u8 * buffer) { - if (TryReadSpecialSaveSection(SECTOR_ID_TRAINER_HILL, buffer) != SAVE_STATUS_OK) + if (TryReadSpecialSaveSector(SECTOR_ID_TRAINER_HILL, buffer) != SAVE_STATUS_OK) return FALSE; memcpy(dest, buffer, sizeof(struct EReaderTrainerHillSet)); diff --git a/src/hall_of_fame.c b/src/hall_of_fame.c index 8d69b03bc..467cd1588 100644 --- a/src/hall_of_fame.c +++ b/src/hall_of_fame.c @@ -487,12 +487,12 @@ static void Task_Hof_InitTeamSaveData(u8 taskId) if (!gHasHallOfFameRecords) { - memset(gDecompressionBuffer, 0, 0x2000); + memset(gDecompressionBuffer, 0, SECTOR_SIZE * NUM_HOF_SECTORS); } else { - if (Save_LoadGameData(SAVE_HALL_OF_FAME) != SAVE_STATUS_OK) - memset(gDecompressionBuffer, 0, 0x2000); + if (LoadGameSave(SAVE_HALL_OF_FAME) != SAVE_STATUS_OK) + memset(gDecompressionBuffer, 0, SECTOR_SIZE * NUM_HOF_SECTORS); } for (i = 0; i < HALL_OF_FAME_MAX_TEAMS; i++, lastSavedTeam++) @@ -853,7 +853,7 @@ void CB2_DoHallOfFamePC(void) gTasks[taskId].tMonSpriteId(i) = SPRITE_NONE; } - sHofMonPtr = AllocZeroed(0x2000); + sHofMonPtr = AllocZeroed(SECTOR_SIZE * NUM_HOF_SECTORS); SetMainCallback2(CB2_HallOfFame); } break; @@ -863,7 +863,7 @@ void CB2_DoHallOfFamePC(void) static void Task_HofPC_CopySaveData(u8 taskId) { sub_81980F0(0, 0x1E, 0, 0xC, 0x226); - if (Save_LoadGameData(SAVE_HALL_OF_FAME) != SAVE_STATUS_OK) + if (LoadGameSave(SAVE_HALL_OF_FAME) != SAVE_STATUS_OK) { gTasks[taskId].func = Task_HofPC_PrintDataIsCorrupted; } @@ -872,7 +872,7 @@ static void Task_HofPC_CopySaveData(u8 taskId) u16 i; struct HallofFameTeam* savedTeams; - CpuCopy16(gDecompressionBuffer, sHofMonPtr, 0x2000); + CpuCopy16(gDecompressionBuffer, sHofMonPtr, SECTOR_SIZE * NUM_HOF_SECTORS); savedTeams = sHofMonPtr; for (i = 0; i < HALL_OF_FAME_MAX_TEAMS; i++, savedTeams++) { diff --git a/src/intro.c b/src/intro.c index 5cf99c97e..0f044c642 100644 --- a/src/intro.c +++ b/src/intro.c @@ -1145,7 +1145,7 @@ void CB2_InitCopyrightScreenAfterBootup(void) SetSaveBlocksPointers(GetSaveBlocksPointersBaseOffset()); ResetMenuAndMonGlobals(); Save_ResetSaveCounters(); - Save_LoadGameData(SAVE_NORMAL); + LoadGameSave(SAVE_NORMAL); if (gSaveFileStatus == SAVE_STATUS_EMPTY || gSaveFileStatus == SAVE_STATUS_CORRUPT) Sav2_ClearSetDefault(); SetPokemonCryStereo(gSaveBlock2Ptr->optionsSound); diff --git a/src/load_save.c b/src/load_save.c index 1ba5a1600..4e788859c 100644 --- a/src/load_save.c +++ b/src/load_save.c @@ -198,13 +198,13 @@ void LoadObjectEvents(void) gObjectEvents[i] = gSaveBlock1Ptr->objectEvents[i]; } -void SaveSerializedGame(void) +void CopyPartyAndObjectsToSave(void) { SavePlayerParty(); SaveObjectEvents(); } -void LoadSerializedGame(void) +void CopyPartyAndObjectsFromSave(void) { LoadPlayerParty(); LoadObjectEvents(); diff --git a/src/pokemon_jump.c b/src/pokemon_jump.c index fb1505c6c..ad3f62c56 100755 --- a/src/pokemon_jump.c +++ b/src/pokemon_jump.c @@ -1282,12 +1282,12 @@ static bool32 SavePokeJump(void) case 2: if (AreLinkQueuesEmpty()) { - CreateTask(Task_LinkSave, 6); + CreateTask(Task_LinkFullSave, 6); sPokemonJump->mainState++; } break; case 3: - if (!FuncIsActiveTask(Task_LinkSave)) + if (!FuncIsActiveTask(Task_LinkFullSave)) { ClearMessageWindow(); sPokemonJump->mainState++; diff --git a/src/record_mixing.c b/src/record_mixing.c index 2197d8542..6613b1311 100644 --- a/src/record_mixing.c +++ b/src/record_mixing.c @@ -1002,11 +1002,11 @@ static void Task_DoRecordMixing(u8 taskId) case 2: // Mixing Ruby/Sapphire records. SetContinueGameWarpStatusToDynamicWarp(); - FullSaveGame(); + WriteSaveBlock2(); task->tState++; break; case 3: - if (CheckSaveFile()) + if (WriteSaveBlock1Sector()) { ClearContinueGameWarpStatus2(); task->tState = 4; @@ -1030,12 +1030,12 @@ static void Task_DoRecordMixing(u8 taskId) case 6: if (!Rfu_SetLinkRecovery(FALSE)) { - CreateTask(Task_LinkSave, 5); + CreateTask(Task_LinkFullSave, 5); task->tState++; } break; - case 7: // wait for Task_LinkSave to finish. - if (!FuncIsActiveTask(Task_LinkSave)) + case 7: // wait for Task_LinkFullSave to finish. + if (!FuncIsActiveTask(Task_LinkFullSave)) { if (gWirelessCommType) { diff --git a/src/recorded_battle.c b/src/recorded_battle.c index e6d5b165b..fd2b3a06b 100644 --- a/src/recorded_battle.c +++ b/src/recorded_battle.c @@ -306,14 +306,14 @@ static bool32 IsRecordedBattleSaveValid(struct RecordedBattleSave *save) return TRUE; } -static bool32 RecordedBattleToSave(struct RecordedBattleSave *battleSave, struct RecordedBattleSave *saveSection) +static bool32 RecordedBattleToSave(struct RecordedBattleSave *battleSave, struct RecordedBattleSave *saveSector) { - memset(saveSection, 0, SECTOR_SIZE); - memcpy(saveSection, battleSave, sizeof(*battleSave)); + memset(saveSector, 0, SECTOR_SIZE); + memcpy(saveSector, battleSave, sizeof(*battleSave)); - saveSection->checksum = CalcByteArraySum((void*)(saveSection), sizeof(*saveSection) - 4); + saveSector->checksum = CalcByteArraySum((void*)(saveSector), sizeof(*saveSector) - 4); - if (TryWriteSpecialSaveSection(SECTOR_ID_RECORDED_BATTLE, (void*)(saveSection)) != SAVE_STATUS_OK) + if (TryWriteSpecialSaveSector(SECTOR_ID_RECORDED_BATTLE, (void*)(saveSector)) != SAVE_STATUS_OK) return FALSE; else return TRUE; @@ -477,9 +477,9 @@ bool32 MoveRecordedBattleToSaveData(void) return ret; } -static bool32 TryCopyRecordedBattleSaveData(struct RecordedBattleSave *dst, struct SaveSection *saveBuffer) +static bool32 TryCopyRecordedBattleSaveData(struct RecordedBattleSave *dst, struct SaveSector *saveBuffer) { - if (TryReadSpecialSaveSection(SECTOR_ID_RECORDED_BATTLE, (void*)(saveBuffer)) != SAVE_STATUS_OK) + if (TryReadSpecialSaveSector(SECTOR_ID_RECORDED_BATTLE, (void*)(saveBuffer)) != SAVE_STATUS_OK) return FALSE; memcpy(dst, saveBuffer, sizeof(struct RecordedBattleSave)); @@ -492,7 +492,7 @@ static bool32 TryCopyRecordedBattleSaveData(struct RecordedBattleSave *dst, stru static bool32 CopyRecordedBattleFromSave(struct RecordedBattleSave *dst) { - struct SaveSection *savBuffer = AllocZeroed(sizeof(struct SaveSection)); + struct SaveSector *savBuffer = AllocZeroed(SECTOR_SIZE); bool32 ret = TryCopyRecordedBattleSaveData(dst, savBuffer); Free(savBuffer); diff --git a/src/reload_save.c b/src/reload_save.c index cdbb2f227..5425d1c7c 100644 --- a/src/reload_save.c +++ b/src/reload_save.c @@ -21,7 +21,7 @@ void ReloadSave(void) SetSaveBlocksPointers(GetSaveBlocksPointersBaseOffset()); ResetMenuAndMonGlobals(); Save_ResetSaveCounters(); - Save_LoadGameData(SAVE_NORMAL); + LoadGameSave(SAVE_NORMAL); if (gSaveFileStatus == SAVE_STATUS_EMPTY || gSaveFileStatus == SAVE_STATUS_CORRUPT) Sav2_ClearSetDefault(); SetPokemonCryStereo(gSaveBlock2Ptr->optionsSound); diff --git a/src/save.c b/src/save.c index 3c8f4360d..cd25977e1 100644 --- a/src/save.c +++ b/src/save.c @@ -13,13 +13,13 @@ #include "link.h" #include "constants/game_stat.h" -static u16 CalculateChecksum(void *data, u16 size); -static bool8 DoReadFlashWholeSection(u8 sector, struct SaveSection *section); -static u8 GetSaveValidStatus(const struct SaveSectionLocation *location); -static u8 sub_8152E10(u16 a1, const struct SaveSectionLocation *location); -static u8 ClearSaveData_2(u16 a1, const struct SaveSectionLocation *location); -static u8 TryWriteSector(u8 sector, u8 *data); -static u8 HandleWriteSector(u16 a1, const struct SaveSectionLocation *location); +static u16 CalculateChecksum(void *, u16); +static bool8 ReadFlashSector(u8, struct SaveSector *); +static u8 GetSaveValidStatus(const struct SaveSectorLocation *); +static u8 CopySaveSlotData(u16, struct SaveSectorLocation *); +static u8 TryWriteSector(u8, u8 *); +static u8 HandleWriteSector(u16, const struct SaveSectorLocation *); +static u8 HandleReplaceSector(u16, const struct SaveSectorLocation *); // Divide save blocks into individual chunks to be written to flash sectors @@ -38,11 +38,10 @@ static u8 HandleWriteSector(u16 a1, const struct SaveSectionLocation *location); * so that the same data is not always being written to the same sector. This * might be done to reduce wear on the flash memory, but I'm not sure, since all * 14 sectors get written anyway. + * + * See SECTOR_ID_* constants in save.h */ -// (u8 *)structure was removed from the first statement of the macro in Emerald. -// This is because malloc is used to allocate addresses so storing the raw -// addresses should not be done in the offsets information. #define SAVEBLOCK_CHUNK(structure, chunkNum) \ { \ chunkNum * SECTOR_DATA_SIZE, \ @@ -50,16 +49,20 @@ static u8 HandleWriteSector(u16 a1, const struct SaveSectionLocation *location); min(sizeof(structure) - chunkNum * SECTOR_DATA_SIZE, SECTOR_DATA_SIZE) : 0 \ } -static const struct SaveSectionOffsets sSaveSectionOffsets[] = +struct { - SAVEBLOCK_CHUNK(gSaveblock2, 0), + u16 offset; + u16 size; +} static const sSaveSlotLayout[NUM_SECTORS_PER_SLOT] = +{ + SAVEBLOCK_CHUNK(gSaveblock2, 0), // SECTOR_ID_SAVEBLOCK2 - SAVEBLOCK_CHUNK(gSaveblock1, 0), + SAVEBLOCK_CHUNK(gSaveblock1, 0), // SECTOR_ID_SAVEBLOCK1_START SAVEBLOCK_CHUNK(gSaveblock1, 1), SAVEBLOCK_CHUNK(gSaveblock1, 2), - SAVEBLOCK_CHUNK(gSaveblock1, 3), + SAVEBLOCK_CHUNK(gSaveblock1, 3), // SECTOR_ID_SAVEBLOCK1_END - SAVEBLOCK_CHUNK(gPokemonStorage, 0), + SAVEBLOCK_CHUNK(gPokemonStorage, 0), // SECTOR_ID_PKMN_STORAGE_START SAVEBLOCK_CHUNK(gPokemonStorage, 1), SAVEBLOCK_CHUNK(gPokemonStorage, 2), SAVEBLOCK_CHUNK(gPokemonStorage, 3), @@ -67,25 +70,24 @@ static const struct SaveSectionOffsets sSaveSectionOffsets[] = SAVEBLOCK_CHUNK(gPokemonStorage, 5), SAVEBLOCK_CHUNK(gPokemonStorage, 6), SAVEBLOCK_CHUNK(gPokemonStorage, 7), - SAVEBLOCK_CHUNK(gPokemonStorage, 8), + SAVEBLOCK_CHUNK(gPokemonStorage, 8), // SECTOR_ID_PKMN_STORAGE_END }; -// iwram common u16 gLastWrittenSector; u32 gLastSaveCounter; u16 gLastKnownGoodSector; u32 gDamagedSaveSectors; u32 gSaveCounter; -struct SaveSection *gFastSaveSection; -u16 gUnknown_03006208; +struct SaveSector *gReadWriteSector; // Pointer to a buffer for reading/writing a sector +u16 gIncrementalSectorId; u16 gSaveUnusedVar; u16 gSaveFileStatus; void (*gGameContinueCallback)(void); -struct SaveSectionLocation gRamSaveSectionLocations[NUM_SECTORS_PER_SLOT]; +struct SaveSectorLocation gRamSaveSectorLocations[NUM_SECTORS_PER_SLOT]; u16 gSaveUnusedVar2; u16 gSaveAttemptStatus; -EWRAM_DATA struct SaveSection gSaveDataBuffer = {0}; +EWRAM_DATA struct SaveSector gSaveDataBuffer = {0}; // Buffer used for reading/writing sectors EWRAM_DATA static u8 sUnusedVar = 0; void ClearSaveData(void) @@ -107,20 +109,20 @@ void Save_ResetSaveCounters(void) gDamagedSaveSectors = 0; } -static bool32 SetDamagedSectorBits(u8 op, u8 bit) +static bool32 SetDamagedSectorBits(u8 op, u8 sectorId) { bool32 retVal = FALSE; switch (op) { case ENABLE: - gDamagedSaveSectors |= (1 << bit); + gDamagedSaveSectors |= (1 << sectorId); break; case DISABLE: - gDamagedSaveSectors &= ~(1 << bit); + gDamagedSaveSectors &= ~(1 << sectorId); break; case CHECK: // unused - if (gDamagedSaveSectors & (1 << bit)) + if (gDamagedSaveSectors & (1 << sectorId)) retVal = TRUE; break; } @@ -128,31 +130,35 @@ static bool32 SetDamagedSectorBits(u8 op, u8 bit) return retVal; } -static u8 SaveWriteToFlash(u16 sectorId, const struct SaveSectionLocation *location) +static u8 WriteSaveSectorOrSlot(u16 sectorId, const struct SaveSectorLocation *locations) { u32 status; u16 i; - gFastSaveSection = &gSaveDataBuffer; + gReadWriteSector = &gSaveDataBuffer; - if (sectorId != 0xFFFF) // for link + if (sectorId != FULL_SAVE_SLOT) { - status = HandleWriteSector(sectorId, location); + // A sector was specified, just write that sector. + // This is never reached, FULL_SAVE_SLOT is always used instead. + status = HandleWriteSector(sectorId, locations); } else { + // No sector was specified, write full save slot. gLastKnownGoodSector = gLastWrittenSector; // backup the current written sector before attempting to write. gLastSaveCounter = gSaveCounter; gLastWrittenSector++; - gLastWrittenSector = gLastWrittenSector % NUM_SECTORS_PER_SLOT; // array count save sector locations + gLastWrittenSector = gLastWrittenSector % NUM_SECTORS_PER_SLOT; gSaveCounter++; status = SAVE_STATUS_OK; for (i = 0; i < NUM_SECTORS_PER_SLOT; i++) - HandleWriteSector(i, location); + HandleWriteSector(i, locations); - if (gDamagedSaveSectors != 0) // skip the damaged sector. + if (gDamagedSaveSectors) { + // At least one sector save failed status = SAVE_STATUS_ERROR; gLastWrittenSector = gLastKnownGoodSector; gSaveCounter = gLastSaveCounter; @@ -162,98 +168,107 @@ static u8 SaveWriteToFlash(u16 sectorId, const struct SaveSectionLocation *locat return status; } -static u8 HandleWriteSector(u16 sectorId, const struct SaveSectionLocation *location) +static u8 HandleWriteSector(u16 sectorId, const struct SaveSectorLocation *locations) { u16 i; u16 sector; u8 *data; u16 size; + // Adjust sector id for current save slot sector = sectorId + gLastWrittenSector; sector %= NUM_SECTORS_PER_SLOT; sector += NUM_SECTORS_PER_SLOT * (gSaveCounter % NUM_SAVE_SLOTS); - data = location[sectorId].data; - size = location[sectorId].size; + // Get current save data + data = locations[sectorId].data; + size = locations[sectorId].size; - // clear save section. - for (i = 0; i < sizeof(struct SaveSection); i++) - ((char *)gFastSaveSection)[i] = 0; + // Clear temp save sector + for (i = 0; i < SECTOR_SIZE; i++) + ((u8 *)gReadWriteSector)[i] = 0; - gFastSaveSection->id = sectorId; - gFastSaveSection->security = UNKNOWN_CHECK_VALUE; - gFastSaveSection->counter = gSaveCounter; + // Set footer data + gReadWriteSector->id = sectorId; + gReadWriteSector->security = SECTOR_SECURITY_NUM; + gReadWriteSector->counter = gSaveCounter; + // Copy current data to temp buffer for writing for (i = 0; i < size; i++) - gFastSaveSection->data[i] = data[i]; + gReadWriteSector->data[i] = data[i]; - gFastSaveSection->checksum = CalculateChecksum(data, size); - return TryWriteSector(sector, gFastSaveSection->data); + gReadWriteSector->checksum = CalculateChecksum(data, size); + + return TryWriteSector(sector, gReadWriteSector->data); } -static u8 HandleWriteSectorNBytes(u8 sector, u8 *data, u16 size) +static u8 HandleWriteSectorNBytes(u8 sectorId, u8 *data, u16 size) { u16 i; - struct SaveSection *section = &gSaveDataBuffer; + struct SaveSector *sector = &gSaveDataBuffer; - for (i = 0; i < sizeof(struct SaveSection); i++) - ((char *)section)[i] = 0; + // Clear temp save sector + for (i = 0; i < SECTOR_SIZE; i++) + ((u8 *)sector)[i] = 0; - section->security = UNKNOWN_CHECK_VALUE; + sector->security = SECTOR_SECURITY_NUM; + // Copy data to temp buffer for writing for (i = 0; i < size; i++) - section->data[i] = data[i]; + sector->data[i] = data[i]; - section->id = CalculateChecksum(data, size); // though this appears to be incorrect, it might be some sector checksum instead of a whole save checksum and only appears to be relevent to HOF data, if used. - return TryWriteSector(sector, section->data); + sector->id = CalculateChecksum(data, size); // though this appears to be incorrect, it might be some sector checksum instead of a whole save checksum and only appears to be relevent to HOF data, if used. + return TryWriteSector(sectorId, sector->data); } static u8 TryWriteSector(u8 sector, u8 *data) { - if (ProgramFlashSectorAndVerify(sector, data) != 0) // is damaged? + if (ProgramFlashSectorAndVerify(sector, data)) // is damaged? { - SetDamagedSectorBits(ENABLE, sector); // set damaged sector bits. + // Failed + SetDamagedSectorBits(ENABLE, sector); return SAVE_STATUS_ERROR; } else { - SetDamagedSectorBits(DISABLE, sector); // unset damaged sector bits. it's safe now. + // Succeeded + SetDamagedSectorBits(DISABLE, sector); return SAVE_STATUS_OK; } } -static u32 RestoreSaveBackupVarsAndIncrement(const struct SaveSectionLocation *location) // location is unused +static u32 RestoreSaveBackupVarsAndIncrement(const struct SaveSectorLocation *locations) { - gFastSaveSection = &gSaveDataBuffer; + gReadWriteSector = &gSaveDataBuffer; gLastKnownGoodSector = gLastWrittenSector; gLastSaveCounter = gSaveCounter; gLastWrittenSector++; gLastWrittenSector %= NUM_SECTORS_PER_SLOT; gSaveCounter++; - gUnknown_03006208 = 0; + gIncrementalSectorId = 0; gDamagedSaveSectors = 0; return 0; } -static u32 RestoreSaveBackupVars(const struct SaveSectionLocation *location) // only ever called once, and gSaveBlock2 is passed to this function. location is unused +static u32 RestoreSaveBackupVars(const struct SaveSectorLocation *locations) { - gFastSaveSection = &gSaveDataBuffer; + gReadWriteSector = &gSaveDataBuffer; gLastKnownGoodSector = gLastWrittenSector; gLastSaveCounter = gSaveCounter; - gUnknown_03006208 = 0; + gIncrementalSectorId = 0; gDamagedSaveSectors = 0; return 0; } -static u8 sub_81529D4(u16 sectorId, const struct SaveSectionLocation *location) +static u8 HandleWriteIncrementalSector(u16 numSectors, const struct SaveSectorLocation *locations) { u8 status; - if (gUnknown_03006208 < sectorId - 1) + if (gIncrementalSectorId < numSectors - 1) { status = SAVE_STATUS_OK; - HandleWriteSector(gUnknown_03006208, location); - gUnknown_03006208++; + HandleWriteSector(gIncrementalSectorId, locations); + gIncrementalSectorId++; if (gDamagedSaveSectors) { status = SAVE_STATUS_ERROR; @@ -269,11 +284,11 @@ static u8 sub_81529D4(u16 sectorId, const struct SaveSectionLocation *location) return status; } -static u8 sub_8152A34(u16 sectorId, const struct SaveSectionLocation *location) +static u8 HandleReplaceSectorAndVerify(u16 sectorId, const struct SaveSectorLocation *locations) { u8 status = SAVE_STATUS_OK; - ClearSaveData_2(sectorId - 1, location); + HandleReplaceSector(sectorId - 1, locations); if (gDamagedSaveSectors) { @@ -284,7 +299,8 @@ static u8 sub_8152A34(u16 sectorId, const struct SaveSectionLocation *location) return status; } -static u8 ClearSaveData_2(u16 sectorId, const struct SaveSectionLocation *location) +// Similar to HandleWriteSector, but fully erases the sector first, and skips writing the first security byte +static u8 HandleReplaceSector(u16 sectorId, const struct SaveSectorLocation *locations) { u16 i; u16 sector; @@ -292,35 +308,39 @@ static u8 ClearSaveData_2(u16 sectorId, const struct SaveSectionLocation *locati u16 size; u8 status; + // Adjust sector id for current save slot sector = sectorId + gLastWrittenSector; sector %= NUM_SECTORS_PER_SLOT; sector += NUM_SECTORS_PER_SLOT * (gSaveCounter % NUM_SAVE_SLOTS); - data = location[sectorId].data; - size = location[sectorId].size; + // Get current save data + data = locations[sectorId].data; + size = locations[sectorId].size; - // clear temp save section. - for (i = 0; i < sizeof(struct SaveSection); i++) - ((char *)gFastSaveSection)[i] = 0; + // Clear temp save sector. + for (i = 0; i < SECTOR_SIZE; i++) + ((u8 *)gReadWriteSector)[i] = 0; - gFastSaveSection->id = sectorId; - gFastSaveSection->security = UNKNOWN_CHECK_VALUE; - gFastSaveSection->counter = gSaveCounter; + // Set footer data + gReadWriteSector->id = sectorId; + gReadWriteSector->security = SECTOR_SECURITY_NUM; + gReadWriteSector->counter = gSaveCounter; - // set temp section's data. + // Copy current data to temp buffer for writing for (i = 0; i < size; i++) - gFastSaveSection->data[i] = data[i]; + gReadWriteSector->data[i] = data[i]; - // calculate checksum. - gFastSaveSection->checksum = CalculateChecksum(data, size); + gReadWriteSector->checksum = CalculateChecksum(data, size); + // Erase old save data EraseFlashSector(sector); status = SAVE_STATUS_OK; - for (i = 0; i < sizeof(struct UnkSaveSection); i++) + // Write new save data up to security field + for (i = 0; i < SECTOR_SECURITY_OFFSET; i++) { - if (ProgramFlashByte(sector, i, ((u8 *)gFastSaveSection)[i])) + if (ProgramFlashByte(sector, i, ((u8 *)gReadWriteSector)[i])) { status = SAVE_STATUS_ERROR; break; @@ -329,16 +349,20 @@ static u8 ClearSaveData_2(u16 sectorId, const struct SaveSectionLocation *locati if (status == SAVE_STATUS_ERROR) { + // Writing save data failed SetDamagedSectorBits(ENABLE, sector); return SAVE_STATUS_ERROR; } else { + // Writing save data succeeded, write security and counter status = SAVE_STATUS_OK; - for (i = 0; i < 7; i++) + // Write security (skipping the first byte) and counter fields. + // The byte of security that is skipped is instead written by WriteSectorSecurityByte or WriteSectorSecurityByte_NoOffset + for (i = 0; i < SECTOR_SIZE - (SECTOR_SECURITY_OFFSET + 1); i++) { - if (ProgramFlashByte(sector, 0xFF9 + i, ((u8 *)gFastSaveSection)[0xFF9 + i])) + if (ProgramFlashByte(sector, SECTOR_SECURITY_OFFSET + 1 + i, ((u8 *)gReadWriteSector)[SECTOR_SECURITY_OFFSET + 1 + i])) { status = SAVE_STATUS_ERROR; break; @@ -347,28 +371,31 @@ static u8 ClearSaveData_2(u16 sectorId, const struct SaveSectionLocation *locati if (status == SAVE_STATUS_ERROR) { + // Writing security/counter failed SetDamagedSectorBits(ENABLE, sector); return SAVE_STATUS_ERROR; } else { + // Succeeded SetDamagedSectorBits(DISABLE, sector); return SAVE_STATUS_OK; } } } -static u8 sav12_xor_get(u16 sectorId, const struct SaveSectionLocation *location) +static u8 WriteSectorSecurityByte_NoOffset(u16 sectorId, const struct SaveSectorLocation *locations) { - u16 sector; - - sector = sectorId + gLastWrittenSector; // no sub 1? + // Adjust sector id for current save slot + // This first line lacking -1 is the only difference from WriteSectorSecurityByte + u16 sector = sectorId + gLastWrittenSector; sector %= NUM_SECTORS_PER_SLOT; sector += NUM_SECTORS_PER_SLOT * (gSaveCounter % NUM_SAVE_SLOTS); - if (ProgramFlashByte(sector, sizeof(struct UnkSaveSection), 0x25)) + // Write just the first byte of the security field, which was skipped by HandleReplaceSector + if (ProgramFlashByte(sector, SECTOR_SECURITY_OFFSET, SECTOR_SECURITY_NUM & 0xFF)) { - // sector is damaged, so enable the bit in gDamagedSaveSectors and restore the last written sector and save counter. + // Sector is damaged, so enable the bit in gDamagedSaveSectors and restore the last written sector and save counter. SetDamagedSectorBits(ENABLE, sector); gLastWrittenSector = gLastKnownGoodSector; gSaveCounter = gLastSaveCounter; @@ -376,22 +403,23 @@ static u8 sav12_xor_get(u16 sectorId, const struct SaveSectionLocation *location } else { + // Succeeded SetDamagedSectorBits(DISABLE, sector); return SAVE_STATUS_OK; } } -static u8 sub_8152CAC(u16 sectorId, const struct SaveSectionLocation *location) +static u8 CopySectorSecurityByte(u16 sectorId, const struct SaveSectorLocation *locations) { - u16 sector; - - sector = sectorId + gLastWrittenSector - 1; + // Adjust sector id for current save slot + u16 sector = sectorId + gLastWrittenSector - 1; sector %= NUM_SECTORS_PER_SLOT; sector += NUM_SECTORS_PER_SLOT * (gSaveCounter % NUM_SAVE_SLOTS); - if (ProgramFlashByte(sector, sizeof(struct UnkSaveSection), ((u8 *)gFastSaveSection)[sizeof(struct UnkSaveSection)])) + // Copy just the first byte of the security field from the read/write buffer + if (ProgramFlashByte(sector, SECTOR_SECURITY_OFFSET, ((u8 *)gReadWriteSector)[SECTOR_SECURITY_OFFSET])) { - // sector is damaged, so enable the bit in gDamagedSaveSectors and restore the last written sector and save counter. + // Sector is damaged, so enable the bit in gDamagedSaveSectors and restore the last written sector and save counter. SetDamagedSectorBits(ENABLE, sector); gLastWrittenSector = gLastKnownGoodSector; gSaveCounter = gLastSaveCounter; @@ -399,22 +427,23 @@ static u8 sub_8152CAC(u16 sectorId, const struct SaveSectionLocation *location) } else { + // Succeded SetDamagedSectorBits(DISABLE, sector); return SAVE_STATUS_OK; } } -static u8 sub_8152D44(u16 sectorId, const struct SaveSectionLocation *location) +static u8 WriteSectorSecurityByte(u16 sectorId, const struct SaveSectorLocation *locations) { - u16 sector; - - sector = sectorId + gLastWrittenSector - 1; // no sub 1? + // Adjust sector id for current save slot + u16 sector = sectorId + gLastWrittenSector - 1; sector %= NUM_SECTORS_PER_SLOT; sector += NUM_SECTORS_PER_SLOT * (gSaveCounter % NUM_SAVE_SLOTS); - if (ProgramFlashByte(sector, sizeof(struct UnkSaveSection), 0x25)) + // Write just the first byte of the security field, which was skipped by HandleReplaceSector + if (ProgramFlashByte(sector, SECTOR_SECURITY_OFFSET, SECTOR_SECURITY_NUM & 0xFF)) { - // sector is damaged, so enable the bit in gDamagedSaveSectors and restore the last written sector and save counter. + // Sector is damaged, so enable the bit in gDamagedSaveSectors and restore the last written sector and save counter. SetDamagedSectorBits(ENABLE, sector); gLastWrittenSector = gLastKnownGoodSector; gSaveCounter = gLastSaveCounter; @@ -422,29 +451,32 @@ static u8 sub_8152D44(u16 sectorId, const struct SaveSectionLocation *location) } else { + // Succeeded SetDamagedSectorBits(DISABLE, sector); return SAVE_STATUS_OK; } } -static u8 sub_8152DD0(u16 a1, const struct SaveSectionLocation *location) +static u8 TryLoadSaveSlot(u16 sectorId, struct SaveSectorLocation *locations) { u8 status; - gFastSaveSection = &gSaveDataBuffer; - if (a1 != 0xFFFF) + gReadWriteSector = &gSaveDataBuffer; + if (sectorId != FULL_SAVE_SLOT) { + // This function may not be used with a specific sector id status = SAVE_STATUS_ERROR; } else { - status = GetSaveValidStatus(location); - sub_8152E10(0xFFFF, location); + status = GetSaveValidStatus(locations); + CopySaveSlotData(FULL_SAVE_SLOT, locations); } return status; } -static u8 sub_8152E10(u16 a1, const struct SaveSectionLocation *location) +// sectorId arg is ignored, this always reads the full save slot +static u8 CopySaveSlotData(u16 sectorId, struct SaveSectorLocation *locations) { u16 i; u16 checksum; @@ -453,96 +485,102 @@ static u8 sub_8152E10(u16 a1, const struct SaveSectionLocation *location) for (i = 0; i < NUM_SECTORS_PER_SLOT; i++) { - DoReadFlashWholeSection(i + slotOffset, gFastSaveSection); - id = gFastSaveSection->id; + ReadFlashSector(i + slotOffset, gReadWriteSector); + + id = gReadWriteSector->id; if (id == 0) gLastWrittenSector = i; - checksum = CalculateChecksum(gFastSaveSection->data, location[id].size); - if (gFastSaveSection->security == UNKNOWN_CHECK_VALUE - && gFastSaveSection->checksum == checksum) + + checksum = CalculateChecksum(gReadWriteSector->data, locations[id].size); + + // Only copy data for sectors whose security and checksum fields are correct + if (gReadWriteSector->security == SECTOR_SECURITY_NUM && gReadWriteSector->checksum == checksum) { u16 j; - for (j = 0; j < location[id].size; j++) - ((u8 *)location[id].data)[j] = gFastSaveSection->data[j]; + for (j = 0; j < locations[id].size; j++) + ((u8 *)locations[id].data)[j] = gReadWriteSector->data[j]; } } return SAVE_STATUS_OK; } -static u8 GetSaveValidStatus(const struct SaveSectionLocation *location) +static u8 GetSaveValidStatus(const struct SaveSectorLocation *locations) { u16 i; u16 checksum; u32 saveSlot1Counter = 0; u32 saveSlot2Counter = 0; - u32 slotCheckField = 0; + u32 validSectorFlags = 0; bool8 securityPassed = FALSE; u8 saveSlot1Status; u8 saveSlot2Status; - // check save slot 1. + // Check save slot 1 for (i = 0; i < NUM_SECTORS_PER_SLOT; i++) { - DoReadFlashWholeSection(i, gFastSaveSection); - if (gFastSaveSection->security == UNKNOWN_CHECK_VALUE) + ReadFlashSector(i, gReadWriteSector); + if (gReadWriteSector->security == SECTOR_SECURITY_NUM) { securityPassed = TRUE; - checksum = CalculateChecksum(gFastSaveSection->data, location[gFastSaveSection->id].size); - if (gFastSaveSection->checksum == checksum) + checksum = CalculateChecksum(gReadWriteSector->data, locations[gReadWriteSector->id].size); + if (gReadWriteSector->checksum == checksum) { - saveSlot1Counter = gFastSaveSection->counter; - slotCheckField |= 1 << gFastSaveSection->id; + saveSlot1Counter = gReadWriteSector->counter; + validSectorFlags |= 1 << gReadWriteSector->id; } } } if (securityPassed) { - if (slotCheckField == 0x3FFF) + if (validSectorFlags == (1 << NUM_SECTORS_PER_SLOT) - 1) saveSlot1Status = SAVE_STATUS_OK; else saveSlot1Status = SAVE_STATUS_ERROR; } else { + // No sectors in slot 1 have the security number, treat it as empty saveSlot1Status = SAVE_STATUS_EMPTY; } - slotCheckField = 0; + validSectorFlags = 0; securityPassed = FALSE; - // check save slot 2. + // Check save slot 2 for (i = 0; i < NUM_SECTORS_PER_SLOT; i++) { - DoReadFlashWholeSection(i + NUM_SECTORS_PER_SLOT, gFastSaveSection); - if (gFastSaveSection->security == UNKNOWN_CHECK_VALUE) + ReadFlashSector(i + NUM_SECTORS_PER_SLOT, gReadWriteSector); + if (gReadWriteSector->security == SECTOR_SECURITY_NUM) { securityPassed = TRUE; - checksum = CalculateChecksum(gFastSaveSection->data, location[gFastSaveSection->id].size); - if (gFastSaveSection->checksum == checksum) + checksum = CalculateChecksum(gReadWriteSector->data, locations[gReadWriteSector->id].size); + if (gReadWriteSector->checksum == checksum) { - saveSlot2Counter = gFastSaveSection->counter; - slotCheckField |= 1 << gFastSaveSection->id; + saveSlot2Counter = gReadWriteSector->counter; + validSectorFlags |= 1 << gReadWriteSector->id; } } } if (securityPassed) { - if (slotCheckField == 0x3FFF) + if (validSectorFlags == (1 << NUM_SECTORS_PER_SLOT) - 1) saveSlot2Status = SAVE_STATUS_OK; else saveSlot2Status = SAVE_STATUS_ERROR; } else { + // No sectors in slot 2 have the security number, treat it as empty. saveSlot2Status = SAVE_STATUS_EMPTY; } if (saveSlot1Status == SAVE_STATUS_OK && saveSlot2Status == SAVE_STATUS_OK) { - if ((saveSlot1Counter == -1 && saveSlot2Counter == 0) || (saveSlot1Counter == 0 && saveSlot2Counter == -1)) + if ((saveSlot1Counter == -1 && saveSlot2Counter == 0) + || (saveSlot1Counter == 0 && saveSlot2Counter == -1)) { if ((unsigned)(saveSlot1Counter + 1) < (unsigned)(saveSlot2Counter + 1)) gSaveCounter = saveSlot2Counter; @@ -559,63 +597,71 @@ static u8 GetSaveValidStatus(const struct SaveSectionLocation *location) return SAVE_STATUS_OK; } + // One or both save slots are not OK + if (saveSlot1Status == SAVE_STATUS_OK) { gSaveCounter = saveSlot1Counter; if (saveSlot2Status == SAVE_STATUS_ERROR) - return SAVE_STATUS_ERROR; - return SAVE_STATUS_OK; + return SAVE_STATUS_ERROR; // Slot 2 errored + return SAVE_STATUS_OK; // Slot 1 is OK, slot 2 is empty } if (saveSlot2Status == SAVE_STATUS_OK) { gSaveCounter = saveSlot2Counter; if (saveSlot1Status == SAVE_STATUS_ERROR) - return SAVE_STATUS_ERROR; - return SAVE_STATUS_OK; + return SAVE_STATUS_ERROR; // Slot 1 errored + return SAVE_STATUS_OK; // Slot 2 is OK, slot 1 is empty } - if (saveSlot1Status == SAVE_STATUS_EMPTY && saveSlot2Status == SAVE_STATUS_EMPTY) + // Neither slot is OK, check if both are empty + if (saveSlot1Status == SAVE_STATUS_EMPTY + && saveSlot2Status == SAVE_STATUS_EMPTY) { gSaveCounter = 0; gLastWrittenSector = 0; return SAVE_STATUS_EMPTY; } + // Both slots errored gSaveCounter = 0; gLastWrittenSector = 0; return SAVE_STATUS_CORRUPT; } -static u8 sub_81530DC(u8 sectorId, u8 *data, u16 size) +static u8 TryLoadSaveSector(u8 sectorId, u8 *data, u16 size) { u16 i; - struct SaveSection *section = &gSaveDataBuffer; - DoReadFlashWholeSection(sectorId, section); - if (section->security == UNKNOWN_CHECK_VALUE) + struct SaveSector *sector = &gSaveDataBuffer; + ReadFlashSector(sectorId, sector); + if (sector->security == SECTOR_SECURITY_NUM) { - u16 checksum = CalculateChecksum(section->data, size); - if (section->id == checksum) + u16 checksum = CalculateChecksum(sector->data, size); + if (sector->id == checksum) { + // Security and checksum are correct, copy data for (i = 0; i < size; i++) - data[i] = section->data[i]; + data[i] = sector->data[i]; return SAVE_STATUS_OK; } else { + // Incorrect checksum return SAVE_STATUS_CORRUPT; } } else { + // Incorrect security value return SAVE_STATUS_EMPTY; } } // Return value always ignored -static bool8 DoReadFlashWholeSection(u8 sector, struct SaveSection *section) +static bool8 ReadFlashSector(u8 sectorId, struct SaveSector *sector) { - ReadFlash(sector, 0, section->data, sizeof(struct SaveSection)); + ReadFlash(sectorId, 0, sector->data, SECTOR_SIZE); return TRUE; } @@ -635,21 +681,20 @@ static u16 CalculateChecksum(void *data, u16 size) static void UpdateSaveAddresses(void) { - int i = 0; - - gRamSaveSectionLocations[i].data = (void*)(gSaveBlock2Ptr) + sSaveSectionOffsets[i].toAdd; - gRamSaveSectionLocations[i].size = sSaveSectionOffsets[i].size; + int i = SECTOR_ID_SAVEBLOCK2; + gRamSaveSectorLocations[i].data = (void*)(gSaveBlock2Ptr) + sSaveSlotLayout[i].offset; + gRamSaveSectorLocations[i].size = sSaveSlotLayout[i].size; for (i = SECTOR_ID_SAVEBLOCK1_START; i <= SECTOR_ID_SAVEBLOCK1_END; i++) { - gRamSaveSectionLocations[i].data = (void*)(gSaveBlock1Ptr) + sSaveSectionOffsets[i].toAdd; - gRamSaveSectionLocations[i].size = sSaveSectionOffsets[i].size; + gRamSaveSectorLocations[i].data = (void*)(gSaveBlock1Ptr) + sSaveSlotLayout[i].offset; + gRamSaveSectorLocations[i].size = sSaveSlotLayout[i].size; } for (; i <= SECTOR_ID_PKMN_STORAGE_END; i++) //setting i to SECTOR_ID_PKMN_STORAGE_START does not match { - gRamSaveSectionLocations[i].data = (void*)(gPokemonStoragePtr) + sSaveSectionOffsets[i].toAdd; - gRamSaveSectionLocations[i].size = sSaveSectionOffsets[i].size; + gRamSaveSectorLocations[i].data = (void*)(gPokemonStoragePtr) + sSaveSlotLayout[i].offset; + gRamSaveSectorLocations[i].size = sSaveSlotLayout[i].size; } } @@ -663,43 +708,48 @@ u8 HandleSavingData(u8 saveType) UpdateSaveAddresses(); switch (saveType) { - case SAVE_HALL_OF_FAME_ERASE_BEFORE: // deletes HOF before overwriting HOF completely. unused + case SAVE_HALL_OF_FAME_ERASE_BEFORE: + // Unused. Erases the special save sectors (HOF, Trainer Hill, Recorded Battle) + // before overwriting HOF. for (i = SECTOR_ID_HOF_1; i < SECTORS_COUNT; i++) EraseFlashSector(i); - case SAVE_HALL_OF_FAME: // hall of fame. + // fallthrough + case SAVE_HALL_OF_FAME: if (GetGameStat(GAME_STAT_ENTERED_HOF) < 999) IncrementGameStat(GAME_STAT_ENTERED_HOF); - SaveSerializedGame(); - SaveWriteToFlash(0xFFFF, gRamSaveSectionLocations); + + // Write the full save slot first + CopyPartyAndObjectsToSave(); + WriteSaveSectorOrSlot(FULL_SAVE_SLOT, gRamSaveSectorLocations); + + // Save the Hall of Fame tempAddr = gDecompressionBuffer; HandleWriteSectorNBytes(SECTOR_ID_HOF_1, tempAddr, SECTOR_DATA_SIZE); HandleWriteSectorNBytes(SECTOR_ID_HOF_2, tempAddr + SECTOR_DATA_SIZE, SECTOR_DATA_SIZE); break; - case SAVE_NORMAL: // normal save. also called by overwriting your own save. + case SAVE_NORMAL: default: - SaveSerializedGame(); - SaveWriteToFlash(0xFFFF, gRamSaveSectionLocations); + CopyPartyAndObjectsToSave(); + WriteSaveSectorOrSlot(FULL_SAVE_SLOT, gRamSaveSectorLocations); break; - case SAVE_LINK: // Link and Battle Frontier - case SAVE_LINK2: // Unused - SaveSerializedGame(); + case SAVE_LINK: + case SAVE_LINK2: + // Used by link / Battle Frontier + // Write only SaveBlocks 1 and 2 (skips the PC) + CopyPartyAndObjectsToSave(); for(i = SECTOR_ID_SAVEBLOCK2; i <= SECTOR_ID_SAVEBLOCK1_END; i++) - ClearSaveData_2(i, gRamSaveSectionLocations); + HandleReplaceSector(i, gRamSaveSectorLocations); for(i = SECTOR_ID_SAVEBLOCK2; i <= SECTOR_ID_SAVEBLOCK1_END; i++) - sav12_xor_get(i, gRamSaveSectionLocations); + WriteSectorSecurityByte_NoOffset(i, gRamSaveSectorLocations); break; - // Support for Ereader was removed in Emerald. - /* - case EREADER_SAVE: // used in mossdeep "game corner" before/after battling old man e-reader trainer - SaveSerializedGame(); - SaveWriteToFlash(0, gRamSaveSectionLocations); - break; - */ case SAVE_OVERWRITE_DIFFERENT_FILE: + // Erase Hall of Fame for (i = SECTOR_ID_HOF_1; i < SECTORS_COUNT; i++) - EraseFlashSector(i); // erase HOF. - SaveSerializedGame(); - SaveWriteToFlash(0xFFFF, gRamSaveSectionLocations); + EraseFlashSector(i); + + // Overwrite save slot + CopyPartyAndObjectsToSave(); + WriteSaveSectorOrSlot(FULL_SAVE_SLOT, gRamSaveSectorLocations); break; } gTrainerHillVBlankCounter = backupVar; @@ -728,19 +778,19 @@ u8 TrySavingData(u8 saveType) } } -bool8 sub_8153380(void) // trade.c +bool8 LinkFullSave_Init(void) { if (gFlashMemoryPresent != TRUE) return TRUE; UpdateSaveAddresses(); - SaveSerializedGame(); - RestoreSaveBackupVarsAndIncrement(gRamSaveSectionLocations); + CopyPartyAndObjectsToSave(); + RestoreSaveBackupVarsAndIncrement(gRamSaveSectorLocations); return FALSE; } -bool8 sub_81533AC(void) // trade.c +bool8 LinkFullSave_WriteSector(void) { - u8 status = sub_81529D4(NUM_SECTORS_PER_SLOT, gRamSaveSectionLocations); + u8 status = HandleWriteIncrementalSector(NUM_SECTORS_PER_SLOT, gRamSaveSectorLocations); if (gDamagedSaveSectors) DoSaveFailedScreen(SAVE_NORMAL); if (status == SAVE_STATUS_ERROR) @@ -749,54 +799,66 @@ bool8 sub_81533AC(void) // trade.c return FALSE; } -bool8 sub_81533E0(void) // trade.c +bool8 LinkFullSave_ReplaceLastSector(void) { - sub_8152A34(NUM_SECTORS_PER_SLOT, gRamSaveSectionLocations); + HandleReplaceSectorAndVerify(NUM_SECTORS_PER_SLOT, gRamSaveSectorLocations); if (gDamagedSaveSectors) DoSaveFailedScreen(SAVE_NORMAL); return FALSE; } -bool8 sub_8153408(void) // trade.c +bool8 LinkFullSave_SetLastSectorSecurity(void) { - sub_8152CAC(NUM_SECTORS_PER_SLOT, gRamSaveSectionLocations); + CopySectorSecurityByte(NUM_SECTORS_PER_SLOT, gRamSaveSectorLocations); if (gDamagedSaveSectors) DoSaveFailedScreen(SAVE_NORMAL); return FALSE; } -u8 FullSaveGame(void) +u8 WriteSaveBlock2(void) { if (gFlashMemoryPresent != TRUE) return TRUE; UpdateSaveAddresses(); - SaveSerializedGame(); - RestoreSaveBackupVars(gRamSaveSectionLocations); - sub_8152A34(gUnknown_03006208 + 1, gRamSaveSectionLocations); + CopyPartyAndObjectsToSave(); + RestoreSaveBackupVars(gRamSaveSectorLocations); + + // Because RestoreSaveBackupVars is called immediately prior, gIncrementalSectorId will always be 0 below, + // so this function only saves the first sector (SECTOR_ID_SAVEBLOCK2) + HandleReplaceSectorAndVerify(gIncrementalSectorId + 1, gRamSaveSectorLocations); return FALSE; } -bool8 CheckSaveFile(void) +// Used in conjunction with WriteSaveBlock2 to write both for certain link saves. +// This will be called repeatedly in a task, writing each sector of SaveBlock1 incrementally. +// It returns TRUE when finished. +bool8 WriteSaveBlock1Sector(void) { - u8 retVal = FALSE; - u16 sectorId = ++gUnknown_03006208; + u8 finished = FALSE; + u16 sectorId = ++gIncrementalSectorId; // Because WriteSaveBlock2 will have been called prior, this will be SECTOR_ID_SAVEBLOCK1_START if (sectorId <= SECTOR_ID_SAVEBLOCK1_END) { - sub_8152A34(gUnknown_03006208 + 1, gRamSaveSectionLocations); - sub_8152D44(sectorId, gRamSaveSectionLocations); + // Write a single sector of SaveBlock1 + HandleReplaceSectorAndVerify(gIncrementalSectorId + 1, gRamSaveSectorLocations); + WriteSectorSecurityByte(sectorId, gRamSaveSectorLocations); } else { - sub_8152D44(sectorId, gRamSaveSectionLocations); - retVal = TRUE; + // Beyond SaveBlock1, don't write the sector. + // Does write 1 byte of the next sector's security field, but as these + // are the same for all valid sectors it doesn't matter. + WriteSectorSecurityByte(sectorId, gRamSaveSectorLocations); + finished = TRUE; } + if (gDamagedSaveSectors) DoSaveFailedScreen(SAVE_LINK); - return retVal; + + return finished; } -u8 Save_LoadGameData(u8 saveType) +u8 LoadGameSave(u8 saveType) { u8 status; @@ -811,15 +873,15 @@ u8 Save_LoadGameData(u8 saveType) { case SAVE_NORMAL: default: - status = sub_8152DD0(0xFFFF, gRamSaveSectionLocations); - LoadSerializedGame(); + status = TryLoadSaveSlot(FULL_SAVE_SLOT, gRamSaveSectorLocations); + CopyPartyAndObjectsFromSave(); gSaveFileStatus = status; gGameContinueCallback = 0; break; case SAVE_HALL_OF_FAME: - status = sub_81530DC(SECTOR_ID_HOF_1, gDecompressionBuffer, SECTOR_DATA_SIZE); + status = TryLoadSaveSector(SECTOR_ID_HOF_1, gDecompressionBuffer, SECTOR_DATA_SIZE); if (status == SAVE_STATUS_OK) - status = sub_81530DC(SECTOR_ID_HOF_2, gDecompressionBuffer + SECTOR_DATA_SIZE, SECTOR_DATA_SIZE); + status = TryLoadSaveSector(SECTOR_ID_HOF_2, &gDecompressionBuffer[SECTOR_DATA_SIZE], SECTOR_DATA_SIZE); break; } @@ -829,29 +891,29 @@ u8 Save_LoadGameData(u8 saveType) u16 GetSaveBlocksPointersBaseOffset(void) { u16 i, slotOffset; - struct SaveSection* savSection; + struct SaveSector* sector; - savSection = gFastSaveSection = &gSaveDataBuffer; + sector = gReadWriteSector = &gSaveDataBuffer; if (gFlashMemoryPresent != TRUE) return 0; UpdateSaveAddresses(); - GetSaveValidStatus(gRamSaveSectionLocations); + GetSaveValidStatus(gRamSaveSectorLocations); slotOffset = NUM_SECTORS_PER_SLOT * (gSaveCounter % NUM_SAVE_SLOTS); for (i = 0; i < NUM_SECTORS_PER_SLOT; i++) { - DoReadFlashWholeSection(i + slotOffset, gFastSaveSection); + ReadFlashSector(i + slotOffset, gReadWriteSector); // Base offset for SaveBlock2 is calculated using the trainer id - if (gFastSaveSection->id == SECTOR_ID_SAVEBLOCK2) - return savSection->data[offsetof(struct SaveBlock2, playerTrainerId[0])] + - savSection->data[offsetof(struct SaveBlock2, playerTrainerId[1])] + - savSection->data[offsetof(struct SaveBlock2, playerTrainerId[2])] + - savSection->data[offsetof(struct SaveBlock2, playerTrainerId[3])]; + if (gReadWriteSector->id == SECTOR_ID_SAVEBLOCK2) + return sector->data[offsetof(struct SaveBlock2, playerTrainerId[0])] + + sector->data[offsetof(struct SaveBlock2, playerTrainerId[1])] + + sector->data[offsetof(struct SaveBlock2, playerTrainerId[2])] + + sector->data[offsetof(struct SaveBlock2, playerTrainerId[3])]; } return 0; } -u32 TryReadSpecialSaveSection(u8 sector, u8* dst) +u32 TryReadSpecialSaveSector(u8 sector, u8* dst) { s32 i; s32 size; @@ -859,19 +921,21 @@ u32 TryReadSpecialSaveSection(u8 sector, u8* dst) if (sector != SECTOR_ID_TRAINER_HILL && sector != SECTOR_ID_RECORDED_BATTLE) return SAVE_STATUS_ERROR; - ReadFlash(sector, 0, (u8 *)&gSaveDataBuffer, sizeof(struct SaveSection)); - if (*(u32*)(&gSaveDataBuffer.data[0]) != SPECIAL_SECTION_SENTINEL) + + ReadFlash(sector, 0, (u8 *)&gSaveDataBuffer, SECTOR_SIZE); + if (*(u32*)(&gSaveDataBuffer.data[0]) != SPECIAL_SECTOR_SENTINEL) return SAVE_STATUS_ERROR; - // copies whole save section except u32 counter + + // Copies whole save sector except u32 counter i = 0; - size = 0xFFB; - savData = &gSaveDataBuffer.data[4]; + size = SECTOR_COUNTER_OFFSET - 1; + savData = &gSaveDataBuffer.data[4]; // data[4] to skip past SPECIAL_SECTOR_SENTINEL for (; i <= size; i++) dst[i] = savData[i]; return SAVE_STATUS_OK; } -u32 TryWriteSpecialSaveSection(u8 sector, u8* src) +u32 TryWriteSpecialSaveSector(u8 sector, u8* src) { s32 i; s32 size; @@ -882,12 +946,12 @@ u32 TryWriteSpecialSaveSection(u8 sector, u8* src) return SAVE_STATUS_ERROR; savDataBuffer = &gSaveDataBuffer; - *(u32*)(savDataBuffer) = SPECIAL_SECTION_SENTINEL; + *(u32*)(savDataBuffer) = SPECIAL_SECTOR_SENTINEL; - // copies whole save section except u32 counter + // Copies whole save sector except u32 counter i = 0; - size = 0xFFB; - savData = &gSaveDataBuffer.data[4]; + size = SECTOR_COUNTER_OFFSET - 1; + savData = &gSaveDataBuffer.data[4]; // data[4] to skip past SPECIAL_SECTOR_SENTINEL for (; i <= size; i++) savData[i] = src[i]; if (ProgramFlashSectorAndVerify(sector, savDataBuffer) != 0) @@ -895,11 +959,13 @@ u32 TryWriteSpecialSaveSection(u8 sector, u8* src) return SAVE_STATUS_OK; } -#define tState data[0] -#define tTimer data[1] -#define tPartialSave data[2] +#define tState data[0] +#define tTimer data[1] +#define tInBattleTower data[2] -void Task_LinkSave(u8 taskId) +// Note that this is very different from TrySavingData(SAVE_LINK). +// Most notably it does save the PC data. +void Task_LinkFullSave(u8 taskId) { s16* data = gTasks[taskId].data; @@ -916,15 +982,15 @@ void Task_LinkSave(u8 taskId) case 2: if (IsLinkTaskFinished()) { - if (!tPartialSave) + if (!tInBattleTower) SaveMapView(); tState = 3; } break; case 3: - if (!tPartialSave) + if (!tInBattleTower) SetContinueGameWarpStatusToDynamicWarp(); - sub_8153380(); + LinkFullSave_Init(); tState = 4; break; case 4: @@ -935,17 +1001,17 @@ void Task_LinkSave(u8 taskId) } break; case 5: - if (sub_81533AC()) + if (LinkFullSave_WriteSector()) tState = 6; else - tState = 4; + tState = 4; // Not finished, delay again break; case 6: - sub_81533E0(); + LinkFullSave_ReplaceLastSector(); tState = 7; break; case 7: - if (!tPartialSave) + if (!tInBattleTower) ClearContinueGameWarpStatus2(); SetLinkStandbyCallback(); tState = 8; @@ -953,7 +1019,7 @@ void Task_LinkSave(u8 taskId) case 8: if (IsLinkTaskFinished()) { - sub_8153408(); + LinkFullSave_SetLastSectorSecurity(); tState = 9; } break; @@ -974,7 +1040,3 @@ void Task_LinkSave(u8 taskId) break; } } - -#undef tState -#undef tTimer -#undef tPartialSave diff --git a/src/save_failed_screen.c b/src/save_failed_screen.c index 4f0373270..ff8c92b33 100644 --- a/src/save_failed_screen.c +++ b/src/save_failed_screen.c @@ -363,9 +363,10 @@ static bool8 VerifySectorWipe(u16 sector) ReadFlash(sector, 0, (u8 *)ptr, SECTOR_SIZE); - for (i = 0; i < 0x400; i++, ptr++) + // 1/4 because ptr is u32 + for (i = 0; i < SECTOR_SIZE / 4; i++, ptr++) if (*ptr) - return TRUE; + return TRUE; // Sector has nonzero data, failed return FALSE; } @@ -375,6 +376,7 @@ static bool8 WipeSector(u16 sector) u16 i, j; bool8 failed = TRUE; + // Attempt to wipe sector with an arbitrary attempt limit of 130 for (i = 0; failed && i < 130; i++) { for (j = 0; j < SECTOR_SIZE; j++) diff --git a/src/start_menu.c b/src/start_menu.c index dcff75ff6..a46d11e98 100644 --- a/src/start_menu.c +++ b/src/start_menu.c @@ -1269,11 +1269,11 @@ static void Task_SaveAfterLinkBattle(u8 taskId) break; case 1: SetContinueGameWarpStatusToDynamicWarp(); - FullSaveGame(); + WriteSaveBlock2(); *state = 2; break; case 2: - if (CheckSaveFile()) + if (WriteSaveBlock1Sector()) { ClearContinueGameWarpStatus2(); *state = 3; @@ -1290,11 +1290,11 @@ static void Task_SaveAfterLinkBattle(u8 taskId) DestroyTask(taskId); break; case 5: - CreateTask(Task_LinkSave, 5); + CreateTask(Task_LinkFullSave, 5); *state = 6; break; case 6: - if (!FuncIsActiveTask(Task_LinkSave)) + if (!FuncIsActiveTask(Task_LinkFullSave)) { *state = 3; } @@ -1374,23 +1374,23 @@ static void RemoveSaveInfoWindow(void) static void Task_WaitForBattleTowerLinkSave(u8 taskId) { - if (!FuncIsActiveTask(Task_LinkSave)) + if (!FuncIsActiveTask(Task_LinkFullSave)) { DestroyTask(taskId); EnableBothScriptContexts(); } } -#define tPartialSave data[2] +#define tInBattleTower data[2] void SaveForBattleTowerLink(void) { - u8 taskId = CreateTask(Task_LinkSave, 5); - gTasks[taskId].tPartialSave = TRUE; + u8 taskId = CreateTask(Task_LinkFullSave, 5); + gTasks[taskId].tInBattleTower = TRUE; gTasks[CreateTask(Task_WaitForBattleTowerLinkSave, 6)].data[1] = taskId; } -#undef tPartialSave +#undef tInBattleTower static void HideStartMenuWindow(void) { diff --git a/src/trade.c b/src/trade.c index 475b82d5e..ba4faed28 100644 --- a/src/trade.c +++ b/src/trade.c @@ -4654,30 +4654,29 @@ static void CB2_SaveAndEndTrade(void) MysteryGift_TryIncrementStat(CARD_STAT_NUM_TRADES, gLinkPlayers[GetMultiplayerId() ^ 1].trainerId); SetContinueGameWarpStatusToDynamicWarp(); - sub_8153380(); + LinkFullSave_Init(); gMain.state++; sTradeData->timer = 0; break; case 51: if (++sTradeData->timer == 5) - { gMain.state++; - } break; case 52: - if (sub_81533AC()) + if (LinkFullSave_WriteSector()) { ClearContinueGameWarpStatus2(); gMain.state = 4; } else { + // Save isn't finished, delay again sTradeData->timer = 0; gMain.state = 51; } break; case 4: - sub_81533E0(); + LinkFullSave_ReplaceLastSector(); gMain.state = 40; sTradeData->timer = 0; break; @@ -4709,7 +4708,7 @@ static void CB2_SaveAndEndTrade(void) case 42: if (_IsLinkTaskFinished()) { - sub_8153408(); + LinkFullSave_SetLastSectorSecurity(); gMain.state = 5; } break; @@ -4965,7 +4964,7 @@ static void CB2_SaveAndEndWirelessTrade(void) StringExpandPlaceholders(gStringVar4, gText_SavingDontTurnOffPower); DrawTextOnTradeWindow(0, gStringVar4, 0); IncrementGameStat(GAME_STAT_POKEMON_TRADES); - sub_8153380(); + LinkFullSave_Init(); sTradeData->timer = 0; } break; @@ -4974,7 +4973,7 @@ static void CB2_SaveAndEndWirelessTrade(void) gMain.state = 4; break; case 4: - if (sub_81533AC()) + if (LinkFullSave_WriteSector()) { gMain.state = 5; } @@ -4985,7 +4984,7 @@ static void CB2_SaveAndEndWirelessTrade(void) } break; case 5: - sub_81533E0(); + LinkFullSave_ReplaceLastSector(); gMain.state = 6; sTradeData->timer = 0; break; @@ -5013,7 +5012,7 @@ static void CB2_SaveAndEndWirelessTrade(void) case 8: if (_IsLinkTaskFinished()) { - sub_8153408(); + LinkFullSave_SetLastSectorSecurity(); gMain.state = 9; } break;