sharpemu icon indicating copy to clipboard operation
sharpemu copied to clipboard

Design: per-instruction stepping for the debug server (currently frame-boundary only)

Open theantipopau opened this issue 2 months ago • 4 comments

`docs/debugger-server.md` lists per-instruction stepping as "surface only (armed as the backend grows hooks)" — the wire protocol has a `step` verb, but `DebugCommandDispatcher` routes it to `_session.StepFrame()`, which steps to the next dispatched frame (process entry / module init), not a single instruction. There's no per-instruction mechanism in the backend at all today.

What's already there:

  • `ICpuDebugFrame.Rflags` (`SharpEmu.Core/Cpu/Debugging/ICpuDebugFrame.cs`) is already read/write, and `ICpuDebugHook` is already the seam a debugger attaches through.
  • `ICpuDebugHook.cs`'s own remarks say per-instruction control is meant to be layered onto this same seam "as the backend gains support" — so the design intent already points here.

Why this needs discussion before a PR:

  • The natural implementation point is `DirectExecutionBackend.Exceptions.cs` — the native VEH exception switch that every game's execution already routes through for access violations, the BMI/SSE4a `#UD` recoveries, and TLS-fault handling. Adding trap-flag (`EFLAGS.TF`) / `STATUS_SINGLE_STEP` handling here touches the most shared, safety-critical path in the CPU backend, not a debug-only file.
  • It's genuinely cross-platform: Windows goes through this VEH file; Linux/macOS go through `DirectExecutionBackend.PosixSignals.cs`, which currently installs `SIGSEGV`/`SIGBUS`/`SIGILL` only — no `SIGTRAP`. A real implementation needs both halves to stay in sync, and needs someone who can test on Linux/macOS.
  • The CLI already logs `Running in mitigated child process (CET/CFG disabled)` at startup — there's an existing CET/CFG mitigation story around this exact execution path that a trap-flag feature needs to not interact badly with.

Proposed direction (open to other approaches): add `OnSingleStep(ICpuDebugFrame frame)` to `ICpuDebugHook`; in `DirectExecutionBackend`, set `EFLAGS.TF` before resuming when a debugger requests a step, recognize `STATUS_SINGLE_STEP` (Windows) / install and handle `SIGTRAP` (POSIX) in the existing fault-normalization path, and dispatch to the new hook method instead of treating it as a fault.

Happy to build the Windows half if that's a direction you'd take, with the POSIX side flagged as explicit follow-up for someone who can verify on Linux/macOS.

theantipopau avatar Sep 09 '26 23:09 theantipopau

Concrete real-world case that motivated filing this: Paw Patrol: Grand Prix (PPSA05521) boots into native execution and hits SharpEmu's import-loop guard after 12.5M consecutive calls to scePthreadMutexLock/Unlock (NID 9UK1vLZQft4) within the 5-second window (DefaultImportLoopGuardSeconds), on the same mutex address, from a single thread (no other thread exists yet — this fires within the first ~10 imports after guest entry).

With SHARPEMU_LOG_PTHREADS=1, every individual lock/unlock on that mutex succeeds cleanly (uncontended, recursion 0→1→0, no stuck owner) — so the pthread/mutex HLE itself isn't at fault here. Reading the guest code at both call-site return addresses and disassembling with Capstone shows the same shape at both:

call <scePthreadMutexLock/Unlock trampoline>
test eax, eax
jne <error handler>            ; matches Rust's std::sys::Mutex::lock() shape: call libc, assert or panic

followed by a hash-table probe (96-byte buckets, tzcnt-based occupancy-bitmap scan) — consistent with a lock-guarded intern/hash table (Rust hashbrown-shaped, or similar) being probed millions of times without whatever condition should stop it ever arriving.

12.5M iterations in ~5 seconds rules out "this is just a large but finite startup workload running slowly under emulation" — it's a genuine spin. But I can't tell why the awaited condition never flips without watching register/memory state change (or not) across iterations, which needs per-instruction stepping rather than a mutex-only trace. Happy to hand over the eboot/repro details if useful once a stepping mechanism exists.

