Files
psxrecomp/tools/_options_session/_dbg.py
T
Matthew Stanley fdbd2b515f runtime: cross-fiber longjmp fix + decouple vblank-present from MMIO read
Two distinct bugs were causing OPTIONS-black hard freezes after 12K-65K
frames:

1. interrupts.c + traps.c: exception_jmpbuf is a single global. setjmp
   captures the running fiber, but longjmp may be requested from a
   different fiber via psx_exception_longjmp / psx_restore_state_escape
   during chain-handler dispatch. Cross-fiber longjmp restores RSP to
   the wrong stack while Win32 still tracks the calling fiber, corrupting
   fiber state until SwitchToFiber eventually hangs.

   Fix: track g_exception_owner_fiber at setjmp time. New
   deferred_exception_longjmp checks the current fiber; if it's not the
   owner, sets a pending flag and SwitchToFiber's back to the owner.
   psx_change_thread_fiber's post-SwitchToFiber path observes the flag
   and executes the longjmp on the correct stack.

2. gpu.c: gpu_read_gpustat fired gpu_vblank_tick() after 1000 polls,
   which invoked sdl_vblank_present (SDL_Delay -> Sleep) from inside
   an MMIO read code path. That meant recompiled MIPS spent wall time
   in Sleep deep inside the fiber call tree -- confusing to reason
   about and a contributor to fiber/longjmp interactions.

   Fix: synthetic VBLANK from a poll-storm only updates emulation state
   (LCF + I_STAT). The host-side render+sleep happens only at the proper
   cycle-paced VBLANK trigger in psx_check_interrupts.

Also adds: dirty_block ring slice to the freeze auto-dump, Win32 main-
thread stack capture for wedge_kind=1 hard freezes (SuspendThread +
StackWalk64 + SymFromAddr), and dbghelp link.

Validated: TombaRecomp psx-runtime ran 30+ minutes / 105K+ frames at
OPTIONS with no hard freeze. Previous freezes consistently hit at
11900, 20493, and 64596 frames.

Diagnostic tooling under tools/_options_session/ that produced this
diagnosis is included.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 12:49:13 -07:00

87 lines
2.5 KiB
Python

"""Tiny TCP-debug-server client used by the OPTIONS-black session.
Single source of truth for talking to:
- psx-runtime (TombaRecomp build) on port 4470
- psx-beetle on port 4380
No game-specific knowledge here. Just request/response and command-name
adapters so the rest of the session scripts read the same way against
either backend, even though the wire verbs differ
(e.g. wtrace_add vs wtrace_arm).
"""
from __future__ import annotations
import json, socket, sys, time
RUNTIME_PORT = 4470
BEETLE_PORT = 4380
def call(port: int, cmd: str, timeout: float = 30.0, **kw):
payload = {"id": 1, "cmd": cmd, **kw}
s = socket.create_connection(("127.0.0.1", port), timeout=timeout)
try:
s.sendall((json.dumps(payload) + "\n").encode())
buf = bytearray()
while not buf.endswith(b"\n"):
chunk = s.recv(1 << 20)
if not chunk:
break
buf.extend(chunk)
finally:
s.close()
return json.loads(buf.decode("utf-8", "replace").strip() or "{}")
def hx(v):
if isinstance(v, int):
return v
if isinstance(v, str):
return int(v, 16) if v.lower().startswith("0x") else int(v)
return v
def read_word(port: int, addr: int) -> int:
"""Little-endian word read at addr via read_ram."""
r = call(port, "read_ram", addr=f"0x{addr:08X}", len=4)
if not r.get("ok"):
raise RuntimeError(f"read_ram failed at 0x{addr:08X}: {r}")
b = bytes.fromhex(r["hex"])
return int.from_bytes(b, "little")
def read_block(port: int, addr: int, n: int) -> bytes:
out = bytearray()
off = 0
while off < n:
chunk = min(0x40000, n - off)
r = call(port, "read_ram", addr=f"0x{addr+off:08X}", len=chunk)
if not r.get("ok"):
raise RuntimeError(f"read_ram failed at 0x{addr+off:08X}: {r}")
out.extend(bytes.fromhex(r["hex"]))
off += chunk
return bytes(out)
def ping_both():
out = {}
for name, port in [("runtime", RUNTIME_PORT), ("beetle", BEETLE_PORT)]:
try:
out[name] = call(port, "ping", timeout=3)
except Exception as e:
out[name] = {"error": str(e)}
return out
if __name__ == "__main__":
if len(sys.argv) == 1 or sys.argv[1] == "ping":
for k, v in ping_both().items():
print(f"{k:8} {v}")
sys.exit(0)
cmd = sys.argv[1]
port = int(sys.argv[2])
args = {}
for a in sys.argv[3:]:
k, _, v = a.partition("=")
args[k] = v
print(json.dumps(call(port, cmd, **args), indent=2))