# SPDX-License-Identifier: MIT """Run MAME 0.285 headless on this board's sets, as a closed-box detector (docs/mame-oracle.md). python -I scripts/mame_trace.py --frames 3 # trace the main CPU python -I scripts/mame_trace.py --frames 3 --driver sitv # ... another set python -I scripts/mame_trace.py --skip 600 --frames 3 # trace 3 frames after 10 s python -I scripts/mame_trace.py --snap 5 # no trace: run, save a PNG Romsets come from MAME_ROMPATH (read in place). Output goes to reference/mame/-/ (git-ignored): run.log (one line per instruction, the state before it executes, plus one line per watched write), snap/, stdout.txt. MAME's source is never read: only its binary is run. One MAME process at a time. """ from __future__ import annotations import argparse import os import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] # Per board: the CPU to trace, the registers to log, and the writes to watch: # (label, space command, start, length). wpset watches program space, wpiset I/O space. BOARD = { "driver": "pacman", "cpu": ":maincpu", "fields": "pc,af,bc,de,hl,sp,i,im,iff1", "watches": [("OUT", "wpiset", "0", "100"), ("LATCH", "wpset", "5000", "8"), ("WSG", "wpset", "5040", "20")], } def lua(frames: int, trace: bool, skip: int = 0) -> str: """The autoboot script; with skip > 0 the trace starts at that frame.""" lines, setup = [], [] if trace: names = BOARD["fields"].split(",") fmt = " ".join(["S"] + ["%X"] * len(names) + ["%d", "%d"]) setup += [ "local dbg = manager.machine.debugger", f'dbg.visible_cpu = manager.machine.devices["{BOARD["cpu"]}"]', f"dbg:command('trace S.trace,{BOARD['cpu']},noloop," f'{{logerror "{fmt}\\\\n",{BOARD["fields"]},totalcycles,beamy}}\')', ] for label, command, start, length in BOARD["watches"]: setup.append( f"dbg:command('{command} {start},{length},w,1," f'{{logerror "{label} %X %X %d %d\\\\n",wpaddr,wpdata,totalcycles,beamy; g}}\')' ) setup.append('dbg:command("go")') if not skip: lines += setup lines += [ "count = 0", "notifier = emu.add_machine_frame_notifier(function()", " count = count + 1", ] if skip: lines += [f" if count == {skip} then"] + [" " + s for s in setup] + [" end"] lines += [ f" if count == {skip + frames} then", " manager.machine.video:snapshot()", " manager.machine:exit()", " end", "end)", ] return "\n".join(lines) + "\n" def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--driver", default=BOARD["driver"]) parser.add_argument("--frames", type=int, default=0, help="trace this many frames") parser.add_argument("--skip", type=int, default=0, help="start tracing after N frames") parser.add_argument("--snap", type=float, default=0, help="untraced run of N seconds") parser.add_argument("--rompath", default=os.environ.get("MAME_ROMPATH")) parser.add_argument("--mame", default="mame") args = parser.parse_args() if not args.rompath: print("set MAME_ROMPATH (a MAME romset collection)", file=sys.stderr) return 2 trace = args.frames > 0 frames = args.frames if trace else max(1, round(args.snap * 60)) out = ROOT / "reference" / "mame" / f"{args.driver}-{'trace' if trace else 'snap'}{f'-at{args.skip}' if args.skip else ''}" out.mkdir(parents=True, exist_ok=True) script = out / "run.lua" script.write_text(lua(frames, trace, args.skip), encoding="utf-8") command = [ args.mame, args.driver, "-rompath", args.rompath, "-homepath", str(out), "-snapshot_directory", str(out / "snap"), "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-log", "-seconds_to_run", str(int((args.skip + frames) / 60) + 5), "-autoboot_script", str(script), ] # fmt: skip if trace: command += ["-debug", "-debugger", "none"] result = subprocess.run(["nice", *command], cwd=out, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) # fmt: skip (out / "stdout.txt").write_text(result.stdout, encoding="utf-8") log = out / "error.log" if log.exists(): log.replace(out / "run.log") # S.trace (MAME's disassembly, interrupt markers included) stays beside run.log. print(f"exit {result.returncode}; output in {out.relative_to(ROOT)}") return result.returncode if __name__ == "__main__": sys.exit(main())