#!/usr/bin/env python3 # SPDX-License-Identifier: GPL-3.0-or-later """Run a Cx4 cartridge on Mesen2 2.1.1 headless: the Cx4 test screen, and a per-instruction Cx4 trace. The emulator-tier detector of docs/validation.md. Mesen2 (``b9fa69dd``, GPL-3) is a library built locally (famicom-python's ``MesenCore.so``; snes-python ``scripts/mesen_run.py`` documents the build and the ctypes recipe this script follows); our code calls it at run time, nothing of it is copied. Two things Mesen2's Lua API cannot do and its C API can (measured 2026-11-06): - **Hold controller 2's B at power-on**, which enters the game's built-in Cx4 test (Mega Man X2/X3, Rockman X2/X3). ``emu.setInput(..., 1)`` is ignored for port 2 in this build (``emu.getInput(1)`` reads back false), so the script uses the debugger's ``SetInputOverrides(1, state)``. - **Trace the Cx4**: Lua exec callbacks with ``emu.cpuType.cx4`` never fire (the Cx4 debugger calls no memory callback), but the trace logger does: ``SetTraceOptions(CpuType::Cx4 = 5, {enabled, format})`` and ``StartLogTraceToFile``. A line is one instruction before it executes: ``PC(24-bit ROM address of the cached word) bytes disassembly registers (decimal) [Cycle]`` (the last column's origin is unclear: it is small and restarts; do not use it as a time stamp). The game's test runs in a loop (79,000 to 197,000 Cx4 instructions a frame, up to 8 MB of text a frame, measured on Mega Man X2), so the trace covers only ``--trace-frames`` frames from ``--trace-start`` and is gzipped afterwards; the Python side starts and stops it when the Lua frame counter says so (polled every 10 ms, so the window edges are within a frame). ``--png`` saves the last frame. python -I scripts/mesen_cx4_trace.py "Mega Man X2 (USA).sfc" --test --frames 300 --png test.png python -I scripts/mesen_cx4_trace.py "Mega Man X2 (USA).sfc" --test --trace-start 120 --trace-frames 2 The cartridge is a loose ``.sfc`` (this Mesen2 build's ``LoadRom`` refuses a ``.zip``; extract it into a scratch directory). Output goes to ``tests/mesen_traces//`` (gitignored). """ from __future__ import annotations import argparse import ctypes import gzip import os import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] # The library: --lib, else MESEN_CORE, else a build in this repository's reference/ (or a # sibling checkout's, e.g. ../famicom-python, which builds the same commit). LIBS = tuple( base / "reference/build-mesen2/Mesen2/InteropDLL/obj.linux-x64/MesenCore.so" for base in (ROOT, ROOT.parent / "snes-python", ROOT.parent / "famicom-python") ) MAXIMUM_SPEED, CONSOLE_MODE = 0x04, 0x10 CX4 = 5 # the C API's CPU type for the Cx4 (see docs/provenance.md "Wave 2", unclear) FORMAT = ("[PC] [ByteCode] [Disassembly] A:[A] P:[P] [PS] MAR:[MAR] MDR:[MDR] DPR:[DPR] " "MH:[MH] ML:[ML] R0:[R0] R1:[R1] R2:[R2] R3:[R3] R4:[R4] R5:[R5] R6:[R6] R7:[R7] " "R8:[R8] R9:[R9] R10:[R10] R11:[R11] R12:[R12] R13:[R13] R14:[R14] R15:[R15] [Cycle] " "PB:[PB] CC:[CycleCount] F:[FrameCount]") # fmt: skip # The C API's SnesConfig offsets (docs/provenance.md "Wave 2", unclear), measured by # snes-python scripts/mesen_run.py: a standard pad in each port, NTSC, zeroed RAM. SNES_CONFIG_SIZE = 10024 PORT_TYPES, SNES_CONTROLLER = (988, 1980), 1 REGION, CHANNEL_VOLUMES, RAM_POWER_ON, GSU_SPEED, BSX_DATE = 9920, 9956, 9992, 10008, 10016 LUA = """\ local frames = 0 {presses} {host} emu.addEventCallback(function() frames = frames + 1 {flush} emu.log("FRAME " .. frames) if frames == {trace_start} or frames == {trace_end} then emu.breakExecution() -- Python starts or stops the trace logger, then resumes end if frames == {frames} then local buf = emu.getScreenBuffer() local parts = {{}} for i = 1, #buf do parts[i] = string.format("%06x", buf[i]) end emu.log("PIXELS " .. #buf .. " " .. table.concat(parts)) emu.log("MESEN-DONE") end end, emu.eventType.endFrame) """ # Controller 1 presses (--press FRAME:BUTTON, held 6 frames from FRAME): Lua ``setInput`` # works for port 0 (only port 2 needs the debugger override). PRESS_LUA = """\ local presses = {{{presses}}} emu.addEventCallback(function() local f = emu.getState()["ppu.frameCount"] for _, p in ipairs(presses) do if f >= p[1] and f < p[1] + 6 then local t = {{}} t[p[2]] = true emu.setInput(t, 0) end end end, emu.eventType.inputPolled) """ # The host stream (--host): every S-CPU read and write of banks 00-3F/80-BF $6000-$7FFF, # in order. A token is "r" or "w", the 16-bit address, ":" and the value(s) as hex pairs: # accesses of one kind at consecutive addresses share a token ("r6000:00e000e0" = four # reads from $6000 on), an access repeated at one address with one value carries "*count" # (status polls), and a write to $7F47, $7F48 or $7F4F (a start) is a token of its own # with "@" + the master clock, which the replay converts to the Cx4's CycleCount # (x 20,000,000 / the NTSC master clock rate: the 20 MHz crystal, fullsnes). One "H ..." log row per # frame; the Python side collects them while polling (the script log keeps 500 rows). HOST_LUA = """\ local buf = {{}} local kind, start, nexta, vals, rep = nil, 0, 0, {{}}, 0 local function close() if kind then local s = kind .. string.format("%04x", start) .. ":" .. table.concat(vals) if rep > 1 then s = s .. "*" .. rep end buf[#buf + 1] = s end kind, vals, rep = nil, {{}}, 0 end local function rec(k, a, v) local hv = string.format("%02x", v) if kind == k and #vals == 1 and a == start and vals[1] == hv then rep = rep + 1 return end if kind == k and rep == 1 and a == nexta then vals[#vals + 1] = hv nexta = a + 1 return end close() kind, start, nexta, vals, rep = k, a, a + 1, {{hv}}, 1 end emu.addMemoryCallback(function(addr, value) if (addr & 0x40E000) == 0x6000 then rec("r", addr & 0xFFFF, value) end end, emu.callbackType.read, 0, 0xFFFFFF, emu.cpuType.snes) emu.addMemoryCallback(function(addr, value) if (addr & 0x40E000) == 0x6000 then local a = addr & 0xFFFF local r = a & 0x3FF if (a & 0x0C00) == 0x0C00 and (r == 0x347 or r == 0x348 or r == 0x34F) then close() buf[#buf + 1] = string.format("w%04x:%02x@%d", a, value, emu.getState()["memoryManager.masterClock"]) else rec("w", a, value) end end end, emu.callbackType.write, 0, 0xFFFFFF, emu.cpuType.snes) local function flush(frame) close() emu.log("H" .. frame .. " " .. table.concat(buf, " ")) buf = {{}} end """ class SnesConfig(ctypes.Structure): _fields_ = [("raw", ctypes.c_ubyte * SNES_CONFIG_SIZE)] class TraceOptions(ctypes.Structure): # the C API's trace options (provenance: unclear) _fields_ = [("enabled", ctypes.c_bool), ("indent", ctypes.c_bool), ("labels", ctypes.c_bool), ("condition", ctypes.c_char * 1000), ("format", ctypes.c_char * 1000)] # fmt: skip class Pad(ctypes.Structure): # the C API's controller state (provenance: unclear) _fields_ = [ (n, ctypes.c_bool) for n in [ "a", "b", "x", "y", "l", "r", "u", "d", "up", "down", "left", "right", "select", "start", ] ] def snes_config() -> SnesConfig: config = SnesConfig() def put(at: int, value: int, size: int = 4) -> None: config.raw[at : at + size] = list(value.to_bytes(size, "little", signed=True)) for port in PORT_TYPES: put(port, SNES_CONTROLLER) put(REGION, 1) for i in range(8): put(CHANNEL_VOLUMES + 4 * i, 100) put(RAM_POWER_ON, 1) put(GSU_SPEED, 100) put(BSX_DATE, -1, 8) return config def frame_of(log: str) -> int: """The newest "FRAME n" row (the log may hold many).""" numbers = [int(row[6:]) for row in log.splitlines() if row.startswith("FRAME ")] return max(numbers, default=0) def run(args: argparse.Namespace, lib: Path, out: Path) -> tuple[str, float]: m = ctypes.CDLL(str(lib)) m.InitializeEmu.argtypes = [ctypes.c_char_p, ctypes.c_void_p, ctypes.c_void_p] + [ ctypes.c_bool ] * 4 m.LoadRom.argtypes = [ctypes.c_char_p, ctypes.c_char_p] m.LoadRom.restype = ctypes.c_bool m.SetEmulationFlag.argtypes = [ctypes.c_uint32, ctypes.c_bool] m.LoadScript.argtypes = [ctypes.c_char_p] * 3 + [ctypes.c_int32] m.LoadScript.restype = ctypes.c_int32 m.GetScriptLog.argtypes = [ctypes.c_int32, ctypes.c_char_p, ctypes.c_uint32] m.SetSnesConfig.argtypes = [SnesConfig] m.SetTraceOptions.argtypes = [ctypes.c_uint8, TraceOptions] m.StartLogTraceToFile.argtypes = [ctypes.c_char_p] m.SetInputOverrides.argtypes = [ctypes.c_uint32, Pad] home = out / "home" home.mkdir(parents=True, exist_ok=True) m.InitDll() m.InitializeEmu(str(home.resolve()).encode(), None, None, True, True, True, True) m.Pause() m.SetEmulationFlag(CONSOLE_MODE, True) m.SetSnesConfig(snes_config()) if not m.LoadRom(str(args.cart.resolve()).encode(), b""): raise SystemExit("LoadRom failed (a .zip? extract the .sfc first)") m.InitializeDebugger() if args.test: pad = Pad() pad.b = True # controller 2 B held from power-on: the Cx4 test m.SetInputOverrides(1, pad) presses = ",".join(f'{{{f},"{b}"}}' for f, b in (p.split(":") for p in args.press)) lua = LUA.format( frames=args.frames, trace_start=args.trace_start if args.trace_frames and args.trace_start else -1, trace_end=args.trace_start + args.trace_frames if args.trace_frames else -1, presses=PRESS_LUA.format(presses=presses) if args.press else "", host=HOST_LUA.format() if args.host else "", flush="flush(frames)" if args.host else "", ) script = m.LoadScript(b"cx4.lua", str(home.resolve()).encode(), lua.encode(), -1) host_rows: dict[int, str] = {} trace = out / "cx4.trace" tracing = done_tracing = args.trace_frames == 0 if not tracing and args.trace_start == 0: m.SetTraceOptions(CX4, TraceOptions(True, False, False, b"", FORMAT.encode())) m.StartLogTraceToFile(str(trace.resolve()).encode()) tracing = True m.SetEmulationFlag(MAXIMUM_SPEED, True) m.IsExecutionStopped.restype = ctypes.c_bool began = time.monotonic() m.Resume() buf = ctypes.create_string_buffer(1 << 26) log = "" while time.monotonic() - began < args.timeout: time.sleep(0.01) stopped = m.IsExecutionStopped() m.GetScriptLog(script, buf, len(buf)) log = buf.value.decode(errors="replace") if args.host: for row in log.splitlines(): if row.startswith("H"): number, _, data = row[1:].partition(" ") host_rows[int(number)] = data if stopped: # the Lua script broke at a window edge: the frame is exact if not tracing: m.SetTraceOptions(CX4, TraceOptions(True, False, False, b"", FORMAT.encode())) m.StartLogTraceToFile(str(trace.resolve()).encode()) tracing = True elif not done_tracing: m.StopLogTraceToFile() # before Release: after it, the call crashes (measured) done_tracing = True m.ResumeExecution() continue if "MESEN-DONE" in log: break if tracing and not done_tracing: m.StopLogTraceToFile() m.GetScriptLog(script, buf, len(buf)) for row in buf.value.decode(errors="replace").splitlines(): if args.host and row.startswith("H"): number, _, data = row[1:].partition(" ") host_rows[int(number)] = data m.Stop() m.Release() if args.host: missing = [n for n in range(1, max(host_rows, default=0) + 1) if n not in host_rows] if missing: print(f"host stream: {len(missing)} frames lost from the script log: {missing[:10]}") with gzip.open(out / "host.txt.gz", "wt", encoding="ascii") as sink: for number in sorted(host_rows): sink.write(f"{number} {host_rows[number]}\n") print(f"host stream: {len(host_rows)} frames: {out / 'host.txt.gz'}") return log, time.monotonic() - began def save_png(log: str, path: Path) -> None: from PIL import Image # only for --png line = next(x for x in log.splitlines() if x.startswith("PIXELS ")) _, count, hexes = line.split(" ", 2) width = 512 if int(count) >= 512 * 448 else 256 data = bytes.fromhex(hexes) Image.frombytes("RGB", (width, len(data) // 3 // width), data).save(path) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("cart", type=Path) parser.add_argument("--test", action="store_true", help="hold controller 2 B from power-on") parser.add_argument("--frames", type=int, default=300, help="frames to run") parser.add_argument("--trace-start", type=int, default=0, help="first traced frame") parser.add_argument("--trace-frames", type=int, default=0, help="frames to trace (0: no trace)") parser.add_argument("--png", type=Path, help="save the last frame (needs Pillow)") parser.add_argument( "--press", action="append", default=[], metavar="FRAME:BUTTON", help="hold a controller 1 button (a b x y l r up down left right select start) 6 frames", ) parser.add_argument( "--host", action="store_true", help="record the S-CPU's $6000-$7FFF accesses (host.txt.gz)" ) parser.add_argument( "--out", type=Path, help="run directory (default tests/mesen_traces/)" ) parser.add_argument("--timeout", type=float, default=300.0, help="wall-clock seconds") parser.add_argument( "--lib", type=Path, default=Path(os.environ["MESEN_CORE"]) if "MESEN_CORE" in os.environ else None, ) args = parser.parse_args() lib = args.lib or next((x for x in LIBS if x.exists()), None) if lib is None: raise SystemExit( "no MesenCore.so: build Mesen2 b9fa69dd (snes-python docs/validation.md) or pass --lib" ) out = args.out or ROOT / "tests" / "mesen_traces" / args.cart.stem.replace(" ", "_") out.mkdir(parents=True, exist_ok=True) log, wall = run(args, lib, out) print(f"{frame_of(log)} frames in {wall:.1f} s") trace = out / "cx4.trace" if trace.exists() and trace.stat().st_size: lines = 0 with ( trace.open("rb") as source, gzip.open(out / "cx4.trace.gz", "wb", compresslevel=6) as sink, ): for line in source: lines += 1 sink.write(line) trace.write_bytes(b"") # keep only the gzip print(f"{lines} Cx4 instructions traced: {out / 'cx4.trace.gz'}") if args.png and "PIXELS" in log: save_png(log, args.png) print(f"screen: {args.png}") elif "MESEN-DONE" not in log: print("timed out") return 1 return 0 if __name__ == "__main__": sys.exit(main())