sharpemu icon indicating copy to clipboard operation
sharpemu copied to clipboard

libSceSaveDataDialog: SYSTEM_MSG (NOSPACE) dialog re-shown in a tight loop after character creation

Open zambasaurus opened this issue 4 months ago • 7 comments

Bug Description

After fixing the SaveDataDialog Initialize/Close state-machine bugs (see the two already-fixed bugs below), Demon's Souls (PPSA01341) now successfully completes character creation and proceeds into real gameplay for the first time — but a SYSTEM_MSG dialog with msgType=4 (SystemMessageType.NOSPACE, i.e. "not enough space") keeps firing in a tight Initialize → Open → poll → GetResult cycle in the background. GetResult succeeds every time (mode=3, the affirmative button, no error), and the cycle doesn't appear to block gameplay from proceeding, but it shouldn't be happening at all — there's no reason a fresh save directory should ever report insufficient space.

What's already fixed (for context)

Two related state-machine bugs in src/SharpEmu.Libs/SaveData/SaveDataDialogExports.cs were already fixed on fix/savedata-dialog-close-loop:

  • SaveDataDialogClose required strictly Running, but the auto-dismiss design already advances Running → Finished before Close is typically called, permanently wedging the dialog.
  • SaveDataDialogInitialize required strictly StatusNone, but nothing in a single-shot system-message flow ever calls Terminate, so every Initialize after the first successful cycle permanently failed with AlreadyInitialized.

With both fixed, the game now reaches real gameplay — but this separate NOSPACE loop remains.

Evidence

