From 299cbcfe68193d268fcd8f81954f3103db8bc02d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Tue, 13 Oct 2026 13:50:50 +0200 Subject: [PATCH] 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) --- Common/Serialize/Serializer.h | 5 ++++- libretro/libretro.cpp | 17 ++++++----------- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/Common/Serialize/Serializer.h b/Common/Serialize/Serializer.h index e583391f28..3b519fd461 100644 --- a/Common/Serialize/Serializer.h +++ b/Common/Serialize/Serializer.h @@ -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 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); diff --git a/libretro/libretro.cpp b/libretro/libretro.cpp index dfa6eea672..ae6ef954b1 100644 --- a/libretro/libretro.cpp +++ b/libretro/libretro.cpp @@ -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();