#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Record the S-CPU's accesses to the Cx4 window ($6000-$7FFF) on MAME 0.285, and screens. MAME 0.285 has **no HG51B CPU device** (none listed by the binary, measured 2026-11-06): its Cx4 is a high-level emulation (``src/mame/nintendo/snescx4.cpp``, GPL-2.0+: read under the old rule, a closed box from now on). It is therefore a **command-level detector**: it records what the game asks of the Cx4 and what the HLE answers, never an instruction. Uses: - the host stream of a window (every read and write the 5A22 makes to banks 00-3F/80-BF $6000-$7FFF, stamped with the frame), to replay into the core's board-free harness (docs/validation.md "The minimal harness"); - the game's built-in Cx4 test (``--press "0:P2 B:360"``) and its screen (``--snapshots``), as a second emulator beside Mesen2. Run directory ``tests/mame_traces//`` (gitignored): ``host.log.gz`` with ``R addr value frame`` / ``W addr value frame`` lines, ``snap/`` screens, ``summary.json``. The cartridge (``.zip``/``.7z``/``.sfc``) is extracted there with ``7z``; MAME needs only ``snes.zip`` (the S-SMP IPL) from ``ROMs (non-merged)``. No data ROM is needed (the HLE has its own tables). python -I scripts/mame_cx4_host.py "Mega Man X2 (USA).zip" --frames 200 \\ --press "0:P2 B:170" --snapshots 200 Traps (snes-python docs/mame-oracle.md, upd7725-python docs/mame-oracle.md): ``-seconds_to_run`` is an integer; a watchpoint action with an unknown symbol or unbalanced braces is silently dropped; watch all banks (the test code runs with DB = 00 and other banks), not only bank 00. """ from __future__ import annotations import argparse import gzip import json import os import shutil import subprocess import sys import time from collections import Counter from pathlib import Path ROOT = Path(__file__).resolve().parents[1] MAME = os.environ.get("MAME", shutil.which("mame") or "mame") # MAME 0.285 on the path #: MAME's own ';'-separated search path (the player's sets: the snes driver's BIOS/devices). DEFAULT_ROMPATH = os.environ.get("MAME_ROMPATH", "") FPS = 60.0988 LUA = """\ local dbg = manager.machine.debugger for _, bank in ipairs({{"000000", "800000"}}) do dbg:command('wpset ' .. bank .. ':maincpu,400000,w,(wpaddr & e000) == 6000,{{logerror "W %X %X %d\\\\n",wpaddr,wpdata,frame; g}}') dbg:command('wpset ' .. bank .. ':maincpu,400000,r,(wpaddr & e000) == 6000,{{logerror "R %X %X %d\\\\n",wpaddr,wpdata,frame; g}}') end for _, line in ipairs(dbg.consolelog) do print("CON " .. line) end dbg:command("go") for tag, dev in pairs(manager.machine.devices) do if string.find(tag, "snsslot") then print("SLOT " .. tag .. " " .. dev.shortname) end end local presses = {presses} local fields = {{}} for ptag, port in pairs(manager.machine.ioport.ports) do for fname, fld in pairs(port.fields) do fields[fname] = fld end end for _, p in ipairs(presses) do if fields[p[2]] == nil then print("NOINPUT " .. p[2]) end end local screen = manager.machine.screens[":screen"] sub = emu.add_machine_frame_notifier(function() local frame = screen:frame_number() for _, p in ipairs(presses) do local fld = fields[p[2]] if fld ~= nil then if frame == p[1] then fld:set_value(1) end if frame == p[1] + p[3] then fld:clear_value() end end end if {snap_every} > 0 and frame > 0 and frame % {snap_every} == 0 then manager.machine.video:snapshot() end if frame >= {frames} then manager.machine:exit() end end) """ def presses_lua(presses: list[str]) -> str: rows = [] for press in presses: parts = press.split(":") hold = int(parts[2]) if len(parts) > 2 else 6 rows.append(f'{{{int(parts[0])}, "{parts[1]}", {hold}}}') return "{" + ", ".join(rows) + "}" def extract(cart: Path, run: Path) -> Path: if cart.suffix.lower() in {".7z", ".zip"}: subprocess.run(["7z", "x", "-y", f"-o{run}", str(cart)], check=True, capture_output=True) found = sorted(p for p in run.iterdir() if p.suffix.lower() in {".sfc", ".smc"}) if not found: raise SystemExit(f"no .sfc/.smc inside {cart}") return found[0] return cart def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("cart", type=Path) parser.add_argument("--frames", type=int, default=200) parser.add_argument("--press", action="append", default=[], metavar="FRAME:FIELD[:HOLD]", help='hold an input field (MAME name, e.g. "P2 B") from FRAME for HOLD frames') # fmt: skip parser.add_argument( "--snapshots", type=int, default=0, metavar="N", help="a screen every N frames" ) parser.add_argument("--rompath", default=os.environ.get("SNES_MAME_ROMPATH", DEFAULT_ROMPATH)) parser.add_argument("--out", type=Path, help="run directory (default tests/mame_traces/)") args = parser.parse_args() run = args.out or ROOT / "tests" / "mame_traces" / args.cart.stem.replace(" ", "_") run.mkdir(parents=True, exist_ok=True) cart = extract(args.cart, run) lua = run / "host.lua" lua.write_text( LUA.format(presses=presses_lua(args.press), snap_every=args.snapshots, frames=args.frames), encoding="utf-8", ) command = [ "nice", "-n", "19", MAME, "snes", "-cart", str(cart), "-rompath", args.rompath, "-homepath", str(run), "-snapshot_directory", str(run / "snap"), "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-debug", "-debugger", "none", "-oslog", "-seconds_to_run", str(int(args.frames / FPS) + 3), "-autoboot_script", str(lua), ] # fmt: skip counts: Counter[str] = Counter() began = time.monotonic() with (run / "mame.stdout").open("w", encoding="utf-8") as stdout: mame = subprocess.Popen(command, cwd=run, stdout=stdout, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace") # fmt: skip with gzip.open(run / "host.log.gz", "wt", encoding="utf-8", compresslevel=6) as sink: for line in mame.stderr: if line[:2] in ("R ", "W "): sink.write(line) address = int(line.split()[1], 16) & 0xFFFF region = ( f"{address:04X}" if address >= 0x7F40 else "data RAM" if address & 0xFFF < 0xC00 else "other" ) counts[f"{line[0]} {region}"] += 1 returncode = mame.wait() console = [ln for ln in (run / "mame.stdout").read_text(encoding="utf-8").splitlines() if ln.startswith(("SLOT", "CON", "NOINPUT"))] # fmt: skip summary = {"cart": args.cart.name, "frames": args.frames, "presses": args.press, "wall_seconds": round(time.monotonic() - began, 1), "mame_exit": returncode, "console": console, "accesses": dict(sorted(counts.items()))} # fmt: skip (run / "summary.json").write_text(json.dumps(summary, indent=1) + "\n", encoding="utf-8") print(json.dumps(summary, indent=1)) return 0 if returncode == 0 else 1 if __name__ == "__main__": sys.exit(main())