# MAME 0.285 and Mesen2 2.1.1 as detectors for the Cx4 Two emulators run the Mega Man X2/X3 cartridges on this machine. **MAME 0.285 cannot trace the HG51B**: it has no HG51B CPU device (a search of the 455 MB `mame` binary for "hg51" finds nothing, 2026-11-06), and its Cx4 is high-level emulation (`snescx4.cpp`, GPL-2.0+; the 2026-11-06 notes quoted its header, a reading withdrawn in Wave 2: MAME's GPL files are closed boxes). **Mesen2 2.1.1 can**: a low-level Cx4 with a trace logger. So the instruction-level detector here is Mesen2; MAME gives a second, independent screen of the self-test and the S-CPU's host stream at command level. Everything here was run on 2026-11-06. ## The cartridges: No-Intro, read in place The player's No-Intro set, `$NO_INTRO_DIR/Nintendo - Super Nintendo Entertainment System/` (or `SNES_NO_INTRO`): Mega Man X2 (USA), (Europe); Rockman X2 (Japan), (Beta 1), (Beta 2); Mega Man X3 (USA), (Europe); Rockman X3 (Japan), (Beta 1-3); and "Mega Man X Legacy Collection" extractions (not surveyed). Header chipset $FFD6 = F3h, $FFBF = 10h (Cx4). MAME's software list (`hash/snes.xml`) names them with `slot` = `lorom_cx4` and an `addon` data area `cx4.bin`; MAME's slot device for a loose `.sfc` is `:snsslot:lorom_cx4`, short name `sns_rom` (measured). No device ROM set is needed (MAME's HLE has its own tables). ## MAME: the recipe (`scripts/mame_cx4_host.py`) ```sh python -I scripts/mame_cx4_host.py "/Mega Man X2 (USA).zip" \ --frames 200 --press "0:P2 B:170" --snapshots 200 ``` runs, in `tests/mame_traces//` (gitignored; the cartridge is extracted there with `7z`): ```sh nice -n 19 mame snes -cart CART.sfc -rompath ";" -homepath RUN \ -snapshot_directory RUN/snap -video none -sound none -nothrottle -noreadconfig \ -skip_gameinfo -debug -debugger none -oslog -seconds_to_run N -autoboot_script RUN/host.lua ``` with a Lua script that sets four watchpoints, ``` wpset 000000:maincpu,400000,w,(wpaddr & e000) == 6000,{logerror "W %X %X %d\n",wpaddr,wpdata,frame; g} ``` (and the `r` twin, and both again at 800000), holds `P2 B` from frame 0, takes snapshots and exits at the last frame; the log goes to stderr (`-oslog`) and is gzipped as `host.log.gz` (`R|W address value frame`). 200 frames of the test take 6 s. ### Measured - Mega Man X2 (USA) and X3 (USA): the Cx4 TEST screen with eight "OK." by frame 200. - X2 test, 200 frames: 201,804 accesses: 3,942 status reads ($7F5E), the register file read and written, 768 DMAs, 802 program starts, 802 cache preloads, 49,312 data RAM writes (validation.md "What each item exercises"). - The game's configuration writes at boot and again in the test: $7F52 = 00, $7F6E/6F = F3 1F (IRQ vector 1FF3h), $7F6A/6B = EF 1F (NMI vector 1FEFh), $7F50 = 44, $7F51 = 01 (IRQ off), base $7F49-4B = 00 80 02, $7F4C = 00. ### Traps found 1. **Watch all banks.** A first run watching only `006000`/`806000` saw no register-file access at all: the test code runs with data banks other than 00 (e.g. `$06:7F52`). The condition `(wpaddr & e000) == 6000` over 00-3F and 80-BF catches them. 2. **An action with an extra brace is accepted with a warning**: `wpset` printed "unbalanced parentheses" yet set the watchpoint and logged. Do not rely on it: keep the action exactly `{logerror "...",...; g}` and check `CON` lines. 3. `-seconds_to_run` is an integer, SIGTERM does not stop a `-debug` MAME, and a FIFO in place of `error.log` gets nothing (upd7725-python mame-oracle.md traps 1, 2, 6): the script exits from a frame notifier and reads `-oslog`. 4. MAME's timing of the host stream is MAME's (HLE answers instantly); never compare a MAME host stream's spacing with the core. ## Mesen2: the recipe (`$EMU_TOOLS_GPL/tools/mesen2/run.py`, machine `snes-cx4`) The runner is mesen2-runner (0.2.0), a GPL-3.0-or-later tool in emu-tools-gpl (`tools/mesen2/README.md` there), run as a separate program; it is not in this repository. Since 2026-11-24 both scripts run it directly; the old harness command line (`tools/hg51b-python/mesen_cx4_trace.py`, a shim over the same runner) is no longer used. ```sh python3 -I "$EMU_TOOLS_GPL/tools/mesen2/run.py" --machine snes-cx4 --rom "Mega Man X2 (USA).sfc" \ --hold-test --frames 300 --frames-out --out x2-test-screen python3 -I "$EMU_TOOLS_GPL/tools/mesen2/run.py" --machine snes-cx4 --rom "Mega Man X2 (USA).sfc" \ --hold-test --frames 150 --trace cx4-text,host --trace-window 120:122 --out x2-test ``` `--trace-window START:END` traces frames START to END - 1 (the old `--trace-start START --trace-frames END-START`; checked on the X2 test: 120:122 gives the old two-frame trace, 120:121 one frame). Presses are the contract's input script (`--input FILE`, port 1): the old `--press F:BUTTON` (held six frames) is a record at F with the button and one at F+6 with none, which gives the old run's Cx4 trace, host stream and picture exactly on X2's title (a record at 899 or 901 does not), OBSERVED 2026-11-24 (Mesen2 b9fa69d via mesen2-runner 0.2.0). The host stream holds exactly frames 1 to `--frames`; the old harness's could run a few rows past. The library is a `MesenCore.so` built from Mesen2 `b9fa69dd`, the pinned commit (the runner's own `build.sh`, or `MESEN_CORE`; each run's `manifest.json` names it); Mesen2 is a closed box (GPL-3): it is built and run, its source never opened. The ctypes declarations the scripts use (the CPU-type number, the config and trace-option layouts) were taken from its headers under the old rule; see docs/provenance.md "Wave 2", item "unclear". snes-python `scripts/mesen_run.py` is the base recipe (ctypes, a SnesConfig with standard pads in both ports, NTSC, zeroed RAM). Additions: - `SetInputOverrides(1, {B})` before `Resume()` holds controller 2 B from power-on. - `SetTraceOptions(5 /* CpuType::Cx4 */, {enabled, format})` + `StartLogTraceToFile(path)` trace the Cx4; `StopLogTraceToFile()` must come **before** `Release()`. - A line: `029C9E 029C9E 01 94 SUB A,#$01 A:1142 P:0 czvn MAR:0 MDR:0 DPR:907 MH:0 ML:0 R0:88273 ... R15:16777215 2`: the cached word's ROM address (base + PB x 512 + PC x 2), the two bytes, Mesen2's disassembly, the registers **in decimal** before the instruction, flags `CZVN` (upper = set), and a `[Cycle]` column that is small and restarts (not a time stamp). ### Measured - The test on Mega Man X2 (USA), Mega Man X3 (USA), Rockman X2 (Japan): eight "OK." each, 300 frames in about 3 s. - Power-on to frame 900 with no input: 361,854 Cx4 instructions (pages 0 and 0Eh). - The test loop: 393,195 instructions in two frames (2.7 MB gzipped). - Lua `emu.addMemoryCallback(..., emu.callbackType.write, 0, 0xFFFFFF, emu.cpuType.snes)` filtered to `(addr & 0xE000) == 0x6000` sees 59,503 S-CPU writes and 802 program starts in 200 frames of the test: the host stream for a replay can come from Mesen2 itself. ### Traps found 1. **`LoadRom` refuses a `.zip`** in this build: extract the `.sfc` (into a scratch directory: it is untrusted data). 2. **`emu.setInput(t, 1)` does nothing for controller 2** (`emu.getInput(1)` reads back all false; port 0 works): use the debugger override. 3. **Lua exec callbacks with `emu.cpuType.cx4` never fire** (0 in 1,500 frames while the chip ran): the Cx4 debugger does not call the memory callback path; use the trace logger. 4. `emu.getState()` has no Cx4 keys in this build. 5. **`StopLogTraceToFile` after `Release()` segfaults** (measured: SIGSEGV in `Emulator::GetDebugger`). 6. **Volume**: an untrimmed trace of the test is 778 MB for 240 frames; trace windows of a few frames and gzip them. Found while building (2026-11-07): 7. **Window edges from Python polling drift.** With `--host` the script parses the log at every 10 ms poll and can see frame 860 only at 863: a window started and stopped in one poll traced nothing, another opened at 1005 instead of 1000. The Lua script now calls `emu.breakExecution()` at the window's first and last frame; Python sees `IsExecutionStopped()`, starts or stops the trace logger and calls `ResumeExecution()`. Frame-exact. 8. **The rows flushed by `StopLogTraceToFile` can repeat older ones**: a 299,416-row window ended with 144 rows whose `CycleCount` went 156 back (the logger writes from a ring buffer). One such window also held a NUL byte in place of a row's first character. The replay cuts a trace where `CC:` goes backwards (`replay.monotonic`); a row that does not parse is an error. 9. **`emu.getState()` costs about 0.3 ms** (it serialises the whole console: 57,939 calls took 18 s): the host stream stamps only the start writes ($7F47/$7F48/$7F4F) with `memoryManager.masterClock` (the 64-bit one; the Lua-only `masterClock` is 32 bits). 10. **The script log keeps 500 rows**; the host stream is one row per frame, compressed (runs of consecutive addresses share a token, repeated polls carry `*count`), collected at every poll. 1,810 frames of X2 are 1.29 M accesses. 11. The trace format gains `PB:[PB] CC:[CycleCount] F:[FrameCount]`: `CycleCount` is the Cx4's own (`masterClock x 20,000,000 / 21,477,270`: the 20 MHz crystal over the NTSC master clock, which lines the runs up), the stamp the replay splits runs by. 12. Mesen2's power-on data RAM follows the SnesConfig's `RamPowerOnState` (1 = all zeros here, as the core's): the boot reads 3 KiB of zeros back. ## The replay (rung 4), as built (`replay.py`, `scripts/record_mesen_windows.py`) 1. **Record** (`run.py --machine snes-cx4 --trace cx4-text,host`; until 2026-11-24 `mesen_cx4_trace.py --host`): from power-on, every S-CPU read and write of banks 00-3F/80-BF $6000-$7FFF (Lua read and write callbacks, `emu.cpuType.snes`), in order, per frame; the start writes stamped with the master clock; and a frame-exact Cx4 trace window. Five windows (`record_mesen_windows.py`): X2 boot, the X2 test, X2 title (Start at 900, page 3), X2 intro stage (page 0, build_oam), X3 title (pages 2, 4). 2. **Replay by events, not by time.** Mesen2's clock model is not the core's (C7, C8, C9: its $7F48 preloads skip cached pages), so a host write is applied when the stream reaches it: a start write first runs the core to idle; a status read Mesen2 answered "idle" runs the core to idle and compares all eight bits; one it answered "running" advances the core 64 clocks and only notes whether the core was already idle; every other read compares the byte. Every $7F4F write opens a run; the trace is split into runs by the start stamps (converted to Cx4 cycles), and inside the window the core is stepped unit by unit and its state before every instruction compared with the trace line: PB, PC, A, P, CZVN, MAR, MDR, DPR, MH, ML, R0-R15 (and the word). 3. **A divergence** is recorded with the instruction that produced it and classified by C entry from that instruction (`replay.classify`); the core then adopts Mesen2's registers so one cause counts once. The report also counts what the C entries ask for: register shift counts (C1), shifted adder operands wider than 24 bits (C2), the deepest stack (C4), far jumps and whether their page was cached (C5), MH/ML read right after a MUL (C6). The numbers are in [validation.md](validation.md) "Results".