Skip to content

Commit 62b09ad

Browse files
committed
Read by the stored file size when loading the settings file
Reading by the size that's going to be stored can result in trying to read more than the size of the file.
1 parent 2319657 commit 62b09ad

File tree

1 file changed

+34
-6
lines changed

1 file changed

+34
-6
lines changed

ttyd-tools/rel/source/memcard.cpp

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -104,20 +104,48 @@ int32_t loadSettings(char *fileName, gc::card::card_file *fileInfo, uint8_t *wor
104104
return ReturnCode;
105105
}
106106

107+
// Set up the array to hold the area of the file that contains the size
108+
char *tempFileData = new char[0x200];
109+
clearMemory(tempFileData, 0x200);
110+
111+
// Get the data from the area that holds the size
112+
ReturnCode = readFromCard(fileInfo, tempFileData, 0x200, 0x2000, nullptr);
113+
if (ReturnCode != CARD_ERROR_READY)
114+
{
115+
delete[] (tempFileData);
116+
gc::card::CARDClose(fileInfo);
117+
gc::card::CARDUnmount(CARD_SLOTA);
118+
return ReturnCode;
119+
}
120+
107121
// Get the size of the file
108-
uint32_t SettingsStructSize = sizeof(struct SettingsStruct);
109-
uint32_t FileSize = 0x2000 + SettingsStructSize + 0x200;
122+
uint32_t StoredFileSize = *reinterpret_cast<uint32_t *>(&tempFileData[0x40]);
123+
124+
// Delete the data that holds the size, as it's not needed anymore
125+
delete[] (tempFileData);
110126

111127
// Adjust the file size to be in multiples of 0x2000, rounding up
128+
uint32_t StoredFileSizeAdjusted = (StoredFileSize + 0x2000 - 1) & ~(0x2000 - 1);
129+
130+
// Make sure the stored file size is at least 0x2000
131+
if (StoredFileSizeAdjusted < 0x2000)
132+
{
133+
StoredFileSizeAdjusted = 0x2000;
134+
}
135+
136+
// Get the size needed to be read
137+
uint32_t FileSize = sizeof(struct SettingsStruct) + 0x200;
138+
139+
// Adjust the struct size to be in multiples of 0x2000, rounding up
112140
uint32_t FileSizeAdjusted = (FileSize + 0x2000 - 1) & ~(0x2000 - 1);
113141

114142
// Set up the memory to be copied from the file
115-
uint32_t MiscDataSize = FileSizeAdjusted - 0x2000; // Remove the extra 0x2000 from the banner and icon
116-
char *MiscData = new char[MiscDataSize];
117-
clearMemory(MiscData, MiscDataSize);
143+
char *MiscData = new char[FileSizeAdjusted];
144+
clearMemory(MiscData, FileSizeAdjusted);
118145

119146
// Get the data from the file
120-
ReturnCode = readFromCard(fileInfo, MiscData, MiscDataSize, 0x2000, nullptr);
147+
// Must read by the stored size, as the struct size may exceed the size of the file
148+
ReturnCode = readFromCard(fileInfo, MiscData, StoredFileSizeAdjusted, 0x2000, nullptr);
121149

122150
// Close and unmount the card, as it's no longer needed
123151
gc::card::CARDClose(fileInfo);

0 commit comments

Comments
 (0)