theantipopau avatar Sep 10 '26 00:09 theantipopau

Follow-up after digging further into the Paw Patrol case: disassembled the full function at the lock call site end-to-end (not just the truncated view in my last comment). It's a bounded, well-formed hash-table slot operation — stack-canary check, clean `ret`, no internal branch loops back toward its own entry. So the 12.5M-repeat spin isn't inside this function; something above it in the call stack invokes it repeatedly, and that caller isn't visible from a mutex-only trace.

I also tried to get at that caller the blunt way: attached the debug server mid-spin and issued `pause`. It didn't interrupt the live native execution — it silently deferred until the next frame boundary (a different module initializer entirely), because the whole spin happens inside one dispatched frame.

Worth calling out explicitly: this means the gap isn't only "no per-instruction granularity" — there's currently no way to interrupt a long-running native frame at all once it's dispatched, single-step or otherwise. Whatever mechanism ends up handling single-step (trap flag + the fault-normalization path discussed above) would need to double as a genuine async-pause trigger too, not just a step primitive, or a case like this stays undebuggable even with stepping added.

theantipopau avatar Sep 10 '26 00:09 theantipopau

Follow-up: looked at how RPCSX (the other active PS5 emulator, GPL-2.0, derived from RPCS3) handles this, since it's a genuinely comparable in-process direct-execution design (their `rx::thread` uses host `ucontext_t`/`mcontext_t` signal-handler bridging for guest x86-64 execution, same fundamental shape as `DirectExecutionBackend`) — worth being upfront that my first guess here (that they get single-stepping for free via Linux `ptrace` over a separate guest process) was wrong. Checked: `orbis::sys_ptrace()` in their kernel/orbis layer is a stub that returns `NOSYS` — that's them handling a guest game's own attempt to call PS4/PS5's ptrace syscall, unimplemented, not a debugging mechanism of theirs.

What they do have, and what's directly relevant here: `rx::printStackTrace(ucontext_t *context, orbis::Thread thread, int fileno)` (`rx/include/rx/backtrace.hpp`) — a guest-native call-stack walker driven off a captured host context. SharpEmu has no equivalent; the only "stack trace" hits in `DirectExecutionBackend.cs` are managed .NET exception traces (`ex.StackTrace`), not a walker over the guest's x86-64 stack.

That's a smaller, lower-risk, independently-useful piece of work compared to full single-stepping: it only needs to read memory once at an existing snapshot point (e.g. `LogStallWatchdogSnapshot`, which already dumps registers and raw `[rsp]`/`[rsp+8]` words when the stall watchdog fires) rather than interrupting live execution. A best-effort RBP-chain walk at that same snapshot point would have let us identify the actual caller in the Paw Patrol case instead of hitting a dead end trying to statically scan the binary for it. Happy to take a shot at this piece specifically, separate from the bigger single-step/interrupt design above, if that split makes sense.

theantipopau avatar Sep 10 '26 02:09 theantipopau

Built the smaller piece I proposed above: #874 adds a best-effort RBP-chain guest stack walk to both the stall watchdog and the import-loop guard's existing diagnostic snapshots.

Validated it against the actual Paw Patrol case from earlier in this thread. Before: the import-loop guard's log gave the repeated NID and a 64-entry ring-buffer trace, no caller context. After:

``` [LOADER][ERROR] Import-loop guest stack (rbp-chain, best-effort): 0x0000000800047DEB <- 0x0000000800047AC3 <- 0x0000000800052717 <- 0x0000000800000064 <- 0x00000008000000A2 <- 0x000001B7A9980000 ```

That's a real, non-trivial guest call chain, landing a few frames above the guest entry point (`0x0000000800000070`) — exactly the caller context that an hour of manual disassembly and static-scanning the 86MB code segment (described further up this thread) failed to find. This doesn't replace the single-step/interrupt design being discussed above — it's frame-pointer-only and only answers "who called this" at an existing snapshot point, not "what changed between iterations" — but it directly unblocks cases like this one without needing the bigger VEH/signal work first.

theantipopau avatar Sep 10 '26 02:09 theantipopau