#!/usr/bin/env python3 """Record MAME 0.285's per-instruction 5A22 trace and B-bus/CPU-register log for a SNES cartridge. Runs the recipe in docs/mame-oracle.md in a fresh directory (default ``tests/mame_traces/-``, gitignored) and leaves ``error.log`` there. The ``snes`` driver needs the S-SMP IPL ROM (``spc700.rom`` inside a MAME ``snes.zip``): bring your own, by ``--rompath`` or ``MAME_ROMPATH``; the default is MAME_ROMPATH (a local MAME non-merged set), read in place. A ``.7z`` or ``.zip`` cartridge (No-Intro style, one ROM inside) is extracted into the run directory with ``7z``; nothing is written elsewhere. python scripts/mame_trace.py snes tests/test_roms/gilyon/cputest/cputest-full.sfc \ --no-trace --seconds 30 --text Success --text Failed python scripts/mame_trace.py snes "$NO_INTRO_DIR/.../Super Mario World (USA).zip" \ --seconds 2 python scripts/mame_trace.py snes ROM.sfc --seconds 1 --spc # S-SMP trace too ``error.log`` then holds, in execution order: - ``C PC A X Y P S D DB E totalcycles beamy beamx frame``: one line per 5A22 instruction, before it executes (hex, then decimal). PC is 24-bit (PB:PC). ``totalcycles`` counts **master clocks** (the 5A22 device is clocked at 21.477272 MHz and charges 6, 8 or 12 per access; docs/mame-oracle.md). beamy/beamx are MAME's *screen* position; the screen is configured at twice the dot clock, so beamx is in half-dots (0-681), not dots; - ``R addr value totalcycles`` / ``W addr value totalcycles`` for every 5A22 access to $2100-$21FF (B bus) and $4200-$43FF (CPU registers, DMA) in bank $00, stamped with the *instruction's start* cycle, not the bus cycle. DMA's own B-bus accesses are not CPU accesses and do not appear; - ``T addr totalcycles``: the first read of each ``--text`` string in the ROM (a cheap result detector for ROMs that print "Success"/"Failed"). With ``--spc``, ``spc.trace`` (beside ``error.log``) holds one ``PC: disassembly`` line per S-SMP instruction, no registers and no cycle count (see SPC_LUA); ``cpu.trace`` is the same for the 5A22. MAME saves a final snapshot at exit under ``snap//``. """ from __future__ import annotations import argparse import os import shutil import subprocess import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] MAME = "/usr/games/mame" # The local MAME set, read in place, from MAME_ROMPATH (snes.zip holds only # spc700.rom, 64 bytes, SHA-1 97e352553e94242ae823547cd853eecda55c20f0). DEFAULT_ROMPATH = os.environ.get("MAME_ROMPATH", "") # Tags from `mame -listdevices snes` (0.285): maincpu = Ricoh 5A22, soundcpu = # S-SMP, s_dsp, ppu, snsslot, ctrl1/ctrl2. DRIVERS = { "snes": "NTSC, 21.477272 MHz master clock", "snespal": "PAL, 21.281370 MHz master clock", } # A logerror action silently drops lines past 14 values (found on the Z80 # boards); the C line has 14 exactly. TRACE_LUA = """\ local dbg = manager.machine.debugger dbg.visible_cpu = manager.machine.devices[":maincpu"] dbg:command('trace cpu.trace,:maincpu,noloop,{{logerror "C %X %X %X %X %X %X %X %X %X %d %d %d %d\\\\n",\ pc,a,x,y,p,s,d,db,e,totalcycles,beamy,beamx,frame}}') {spc}dbg:command('wpset 2100,100,r,1,{{logerror "R %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}') dbg:command('wpset 2100,100,w,1,{{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}') dbg:command('wpset 4200,200,r,1,{{logerror "R %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}') dbg:command('wpset 4200,200,w,1,{{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}') {text}dbg:command("go") """ # A trace action's logerror is evaluated with the *visible* CPU's symbols # (measured 2026-10-21: "S" lines carried the 5A22's PC and registers, even # with visible_cpu switched while the command was parsed), so the S-SMP is # traced without an action: MAME writes "PC: disassembly" to spc.trace. SPC_LUA = "dbg:command('trace spc.trace,:soundcpu,noloop')\n" # One-shot watchpoint per text string: log, then clear itself (wpclear by index # is not stable across MAME versions, so a flag variable gates the log). TEXT_LUA = ( 'dbg:command(\'wpset {addr:X},1,r,temp{n}==0,{{logerror "T {word} {addr:X} %d\\\\n",' "totalcycles; temp{n}=1; g}}')\n" ) def extract(cart: Path, out: Path) -> Path: """The ROM image inside a .7z/.zip, extracted into ``out``; a plain image is copied.""" if cart.suffix.lower() not in {".7z", ".zip"}: target = out / cart.name shutil.copyfile(cart, target) return target subprocess.run(["7z", "e", "-y", f"-o{out}", str(cart)], check=True, stdout=subprocess.DEVNULL) images = [ p for p in out.iterdir() if p.suffix.lower() in {".sfc", ".smc", ".swc", ".fig", ".bin"} ] if len(images) != 1: raise SystemExit(f"expected one ROM image in {cart.name}, found {[p.name for p in images]}") return images[0] def lorom_addresses(image: bytes, word: str) -> list[int]: """CPU addresses (banks $00 and $80) of ``word`` in a LoROM image; [] if not found.""" data = image[512:] if len(image) % 1024 == 512 else image # copier header offset = data.find(word.encode("ascii")) if offset < 0: return [] low = (offset >> 15) << 16 | 0x8000 | (offset & 0x7FFF) return [low, low | 0x800000] def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("driver", choices=sorted(DRIVERS)) parser.add_argument("cart", type=Path, help=".sfc/.smc image, or a .7z/.zip holding one") parser.add_argument("--seconds", type=int, default=2, help="emulated seconds") parser.add_argument("--no-trace", action="store_true", help="no instruction or register trace") parser.add_argument("--spc", action="store_true", help="also trace the S-SMP") parser.add_argument( "--text", action="append", default=[], help="log the first read of this ROM string (LoROM)" ) parser.add_argument("--rompath", default=DEFAULT_ROMPATH) parser.add_argument("--out", type=Path) parser.add_argument("--mame", default=MAME) args = parser.parse_args() cart = args.cart.resolve() stem = cart.stem.split(" (")[0].replace(" ", "_") out = (args.out or ROOT / "tests" / "mame_traces" / f"{args.driver}-{stem}").resolve() if out.exists(): shutil.rmtree(out) out.mkdir(parents=True) image_path = extract(cart, out) image = image_path.read_bytes() text = "" for n, word in enumerate(args.text): for addr in lorom_addresses(image, word): text += TEXT_LUA.format(addr=addr, n=n % 10, word=word) debugging = not args.no_trace or bool(text) if args.no_trace and text: lua = "local dbg = manager.machine.debugger\n" + text + 'dbg:command("go")\n' elif not args.no_trace: lua = TRACE_LUA.format(spc=SPC_LUA if args.spc else "", text=text) else: lua = "" script = [] if lua: (out / "trace.lua").write_text(lua, encoding="utf-8") script = ["-autoboot_script", str(out / "trace.lua")] version = subprocess.run( [args.mame, "-version"], capture_output=True, text=True, check=True ).stdout.strip() debug = ["-debug", "-debugger", "none"] if debugging else [] began = time.monotonic() # error.log lands in the working directory, not under -homepath. subprocess.run( [args.mame, args.driver, "-cart", image_path.name, "-rompath", args.rompath, "-homepath", str(out), "-snapshot_directory", "snap", "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", *debug, "-log", "-seconds_to_run", str(args.seconds), *script], cwd=out, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) # fmt: skip wall = time.monotonic() - began counts = {b"C": 0, b"R": 0, b"W": 0} found = [] with (out / "error.log").open("rb") as log: for line in log: key = line[:1] if line[1:2] == b" " and key in counts: counts[key] += 1 elif line.startswith(b"T "): found.append(line.decode("ascii", "replace").strip()) print( f"MAME {version}, {args.driver}, {args.seconds} s emulated in {wall:.1f} s: {out / 'error.log'}" ) if not args.no_trace: print( f" {counts[b'C']:,} 5A22 instructions, " f"{counts[b'R']:,} register reads, {counts[b'W']:,} register writes" ) if args.spc and (out / "spc.trace").exists(): with (out / "spc.trace").open("rb") as spc: print(f" {sum(1 for _ in spc):,} S-SMP instructions in spc.trace") for line in found: print(f" {line}") return 0 if __name__ == "__main__": sys.exit(main())