# SPDX-License-Identifier: GPL-3.0-or-later """The Cx4 adapter (a SNES cartridge with the Cx4): the test screen, a per-instruction Cx4 trace, and the S-CPU's accesses to the Cx4 window, for hg51b-python's closed-box runs. From ``hg51b-mesen-harness/mesen_cx4_trace.py`` (GPL-3.0-or-later, alewman; moved out of hg51b-python on 2026-11-19), folded in here 2026-11-23 without changing what it does. Two things Mesen2's Lua API cannot do and its C API can (OBSERVED by hg51b-python, 2026-11-06): - **Hold controller 2's B at power-on**, which enters a game's built-in Cx4 test (Mega Man X2/X3). Lua's input call is ignored for port 2 in this build, so the runner uses the debugger's input override. - **Trace the Cx4**: Lua execution callbacks never fire for it, but the trace logger does. A line is one instruction before it executes: the 24-bit ROM address of the cached word, the bytes, the disassembly, the registers (decimal) and a cycle column whose origin is unclear (small and restarting; not a time stamp). A game's test runs 79,000 to 197,000 Cx4 instructions a frame (up to 8 MB of text a frame, OBSERVED on Mega Man X2), so the trace covers only ``trace_frames`` frames from ``trace_start``; the script breaks execution at each window edge, where the runner starts or stops the trace logger, so the edges are exact to the frame. The trace is gzipped afterwards. """ from __future__ import annotations import ctypes import gzip import time from pathlib import Path from . import api from .lua import tagged from .snes import SnesConfig, snes_config CX4 = api.CPU_TYPES["cx4"] 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 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() -- the runner 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("{done}") end end, emu.eventType.endFrame) """ # Controller 1 presses (FRAME:BUTTON, held 6 frames from FRAME): Lua's input call 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: 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. # One "H ..." log row per frame; the runner 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 """ #: The buttons a press may name. BUTTONS = ("a", "b", "x", "y", "l", "r", "up", "down", "left", "right", "select", "start") 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( lib: Path, cart: Path, out: Path, *, test: bool = False, frames: int = 300, trace_start: int = 0, trace_frames: int = 0, press: list[str] = (), host: bool = False, timeout: float = 300.0, prefix_lua: str = "", extra_lua: str = "", done: str = "MESEN-DONE", until: str | None = None, config: SnesConfig | None = None, script_io: bool | None = None, tag: bool = False, ) -> tuple[str, float]: """One run into ``out``: ``cx4.trace`` (raw, gzipped by ``finish_trace``), ``host.txt.gz`` with ``host``. Returns the script's log and the wall time. ``prefix_lua`` and ``extra_lua`` go before and after the runner's script (its lines tagged with ``lua.TAG`` if ``tag``), which logs ``done`` after the picture; the run ends when ``until`` (default ``done``) is logged. ``config`` replaces ``snes_config()``; ``script_io`` (None: as Mesen2 has it) allows Lua's io and os libraries.""" until = until or done # The polled host stream (hg51b-mesen-harness's way): not with ``tag`` (run.py), whose lines # are tagged and which takes every row from the full script log itself. poll_host = host and not tag m = api.load(lib) m.SetSnesConfig.argtypes = [SnesConfig] m.SetInputOverrides.argtypes = [ctypes.c_uint32, api.Pad] home = out / "home" home.mkdir(parents=True, exist_ok=True) api.start(m, home) m.Pause() m.SetEmulationFlag(api.CONSOLE_MODE, True) if script_io is not None: m.SetDebugConfig(api.debug_config(script_io)) m.SetSnesConfig(config if config is not None else snes_config()) if not m.LoadRom(str(cart.resolve()).encode(), b""): raise SystemExit("LoadRom failed (a .zip? extract the .sfc first)") m.InitializeDebugger() if test: pad = api.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 press)) lua = LUA.format( frames=frames, trace_start=trace_start if trace_frames and trace_start else -1, trace_end=trace_start + trace_frames if trace_frames else -1, presses=PRESS_LUA.format(presses=presses) if press else "", host=HOST_LUA.format() if host else "", flush="flush(frames)" if host else "", done=done, ) lua = prefix_lua + (tagged(lua) if tag else lua) + extra_lua script = m.LoadScript(b"cx4.lua", str(home.resolve()).encode(), lua.encode(), -1) host_rows: dict[int, str] = {} trace = out / "cx4.trace" options = api.TraceLoggerOptions(True, False, False, b"", FORMAT.encode()) tracing = done_tracing = trace_frames == 0 if not tracing and trace_start == 0: m.SetTraceOptions(CX4, options) m.StartLogTraceToFile(str(trace.resolve()).encode()) tracing = True m.SetEmulationFlag(api.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 < timeout: time.sleep(0.01) stopped = m.IsExecutionStopped() m.GetScriptLog(script, buf, len(buf)) log = buf.value.decode(errors="replace") if poll_host: for row in log.splitlines(): if row.startswith("H"): number, _, data = row[1:].partition(" ") host_rows[int(number)] = data if tag and until in log: # run.py: held at the end of the last frame (before an edge) break if stopped: # the script broke at a window edge: the frame is exact if not tracing: m.SetTraceOptions(CX4, options) m.StartLogTraceToFile(str(trace.resolve()).encode()) tracing = True elif not done_tracing: m.StopLogTraceToFile() # before Release: after it, the call crashes (OBSERVED) done_tracing = True m.ResumeExecution() continue if until 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 poll_host and row.startswith("H"): number, _, data = row[1:].partition(" ") host_rows[int(number)] = data api.finish(m) if poll_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 finish_trace(out: Path) -> int | None: """Gzip ``out/cx4.trace`` into ``cx4.trace.gz`` and empty the raw file; the line count, or None when there was no trace.""" trace = out / "cx4.trace" if not (trace.exists() and trace.stat().st_size): return None 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 return lines