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>
The actual fix for TombaRecomp/ISSUES.md #6 ("Not Responding"
freezes). Earlier claim that SDL_RENDERER_SOFTWARE fixed it
(commit 9eb4ab3) was wrong — based on a too-short stress test
that didn't reach the freeze threshold. The corrected story:
1. SDL_RENDERER_ACCELERATED → froze.
2. SDL_RENDERER_SOFTWARE (Windows GDI backend) → still froze.
3. SDL_HINT_RENDER_DRIVER=opengl + ACCELERATED → no freeze
after 11+ min / 40k+ frames, well past every prior failure.
Why it intermittently triggered: the FMV-speed fix (b486c13)
raised guest cycle throughput, which raised the GDI present
rate enough to trip the underlying Windows GDI hang. Before
that fix the workload stayed below threshold.
Three changes in this commit:
* runtime/src/main.cpp + runtime/src/beetle_main.cpp:
switch from SDL_RENDERER_SOFTWARE to OpenGL via
SDL_SetHint(SDL_HINT_RENDER_DRIVER, "opengl").
* runtime/src/main.cpp: PSX_SDL_NO_AUDIO and PSX_SDL_NO_RENDER
compile-flag guards added for bisection. Pass via -DCMAKE_C_FLAGS
when needed; default behavior is unchanged.
* runtime/src/freeze_heartbeat.c:
- Always-on regardless of PSX_NO_DEBUG_TOOLS. This thread
was the key diagnostic — it survives main-thread stalls
because it runs in its own thread, so its ring captures
pre-freeze state when the TCP server can't respond.
- Added a 64-entry pre-freeze history ring (~6 s window)
to the heartbeat JSON. Each entry snapshots frame_count,
psx_cycle_count, exc_reentry_blocks, dirty_ram_insns,
current_func, last_store_pc, i_stat, sio_stat/ctrl,
in_exception, mc_max_state. When all those columns stop
advancing while wall_clock keeps ticking, that's the
stall point. This signal proved the freeze is in HOST
code (not guest), which redirected the investigation
from "fix the recomp" to "fix the SDL/Windows path."
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two observability additions, both gated by the new
-DPSX_DEBUG_TOOLS=OFF flag for production builds.
1. Freeze heartbeat thread (`runtime/src/freeze_heartbeat.c`):
Background thread spawned at startup that snapshots runtime
state (frame_count, psx_cycle_count, in_exception, exception
counters, sio/mc state, i_stat/i_mask, dirty_ram counters) to
`psx_freeze_heartbeat.json` every 100 ms. Survives main-thread
freezes — writer is independent of the SDL loop and the TCP
debug server. Atomic file replace via .tmp + MoveFileEx so a
reader never catches a half-written JSON.
Already paid off: captured a freeze pattern (frame_count stuck,
psx_cycle_count stuck, in_exception=0, current_func in
install-stub kernel code) that the TCP server couldn't show
because its accept queue was wedged by the same stalled main
thread.
2. PSX_DEBUG_TOOLS CMake flag (`runtime/runtime.cmake`):
- Default ON: builds with the TCP debug server, heartbeat
thread, and per-block recording (debug_server_log_call_entry
fires for every recompiled function entry).
- OFF (`cmake -DPSX_DEBUG_TOOLS=OFF`): production build. The
hot-path log functions early-return; TCP server doesn't
start; heartbeat doesn't spawn. The ring buffer arrays still
exist in the binary (their definitions live in
debug_server.c) but no writes happen so the demand-paged
memory stays committed at a much lower level (~77 MB at
idle vs ~245 MB in debug mode).
The flag propagates to psx-beetle via the option declared at
the top of runtime.cmake.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Pure observability change — not a fix claim.
Both psx-runtime (was 1) and psx-beetle (was 4) had small accept-
queue backlogs. When the SDL main thread stalls (the exact state
we want to probe during a freeze investigation), the kernel
queues the first pending connect and rejects subsequent attempts
with RST. From the client side this looks like ConnectionRefused,
making it impossible to diagnose the stalled process from another
shell.
Backlog 16 lets a handful of probes queue up. Main thread will
eventually accept them in order if it ever resumes. If the
main thread is permanently dead the probes still fail, but at
least the failure mode changes from "looks like the server is
gone" to "the queue is genuinely deep + still stalled."
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
NES recomp template PRINCIPLES.md §13a calls a dispatch miss a
"SILENT GAME-BREAKING BUG" and mandates checking
`dispatch_misses.log` after every game run. We don't write that log
(no log files per CLAUDE.md §3) — we have an in-memory ring +
`unknown_dispatch_log` TCP command instead. But nothing routinely
surfaces the count, so silent misses can accumulate across sessions
unnoticed.
Now `ping` includes `dispatch_miss_total` and `dispatch_miss_unique`
fields. Every routine health check reveals if discovery has gaps.
0 = healthy. Non-zero on any session = stop and add the addresses
to game.toml / regen before continuing.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Tomba's `ResetGraph` (FUN_8005E694 at 0x8005E694) calls
`FUN_80061620` to autodetect the GPU video mode. That function
writes `GP1(0x10000007)` ("Get GPU info", subcommand 7 = GPU
version) and reads back GPUREAD; if the low 24 bits equal 2 it
returns 3 (the byte stored at `0x80090C9C`).
Our `gp1_get_info` was treating subcommand 7 as "leave latch
unchanged" (a misleading DuckStation-derived note in the source).
So GPUREAD held stale junk, the `== 2` check failed, and
`0x80090C9C` ended up 0 instead of 3 — landing the OPTIONS draw
code on a no-draw config table entry that produces 11 GP0 commands
per frame with zero draw primitives.
Mednafen-psx (`beetle-psx/mednafen/psx/gpu.cpp:1212`) returns 2
hardcoded for subcommand 7 — that's the GPU-version constant real
hardware returns. We now do the same, plus subcommand 8 = 0 (also
matches mednafen), and mask the subcommand with `& 0x0F` instead of
`& 0x07` to match mednafen's decode.
Verified: runtime's `0x80090C9C` now reads `0x03` at boot,
matching beetle. OPTIONS UI is still black so more downstream
divergences remain — but this is a real root cause and a step
forward.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The SDL accelerated renderer (`SDL_RENDERER_ACCELERATED`) lets
`SDL_RenderPresent` block inside the GPU driver, which has been
reproducibly hanging the SDL main thread mid-frame after extended
uptime. Both psx-runtime and psx-beetle showed the same signature:
process alive, debug socket dead, partial framebuffer (top half
rendered, bottom half stale) — a classic GPU-driver-side hang.
Switching both binaries to `SDL_RENDERER_SOFTWARE` removes the GPU
driver from the path. Verified under stress: five consecutive
`wtrace_dump count=200000` (~6.2 s each, 31 s cumulative
main-thread block) without a single freeze. Beetle, which had been
freezing at ~15 min of plain title-screen idle with constant 90 MB
RSS (so memory pressure was definitively not the cause), now stays
responsive indefinitely.
Cost: a few percent more CPU. Worth it.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
psx-beetle previously hard-coded "dummy.cue" in the BIOS system dir
and ejected the disc on init so the BIOS booted to its shell. That
covered BIOS-only testing but not "what should this game look like at
this frame" comparisons against psx-runtime.
Add `beetle_init_with_disc(bios_path, disc_path)`: if disc_path is
non-NULL, retro_load_game() loads that real disc and the disc stays
inserted (BIOS proceeds straight into game boot). NULL keeps the
existing dummy-cue + eject behavior. beetle_init() is now a wrapper
preserving the old signature.
beetle_main.cpp learns `--disc <path>` CLI flag.
Verified: `psx-beetle.exe bios/SCPH1001.BIN --disc tomba.cue` boots
Tomba through the SCEA splash on the SDL window. Debug server on port
4380 responds (ping returns frame counter), so the same wire protocol
that psx-runtime exposes on 4470 is now available for side-by-side
state comparison while both binaries run the same game.
Use case driving this: Issue #5 OPTIONS-black SIO protocol divergence
diagnosis — need beetle as authoritative reference for what bytes the
card should send Tomba.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
VBlank firing in psx_check_interrupts was gated on dispatch_count
(block-dispatch count, ~5-6 cycles each), not on guest cycles.
50000 dispatches ≈ 289k cycles per VBlank, vs real PSX 564480
cycles per VBlank. Effect: game-internal time ran at ~51% of real
PSX rate, breaking every cycle-paced game flow including FMV.
This was the root cause of TombaRecomp ISSUES.md #4 — FMV played
at 6.7 fps because Tomba's FMV state machine is driven by DMA Ch1
(MDEC-out done) IRQ, which in turn fires once per full FMV-frame
pipeline iteration, which is bounded by cycle-paced steps
(CDROM sector ready, MDEC decode "complete", DMA transfer).
At 51% guest-time rate, a Tomba-designed 15-fps FMV becomes 7-8 fps.
Fix:
- New VBLANK_CYCLES = 564480 (33.8688 MHz / 60 Hz NTSC).
- Add interrupts_advance_cycles(cycles) called from
psx_advance_cycles() so the cycle counter for VBlank gating
tracks emitted guest cycles.
- Change the trigger from `dispatch_count >= VBLANK_INTERVAL` to
`cycles_since_vblank >= VBLANK_CYCLES`.
- On VBlank fire, subtract one period (not reset to 0) so cycle
overshoot from long blocks carries forward.
- dispatch_count is kept for the SIO card-protocol stale check —
that uses total_checks, which is the real load-bearing field
there, dispatch_count itself is now incidental.
Verified:
- Cycles/VBlank: 289k -> 564k (exactly VBLANK_CYCLES).
- Cycles/sec: 20.6 M -> 41 M (121% of real PSX; slight wall-clock
overshoot to investigate, but game-internal pacing now correct).
- FMV decode rate: 0.111 -> 0.250 decodes/VBlank = 15.0 fps exactly,
matching Tomba's designed FMV rate.
- Measured via tools/_mdec_pace.py.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Per CLAUDE.md global rule #2 (and direct user instruction): pause-and-
inspect is the wrong observation primitive for this codebase. It
synthesizes a snapshot at probe time rather than reading the system's
own continuously-recorded history. It also accidentally became a
freeze vector — a Python client that sent `pause` without `continue`
left s_paused=1 with no client to clear it, so the runtime spun in
debug_server_wait_if_paused forever and looked frozen.
Replacement is the ring buffers that already exist:
- fn_entry_dump / fn_entry_tail what code ran
- wtrace_dump what memory was written
- gpu_frame_dump frame=N what GP0 commands were issued
- mdec_trace MDEC events
- sio_trace / sio_pc_trace SIO history
- frame_range / get_frame per-frame state snapshots
Changes:
- handle_pause, handle_continue, handle_step, handle_run_to_frame
now return send_err with a migration message pointing at the
appropriate ring. The state variables (s_paused, s_step_count,
s_run_to) stay declared and zero-valued so freeze_check fields keep
reporting them as 0 (protocol stability).
- debug_server_wait_if_paused is now a no-op (kept exported so
main.cpp's vblank callback stays unchanged).
- The post-frame `if (s_step_count > 0)` / `if (s_run_to > 0)` hooks
are gated behind `if (0)` — dead code, kept as a comment marker.
- debug_server_dirty_break_maybe_pause no longer sets s_paused; it
still records the hit (target, ra, regs, sp, frame) so
dirty_break_state can be queried for the latest event.
- Reverted the client-disconnect auto-clear-of-pause logic added in
40e9b79 — no longer needed, pause is gone.
Verified: pause/step/continue all return the migration error,
frame_count advances steadily (~50 fps) for 30 seconds, no freeze.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Root cause of the apparent "freeze" observed after issuing debug
commands: tools/_dbg.py and similar one-shot Python clients open a
fresh TCP connection per command, send their request, read the reply,
then close. If the command was `pause` or `step`, the runtime is left
with s_paused=1 and no client to issue `continue`. The runtime then
spins in debug_server_wait_if_paused() forever — SDL window stops
updating, frame counter stuck — and the user reads this as "frozen"
even though the process is healthy.
The legitimate "open a persistent connection, pause, investigate,
continue" workflow keeps the socket open across all of that, so the
disconnect-then-clear behavior doesn't affect it.
Fix: when the client disconnects, clear s_paused / s_step_count /
s_run_to. Verified by sending pause via _dbg.py and watching the
frame counter keep advancing on the next freeze_check query.
Visibility: freeze_check now reports frame_count, paused, step_count,
run_to, client_connected. A "frozen" state can now be classified
without guessing — paused=1 = leftover-pause, paused=0 + frame_count
stuck = real game-loop wedge.
Ring cap reductions:
- WRITE_TRACE_CAP 4M -> 256K (-360 MB worst-case)
- SIO_PC_TRACE_CAP 4M -> 256K
- MMIO_TRACE_CAP 4M -> 256K
- FN_TRACE_CAP 1M -> 256K
- FN_EXIT_TRACE_CAP 4M -> 256K
At 60Hz and ~thousand events/frame each ring still covers ~4 sec —
plenty for the diagnostic flows we actually run. Worst-case runtime
RSS drops from ~1 GB potential to ~100 MB.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Replace the O(N^3) reference IDCT in idct_block (1024 multiplies per
8x8 block) with FFmpeg's simple_idct butterfly decomposition (~64
multiplies per block). Both row and column passes ported to produce
int16_t output so the rest of mdec.c (to_output_u8,
append_color_macroblock, append_luma_block) keeps working unchanged.
Source: FFmpeg libavcodec/simple_idct_template.c (BIT_DEPTH=8),
LGPL-2.1+. Previously imported into legacy runner/src/fmv_player.cpp
on the legacy-2026-05-11 branch; salvaged into v4's hardware-emulated
MDEC path. Attribution preserved in the source comment.
Side effect: the new IDCT computes cosines from the W1..W7 constants
directly and no longer depends on mdec.scale. The prior implementation
treated SET_SCALE input as the cosine matrix; real PSX hardware ignores
SET_SCALE for IDCT (it only seeds the dequant tables), so the new code
matches hardware more closely as well.
Verified visually: Tomba boots through Sony splash + Whoopee Camp FMV;
intro FMV reaches the mountain-valley scene with correct colors. No
visual regression vs the prior implementation.
This addresses one piece of TombaRecomp ISSUES.md #3.D / FMV-speed
goal. Whether the IDCT was the actual FMV bottleneck still needs an
A/B timing test; this is a clean CPU win regardless.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Always-on ring captures every GP0 command (header + first 6 payload
words) stamped with the frame number issued. Hooked at
gp0_execute_command() for fixed-length commands and at the polyline
start path for variable-length ones. ~70 MB at 1 048 576 entries
(34 bytes/entry); lazy-allocated on first record.
New debug-server commands:
- gpu_ring_stats: total/capacity/oldest+newest frame in buffer
- gpu_frame_dump frame=N count=M: per-frame GP0 entries with raw words
Designed per CLAUDE.md ring-buffer rule (CLAUDE.md global #2):
capture is continuous; observers query a window of interest
post-hoc. No arming, no timed attach.
Use case driving this: fuzzy menu text bug on Tomba title screen
(TombaRecomp ISSUES.md #3 'D'). Lifetime opcode counts couldn't
distinguish which 0x64/0x2C calls draw the menu vs the static
text. With per-frame dump we can now show that frame N has 88 GP0
commands and isolate the 6 0x2C entries that render with degenerate
top-right vertices (= the fuzzy text).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- Config loader (recompiler/src/config_loader.{h,cpp}): single source of
truth for both BIOS and game runtime settings (debug_port, window_title,
memcard_dir, disc path). psxrecomp-bios and psxrecomp-game both accept
--config <toml>; runtime takes --game <toml> (no more CLI overrides).
- runtime/src/main.cpp: replaced --disc/--memcard-dir/--game-root CLI
overrides with --game <toml>; game.toml is the single source of truth.
Discless launch (no args) goes to BIOS shell.
- runtime/src/dma.c: fixed update_master_irq() re-asserting I_STAT bit 3
on every DICR read. BIOS shell DMA handler at 0x80058628 only clears
DICR bit 27 (ch3 flag), so level-sensitive re-assert pinned the kernel
in the exception loop. Bit 3 is now edge-triggered (one assert per DMA
completion). Discless boot now reaches MAIN MENU / MEMORY CARD / CD
PLAYER. With-disc Tomba boots through to Whoopee Camp splash.
- Audit tooling: codegen_audit.py (BIOS), codegen_audit_game.py (game),
audit_config.py (config loader for tools), verify_audit_schema.py.
Replaces older tools/_codegen_audit.py probe.
- Docs: CURRENT_STATE.md (project state), UNIFICATION_PLAN.md (Phase C
translator merge plan), docs/config_schema.md (TOML schema reference),
docs/audit_inventory.md (audit tier inventory).
- .gitignore: tools/_*.py convention for ad-hoc scratch probes.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Recompiler: register jump-table targets with the cross-function
continuation pass before filtering local goto labels — BIOS jump
tables can legally branch into another discovered function's body,
so the prior local-only check dropped valid emit-side edges.
Dirty-RAM interpreter:
- Dispatch non-local JAL/JALR targets back through psx_dispatch_call
instead of forcing them into the interpreter when the target sits
in static-recompiled code (only targets in dirty pages stay local).
- New always-on flow + per-instruction ring buffers (insn_log,
flow_log) capturing reg state, current_tcb, and task fields for
post-hoc analysis. Block log gains t0/t1/t2.
- guard_yields counter; richer last_unsupported state (entry PC,
entry RA/SP, insn count) for dead-end diagnosis.
SIO: ACK is now visible across a small read window (2 STAT reads)
matching BIOS poll patterns that re-read STAT after CTRL_ACK clears
IRQ but expect ACK to still latch. Per-channel ack_irq_en captured
at shift start so a CTRL write that disables ACK_IRQ_EN mid-shift
doesn't suppress the firing. sio_init now zeros all paced-model
state. Read/write paths poll the debug server every ~1k accesses
so long pad/card spins don't starve diagnostics.
Memcard: auto-format slot files on first init when missing, so
the BIOS shell sees a present-but-empty card instead of "no card".
Runtime main: SDL nearest-neighbor texture scaling (no bilinear
blur on the integer-scaled framebuffer).
Debug server: large expansion of ring-buffer queries and dump
commands feeding the new insn/flow logs.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adapted from SuperMarioWorldRecomp's release.yml. Triggers on tag push
(v*) and workflow_dispatch. Builds psx-runtime in Release on
windows-latest under MSYS2 mingw64, stages the exe + SDL2 + mingw
runtime DLLs + LICENSE + a release README + bios/saves placeholders,
zips as psxrecomp-v2-windows-x64.zip, and attaches it to a GitHub
Release on tag builds.
Caveat: the recompiler step needs a real BIOS to operate on, which CI
does not have. The current workflow is a scaffold — it builds the
runtime artefact correctly but the recompile step will fail unless
the BIOS is supplied via a secret or a separate ingest step. Wire up
end-to-end before relying on tag builds.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Replaces the Phase-1-internal milestone notes with a user-facing README
suitable for the GitHub repo's new role: in-place v2 of mstan/psxrecomp.
Calls out explicitly:
- CD-ROM / disc-based game loading is untested and likely non-functional
in psx-runtime today. BIOS-only memcard management is the supported
use case.
- MDEC video decode is slow / partial.
- SPU/GPU/GTE coverage is partial.
Includes setup (release binary path + build-from-source path), keyboard
map, memcard-management walkthrough, and v1 reference (legacy-2026-05-11
branch).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The `generated/` tree contains C and JSON produced by the recompiler from
SCPH1001.BIN — derivative of copyrighted Sony BIOS code. It is regenerated
from a user-supplied BIOS on local build; not committed.
Mirrors the convention used by nesrecomp and snesrecomp.
Also covers release-stage/ and *.zip so local release packaging artifacts
stay out of the tree.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Matches the license used by the v1 repo. Copyright preserved as
'2026 Matthew Stan'.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Vendored rabbitizer ships with Python bindings, Rust bindings, an
upstream Makefile, packaging files, docs, tests, and an upstream
changelog. Our CMake build consumes only the C/C++ sources, headers,
and instruction tables:
recompiler/lib/rabbitizer/
include/ (kept — C headers)
cplusplus/ (kept — C++ headers + sources)
src/ (kept — C sources)
tables/ (kept — instruction tables)
LICENSE (kept — MIT requires the copyright notice)
Everything else is upstream project scaffolding that has never been
referenced by our build. Removed:
CHANGELOG.md, README.md, Cargo.toml, Makefile, MANIFEST.in,
pyproject.toml, setup.py
docs/ (upstream usage docs + GTE macros)
tests/ (upstream's own test suite)
rust/ (Rust language bindings)
rabbitizer/ (Python language bindings + .pyi stubs)
MIT obligations remain satisfied: the LICENSE file with the
Decompollaborate copyright notice is unchanged. No source files,
headers, or instruction tables were touched.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Recompiler — `recompiler/src/function_analysis.cpp` now stops a
function's end_addr at its mapped `jr $ra` + delay slot instead of
stretching through trailing data. Fixes Tomba's 0x80076DB0, a real
136-byte function that was being emitted as a psx_unknown_dispatch
stub because data after it poisoned the boundary heuristic.
`code_generator.cpp` emits `func_<next>(cpu); return;` as a tail
call when a mid-function seed split leaves the physical fall-through
in a different C function, plus a `debug_server_log_call_entry` at
every function entry. `full_function_emitter.cpp` splits dispatch
into `psx_dispatch_impl(cpu, addr, stop_addr)` with public
`psx_dispatch` and new `psx_dispatch_call(cpu, addr, return_addr)`
so JAL/JALR into RAM stubs can return cleanly without growing the
native stack.
Runtime — `runtime/src/dma.c`/`include/dma.h`/`src/memory.c` now
expose `dma_write_masked()`; the 16-bit and 8-bit mmio paths route
DICR/DPCR/CHCR partial writes through it so a partial DICR write no
longer accidentally clears unrelated channels' pending IRQ flags,
and CHCR only triggers DMA when the written mask actually includes
the start bit. Unified `complete_transfer(ch)` across all channels,
removed `prev_master_flag` edge detection.
MDEC (`runtime/src/mdec.c`, `include/mdec.h`) gains a full debug
surface: `MDECDebugState` snapshot, an always-on 4096-entry
`MDECDebugEvent` ring with 11 event kinds (reset, ctrl_write,
cmd_begin/done, decode_done, dma_in/out start/end, output_drained,
read_underflow), and `mdec_state` / `mdec_trace` / `mdec_trace_clear`
debug-server commands. DMA ch0/1 emit start/end events around MDEC
transfers.
CDROM (`runtime/src/cdrom.c`, `include/cdrom.h`) — read stream
separated from one-shot pending state (`read_cmd`, `read_delay`,
`start_read_stream`, `stop_read_stream`, `deliver_read_sector`);
`cdrom_state`/`cdrom_trace` report the new fields.
Thread/fiber tracing — `traps.c`'s Win32-fiber TCB save/restore now
emits 12 thread-event kinds; new `ThreadTraceEntry` ring (64 K) plus
`thread_trace` / `thread_trace_clear` debug-server commands report
both live CPU regs and the target TCB's full saved register block.
wtrace / mmio rings — `WriteTraceEntry` grew (cpu_pc, sp, v0/v1/a0-a3/
t0/t1); capacity 1 M -> 4 M. `MmioTraceEntry` grew (pc, cpu_pc, sp,
a0-a3, sr, epc, i_stat, i_mask). Both dump commands accept
`count`/`newest=1` for reverse iteration. `restore_trace` and
`dirty_block_log` emit extended register fields (a2/a3/sp).
Misc — `interrupts.c` polls debug-server every 16K checks so it
stays responsive without a separate thread. `psx_runtime.h`'s
`call_by_address` routes through `psx_dispatch_call`. Dirty-RAM
interp JAL/JALR consult `psx_dispatch_game_compiled` when the game
is wired in. iso_reader gains the entry points needed by the game
disc path. New `tools/_tomba_probe.py` for port-4470 health checks.
Generated — regenerated `SCPH1001_dispatch.c` against the new
`psx_dispatch_impl` shape.
ISSUES.md — opened Issue #3 (BIOS PS-logo glyph missing on the
disc-detected screen, cosmetic).
.gitignore — added `recompiler/build-asan*/`, `build-checked/`,
`__pycache__/`.
Validated end-to-end: BIOS boots, disc detected, Whoopee Camp FMV
plays with audio. Frame count advances through ~40K frames without
freezes. `unknown_dispatch_log.total = 0`. Remaining FMV cluster
issues (1/4-size render, FMV-2 audio missing, no skip) tracked
under TombaRecomp/ISSUES.md.
Co-Authored-By: Codex (OpenAI) <noreply@openai.com>
traps.c — ThreadWaitFrame setjmp stack plus a Win32-fiber-based
HostThreadFiber pool for BIOS thread context switches. TCB save/restore
maps SR low-4-bits → low-6-bits via the standard PSX exception entry
shift. Backs the BIOS OpenTh/ChangeTh/ReturnFromException paths that
the kernel uses to schedule its own threads on top of the recompiled
exception handler.
debug_server.c — new TCP commands:
- cdrom_state: snapshot of index/stat/irq regs, FIFOs, pending cmd,
seek/read MSF, i_stat.
- cdrom_trace: paginated dump of the cdrom_trace ring (kind/addr/val/
func/pc/frame + state snapshot per entry).
- dirty_ram_unsupported: counts and last PC/insn/reason for opcodes
the dirty-RAM interpreter rejected.
- dirty_ram_stats now also exports the full bitmap as
dirty_bitmap_words[] (matches the bitmap promotion in this branch).
Both surfaces are query-only against always-on ring buffers, no
log files or stderr emission — consistent with the
no-stdio-debug rule.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
New runtime/src/mdec.c + runtime/include/mdec.h: MDEC register port
and DMA word ports. Reads command stream from DMA channel 0 (in);
emits decoded macroblocks via DMA channel 1 (out). mdec_init wired
into main.cpp init sequence.
dma.c — execute_ch0_mdec_in and execute_ch1_mdec_out implementations
for MDEC pipes. transfer_word_count handles sync mode 1 block-count
form (BCR upper half * BCR lower half) plus default block size.
complete_transfer(ch) clears active/start bits and raises DICR + i_stat
bit 3. Channels 2/3/4 still default.
memory.c — dirty-RAM bitmap promoted from u32 (16-page kernel-only) to
DIRTY_RAM_BITMAP_WORDS covering all 2 MB RAM. CD-ROM DMA flags overlay
load ranges via new dirty_ram_mark_executable_range(phys, len), without
treating arbitrary data writes as executable. CPU writes still only
mark the kernel-RAM code region (0..0xFFFF) as before.
dirty_ram_interp.c — opcode coverage extended for game-side install
stubs: MFHI/MTHI/MFLO/MTLO/COP0 MFC0/MTC0/RFE. Add
psx_dispatch_game_compiled hook gated on PSX_HAS_GAME_DISPATCH so
recompiled game EXE entries can take precedence over interpretation
on RAM PCs that are also covered by static codegen.
dirty_ram_interp.h — expose dirty_ram_get_bitmap_word(i) +
_word_count, dirty_ram_mark_executable_range, and the
last_unsupported_pc/insn/reason for the debug_server query landed
in a later commit.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
timers.c — timers_advance(cycles) replaces per-frame timers_tick().
Per-timer fractional accumulator + proper divisors:
- Timer 0 dotclock approx (cycles/5)
- Timer 1 HBlank clock (cycles/2146, ~263 HBlanks per NTSC frame)
- Timer 2 SYSCLK or SYSCLK/8 per mode register bit 8..9
Target/overflow flags fire IRQ when bit 4/5 of mode is set.
cdrom.c — cdrom_advance(cycles) replaces per-frame cdrom_tick().
Sector pacing from CPU clock: 451584 cycles at 1x, 225792 at 2x
(SetMode bit 7). Whole-sector mode bit 5 prepends a 12-byte BCD-MSF
header to the data buffer; SECTOR_BUFFER_SIZE = 12 + 2048.
cdrom_trace ring: always-on CDROMTraceEntry[1<<16] capturing every
register write, IRQ raise/mask, sector load, and command dispatch
with the current func/PC/frame snapshot. Query via the new
debug_server commands landed in a later commit.
psx_cycles.c — psx_advance_cycles now drives cdrom_advance and
timers_advance in addition to sio_advance.
interrupts.c — legacy per-frame timers_tick + cdrom_tick now gated
behind #ifndef PSX_ENABLE_BLOCK_CYCLES, so block-cycle builds use
the cycle-paced path exclusively.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Extend psxrecomp_v4_add_runtime_target():
- SDL2 discovery via MSVC dev-pkg layout (sdl2-msvc/SDL2-*) or pkg-config
next to the C compiler on mingw. Centralizes what was inline in
runtime/CMakeLists.txt before the runtime-as-library refactor.
- Track PSXRT_GAME_GENERATED_FULL_C / DISPATCH_C and emit
PSX_HAS_GAME_DISPATCH=1 when a game-EXE codegen output is wired in.
- Register runtime/src/mdec.c as a default runtime source.
New runtime/include/psx_runtime.h: call_by_address(cpu, addr) thin
wrapper over psx_dispatch — call site that generated game-EXE code
will use for indirect jumps after psxrecomp-game emits.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Add 3 dispatch_miss seeds for Tomba boot path:
- 0xBFC04910: BIOS init routine (0xBFC048D0..0xBFC04ABC, ret at 0xBFC04A98)
- 0xBFC04850: BIOS callback-list init (0xBFC0472C..0xBFC048D0, ret at 0xBFC048C8)
- 0xBFC079F8: tiny BIOS table-leaf (sw a0,0(sp); jr ra; clear v0)
Retire 4 prior BANDAID seeds covered by the new state-continuation pass
and dispatch-miss heuristics:
- 0xBFC02918 card_copy_dispatch_miss
- 0xBFC09890 card_cmd_is_not_read
- 0xBFC0989C card_cmd_is_not_write
- 0xBFC1A1BC modal_stub_dispatch_miss
Validated by re-running BIOS shell with full suite of memcard ops
(COPY ALL, DELETE, persist-across-restart) — all green on master HEAD
plus the new recompiler discovery passes.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Add Pass 2.6 to FunctionAnalyzer: detect JAL targets whose callee starts
with `sw $ra, imm($a0)` (SaveState-style context-save helpers) and force
the post-delay-slot PC into the dispatch table. Recovers continuation
entries that aren't reached by JAL prologue or jr $ra discovery.
Extend find_function_start to recognize `lui rt; lw rt, off(rt)` 8 bytes
before jr $ra as a prologue marker. Rewrite analyze_function block-build
from std::set boundaries to a sorted std::vector + binary_search.
main_psx CLI: --seeds, --out-dir, --strict, --inspect; out_dir support.
Add psxrecomp-game executable target alongside PSXRecomp.
code_generator: reg_name() now emits cpu->gpr[N] consistently (matching
what the rest of the codegen already emitted — the old reg_names[] table
returning cpu->v0/cpu->ra was unreachable because CPUState has no named
fields, only gpr[32]). LWL/LWR/SWL/SWR moved from cpu->lwl(...) member
form to psx_lwl(cpu, ...) free-function form for game-EXE codegen reuse.
Remove a stray fmt::print left in build_basic_blocks that spammed
stdout on every regen — per the no-stdio-debug rule (memory v4).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Root cause: BIOS music engine reads voice register 6 (byte offset 0x0C,
CURVOL / ADSR_LEVEL) to find a free voice; recomp returned the never-
written spu_regs value (always 0), so the engine saw every voice as
silent and over-recycled voices 0-3 instead of fanning across all 24.
After fix, recomp KEYON-per-voice counts match Beetle exactly (e.g.
v0 2/2, v18 2/2, v22 1/1).
Also:
- Full ADSR envelope (Attack/Decay/Sustain/Release) ported from Beetle's
CalcVCDelta/RunEnvelope. KEYOFF now triggers Release-phase decay
rather than immediate silencing.
- End-without-loop triggers Release (matches RunDecoder), not active=0.
- ENDX latch at 0x1F801D9C/9E now reports actual block-end-reached
state instead of active-mask.
- SPU event ring (KEYON/KEYOFF/END_STOP/END_LOOP) on both backends with
frame-stamped per-voice payload; 1 M entries each (32 MB) for chime +
game-scene headroom. Beetle-side env>0 filter so silent-loop noise
doesn't bury the audible-voice timeline (matches recomp behavior
where deactivated voices don't fire further events).
- spu_voices / spu_events / spu_events_reset debug-server commands on
both ports. send_fmt buffer kept single-shot to avoid extra newlines.
- tools/_spu_ring_diff.py: frame-aligned event-ring diff with per-voice
count summary; chunk-count cap removed (was aborting reads at 98 KB).
- tools/_spu_capture.py, _spu_probe.py, _probe_one.py: targeted probes
used during diagnosis.
Local-only beetle-psx change (gitignored): same env>0 filter at
mednafen/psx/spu.cpp around line 345/352. Rebuild beetle-psx static
lib if reapplying.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Boot was running at ~17 simulated FPS (12x slower than realtime) and
audio dropouts followed because the SPU pump generated 735 samples
per simulated vblank. Two changes:
* fntrace_record now no-ops by default (record only when armed). The
legacy "record-all-when-unarmed" path made the runtime burn ~10%
CPU writing every dispatch into a 4M-entry ring. Opt-in to
record-all via fntrace_arm(0xFFFFFFFF).
* function_trace_record gated behind s_fn_trace_active flag (default
off). Previously did a stack walk + tail-call detection + 9-field
ring write on every dispatch, even when no fn-trace filter was set.
Flipped on by handle_fn_filter; new fn_disable command turns it
off again.
Combined: ~12x speedup. Recomp now hits 200+ simulated FPS uncapped,
matching beetle's ~230 FPS.
* Wall-clock pacer in sdl_vblank_present and beetle_main.cpp locks
both backends to PSX-native 59.94 Hz. Audio queue (SDL device
drains at 44100 Hz) now matches generation rate (735 samples * 60
≈ 44100/sec). TAB still works as turbo override on both windows.
The COPY/DELETE flows were silently no-oping the SIO write protocol:
60 dispatches per copy were missing the 3-instruction predicate fn at
0xBFC0989C (the WRITE-command sibling of 0xBFC09890), so the BIOS's
write-handler fork test returned junk via uninitialized v0 and the
BIOS skipped sending 0x57 over SIO entirely. The in-memory card cache
appeared updated (visual UI worked, leave/re-enter showed copies) but
nothing reached memcard_write_sector or the .mcd files.
Also reorganize memcard directory resolution: production builds put
cards next to the exe; dev builds (CMake build tree detected) keep
them in the project root next to bios/ so a runtime rebuild doesn't
delete them. --memcard-dir still overrides.
New runtime/src/crash_trace.c writes psx_last_run_report.json with:
reason / timestamp / frame / last_func_addr / last_store_pc
full CPU register state (all 32 GPRs + hi/lo/sr/cause/epc)
dispatch_ring tail (last 256 dispatched func entries)
unknown_dispatch tail (last 50 entries with addr/phys/ra/a0/a1)
dirty_block_log tail (last 100 entries)
Windows SEH info (when triggered from SEH filter)
Triggered from:
- SIGSEGV / SIGABRT signal handlers
- Windows SetUnhandledExceptionFilter (catches access violations)
- atexit
- psx_unknown_dispatch fail-fast path (set PSX_FAIL_FAST_UNKNOWN_DISPATCH=1)
- trap_crash (existing fatal trap path)
File overwrites per dump (last-write-wins). Per CLAUDE.md §3 this is not
a log — it's a one-shot final state snapshot for crashes the running
TCP server cannot intercept.
Pattern mirrors F:/Projects/SuperMarioWorldRecomp/src/post_mortem.c.
Used the new infrastructure to capture a controlled crash with
0xBFC0989C re-seeded. Crash dump revealed the chain:
- JAL at 0xBFC09788 is jalr $s3, NOT jalr $a0
- $s3 was set in func_1FC09598 prologue: $s3 = $a2 (callee saves arg)
- Caller at 0xBFC093C4 in func_1FC092EC: $a2 = $s3 - 128 (delay slot)
- func_1FC092EC at 0xBFC09314: $s3 = $a3 (callee saves arg)
So real bug is upstream-of-upstream caller passing $a3 = 131 (0x83)
to func_1FC092EC, propagating down to a misaligned function pointer.
The 0xA000E1E8 we suspected as a function-pointer table was a
red herring — $a0 in the loop body is loaded from $fp+s1*4 (the
ARG to pass to the called fn), not the call target.
0xBFC0989C reverted out of seed list (was diagnostic-only).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Outcomes:
- YES/NO COPY confirm modal closes correctly on CROSS press (returns to
COPY menu — matches Beetle behavior)
- No crash, no freeze
- Memory card 2 visible with a known-good save (sourced from Beetle's
dummy.1.mcr; backup of prior card2.mcd kept as .bak.before_beetle_copy)
- TAB held = turbo mode (skips VRAM->ARGB conversion + SDL_RenderPresent
every frame except every 30th); useful for navigation cycles
Remaining bug:
- The actual save data is NOT being copied. Source card content is not
written to destination. card1.mcd hash unchanged after a copy attempt.
- 0xBFC0989C still hits psx_unknown_dispatch 60x per copy. Bisect
confirmed seeding 0xBFC0989C alone causes a misaligned-dispatch crash
from caller 0xBFC09790 (function-pointer table at runtime addr
0xA000E1E8 indexed by predicate result, gives garbage target 0x3).
Seeding both 0xBFC09890 + 0xBFC0989C causes a softlock instead of crash.
Therefore 0xBFC0989C is intentionally NOT seeded; the copy data path
short-circuits because the predicate's stale-v0 result fails to enter
the actual write code.
Status of the function-discovery-miss bug class:
- VALIDATED for 0xBFC1A1BC (commit 6889f5c) — bandaid worked, modal
closes
- PARTIALLY VALIDATED for the BFC09xxx area — adding 0xBFC09890 alone is
safe but doesn't unblock the copy. 0xBFC0989C cannot be safely seeded
because it's likely a mid-function label, not a function entry. The
proper fix requires recompiling the full function containing 0xBFC09790
(the caller of these predicates) and ensuring the function-pointer
table at runtime address 0xA000E1E8 is populated with valid recompiled
function targets.
Turbo mode: hold TAB on the SDL window. Suppresses 29/30 frame presents,
keeps simulated CPU advancing at full speed.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Modal close on YES/NO COPY confirm now works on recomp. Cause: function
discovery (Ghidra + transitive walk) missed the function at 0xBFC1A1BC
which the BIOS shell calls indirectly during modal close. The 5 nearby
"missing" PCs the diagnostic identified are all in the same gap from
0xBFC1A1B8 to 0xBFC1A3B8; seeding 0xBFC1A1BC discovers the rest
transitively.
Status: modal closes cleanly on X. Actual copy execution still has
downstream missing-function-discovery issues (3 more PCs hit
psx_unknown_dispatch on copy: 0xBFC09890, 0xBFC0989C, 0xBFC02918)
plus likely additional bugs that softlock when those are seeded.
Those remain for follow-up; this commit is the modal-close milestone.
This is a BANDAID per user permission. The proper fix is to improve
function discovery so missed functions like 0xBFC1A1BC are found
automatically. Ghidra didn't see this function, and our transitive
walk didn't reach it either.
Tooling additions:
- psx_unknown_dispatch_record() ring buffer + unknown_dispatch_log
debug command. Replaces the prior file-based miss log per
CLAUDE.md §3 (no log files, ever). Always-on; queryable summary
(per-target counts) or tail (last N entries with addr/phys/ra/a0/a1).
- WTRACE_MAX_RANGES bumped from 16 -> 64 (boot defaults were
crowding out investigative arms).
- DirtyRamBlockLogEntry +a0/a1 fields, ring CAP 16K -> 4M
(previous 28ms eviction made retroactive press-window analysis
impossible).
Diagnostic scripts (kept):
tools/_unknown_dispatch.py — query unknown_dispatch_log
tools/_dispatch_check_v3.py — was a PC ever dispatched (RAM->ROM map)
tools/_dispatch_tail.py — last N dispatched targets
tools/_freeze_diag2.py — softlock investigator
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Switches diagnostic methodology from a single binary running both backends
in lockstep (psx-beetleoracle.exe) to two independent processes:
psx-runtime.exe (recomp only, port 4370)
psx-beetle.exe (Beetle libretro only, port 4380)
Both expose the same JSON wire protocol for the common debug commands
(read_ram, press, set_input, clear_input, pad_status, screenshot_file,
wtrace_*, fntrace_* on Beetle). Cross-process comparison is done by
querying both ports from a tool, NOT by sharing input or memory.
Why: the embedded-oracle setup required keyboard input to drive both
backends in lockstep. Once their state diverged, the same keypress
drove them to different screens and "compare on the same press" became
unreliable. Two independent processes lets each backend be navigated
to its own state and queried on its own timeline.
Removed:
- runtime/src/beetle_psx_bridge.cpp (cannibalised into beetle_libretro.cpp)
- runtime/src/duckstation_bridge.cpp
- runtime/src/psx_oracle_cmds.c
- runtime/src/psx_oracle_stub.c
- runtime/include/psx_oracle_backend.h
- psx-beetleoracle and psx-dsoracle cmake targets
- 22 dual-backend tools (emu_read_ram / find_first_divergence / etc)
Added:
- runtime/src/beetle_main.cpp (SDL window + libretro driver + keyboard)
- runtime/src/beetle_libretro.cpp (libretro callbacks + wtrace/fntrace/sio rings)
- runtime/src/beetle_debug_server.c (TCP server, port 4380, same wire protocol)
- psx-beetle cmake target
Also bumps tooling caps surfaced during modal investigation:
- DIRTY_RAM_BLOCK_LOG_CAP: 16K -> 4M (28ms eviction -> ~7s retention)
- WTRACE_MAX_RANGES: 16 -> 64 (boot defaults filled the prior cap)
- DirtyRamBlockLogEntry: added a0/a1 fields for richer dispatch context
CLAUDE.md section 16 rewritten for the new methodology. New memory note
locks the direction so future sessions don't reach for the deleted
embedded-oracle commands.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Codegen audit (tools/_codegen_audit.py) revealed two related dispatch-miss
classes after the predicate-init fix.
(1) Discovery missed the A0/B0/C0 syscall trampolines at BFC428D0-BFC42C00.
These are 8-16 byte stubs of the form
li t2, 0xa0/b0/c0
jr t2
_li t1, FUN_ID
that wrap kernel syscall dispatch. Ghidra had no xrefs to them (callers
reach them via patterns auto-analysis didn't trace), so they never made
it into ghidra_function_starts.json and from there into seeds. The
recompiler decoded JALs targeting them (visible as `psx_dispatch(cpu,
0xB005A8F0u)` etc. in regen output) but with no dispatch table entry,
these calls hit psx_unknown_dispatch and silently no-op'd.
For the YES/NO confirm modal, this likely manifested as the modal's
CROSS handler calling e.g. TestEvent (B0:0xB at BFC42A00) and getting
no result, leaving the modal in indeterminate state.
Added 50 explicit seeds for BFC428D0..BFC42C00 (trampolines) plus four
small kernel/libgte stubs (BFC304AC, BFC30584, BFC33C90, BFC33D1C —
`jr ra; _li v0, X` return-constant helpers) which were also dispatch
misses via tail-call paths.
(2) full_function_emitter.cpp's relocate_j_target/relocate_ra clamped the
shell relocation range at phys 0x1FC427FF, but the runtime dispatcher's
normalize() (SCPH1001_dispatch.c) handles shell up to phys 0x1FC42FFF.
This left JALs in BFC42800-BFC42FFF un-relocated — the JAL target kept
ROM PC[31:28]=0xB instead of being remapped to RAM PC[31:28]=0x8.
Concrete example: `jal 0xB005A910` at BFC4282C, where the intended
runtime target 0x8005A910 (a trampoline at RAM offset 0x2A910 = ROM
BFC42910) became 0xB005A910 (KSEG1 mirror of RAM 0x005A910 — random
address far outside any dispatch-table entry).
Extended bound to 0x1FC42FFF in both lambdas to match the runtime.
Audit results: direct dispatch misses 47 -> 0, tail-call misses 5 -> 1.
Remaining 1 is RAM 0x00000CF0 (dynamic install stub, handled by
dirty_ram_dispatch per Rule 18).
Awaiting user repro to confirm YES/NO modal action handlers now fire.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
When a `beq+delay-slot` terminator's delay-slot address is also a basic-block
label (target of an external `b BFCxxxx` from a sibling branch), the previously
emitted C placed the variable declaration BEFORE the next block label and the
dangling if-goto AFTER it:
label_BFC2185C:
capture brA, brB
int psx_taken_BFC2185C = (brA == brB); // declaration
label_BFC21860: // goto target
cpu->gpr[1] = ...; // delay-slot c_code
if (psx_taken_BFC2185C) goto label_BFC21800; // ← dangling
When control reaches `label_BFC21860` via a goto from elsewhere (e.g., the
COPY branch ends with `b 0xbfc21860`), C semantics make `psx_taken_BFC2185C`
indeterminate because its declaration with initializer was skipped. On MinGW,
stack garbage is non-zero → the if-goto fires unconditionally → spurious
cross-branch jump → infinite loop in DELETE branch (BFC21800).
Concretely this caused the memcard COPY confirm-modal freeze: pressing CROSS
on a save-block target should push widget 0xA modal, but the COPY branch
would push 0xA correctly, then on `b 0xbfc21860` cleanup the dangling
if-goto would fire spuriously and jump into the DELETE branch, which keeps
re-pushing widget 0xB and reverting state.
Fix: in the first pass, collect every branch terminator address and emit
`int psx_taken_BFCxxxx = 0;` at function entry. Change the terminator-emit
from declaration to assignment. Now external gotos that bypass the
assignment see the zero default and the dangling if-goto correctly does
not fire.
Regenerated `generated/SCPH1001_full.c`: 6083 zero-init declarations,
all `int psx_taken_*` at terminator sites converted to assignments.
User-verified: COPY confirm-modal now appears. (YES/NO button/close
behavior still broken — likely additional bugs in the same class or
adjacent codegen edge cases; tracked separately.)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds 0x66BC0..0x66BD0 to the always-on wtrace ranges. Used to find that
the freeze on COPY click in BIOS shell memcard menu happens because:
- shell state-machine index at mem[0x80078320] advances to 7
- state-7 struct at 0x80113C80 has handler=0x800321BC (RAM, non-null)
and input_mask=0x00F000F0 (D-pad bits only)
- non-D-pad buttons (CROSS/CIRCLE/TRIANGLE) are masked out in this
state, and the D-pad handler at 0x800321BC never advances state
Memo follows separately. This commit is purely the diagnostic addition
so the wtrace coverage is in master for future repro.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Python clients open a fresh socket per command — every press call would
return its OK, the client would close, and the server's recv path would
see the close and reset s_input_override = -1 the same frame. Net effect
was that every scheduled press lasted ~1 frame regardless of the
requested frame count, leaving the BIOS to see at most a single edge
event before the override evaporated.
Removing the reset lets s_input_frames count down naturally, so a press
holds for the full requested duration even though the issuing client
isn't connected for the duration. pad_status now reports
override=0xBFFF override_frames=110/99/88/... across half-second polls
during a 120-frame press, instead of override=-1 the moment after the
press is scheduled.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Before: only sector 0 read succeeded; sector ≥1 reads aborted at 2 bytes
because mc_flag was loaded from mc_slots[].flag on every 0x81 select but
never saved back. The clear in MC_CMD lived only in the working static, so
every reselect re-loaded the stale 0x08 ("new card / changed battery") init
value, and the BIOS bailed every multi-sector op as "card was just inserted,
re-init."
After: BIOS shell memcard menu reads the full 15-sector directory area for
both slots. Real save filenames decode (e.g. "BISLPS-01234SAVE00") and per
card icons render in the bottom panes — the Phase 4 success criterion.
Also bundled this session:
- debug_server: B9D0..B9F0 added to always-on wtrace ranges; fn_dump_parse
default window scoped to 1M most-recent entries (filter scans against the
full 128M ring used to freeze the debug server thread for many seconds).
- ISSUES.md + diagnostic tools/*.py written during the audit.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds the Beetle-discovered chain writer/init PCs as dispatch_miss seeds
so the recompiler emits standalone functions for them at their RAM
destination addresses (via the existing Phase 1e ROM↔RAM alias rule
RAM = ROM - 0xBFC10000 + 0x500):
0xBFC14A54 → 0x00004F54 (chain BUSY-writer)
0xBFC158D0 → 0x00005DD0 (chain init slot-0 BUSY)
0xBFC158D8 → 0x00005DD8 (chain init slot-1 BUSY)
0xBFC159F4 → 0x00005EF4 (chain step 0x02-OPEN writer — KEY)
0xBFC15AA8 → 0x00005FA8 (chain step 0x04-OPEN writer — KEY)
Post-regen dispatch_table contains all 5 as standalone entries. e.g.
func_00005EF4 is a clean 3-instruction leaf (sb $t3, 0($a3); v0=1; jr ra).
Validation (full output in docs/CASE_A_AOT_GAP.md "Vertical slice result"):
- ✓ dispatch_table contains all 5 entries
- ✗ none of the 5 are reached at runtime — chain still doesn't dispatch
- ✗ [0x80007510..0x7570] all-zero — the chain init function FUN_bfc158a8
(= func_00005DA8) never runs in our recomp during this session, gates
haven't even reached the initial 0x01 BUSY state
- ✓ shell IS on memcard screen ([0x80066948] = 0x32)
The seed addition is correct and necessary work — it removes one of two
layers of "writer is unreachable". The remaining layer is upstream:
nothing in our recomp causes FUN_bfc14b00 / FUN_bfc158a8 to run during
the memcard flow. That's a different category from "chain runs but
fails on byte N" and is not chased here per Case A directive.
Beetle wtrace also revealed the writers at 0x5EF4 / 0x5FA8 are tiny
leaf utilities called from BIOS code in BFC08{B98,C94,D08,F28} — NOT
chain-step jump-table targets as initially assumed. The chain step
tables at RAM 0x6c70/0x6c98/0x6ccc point at 0x52xx / 0x56xx-0x5Axx /
0x5Bxx-0x5Dxx ranges. Memo updated accordingly.
Includes 4 new validation scripts under tools/ used during this audit.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds a RAM-write trace hook to mednafen-PSX (SB/SH/SW handlers fire
g_psxrecomp_wtrace_cb after each write), a ring buffer + TCP commands
in psx-beetleoracle, and verification scripts that drive CROSS in
both Beetle and recomp and diff the gate-byte writers.
Conclusion (docs/CASE_A_AOT_GAP.md): the [0x7568+slot] LSB-clear
writers are at RAM PCs 0x5EF4 / 0x5FA8 (and 0x4F54 sets BUSY).
Recomp never dispatches any of those PCs, never executes the
0x4F00..0x4FFF or 0x5800..0x5FFF RAM windows, and never writes the
gate. Selective coverage pattern (interp reaches 0xCF0/0x52xx/0x6xxx
but not 0x4Fxx/0x5xxx) is install/dispatch path gap, not interpreter
bug. PLAN.md:941 already names this work as a hard gate.
Beetle-side modifications live inside the vendored beetle-psx/ git
clone; docs/beetle_wtrace_hook.patch captures the diff so they
survive a re-clone.
Memcard symptom debugging stops here. Next: trace-generated AOT
RAM-code manifest + recompiler ingestion (Phases B–F).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>