libretro: check the state size inside MeasureAndSavePtr

The size check in retro_serialize measured the state separately before
MeasureAndSavePtr measured it again, a third DoState pass on every save,
which rewind and run-ahead do every frame. MeasureAndSavePtr now takes
the capacity of a caller-provided buffer and fails after its own measure
pass if the state doesn't fit.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Henrik RydgårdandClaude Opus 5.5 committed 2026-10-13 13:50:54 +02:00
1 parent fb61ec51cb
commit 299cbcfe68
2 files changed
+10 -12

No files matched your search

+4 -1
View File
@@ -227,7 +227,8 @@ public:
}
// If *saved is null, will allocate storage using malloc.
// If it's not null, it will be used, but only hope can save you from overruns at the end. For libretro.
// If it's not null, it will be used, and *savedSize is its capacity: a state that doesn't fit fails with
// ERROR_BAD_ALLOC. For libretro.
template<class T>
static Error MeasureAndSavePtr(T &_class, u8 **saved, size_t *savedSize)
{
@@ -239,6 +240,8 @@ public:
size_t measuredSize = p.Offset();
u8 *data;
if (*saved) {
if (measuredSize > *savedSize)
return ERROR_BAD_ALLOC;
data = *saved;
} else {
data = (u8 *)malloc(measuredSize);
+6 -11
View File
@@ -1804,19 +1804,14 @@ bool retro_serialize(void *data, size_t size) {
}
SaveState::SaveStart state;
bool retVal = false;
// The buffer was sized by an earlier retro_serialize_size(); the state
// may have grown since, so never write past 'size'.
size_t measuredSize = CChunkFileReader::MeasurePtr(state);
if (measuredSize <= size) {
u8 *buffer = (u8 *)data;
auto err = CChunkFileReader::MeasureAndSavePtr(state, &buffer, &measuredSize);
retVal = err == CChunkFileReader::ERROR_NONE;
} else {
ERROR_LOG(Log::SaveState, "Savestate (%d bytes) does not fit in frontend buffer (%d bytes)",
(int)measuredSize, (int)size);
}
u8 *buffer = (u8 *)data;
size_t savedSize = size;
auto err = CChunkFileReader::MeasureAndSavePtr(state, &buffer, &savedSize);
if (err == CChunkFileReader::ERROR_BAD_ALLOC)
ERROR_LOG(Log::SaveState, "Savestate does not fit in the frontend's buffer (%d bytes)", (int)size);
bool retVal = err == CChunkFileReader::ERROR_NONE;
if (useEmuThread)
EmuThreadStart();