Files
Matthew Stanley 76a53d9090 Invalidate per-PC code caches when a savestate replaces RAM
Several consumers cache a classification of the instruction at a given PC and
key that cache on g_dirty_ram_code_gen, per the contract stated where the
counter is defined (runtime/src/memory.c): "Consumers that cache per-PC
classifications of RAM instructions compare against this and re-derive after any
code change - a cached kind must never survive an overlay reload." Today that
counter is bumped from exactly two places, both on the instrumented store path:
a page's clean->dirty transition, and dirty_ram_mark_executable_range().

A savestate restore reaches neither. BS_SEC_RAM applies a raw memcpy over all
2 MB, so code identity at any address can change completely while no page makes
a clean->dirty transition and no executable range is marked. Every cache keyed
on the generation therefore keeps serving verdicts derived from the PREVIOUS
contents. The overlay loader's negative "no native owner" cache is the damaging
one, because overlay_loader_dispatch() consults it before rediscovery, so one
stale entry can pin an address to the wrong implementation for the rest of the
run.

Note the same restore already invalidates psx_kernel_bless_note_range(), so the
path is aware it must invalidate downstream caches - it only ever did one of
them.

Fix: add dirty_ram_invalidate_code_caches() and call it after the BS_SEC_RAM
memcpy. dirty_ram_set_bitmap_words() (the BS_SEC_DIRTY apply path) calls it too,
since a wholesale bitmap replacement changes which addresses are RAM-resident
code by the same argument. Bumping the generation is sufficient by construction:
each cache stores the generation it was derived under and re-derives on
mismatch, so this fixes every consumer at once instead of patching them
individually.

Scope, stated honestly: this closes a real latent correctness gap in the load
path and is worth having on its own. It is NOT a fix for the separate,
still-open bug where loading a gameplay state into a process that never entered
that stage leaves the player unable to move - that was measured and the overlay
cache is demonstrably NOT its cause (the dirty bitmap is identical between a
working and a broken instance, and covers only the kernel window, so the
player's code is static-dispatched in both). No behaviour change for a process
that never loads a state.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-24 23:39:41 -07:00
..