Dumped the SystemMessageParam the dialog carries (paramAddress + 0x58, per shadPS4's savedatadialog_ui.h):

save_data_dialog.sys_msg_param ptr=0x... msgType=4 value=0x0000000000000060

msgType=4 is SystemMessageType.NOSPACE. value=0x60 (96) is presumably the required space in some unit.

Checked the two obvious candidates for a space-reporting bug in src/SharpEmu.Libs/SaveData/SaveDataExports.cs:

  • sceSaveDataGetAllSize reports used space from the real save directory (correctly 0 for a fresh install), not available space — doesn't look like the source.
  • sceSaveDataPrepare always returns success unconditionally, never checks or reports space at all.

Did not find an implemented "free/available space" query export in SaveDataExports.cs at all — it's possible the relevant check reads something outside libSceSaveData entirely (e.g. a generic filesystem/device free-space call), or the title computes this from data SharpEmu doesn't populate correctly elsewhere. Not yet root-caused.

Suggested Next Step

Trace what other imports fire immediately around this cycle (not just save_data_dialog.*) to find what's actually driving the "not enough space" determination, and check whether there's a real sceSaveData/kernel export involved that's unimplemented or returns a wrong value.

Hardware

Same dev machine as prior reports in this repo (Windows 11, RTX 3090).

zambasaurus avatar Jul 25 '26 20:07 zambasaurus

Update: this loop likely causes a visible freeze once it can run unthrottled

Pushed further past character creation tonight (with the Initialize fix from fix/savedata-dialog-close-loop applied) — the title now gets through most/all of the opening cinematic, further than this project has reached before. It then hit what looked at first like a GPU hang: FPS collapsed to ~0.3-1, the window stopped visually updating, GPU usage spiked briefly then dropped to near-idle.

Checked the trace right up to the point I killed it: in the last 2000 traced calls, the overwhelming majority were libc:vsnprintf (957), libc:memcpy (559), and libc:sprintf (119) — with only a small handful of real libSceAgc (GPU) calls in the same window. sceSaveDataDialogInitialize/Open/GetResult/UpdateStatus (this issue's loop) accounted for ~330 of the 2000.

This doesn't look like a GPU hang at all (GPU usage briefly spiked then dropped to near-idle, not sustained high usage). It looks like the title is spending nearly all its CPU time re-formatting text — very plausibly the NOSPACE dialog's own message string — in the same tight loop this issue is about, at a rate fast enough to consume a full CPU core and starve frame presentation entirely. That would explain both symptoms at once: the loop itself, and the apparent "freeze" (GPU idle because the render thread never gets enough CPU time to submit a new frame).

If this is right, fixing the underlying NOSPACE trigger (this issue) would likely also resolve what currently looks like a hang once a title reaches a point in real gameplay where this loop runs completely unthrottled (it seemed comparatively harmless/backgrounded during character creation, but became severe right after).

Didn't have live process access left to confirm directly (already killed for safety — memory was past 30GB by this point too, feeding into #639's concerns) — flagging this correlation as a strong lead for whoever picks up the NOSPACE root cause, not a confirmed fact.

zambasaurus avatar Jul 25 '26 20:07 zambasaurus

Update: found and fixed a real bug, but it's NOT the cause of this loop

Investigated sceSaveDataGetMountInfo (src/SharpEmu.Libs/SaveData/SaveDataExports.cs) since it's the one export that reports space/block stats to a title. Found a real bug there, confirmed against shadPS4's reference implementation (savedata.cpp):

struct OrbisSaveDataMountInfo { OrbisSaveDataBlocks blocks; OrbisSaveDataBlocks freeBlocks; ... };
info->freeBlocks = blocks - size / OrbisSaveDataBlockSize;  // total minus used

SharpEmu's version was writing the used block count directly into the freeBlocks slot instead of total - used — meaning a fresh, empty save directory would report zero free blocks, backwards from what it should report. Fixed to compute the actual difference.

Tested live and confirmed this does NOT fix the NOSPACE loop this issue is about. Same trace, same msgType=4 value=0x60 repeating, same call volume, completely unaffected by the fix. This is consistent with earlier research: the title never calls any sceSaveDataMount*/GetMountInfo function in this trace at all — the NOSPACE determination is coming from somewhere else entirely, not from real save-space reporting. The GetMountInfo fix is being kept as a genuine, separate bug fix on its own merits (confirmed correct against the reference implementation), but it doesn't resolve this issue.

Additional data: GPU telemetry now confirms the freeze characterization

Set up nvidia-smi-based GPU logging (scripts/gpu_monitor.ps1) for this test. During normal active rendering (character creation + cinematic), GPU utilization legitimately hits 80-100% regularly. This is a useful baseline: the earlier-reported "freeze" (FPS collapse, GPU usage dropping to near-idle) is clearly a different, distinct state from normal heavy rendering — further supporting that it's a CPU-bound stall (the vsnprintf/memcpy storm reported in the previous update), not a GPU hang.

Root cause of the NOSPACE trigger itself remains unfound. Next idea, not yet tried: trace what happens immediately before the first sys_msg_param msgType=4 appears in a fresh run, to see what the title checks right before deciding space is insufficient — that might point to a completely different subsystem (maybe not libSceSaveData at all).

zambasaurus avatar Jul 25 '26 20:07 zambasaurus

Update: found and fixed the actual root cause, though it doesn't fully unblock character creation yet.

Root cause: sceSaveDataCreateTransactionResource's DES guard (added in #480 to avoid a crash) writes a null (0) resource handle back to the title for the small-integer-as-pointer call shape Demon's Souls uses on the fresh-save path. That avoids the original crash (dereferencing a small integer handle as a pointer), but the title's own transaction logic reads the handle back and treats a null result as "resource allocation failed" - which cascades into a fallback SaveDataDialog system message, worded as NOSPACE, instead of a real free-space check. Confirmed live via tracing that sceSaveDataGetMountInfo is never even called in this path, ruling out an actual space computation - the freeBlocks bug I fixed earlier (backwards used/free) is real but unrelated to this loop.

Fix: fix/savedata-des-transaction-resource-handle writes the resource address back into itself instead of null. This keeps [handle + 8] == desWorkAddress (the title's own already-mapped work buffer, so the dereference that caused the original crash still lands in valid memory) while giving the title a non-null handle instead of a failure sentinel.

Verified live: after this fix, save_data_dialog.open is no longer called following the DES guard call (previously it fired immediately with msgType=NOSPACE value=0x60).

Not fully resolved yet: character creation still doesn't complete end-to-end. Immediately after the DES guard call now, the title enters what looks like a spin-wait - hundreds of millions of libc:vsnprintf calls with identical arguments in under a minute, no forward progress. My guess is the title is polling some completion/status flag inside the DES work buffer that a real implementation would need to populate, which we don't compute. Haven't dug into what offset/value it's waiting on yet - will file that separately if I can pin it down.

zambasaurus avatar Jul 25 '26 23:07 zambasaurus

Follow-up on the post-DES-guard spin-loop mentioned in my last comment. Added a diagnostic (dumps the vsnprintf format/rendered text and the DES work buffer content periodically during the spin) and re-tested live.

Findings:

  • The spin is calling vsnprintf(NULL, 0, "%s%d", "PlayerProfile", 0) - the standard C idiom for measuring a formatted string's length before allocating a buffer for it - hundreds of millions of times with byte-identical arguments (confirmed via sampling every 200,000th call across a call-count range from ~12M to ~34M+, all identical).
  • The DES work buffer content is completely static across this entire window - nothing ever writes to it during the spin. That rules out my earlier theory that the title is polling a completion flag inside that buffer; whatever it's waiting on isn't there.
  • Zero further libSceSaveData calls of any kind happen after the DES guard fires - no GetMountInfo, no further transaction-resource calls, nothing. So the loop is entirely internal to the title's own code, building a "PlayerProfile0"-style name (likely a save-slot/profile identifier) as a side effect of whatever it's checking on each iteration.

This looks like the same "unbounded retry with no backoff" pattern as #619, just a different call site (title-internal, not one of our HLE exports), which means it's not something a guest-side emulator fix can address the way the DES guard fix did - there's no host-implemented function here to change the return value of. Pinning down what specific condition it's waiting on would need actual disassembly of Demon's Souls' save-creation code, which is beyond what black-box tracing can resolve. Parking this here for now; the DES guard fix (PR up) is a real, confirmed improvement (false NOSPACE dialog is gone) even though it doesn't get the title all the way to a working save.

zambasaurus avatar Jul 26 '26 03:07 zambasaurus

none of those commits actually work or allow entering name, i've tried them all, not even showing in the log when i press the button to try to open the dialogue/keyboard to enter name, the dialog simply does not open or work in anyway, not showing in the log

alienwithinisolation avatar Jul 26 '26 12:07 alienwithinisolation

Re: @alienwithinisolation's report that the name-entry dialog doesn't open or log anything — I think I found why, while reading through the pinned #2 thread looking for stated priorities.

`ImeDialogExports.cs` doesn't implement a real dialog at all. `sceImeDialogInit` (`ImeDialogExports.cs:34`) immediately writes a hardcoded literal string back to the guest and marks status as `StatusFinished` in the same call:

```csharp private const string DefaultInputText = "Sharp"; ... public static int ImeDialogInit(CpuContext ctx) { ... TryWriteInputText(ctx, parameterAddress); lock (_gate) { _status = StatusFinished; } return SetReturn(ctx, 0); }


No window, no text capture, no log line — it can't "not open," because it was never going to open in the first place. It always instantly succeeds with the string "Sharp", regardless of what the player does. That's presumably why some earlier testers got *past* character creation (the guest just receives "Sharp" as the name and moves on) while for others it apparently doesn't unblock things the same way, depending on what the title does with the result afterward.

Separately: the host window (\`SdlHostWindow.cs\`) already handles some keyboard events (\`HandleKey\`, currently just debug hotkeys + keyboard-as-gamepad mapping), but there's no \`SDL_EVENT_TEXT_INPUT\` handling and no rendered text-entry UI anywhere yet — real IME support would need both. That's a genuinely bigger feature (host text capture + some on-screen rendering, cross-platform) than a quick fix, so flagging the root cause here rather than attempting it blind.

theantipopau avatar Sep 10 '26 11:09 theantipopau

Re: the `vsnprintf(NULL, 0, "%s%d", "PlayerProfile", 0)` spin — this looks like exactly the case #874 (open PR) was built for.

`vsnprintf` is one of the NIDs already classified `IsNoBlockLeafImport` in `DirectExecutionBackend.Imports.cs`, which means a tight repeat loop calling it byte-identically hundreds of millions of times will eventually trip the generic import-loop guard (`TryForceGuestExitToHostStub`) the same way a stuck `scePthreadMutexLock` loop does elsewhere. #874 adds a best-effort RBP-chain guest stack trace right at that guard's firing point — it doesn't require live debugging, just running with that PR's build.

I ran into the same wall on a different title this week (a guest-internal loop, same NID hammered with identical args, nothing visible over HLE) and #874's stack trace is what actually got me a real caller chain instead of a dead end — see #875 for the writeup, and the earlier comments on #873/#11 for how it was built and validated.

Worth a re-test with #874 applied before concluding this needs manual disassembly — it might just hand you the caller directly.

theantipopau avatar Sep 10 '26 20:09 theantipopau