From 3f6b55ff53b36cd0b3f9d8e8f61dd587564a2025 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sun, 1 Nov 2026 09:26:47 +0100 Subject: [PATCH 1/6] SaveState: Store the disc ID and version, first in SaveStart Fixed width, at the start of the first section, so the game a state belongs to can be read without loading it, to boot from a state alone. A load into a different game is logged. Co-Authored-By: Claude Opus 5.5 --- Core/SaveState.cpp | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/Core/SaveState.cpp b/Core/SaveState.cpp index eac38c9dda..e5d0ded280 100644 --- a/Core/SaveState.cpp +++ b/Core/SaveState.cpp @@ -212,10 +212,29 @@ int g_screenshotFailures; if (gpu) gpu->FlushPendingDrawing(); - auto s = p.Section("SaveStart", 1, 5); + auto s = p.Section("SaveStart", 1, 6); if (!s) return; + if (s >= 6) { + // Fixed width and first, so the game a state belongs to can be read without loading it. + char discID[16]{}; + char discVersion[8]{}; + if (p.mode != p.MODE_READ) { + truncate_cpy(discID, g_paramSFO.GetValueString("DISC_ID").c_str()); + truncate_cpy(discVersion, g_paramSFO.GetValueString("DISC_VERSION").c_str()); + } + p.DoVoid(discID, sizeof(discID)); + p.DoVoid(discVersion, sizeof(discVersion)); + if (p.mode == p.MODE_READ) { + const std::string stateDiscID(discID, strnlen(discID, sizeof(discID))); + const std::string runningDiscID = g_paramSFO.GetValueString("DISC_ID"); + if (stateDiscID != runningDiscID) { + WARN_LOG(Log::SaveState, "Loading a state saved from %s into %s", stateDiscID.c_str(), runningDiscID.c_str()); + } + } + } + if (s >= 2) { // This only increments on save, of course (once, not also in the measuring pass.) if (p.mode == p.MODE_WRITE && countsAsSave) { From 60dc6687f2de9bdbc3841f52e132fddf6a9b4049 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sun, 1 Nov 2026 09:26:47 +0100 Subject: [PATCH 2/6] SaveState: Store mounts by prefix, with the size of each one's state Mounts were stored by position with no size, so adding, removing or reordering one broke every older state, or silently fed sections to the wrong filesystem. Now a load pairs them by prefix, skips a mount it doesn't have, and leaves one the state doesn't have as it is. Older states load as before. Co-Authored-By: Claude Opus 5.5 --- Core/FileSystems/MetaFileSystem.cpp | 90 ++++++++++++++++++++++++----- Core/FileSystems/MetaFileSystem.h | 1 + unittest/UnitTest.cpp | 53 +++++++++++++++++ 3 files changed, 130 insertions(+), 14 deletions(-) diff --git a/Core/FileSystems/MetaFileSystem.cpp b/Core/FileSystems/MetaFileSystem.cpp index d1065b17c3..5e41c6d618 100644 --- a/Core/FileSystems/MetaFileSystem.cpp +++ b/Core/FileSystems/MetaFileSystem.cpp @@ -15,6 +15,9 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. +#include +#include + #include "Common/Serialize/Serializer.h" #include "Common/Serialize/SerializeFuncs.h" #include "Common/Serialize/SerializeMap.h" @@ -646,7 +649,7 @@ u64 MetaFileSystem::FreeDiskSpace(const std::string &path) { void MetaFileSystem::DoState(PointerWrap &p) { std::lock_guard guard(lock); - auto s = p.Section("MetaFileSystem", 1); + auto s = p.Section("MetaFileSystem", 1, 2); if (!s) return; @@ -655,7 +658,75 @@ void MetaFileSystem::DoState(PointerWrap &p) { // Save/load per-thread current directory map Do(p, currentDir); - u32 n = (u32) fileSystems.size(); + if (s < 2) { + DoStatePositionalMounts(p); + return; + } + + // Each mount is stored as its prefix, the size of its filesystem's state, and that state. A load + // pairs them with our mounts by prefix, skips any we don't have, and leaves a mount the state + // doesn't have as it is. So mounts can be added, removed and reordered freely. + u32 n = (u32)fileSystems.size(); + Do(p, n); + + if (p.mode == PointerWrap::MODE_READ) { + for (u32 i = 0; i < n; i++) { + std::string prefix; + u32 size = 0; + Do(p, prefix); + Do(p, size); + if (p.Failed() || !p.CheckRead(size)) { + p.SetError(p.ERROR_FAILURE); + ERROR_LOG(Log::FileSystem, "Savestate failure: bad mount entry %d", (int)i); + return; + } + u8 *data = *p.ptr; + p.SkipBytes(size); + + auto mount = std::find_if(fileSystems.begin(), fileSystems.end(), [&](const MountPoint &m) { + return m.prefix == prefix; + }); + if (mount == fileSystems.end()) { + WARN_LOG(Log::FileSystem, "Savestate has a mount we don't have, skipping it: %s", prefix.c_str()); + continue; + } + + // Read through a PointerWrap of its own, so it can't read past its own data. + PointerWrap sub(&data, PointerWrap::MODE_READ); + sub.SetReadEnd(data + size); + mount->system->DoState(sub); + if (sub.Failed()) { + p.SetError(p.ERROR_FAILURE); + ERROR_LOG(Log::FileSystem, "Savestate failure: couldn't load mount %s (at section %s)", prefix.c_str(), sub.GetBadSectionTitle() ? sub.GetBadSectionTitle() : "unknown"); + return; + } + } + return; + } + + for (const MountPoint &mount : fileSystems) { + std::string prefix = mount.prefix; + Do(p, prefix); + // Filled in once the filesystem's state is written. + u8 *sizePtr = *p.ptr; + if (p.mode == PointerWrap::MODE_VERIFY) { + p.SkipBytes(sizeof(u32)); + } else { + u32 size = 0; + Do(p, size); + } + const size_t start = p.Offset(); + mount.system->DoState(p); + if (p.mode == PointerWrap::MODE_WRITE) { + const u32 size = (u32)(p.Offset() - start); + memcpy(sizePtr, &size, sizeof(size)); + } + } +} + +// Version 1 of the state: the mounts with no prefixes or sizes, one after another. +void MetaFileSystem::DoStatePositionalMounts(PointerWrap &p) { + u32 n = (u32)fileSystems.size(); Do(p, n); // The mounts are serialized positionally: one section per mount, in fileSystems order, with no @@ -665,18 +736,9 @@ void MetaFileSystem::DoState(PointerWrap &p) { // sections for mounts that didn't exist yet, and we have to leave out exactly those to stay // lined up. We only know how many are missing (n), not which, hence the list below. // - // ADDING A NEW MOUNT: prepend its prefix here, or every existing savestate stops loading with - // "Failure at ". Newest first, because a state missing k mounts is - // missing the k most recently added ones. Where the new mount falls in the order doesn't - // matter - skipping it by prefix leaves the relative order of all the others unchanged. - // - // DO NOT REORDER EXISTING MOUNTS. Sections are paired with filesystems purely by position, so - // swapping two Mount() calls feeds every old savestate's sections to the wrong filesystems, - // silently and with no version to catch it. - // - // RENAMING OR REMOVING A MOUNT isn't handled here either: a section in the state we have no - // mount for can't be skipped, because we can't know how long it is. Either of those needs a - // format change - storing the prefixes, or a length per section. + // Mounts added before version 2, newest first: a state missing k mounts is missing the k most + // recently added ones. Mounts added since don't go here (version 2 states name their mounts), + // but old states still rely on the existing mounts keeping their relative order. static const char * const mountsAddedOverTime[] = { "flash1:", "pfat0:" }; const size_t missing = n < (u32)fileSystems.size() ? fileSystems.size() - n : 0; diff --git a/Core/FileSystems/MetaFileSystem.h b/Core/FileSystems/MetaFileSystem.h index ffbde32dd1..12ad4102bd 100644 --- a/Core/FileSystems/MetaFileSystem.h +++ b/Core/FileSystems/MetaFileSystem.h @@ -158,5 +158,6 @@ public: void Describe(char *buf, size_t size) const override { snprintf(buf, size, "Meta"); } private: + void DoStatePositionalMounts(PointerWrap &p); int64_t RecursiveSize(std::string_view dirPath); }; diff --git a/unittest/UnitTest.cpp b/unittest/UnitTest.cpp index 0c2bf3271f..c5a4722270 100644 --- a/unittest/UnitTest.cpp +++ b/unittest/UnitTest.cpp @@ -118,6 +118,7 @@ #include "Core/FileSystems/FileSystem.h" #include "Core/FileSystems/ISOFileSystem.h" #include "Core/FileSystems/DirectoryFileSystem.h" +#include "Core/FileSystems/MetaFileSystem.h" #include "Core/HLE/sceUmd.h" #include "Core/Loaders.h" #include "Core/MemMap.h" @@ -241,6 +242,57 @@ bool TestMathUtil() { return true; } +// A filesystem whose state is one number, under a section name of our choosing. +class SaveStateTestFileSystem : public EmptyFileSystem { +public: + SaveStateTestFileSystem(const char *section, int value) : section_(section), value_(value) {} + void DoState(PointerWrap &p) override { + auto s = p.Section(section_, 1); + if (!s) + return; + Do(p, value_); + } + int Value() const { return value_; } + +private: + const char *section_; + int value_; +}; + +bool TestSaveStateMounts() { + auto a = std::make_shared("TestFS", 1); + auto b = std::make_shared("TestFS", 2); + auto c = std::make_shared("TestFS", 3); + MetaFileSystem saved; + saved.Mount("a:", a); + saved.Mount("b:", b); + saved.Mount("c:", c); + + std::vector data; + EXPECT_TRUE(CChunkFileReader::MeasureAndSavePtr(saved, &data) == CChunkFileReader::ERROR_NONE); + + // Reordered, without b: and with a d: the state doesn't have. + auto a2 = std::make_shared("TestFS", 0); + auto c2 = std::make_shared("TestFS", 0); + auto d2 = std::make_shared("TestFS", 40); + MetaFileSystem loaded; + loaded.Mount("c:", c2); + loaded.Mount("d:", d2); + loaded.Mount("a:", a2); + std::string error; + EXPECT_TRUE(CChunkFileReader::LoadPtr(data.data(), data.size(), loaded, &error) == CChunkFileReader::ERROR_NONE); + EXPECT_EQ_INT(a2->Value(), 1); + EXPECT_EQ_INT(c2->Value(), 3); + EXPECT_EQ_INT(d2->Value(), 40); + + // A mount whose filesystem doesn't match the state's fails the load. + MetaFileSystem mismatched; + mismatched.Mount("a:", std::make_shared("OtherFS", 0)); + EXPECT_TRUE(CChunkFileReader::LoadPtr(data.data(), data.size(), mismatched, &error) != CChunkFileReader::ERROR_NONE); + + return true; +} + bool TestInetPton() { uint8_t ip4[4]; EXPECT_EQ_INT(net::inet_pton(AF_INET, "1.2.3.4", ip4), 1); @@ -4176,6 +4228,7 @@ TestItem availableTests[] = { TEST_ITEM(RequestManager), TEST_ITEM(StackWalk), TEST_ITEM(InetPton), + TEST_ITEM(SaveStateMounts), }; int main(int argc, const char *argv[]) { From 09f65a860c93bfbc797a9180d86ef9e4591cb341 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sun, 1 Nov 2026 09:54:54 +0100 Subject: [PATCH 3/6] SaveState: Store what the game was booted from, and read a state's start without loading it SaveStart (still version 6) also stores whether the game was booted from an ISO, a PBP, an ELF or a disc directory. PeekBootInfo decompresses only the start of a state to read them with the disc ID, so a boot from a state alone can be set up before the state is loaded. Co-Authored-By: Claude Opus 5.5 --- Common/Serialize/Serializer.cpp | 27 +++++++++++++-- Common/Serialize/Serializer.h | 3 ++ Core/SaveState.cpp | 58 +++++++++++++++++++++++++++++++-- Core/SaveState.h | 19 +++++++++++ unittest/UnitTest.cpp | 50 ++++++++++++++++++++++++++++ 5 files changed, 152 insertions(+), 5 deletions(-) diff --git a/Common/Serialize/Serializer.cpp b/Common/Serialize/Serializer.cpp index d6c983e887..065c05d71a 100644 --- a/Common/Serialize/Serializer.cpp +++ b/Common/Serialize/Serializer.cpp @@ -403,7 +403,8 @@ CChunkFileReader::Error CChunkFileReader::GetFileTitle(const Path &filename, std } // Streams the file through the decompressor, so the compressed data is never all in memory at once. -static bool DecompressZstdFromFile(File::IOFile &file, size_t compressedSize, u8 *out, size_t outSize) { +// With onlyStart, stops once out is full, rather than requiring the data to be exactly that long. +static bool DecompressZstdFromFile(File::IOFile &file, size_t compressedSize, u8 *out, size_t outSize, bool onlyStart = false) { ZSTD_DCtx *ctx = ZSTD_createDCtx(); if (!ctx) { return false; @@ -414,6 +415,9 @@ static bool DecompressZstdFromFile(File::IOFile &file, size_t compressedSize, u8 size_t ret = 1; bool success = true; while (left > 0 && success) { + if (onlyStart && output.pos == outSize) { + break; + } const size_t chunk = std::min(left, in.size()); if (!file.ReadBytes(in.data(), chunk)) { ERROR_LOG(Log::SaveState, "ChunkReader: Error reading file"); @@ -422,7 +426,7 @@ static bool DecompressZstdFromFile(File::IOFile &file, size_t compressedSize, u8 } left -= chunk; ZSTD_inBuffer input{ in.data(), chunk, 0 }; - while (input.pos < input.size) { + while (input.pos < input.size && !(onlyStart && output.pos == outSize)) { const size_t inPos = input.pos; const size_t outPos = output.pos; ret = ZSTD_decompressStream(ctx, &output, &input); @@ -434,6 +438,9 @@ static bool DecompressZstdFromFile(File::IOFile &file, size_t compressedSize, u8 } } ZSTD_freeDCtx(ctx); + if (onlyStart) { + return success && output.pos == outSize; + } // ret is 0 once a frame is completely decoded. return success && ret == 0 && output.pos == outSize; } @@ -465,6 +472,22 @@ static bool CompressZstd(const u8 *data, size_t size, std::vector *out) { return !ZSTD_isError(remaining); } +CChunkFileReader::Error CChunkFileReader::LoadFileStart(const Path &filename, u8 *out, size_t size) { + File::IOFile pFile(filename, "rb"); + SChunkHeader header; + Error err = LoadFileHeader(pFile, header, nullptr); + if (err != ERROR_NONE) { + return err; + } + if (!header.Compress) { + return size <= header.ExpectedSize && pFile.ReadBytes(out, size) ? ERROR_NONE : ERROR_BAD_FILE; + } + if (SerializeCompressType(header.Compress) != SerializeCompressType::ZSTD || size > header.UncompressedSize) { + return ERROR_BAD_FILE; + } + return DecompressZstdFromFile(pFile, header.ExpectedSize, out, size, true) ? ERROR_NONE : ERROR_BAD_FILE; +} + CChunkFileReader::Error CChunkFileReader::LoadFile(const Path &filename, std::string *gitVersion, u8 *&_buffer, size_t &sz) { if (!File::Exists(filename)) { ERROR_LOG(Log::SaveState, "ChunkReader: File doesn't exist"); diff --git a/Common/Serialize/Serializer.h b/Common/Serialize/Serializer.h index a56ad6e8be..8a27297dc5 100644 --- a/Common/Serialize/Serializer.h +++ b/Common/Serialize/Serializer.h @@ -360,6 +360,9 @@ public: // The file half of Load() and Save(), for doing it away from the state itself. LoadFile hands back // a new[]'d buffer; SaveFile takes ownership of a malloc'd one (as from MeasureAndSavePtr). static Error LoadFile(const Path &filename, std::string *gitVersion, u8 *&buffer, size_t &sz); + // Reads only the first size bytes of the state, decompressing no more than that. Not for snappy + // compressed (old) states. + static Error LoadFileStart(const Path &filename, u8 *out, size_t size); static Error SaveFile(const Path &filename, const std::string &title, const char *gitVersion, u8 *buffer, size_t sz); private: diff --git a/Core/SaveState.cpp b/Core/SaveState.cpp index e5d0ded280..3cc486e86d 100644 --- a/Core/SaveState.cpp +++ b/Core/SaveState.cpp @@ -204,6 +204,26 @@ int g_screenshotFailures; // we should probably just read back memory then instead (GTA for example). But this is a really unimportant edge case, // when in-game it's just not an issue. + static constexpr size_t DISC_ID_SIZE = 16; + static constexpr size_t DISC_VERSION_SIZE = 8; + + static BootType GetBootType(IdentifiedFileType type) { + switch (type) { + case IdentifiedFileType::PSP_ISO: + case IdentifiedFileType::PSP_ISO_NP: + return BootType::ISO; + case IdentifiedFileType::PSP_PBP: + case IdentifiedFileType::PSP_PBP_DIRECTORY: + return BootType::PBP; + case IdentifiedFileType::PSP_ELF: + return BootType::ELF; + case IdentifiedFileType::PSP_DISC_DIRECTORY: + return BootType::DISC_DIRECTORY; + default: + return BootType::UNKNOWN; + } + } + void SaveStart::DoState(PointerWrap &p) { // Nothing may still be writing PSP memory while it's saved, or be left to write into what's loaded. __UtilityWaitForIO(); @@ -217,15 +237,19 @@ int g_screenshotFailures; return; if (s >= 6) { - // Fixed width and first, so the game a state belongs to can be read without loading it. - char discID[16]{}; - char discVersion[8]{}; + // Fixed width and first, so the game a state belongs to can be read without loading it + // (see PeekBootInfo). + char discID[DISC_ID_SIZE]{}; + char discVersion[DISC_VERSION_SIZE]{}; + u8 bootType = 0; if (p.mode != p.MODE_READ) { truncate_cpy(discID, g_paramSFO.GetValueString("DISC_ID").c_str()); truncate_cpy(discVersion, g_paramSFO.GetValueString("DISC_VERSION").c_str()); + bootType = (u8)GetBootType(PSP_CoreParameter().fileType); } p.DoVoid(discID, sizeof(discID)); p.DoVoid(discVersion, sizeof(discVersion)); + Do(p, bootType); if (p.mode == p.MODE_READ) { const std::string stateDiscID(discID, strnlen(discID, sizeof(discID))); const std::string runningDiscID = g_paramSFO.GetValueString("DISC_ID"); @@ -597,6 +621,34 @@ int g_screenshotFailures; return title + " (" + filename + ")"; } + bool PeekBootInfo(const Path &filename, BootInfo *info, std::string *error) { + // The start of SaveStart, laid out as PointerWrap::Section writes it: a 16 byte name and the + // version, then the fields from version 6. + u8 start[16 + 4 + DISC_ID_SIZE + DISC_VERSION_SIZE + 1]; + if (CChunkFileReader::LoadFileStart(filename, start, sizeof(start)) != CChunkFileReader::ERROR_NONE) { + *error = "Couldn't read the state"; + return false; + } + char name[16]{}; + strncpy(name, "SaveStart", sizeof(name)); + if (memcmp(start, name, sizeof(name)) != 0) { + *error = "Not a savestate"; + return false; + } + s32 version; + memcpy(&version, start + 16, sizeof(version)); + if (version < 6) { + *error = "The state is too old to say which game it's from"; + return false; + } + const char *discID = (const char *)start + 20; + const char *discVersion = discID + DISC_ID_SIZE; + info->discID.assign(discID, strnlen(discID, DISC_ID_SIZE)); + info->discVersion.assign(discVersion, strnlen(discVersion, DISC_VERSION_SIZE)); + info->bootType = (BootType)start[sizeof(start) - 1]; + return true; + } + std::string GetTitle(const Path &filename) { std::string title; if (CChunkFileReader::GetFileTitle(filename, &title) == CChunkFileReader::ERROR_NONE) { diff --git a/Core/SaveState.h b/Core/SaveState.h index 33840e41ef..8ecbd6e101 100644 --- a/Core/SaveState.h +++ b/Core/SaveState.h @@ -94,6 +94,25 @@ namespace SaveState { std::string GetTitle(const Path &filename); + // What the game was booted from. Stored in states, so the values are fixed. + enum class BootType : u8 { + UNKNOWN = 0, + ISO = 1, + PBP = 2, + ELF = 3, + DISC_DIRECTORY = 4, + }; + + // What a boot needs to know about a state before it's loaded. + struct BootInfo { + std::string discID; + std::string discVersion; + BootType bootType = BootType::UNKNOWN; + }; + + // Reads only the start of the state. Fails for states older than the disc ID in them. + bool PeekBootInfo(const Path &filename, BootInfo *info, std::string *error); + // Load the specified file into the current state (async.) The file is read while emulation goes // on, and the state applied in a later Process(). // Returns true if queued. The callback runs from Process(), once the state has been applied. diff --git a/unittest/UnitTest.cpp b/unittest/UnitTest.cpp index c5a4722270..521a350618 100644 --- a/unittest/UnitTest.cpp +++ b/unittest/UnitTest.cpp @@ -119,6 +119,7 @@ #include "Core/FileSystems/ISOFileSystem.h" #include "Core/FileSystems/DirectoryFileSystem.h" #include "Core/FileSystems/MetaFileSystem.h" +#include "Core/SaveState.h" #include "Core/HLE/sceUmd.h" #include "Core/Loaders.h" #include "Core/MemMap.h" @@ -293,6 +294,54 @@ bool TestSaveStateMounts() { return true; } +// The start of a state as SaveStart writes it, and a little more. +struct PeekTestState { + int version; + void DoState(PointerWrap &p) { + auto s = p.Section("SaveStart", 1, version); + if (!s) + return; + if (s >= 6) { + char discID[16] = "ULUS12345"; + char discVersion[8] = "1.01"; + u8 bootType = (u8)SaveState::BootType::PBP; + p.DoVoid(discID, sizeof(discID)); + p.DoVoid(discVersion, sizeof(discVersion)); + Do(p, bootType); + } + std::vector rest(100000, 0x55); + Do(p, rest); + } +}; + +static bool SavePeekTestState(const Path &path, int version) { + PeekTestState state{ version }; + u8 *data = nullptr; + size_t size = 0; + if (CChunkFileReader::MeasureAndSavePtr(state, &data, &size) != CChunkFileReader::ERROR_NONE) { + return false; + } + return CChunkFileReader::SaveFile(path, "Test", "v1.0", data, size) == CChunkFileReader::ERROR_NONE; +} + +bool TestSaveStatePeek() { + const Path path = UnitTestTempPath("unittest_peek.ppst"); + SaveState::BootInfo info; + std::string error; + + EXPECT_TRUE(SavePeekTestState(path, 6)); + EXPECT_TRUE(SaveState::PeekBootInfo(path, &info, &error)); + EXPECT_EQ_STR(info.discID, std::string("ULUS12345")); + EXPECT_EQ_STR(info.discVersion, std::string("1.01")); + EXPECT_TRUE(info.bootType == SaveState::BootType::PBP); + + EXPECT_TRUE(SavePeekTestState(path, 5)); + EXPECT_FALSE(SaveState::PeekBootInfo(path, &info, &error)); + + File::Delete(path); + return true; +} + bool TestInetPton() { uint8_t ip4[4]; EXPECT_EQ_INT(net::inet_pton(AF_INET, "1.2.3.4", ip4), 1); @@ -4229,6 +4278,7 @@ TestItem availableTests[] = { TEST_ITEM(StackWalk), TEST_ITEM(InetPton), TEST_ITEM(SaveStateMounts), + TEST_ITEM(SaveStatePeek), }; int main(int argc, const char *argv[]) { From 8122a5ec70e6bf4b35013ee3a95e5c4e4077fca2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sun, 1 Nov 2026 11:04:26 +0100 Subject: [PATCH 4/6] Headless: Boot a savestate without its game Running a .ppst boots a placeholder program, with the disc ID and boot type peeked from the state, then loads the state over it. An ISO game gets a disc with nothing on it, which the mounts now load into by name. Meant for measuring performance with states that can be kept without the games; the app still refuses to boot a state. Co-Authored-By: Claude Opus 5.5 --- Core/CoreParameter.h | 2 ++ Core/HLE/sceKernelModule.cpp | 23 ++++++++++++++ Core/HLE/sceKernelModule.h | 2 ++ Core/PSPLoaders.cpp | 60 ++++++++++++++++++++++++++++++++++++ Core/PSPLoaders.h | 4 +++ Core/System.cpp | 17 +++++++++- docs/debugging.md | 8 +++++ headless/Headless.cpp | 12 ++++++++ 8 files changed, 127 insertions(+), 1 deletion(-) diff --git a/Core/CoreParameter.h b/Core/CoreParameter.h index 419af33daf..16012a1ed1 100644 --- a/Core/CoreParameter.h +++ b/Core/CoreParameter.h @@ -92,6 +92,8 @@ struct CoreParameter { bool startBreak = false; std::string *collectDebugOutput = nullptr; bool headLess = false; // Try to avoid messageboxes etc + // Headless only: allows booting a savestate without its game, for measuring performance. + bool bootFromState = false; // Headless leaves out compat settings when replaying frame dumps, unless this is set. bool dumpCompat = false; // Headless: GPU_USE_ feature bits to turn off, to test the fallbacks for GPUs without them. diff --git a/Core/HLE/sceKernelModule.cpp b/Core/HLE/sceKernelModule.cpp index 54131b836e..6b21faed0d 100644 --- a/Core/HLE/sceKernelModule.cpp +++ b/Core/HLE/sceKernelModule.cpp @@ -2618,6 +2618,29 @@ bool __KernelLoadGEDump(MIPSState *mips, std::string_view base_filename, std::st return true; } +void __KernelLoadStateBootStub(MIPSState *mips) { + __KernelLoadReset(); + + constexpr u32 codeStartAddr = PSP_GetUserMemoryBase(); + mips->pc = codeStartAddr; + // b . (to itself), and the delay slot. + Memory::WriteUnchecked_U32(MIPS_MAKE_B(-1), codeStartAddr); + Memory::WriteUnchecked_U32(MIPS_MAKE_NOP(), codeStartAddr + 4); + + PSPModule *module = new PSPModule(); + kernelObjects.Create(module); + loadedModules.insert(module->GetUID()); + memset(&module->nm, 0, sizeof(module->nm)); + module->isFake = true; + module->nm.entry_addr = codeStartAddr; + module->nm.gp_value = -1; + + SceUID threadID = __KernelSetupRootThread(module->GetUID(), 0, nullptr, 0x20, 0x1000, 0); + __KernelSetThreadRA(threadID, NID_MODULERETURN); + + __KernelStartIdleThreads(module->GetUID()); +} + int __KernelGPUReplay(MIPSState *mips) { // Special ABI: s0 and s1 are the "args". Not null terminated. const char *filenamep = Memory::GetCharPointer(mips->r[MIPS_REG_S1]); diff --git a/Core/HLE/sceKernelModule.h b/Core/HLE/sceKernelModule.h index 1ab357464d..32541b885c 100644 --- a/Core/HLE/sceKernelModule.h +++ b/Core/HLE/sceKernelModule.h @@ -241,6 +241,8 @@ class MIPSState; u32 __KernelGetModuleGP(SceUID module); bool KernelModuleIsKernelMode(SceUID module); bool __KernelLoadGEDump(MIPSState *mips, std::string_view base_filename, std::string *error_string); +// A placeholder program that loops until a savestate is loaded over it. +void __KernelLoadStateBootStub(MIPSState *mips); // hostArgs, if set, are passed to the module instead of what paramPtr points to. bool __KernelLoadExec(MIPSState *mips, const char *filename, u32 paramPtr, std::string *error_string, const std::vector *hostArgs = nullptr); // The VSH (the XMB) is what's running, not a game it launched. diff --git a/Core/PSPLoaders.cpp b/Core/PSPLoaders.cpp index 571b7acdd5..82cdd235c1 100644 --- a/Core/PSPLoaders.cpp +++ b/Core/PSPLoaders.cpp @@ -54,6 +54,7 @@ #include "Core/ConfigValues.h" #include "Core/System.h" #include "Core/PSPLoaders.h" +#include "Core/SaveState.h" #include "Core/HLE/sceKernelModule.h" #include "Core/HLE/PopsBoot.h" #include "Core/Util/PSARUnpack.h" @@ -699,6 +700,65 @@ bool Load_PSP_POPS(FileLoader *fileLoader, std::string *error_string) { return true; } +// A disc with nothing on it. Every block reads as zeros, so the ISO filesystem finds no volume +// descriptor and no files. +class EmptyDiscBlockDevice : public BlockDevice { +public: + EmptyDiscBlockDevice() : BlockDevice(nullptr) {} + bool ReadBlock(int blockNumber, u8 *outPtr, bool uncached) override { + memset(outPtr, 0, GetBlockSize()); + return true; + } + u32 GetNumBlocks() const override { return 0; } + bool IsDisc() const override { return true; } +}; + +bool MountStateBoot(const Path &statePath, std::string *errorString) { + SaveState::BootInfo info; + if (!SaveState::PeekBootInfo(statePath, &info, errorString)) { + return false; + } + if (info.discID.empty()) { + *errorString = "The state doesn't say which game it's from"; + return false; + } + switch (info.bootType) { + case SaveState::BootType::ISO: + { + // The game's open files on the disc are dropped as the state loads, and opening any + // file fails, so the game only gets so far. + auto iso = std::make_shared(&pspFileSystem, std::make_shared()); + auto blockSystem = std::make_shared(iso); + pspFileSystem.Mount("umd0:", blockSystem); + pspFileSystem.Mount("umd1:", blockSystem); + pspFileSystem.Mount("umd:", blockSystem); + pspFileSystem.Mount("disc0:", iso); + break; + } + case SaveState::BootType::PBP: + case SaveState::BootType::ELF: + break; + default: + *errorString = "Can only boot states of games run from an ISO, PBP or ELF without the game"; + return false; + } + + g_paramSFO.SetValue("DISC_ID", info.discID, 16); + g_paramSFO.SetValue("DISC_VERSION", info.discVersion, 8); + g_paramSFO.SetValue("TITLE", SaveState::GetTitle(statePath), 128); + INFO_LOG(Log::Loader, "Booting state %s of %s %s without the game", statePath.c_str(), info.discID.c_str(), info.discVersion.c_str()); + return true; +} + +bool Load_PSP_StateBoot(std::string *error_string) { + if (PSP_CoreParameter().loadGameConfigs) { + g_Config.LoadGameConfig(g_paramSFO.GetDiscID()); + System_PostUIMessage(UIMessage::CONFIG_LOADED); + } + __KernelLoadStateBootStub(currentMIPS); + return true; +} + bool Load_PSP_GE_Dump(FileLoader *fileLoader, std::string *error_string) { auto umd = std::make_shared(&pspFileSystem, fileLoader, "data.ppdmp"); pspFileSystem.Mount("disc0:", umd); diff --git a/Core/PSPLoaders.h b/Core/PSPLoaders.h index 7592b43427..b4cddd6c86 100644 --- a/Core/PSPLoaders.h +++ b/Core/PSPLoaders.h @@ -26,6 +26,10 @@ class BlockDevice; bool Load_PSP_ISO(FileLoader *fileLoader, std::string *error_string); bool Load_PSP_ELF_PBP(FileLoader *fileLoader, std::string_view discId, bool loadGameConfigs, std::string *error_string); bool Load_PSP_GE_Dump(FileLoader *fileLoader, std::string *error_string); +// Booting a savestate without its game: the first sets up the disc ID and a disc with nothing on it, +// the second a placeholder program that runs until the state is loaded. +bool MountStateBoot(const Path &statePath, std::string *errorString); +bool Load_PSP_StateBoot(std::string *error_string); bool Load_PSP_POPS(FileLoader *fileLoader, std::string *error_string); bool MountGameISO(FileLoader *fileLoader, std::string *errorString); diff --git a/Core/System.cpp b/Core/System.cpp index 420812f733..133f58de20 100644 --- a/Core/System.cpp +++ b/Core/System.cpp @@ -297,7 +297,7 @@ static void GetBootError(IdentifiedFileType type, std::string *errorString) { case IdentifiedFileType::PS2_ISO: *errorString = "PS2 game image detected."; break; case IdentifiedFileType::PS3_ISO: *errorString = "PS2 game image detected."; break; case IdentifiedFileType::NORMAL_DIRECTORY: *errorString = "Just a directory."; break; - case IdentifiedFileType::PPSSPP_SAVESTATE: *errorString = "This is a saved state, not a game."; break; // Actually, we could make it load it... + case IdentifiedFileType::PPSSPP_SAVESTATE: *errorString = "This is a saved state, not a game."; break; case IdentifiedFileType::PSP_SAVEDATA_DIRECTORY: *errorString = "This is save data, not a game."; break; case IdentifiedFileType::PSP_PS1_PBP: *errorString = "PS1 EBOOTs are not supported by PPSSPP."; break; case IdentifiedFileType::PSP_UMD_VIDEO_ISO: *errorString = std::string("UMD Video plays in the XMB, which needs PSP firmware ") + UMD_VIDEO_MIN_FIRMWARE + " or later."; break; @@ -481,6 +481,15 @@ static bool CPU_Init(FileLoader *fileLoader, IdentifiedFileType type, std::strin // Title and disc ID; the PS1 image itself is read by the firmware's POPS manager. LoadParamSFOFromPBP(fileLoader); break; + case IdentifiedFileType::PPSSPP_SAVESTATE: + if (!g_CoreParameter.bootFromState) { + GetBootError(type, errorString); + return false; + } + if (!MountStateBoot(g_CoreParameter.fileToStart, errorString)) { + return false; + } + break; case IdentifiedFileType::PSP_UMD_VIDEO_ISO: { // The game list boots the XMB for these, which plays them. @@ -669,6 +678,12 @@ static bool CPU_Init(FileLoader *fileLoader, IdentifiedFileType type, std::strin return false; } break; + case IdentifiedFileType::PPSSPP_SAVESTATE: + // Headless loads the state itself, as with --state. + if (!Load_PSP_StateBoot(errorString)) { + return false; + } + break; default: GetBootError(type, errorString); diff --git a/docs/debugging.md b/docs/debugging.md index c10ff6f092..a3777388e0 100644 --- a/docs/debugging.md +++ b/docs/debugging.md @@ -223,6 +223,14 @@ To check that a game keeps running after `--state=` loads, pass `--frame-stats`: the flips in each emulated second since the load. A stuck or crashed game shows as zeros or a short list, and a steady game as a flat 30 or 60. The state's load result is printed too, and a failed load exits 1. +Headless can also boot a savestate without its game: pass the `.ppst` as the file to run, without `--state=`. +The state says which game it's from and whether that was booted from an ISO, a PBP or an ELF, so compat.ini and +the game's config apply. An ISO game gets a disc with nothing on it: files it had open are dropped when the state +loads, and opening any file fails. Most games keep running for a few seconds without the disc, enough to measure, +but a state taken while the game streams music or video, or just before it loads a level, soon hits those errors, +so save perf states in the middle of gameplay. Only states saved since the disc ID was added to them (`SaveStart` +version 6) boot this way. The app doesn't: it refuses a `.ppst` as before. + To get past menus, `--press=SECONDS:MASK[:DURATION],...` holds buttons at emulated times (`MASK` is a sceCtrl mask, `0x8` START and `0x4000` CROSS, held 0.15 seconds by default), and `--screenshot-at=SECONDS:FILE,...` saves screenshots along the way. diff --git a/headless/Headless.cpp b/headless/Headless.cpp index 23b5d9a838..77a7ebd2b4 100644 --- a/headless/Headless.cpp +++ b/headless/Headless.cpp @@ -1042,6 +1042,17 @@ int main(int argc, const char* argv[]) { testFilenames.end() ); + // A savestate on its own boots without its game, and then loads. + std::string stateBootPath; + if (testFilenames.size() == 1 && endsWithNoCase(testFilenames[0], ".ppst")) { + stateBootPath = testFilenames[0]; + if (stateToLoad) { + fprintf(stderr, "--state can't be used when booting a state\n"); + return 1; + } + stateToLoad = stateBootPath.c_str(); + } + g_Config.bEnableLogging = (fullLog || outputDebugStringLog); g_logManager.Init(&g_Config.bEnableLogging, outputDebugStringLog); @@ -1333,6 +1344,7 @@ int main(int argc, const char* argv[]) { coreParameter.mountRoot = mountRoot.empty() ? Path() : Path(mountRoot); coreParameter.startBreak = false; coreParameter.headLess = true; + coreParameter.bootFromState = !stateBootPath.empty(); coreParameter.dumpCompat = cmdLineOptions.dumpCompat.value_or(false); if (cmdLineOptions.disableGPUFeatures.has_value()) { std::vector names; From 5c37b0d798adfafc4086525de1dd985d5e81574f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sun, 1 Nov 2026 11:15:35 +0100 Subject: [PATCH 5/6] Headless: Count failed disc reads when booting a state, and benchmark such states The count is opens of files missing from the disc, and reads and seeks on handles whose file was dropped as the state loaded, from the load on. It tells how far a game booted without its disc has strayed from its usual path. headless_bench.py takes bare .ppst files and directories of them (--state-dir), and reports the count with the timings. Co-Authored-By: Claude Opus 5.5 --- Core/FileSystems/MetaFileSystem.cpp | 22 +++++++++++++--------- Core/FileSystems/MetaFileSystem.h | 9 +++++++++ Tools/headless_bench.py | 23 ++++++++++++++++++++--- docs/debugging.md | 9 +++++++-- headless/Headless.cpp | 6 ++++++ 5 files changed, 55 insertions(+), 14 deletions(-) diff --git a/Core/FileSystems/MetaFileSystem.cpp b/Core/FileSystems/MetaFileSystem.cpp index 5e41c6d618..999d21de2d 100644 --- a/Core/FileSystems/MetaFileSystem.cpp +++ b/Core/FileSystems/MetaFileSystem.cpp @@ -356,10 +356,14 @@ int MetaFileSystem::OpenFile(std::string filename, FileAccess access, const char std::string of; MountPoint *mount; int error = MapFilePath(filename, &of, &mount); - if (error == 0) - return mount->system->OpenFile(of, access, mount->prefix.c_str()); - else + if (error != 0) { return error; + } + int handle = mount->system->OpenFile(of, access, mount->prefix.c_str()); + if (handle < 0 && (mount->system->Flags() & FileSystemFlags::UMD)) { + failedDiscReads_++; + } + return handle; } PSPFileInfo MetaFileSystem::GetFileInfo(std::string filename) @@ -568,8 +572,8 @@ size_t MetaFileSystem::ReadFile(u32 handle, u8 *pointer, s64 size) IFileSystem *sys = GetHandleOwner(handle); if (sys) return sys->ReadFile(handle, pointer, size); - else - return 0; + failedDiscReads_++; + return 0; } size_t MetaFileSystem::WriteFile(u32 handle, const u8 *pointer, s64 size) @@ -588,8 +592,8 @@ size_t MetaFileSystem::ReadFile(u32 handle, u8 *pointer, s64 size, int &usec) IFileSystem *sys = GetHandleOwner(handle); if (sys) return sys->ReadFile(handle, pointer, size, usec); - else - return 0; + failedDiscReads_++; + return 0; } size_t MetaFileSystem::WriteFile(u32 handle, const u8 *pointer, s64 size, int &usec) @@ -608,8 +612,8 @@ size_t MetaFileSystem::SeekFile(u32 handle, s32 position, FileMove type) IFileSystem *sys = GetHandleOwner(handle); if (sys) return sys->SeekFile(handle, position, type); - else - return 0; + failedDiscReads_++; + return 0; } int MetaFileSystem::ReadEntireFile(const std::string &filename, std::vector &data, bool quiet) { diff --git a/Core/FileSystems/MetaFileSystem.h b/Core/FileSystems/MetaFileSystem.h index 12ad4102bd..37a7864ddc 100644 --- a/Core/FileSystems/MetaFileSystem.h +++ b/Core/FileSystems/MetaFileSystem.h @@ -17,6 +17,7 @@ #pragma once +#include #include #include #include @@ -65,6 +66,12 @@ public: Reset(); } + // Opens of files that aren't on the disc, and reads and seeks on handles whose file was dropped + // when a savestate loaded. On a real disc these don't happen, so they tell when a game booted + // from a state alone has missed data it needed. + int FailedDiscReads() const { return failedDiscReads_; } + void ResetFailedDiscReads() { failedDiscReads_ = 0; } + // Will replace the existing mount if already exists. Mount with an optional sub-directory inside the filesystem to treat as the root. void Mount(std::string_view prefix, std::shared_ptr system, std::string_view subDir = std::string_view()); void UnmountAll(); @@ -158,6 +165,8 @@ public: void Describe(char *buf, size_t size) const override { snprintf(buf, size, "Meta"); } private: + std::atomic failedDiscReads_{}; + void DoStatePositionalMounts(PointerWrap &p); int64_t RecursiveSize(std::string_view dirPath); }; diff --git a/Tools/headless_bench.py b/Tools/headless_bench.py index 5f46a16723..601129626f 100755 --- a/Tools/headless_bench.py +++ b/Tools/headless_bench.py @@ -34,7 +34,10 @@ Example: --game "~/PSP/LocoRoco.cso@~/.config/ppsspp/PSP/PPSSPP_STATE/UCES00304_1.01_0.ppst" \\ old/PPSSPPHeadless build-release/PPSSPPHeadless -A game is ISO[@SAVESTATE], or a frame dump (.ppdmp), which replays and exits on its own. +A game is ISO[@SAVESTATE], a frame dump (.ppdmp), which replays and exits on its own, or a savestate (.ppst) +on its own, which headless boots without its game. --state-dir adds every .ppst in a directory. For those, +"discfail" counts the disc reads that failed because the game isn't there. When it isn't 0, the game has +left its usual path at least a little, so a state with fewer is a better benchmark. """ import argparse @@ -168,6 +171,7 @@ def run_once(binary, game, args, prefix, kind): is_dump = iso.lower().endswith('.ppdmp') if not is_dump: cmd += ['--timeout-emulated=%g' % args.emu_secs, '--timeout-wall=%d' % args.wall_limit] + is_state_boot = iso.lower().endswith('.ppst') if state: cmd.append('--state=' + os.path.expanduser(state)) cmd += args.extra @@ -194,12 +198,17 @@ def run_once(binary, game, args, prefix, kind): if not is_dump and 'TIMEOUT (emulated)' not in output: raise RuntimeError('%s didn\'t run %s for its emulated time:\n%s' % (binary, game, output[-2000:])) # Loaded State, or a warning that starts with Loaded. - if state and not re.search(r'^Loaded', output, re.M): + if (state or is_state_boot) and not re.search(r'^Loaded', output, re.M): raise RuntimeError('%s didn\'t load the savestate for %s:\n%s' % (binary, game, (stdout + stderr)[-2000:])) result = {'wall': wall} if cpu is not None: result['cpu'] = cpu result.update(parse_counters(kind, stderr)) + if is_state_boot: + m = re.search(r'^Failed disc reads: (\d+)', stderr, re.M) + if not m: + raise RuntimeError('%s didn\'t report failed disc reads for %s (too old to boot a state?)' % (binary, game)) + result['discfail'] = int(m.group(1)) return result @@ -220,6 +229,8 @@ def report(game, binaries, results): delta = ' (%+.2f%%)' % (100.0 * (med / base[k] - 1.0)) value = ('%.2fs' % med) if k in ('wall', 'cpu') else ('%.4g' % med) cols.append('%s %s%s +-%.1f%%' % (k, value, delta, spread / 2)) + if all('discfail' in r for r in results[b]): + cols.append('discfail %d' % statistics.median(r['discfail'] for r in results[b])) print(' %-28s %s' % (os.path.basename(os.path.dirname(b)) + '/' + os.path.basename(b), ' '.join(cols))) @@ -228,6 +239,7 @@ def main(): parser.add_argument('binaries', nargs='+', help='PPSSPPHeadless binaries; the first is the baseline') parser.add_argument('--game', action='append', default=[], help='ISO[@SAVESTATE] or a .ppdmp (repeatable)') parser.add_argument('--games', help='JSON file: a list of games as for --game') + parser.add_argument('--state-dir', action='append', default=[], help='directory of savestates to boot without their games (repeatable)') parser.add_argument('--rounds', type=int, default=4, help='runs per binary and game (default 4)') parser.add_argument('--warmup', type=int, default=1, help='uncounted rounds first (default 1)') parser.add_argument('--emu-secs', type=float, default=5, help='emulated seconds per run (default 5)') @@ -249,8 +261,13 @@ def main(): games = list(args.game) if args.games: games += json.load(open(args.games)) + for d in args.state_dir: + found = sorted(glob.glob(os.path.join(os.path.expanduser(d), '*.ppst'))) + if not found: + parser.error('no .ppst files in ' + d) + games += found if not games: - parser.error('no games: pass --game or --games') + parser.error('no games: pass --game, --games or --state-dir') binaries = [os.path.abspath(b) for b in args.binaries] for b in binaries: if not os.access(b, os.X_OK): diff --git a/docs/debugging.md b/docs/debugging.md index a3777388e0..43f2441e66 100644 --- a/docs/debugging.md +++ b/docs/debugging.md @@ -228,8 +228,13 @@ The state says which game it's from and whether that was booted from an ISO, a P the game's config apply. An ISO game gets a disc with nothing on it: files it had open are dropped when the state loads, and opening any file fails. Most games keep running for a few seconds without the disc, enough to measure, but a state taken while the game streams music or video, or just before it loads a level, soon hits those errors, -so save perf states in the middle of gameplay. Only states saved since the disc ID was added to them (`SaveStart` -version 6) boot this way. The app doesn't: it refuses a `.ppst` as before. +so save perf states in the middle of gameplay. Headless prints `Failed disc reads: N` at the end, counted from +the load: opens of files on the disc and reads and seeks on dropped handles. A state that keeps it at 0, or close, +measures the game as it really runs. Only states saved since the disc ID was added to them (`SaveStart` version 6) +boot this way. The app doesn't: it refuses a `.ppst` as before. + +`Tools/headless_bench.py` takes such states as games (`--game some.ppst`, or `--state-dir DIR` for every `.ppst` +in a directory), and reports the failed disc reads with the timings. To get past menus, `--press=SECONDS:MASK[:DURATION],...` holds buttons at emulated times (`MASK` is a sceCtrl mask, `0x8` START and `0x4000` CROSS, held 0.15 seconds by default), and `--screenshot-at=SECONDS:FILE,...` saves diff --git a/headless/Headless.cpp b/headless/Headless.cpp index 77a7ebd2b4..60b7576a1d 100644 --- a/headless/Headless.cpp +++ b/headless/Headless.cpp @@ -58,6 +58,7 @@ #include "Core/Instance.h" #include "Core/ConfigValues.h" #include "Core/Core.h" +#include "Core/FileSystems/MetaFileSystem.h" #include "Core/CoreTiming.h" #include "Core/EmuThread.h" #include "Core/HLE/HLE.h" @@ -757,6 +758,10 @@ static bool RunAutoTest(GraphicsContext *graphicsContext, CoreParameter &corePar } fprintf(stderr, "Frame stats: %d flips in %d emulated seconds, wall %.1fs, per second:%s\n", total, (int)flipsPerSecond.size(), time_now_d() - startTime, perSecond.c_str()); } + if (coreParameter.bootFromState) { + // Counted from the state's load. More than a few, and the game has gone off its usual path. + fprintf(stderr, "Failed disc reads: %d\n", pspFileSystem.FailedDiscReads()); + } // Before EndDrawFrame: Vulkan can only read back a framebuffer inside a frame. if (!g_screenshotSavePath.empty() && !g_screenshotSaved) { @@ -1582,6 +1587,7 @@ int main(int argc, const char* argv[]) { } g_stateLoadFailed = true; } + pspFileSystem.ResetFailedDiscReads(); g_stateLoadPending = false; }); } From bf2c81e37d6fd44538cbf1e4be7f75d990a713b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sun, 1 Nov 2026 15:41:23 +0100 Subject: [PATCH 6/6] Headless: Don't save states while running from a state without its game The game runs without its disc there, so a state saved from it would keep that broken environment. Saves are refused, and so is --save-state together with a state to boot. Co-Authored-By: Claude Opus 5.5 --- Core/FileSystems/MetaFileSystem.h | 2 +- Core/SaveState.cpp | 9 +++++++++ docs/debugging.md | 3 ++- headless/Headless.cpp | 4 ++-- 4 files changed, 14 insertions(+), 4 deletions(-) diff --git a/Core/FileSystems/MetaFileSystem.h b/Core/FileSystems/MetaFileSystem.h index 37a7864ddc..be79268f0b 100644 --- a/Core/FileSystems/MetaFileSystem.h +++ b/Core/FileSystems/MetaFileSystem.h @@ -67,7 +67,7 @@ public: } // Opens of files that aren't on the disc, and reads and seeks on handles whose file was dropped - // when a savestate loaded. On a real disc these don't happen, so they tell when a game booted + // when a savestate loaded. With the real disc these are rare, so they tell when a game booted // from a state alone has missed data it needed. int FailedDiscReads() const { return failedDiscReads_; } void ResetFailedDiscReads() { failedDiscReads_ = 0; } diff --git a/Core/SaveState.cpp b/Core/SaveState.cpp index 3cc486e86d..836cbacba7 100644 --- a/Core/SaveState.cpp +++ b/Core/SaveState.cpp @@ -498,6 +498,15 @@ int g_screenshotFailures; CallbackRefused(op.callback); return false; } + // A game booted from a state alone (headless) runs without its disc. A state saved from that + // would hold the broken environment, and be no use with the game or without it. + if (op.type == OperationType::Save && PSP_CoreParameter().fileType == IdentifiedFileType::PPSSPP_SAVESTATE) { + ERROR_LOG(Log::SaveState, "Can't save a state while running from a state without its game"); + if (op.callback) { + op.callback(Status::FAILURE, "Can't save a state while running from a state without its game", ""); + } + return false; + } // Verify saves and loads back in place, with the mounts as they are. if (op.type != OperationType::Verify && WarnUserIfVSHSession()) { CallbackRefused(op.callback); diff --git a/docs/debugging.md b/docs/debugging.md index 43f2441e66..359a3c8a1c 100644 --- a/docs/debugging.md +++ b/docs/debugging.md @@ -231,7 +231,8 @@ but a state taken while the game streams music or video, or just before it loads so save perf states in the middle of gameplay. Headless prints `Failed disc reads: N` at the end, counted from the load: opens of files on the disc and reads and seeks on dropped handles. A state that keeps it at 0, or close, measures the game as it really runs. Only states saved since the disc ID was added to them (`SaveStart` version 6) -boot this way. The app doesn't: it refuses a `.ppst` as before. +boot this way. The app doesn't: it refuses a `.ppst` as before. States can't be saved while running from one this +way (`--save-state` is refused): without the disc the game isn't in a state worth keeping. `Tools/headless_bench.py` takes such states as games (`--game some.ppst`, or `--state-dir DIR` for every `.ppst` in a directory), and reports the failed disc reads with the timings. diff --git a/headless/Headless.cpp b/headless/Headless.cpp index 60b7576a1d..e4a2fba86d 100644 --- a/headless/Headless.cpp +++ b/headless/Headless.cpp @@ -1051,8 +1051,8 @@ int main(int argc, const char* argv[]) { std::string stateBootPath; if (testFilenames.size() == 1 && endsWithNoCase(testFilenames[0], ".ppst")) { stateBootPath = testFilenames[0]; - if (stateToLoad) { - fprintf(stderr, "--state can't be used when booting a state\n"); + if (stateToLoad || cmdLineOptions.stateToSave.has_value()) { + fprintf(stderr, "--state and --save-state can't be used when booting a state\n"); return 1; } stateToLoad = stateBootPath.c_str();