# SPDX-License-Identifier: MIT """Run MAME 0.285's Konami System GX driver headless, as a closed-box detector. MAME_ROMPATH=... python -I scripts/mame_trace.py salmndr2 --cpu main --seconds 2 MAME_ROMPATH=... python -I scripts/mame_trace.py salmndr2 --cpu sound --seconds 2 MAME_ROMPATH=... python -I scripts/mame_trace.py salmndr2 --cpu dasp --seconds 1 MAME_ROMPATH=... python -I scripts/mame_trace.py salmndr2 --cpu main --seconds 3 \\ --from-frame 120 --frames 60 # one window only MAME_ROMPATH=... python -I scripts/mame_trace.py salmndr2 --maps # address maps only MAME_ROMPATH=... python -I scripts/mame_trace.py tbyahhoo --snap 4 # PNG every 4 s MAME_ROMPATH=... python -I scripts/mame_trace.py salmndr2 --watch main,CC0000,4 --seconds 25 One instruction per line goes to reference/mame/-/error.log (MAME's -log output; the run's cwd), as "T pc totalcycles frame vpos". Only short runs (a few emulated seconds): one MAME process at a time on this machine. Tags (from `-listxml`, MAME 0.285): ":maincpu" is the MC68EC020, ":soundcpu" the MC68000, ":dasp" the TMS57002. State names were probed with the debugger's `state` listing before use (docs/mame-oracle.md). Adapted from konami68k-python's mame_trace.py (the family's own MIT tooling). """ 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] CPUS = { "main": (":maincpu", "pc,sr,d0,d1,a0,a7"), "sound": (":soundcpu", "pc,sr,d0,d1,a0,a7"), "dasp": (":dasp", "pc"), } def lua(cpu: str | None, snap: int | None, start: int, frames: int | None, watch: tuple[str, str, str] | None = None) -> str: """The autoboot script. With --from-frame/--frames the trace is switched on and off again at those emulated times, counted in sixtieths of a second (so 1500 = 25 s), and only that window is written.""" out = [] if cpu: tag, fields = CPUS[cpu] fmt = " ".join(["T"] + ["%X"] * len(fields.split(",")) + ["%d", "%d", "%d"]) trace_on = (f"trace T.trace,{tag},noloop," f'{{logerror "{fmt}\\n",{fields},totalcycles,frame,beamy}}') out += [ "local dbg = manager.machine.debugger", f'dbg.visible_cpu = manager.machine.devices["{tag}"]', ] if start == 0 and frames is None: out += [f"dbg:command('{trace_on}')", 'dbg:command("go")'] else: # Emulated time, not a frame count: boards that reprogram their CRTC change # their frame rate (Racin' Force runs below 55 Hz), so frames are not seconds. stop = start + frames if frames is not None else 10**9 out += [ 'dbg:command("go")', "tstate = 0", "ttap = emu.add_machine_frame_notifier(function()", " local t = manager.machine.time:as_double() * 60", f" if tstate == 0 and t >= {start} then tstate = 1; dbg:command('{trace_on}') end", f" if tstate == 1 and t >= {stop} then tstate = 2; dbg:command('trace off,{tag}') end", "end)", ] if watch: tag, fields = CPUS[watch[0]] addr, length = watch[1], watch[2] out += [ "local wdbg = manager.machine.debugger", f'wdbg.visible_cpu = manager.machine.devices["{tag}"]', f"wdbg:command('wpset {addr},{length},w,1,{{logerror \"W %X %X %X %d %d\\\\n\",pc,wpaddr,wpdata,frame,beamy; go}}')", 'wdbg:command("go")', ] if snap: out += [ "frames = 0", "tap = emu.add_machine_frame_notifier(function()", " frames = frames + 1", f" if frames % {snap * 60} == 0 then manager.machine.video:snapshot() end", "end)", ] return "\n".join(out) + "\n" def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("game") ap.add_argument("--cpu", choices=sorted(CPUS)) ap.add_argument("--seconds", type=int, default=2) ap.add_argument("--snap", type=int, help="save a PNG every N emulated seconds") ap.add_argument("--from-frame", type=int, default=0, help="start the trace at this many 1/60 s") ap.add_argument("--frames", type=int, help="trace this many 1/60 s, then stop") ap.add_argument("--maps", action="store_true", help="print the address maps and exit") ap.add_argument("--watch", help="CPU,ADDR,LEN: log every write there as 'W pc addr data " "frame vpos' (a debugger watchpoint)") a = ap.parse_args() rompath = os.environ.get("MAME_ROMPATH") if not rompath: sys.exit("set MAME_ROMPATH") label = a.cpu or ("maps" if a.maps else "watch" if a.watch else "snap") work = ROOT / "reference" / "mame" / f"{a.game}-{label}" work.mkdir(parents=True, exist_ok=True) for stale in ("error.log", "T.trace", "maps.txt"): if (work / stale).exists(): trash = ROOT / "trash" / "mame-runs" trash.mkdir(parents=True, exist_ok=True) shutil.move(str(work / stale), str(trash / f"{time.strftime('%Y%m%d-%H%M%S')}-{a.game}-{label}-{stale}")) script = ROOT / "scripts" / "mame_maps.lua" if a.maps else work / "run.lua" if not a.maps: watch = tuple(a.watch.split(",")) if a.watch else None script.write_text(lua(a.cpu, a.snap, a.from_frame, a.frames, watch)) mame = os.environ.get("MAME") or shutil.which("mame") or sys.exit("put mame on PATH or set MAME") cmd = [mame, a.game, "-rompath", rompath, "-homepath", str(work), "-snapshot_directory", str(work / "snap"), "-cfg_directory", str(work / "cfg"), "-nvram_directory", str(work / "nvram"), "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-seconds_to_run", str(a.seconds), "-autoboot_script", str(script)] if a.cpu or a.watch: cmd += ["-debug", "-debugger", "none", "-log"] print(" ".join(cmd[:2]), "...", file=sys.stderr) if a.maps: r = subprocess.run(cmd, cwd=work, capture_output=True, text=True) lines = [ln for ln in r.stdout.splitlines() if ln.startswith("MAP ")] (work / "maps.txt").write_text("\n".join(lines) + "\n") print(f"{a.game}: {len(lines)} map entries -> {work / 'maps.txt'}") return 0 r = subprocess.run(cmd, cwd=work) log = work / "error.log" if a.cpu and log.exists(): n = sum(1 for line in log.open(errors="replace") if line.startswith("T ")) print(f"{a.game} {a.cpu}: {n} instructions traced in {a.seconds} s -> {log}") return r.returncode if __name__ == "__main__": raise SystemExit(main())