# SPDX-License-Identifier: MIT """Run MAME 0.285's Saturn driver headless, as a closed-box detector (docs/mame-oracle.md). python -I scripts/mame_trace.py --frames 10 # trace the master SH-2 python -I scripts/mame_trace.py --frames 10 --cpu slave # ... or another CPU python -I scripts/mame_trace.py --snap 4 # no trace: run, save a PNG No disc is mounted: the boot ROM runs to its own screen (the CD player / system settings), which is all the board's first milestones need. The romsets come from MAME_ROMPATH (saturn.zip holds the boot ROMs and the CD block ROMs). Output goes to reference/mame/-/ (git-ignored): the run's log with one line per instruction ("S pc sr pr r15 totalcycles") and SMPC/SCU register writes, and snap/. Traps: the SH-2 DRC must be off while tracing (-nodrc), as in sh2-python's recipe; tags are ":maincpu", ":slave", ":audiocpu", ":saturn_cdb:cdbcpu", ":scu:scudsp". """ from __future__ import annotations import argparse import os import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] CPUS = { "master": ":maincpu", "slave": ":slave", "sound": ":audiocpu", "cdb": ":saturn_cdb:cdbcpu", } FIELDS = { "master": "pc,sr,pr,r15", "slave": "pc,sr,pr,r15", "sound": "pc,sr,a7", "cdb": "pc,sr,pr,r15", } # SH-2 external writes MAME masks to 27 bits: the SMPC command register (IREG/COMREG window) # and the SCU's register block. WATCHES = [("SMPC", "0010001f", "1", "w"), ("SCU", "05fe0000", "100", "w")] def lua(cpu: str, frames: int, trace: bool) -> str: lines = ["local dbg = manager.machine.debugger"] if trace else [] if trace: names = FIELDS[cpu].split(",") fmt = " ".join(["S"] + ["%X"] * len(names) + ["%d"]) lines += [ f'dbg.visible_cpu = manager.machine.devices["{CPUS[cpu]}"]', f"dbg:command('trace S.trace,{CPUS[cpu]},noloop," f'{{logerror "{fmt}\\\\n",{FIELDS[cpu]},totalcycles}}\')', ] if cpu in ("master", "slave"): for tag, start, length, rw in WATCHES: lines.append( f"dbg:command('wpset {start},{length},{rw},1," f'{{logerror "{tag} %X %X %X %d\\\\n",wpaddr,wpsize,wpdata,totalcycles; g}}\')' ) lines.append('dbg:command("go")') lines += [ "count = 0", "notifier = emu.add_machine_frame_notifier(function()", " count = count + 1", f" if count == {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="saturn", help="saturn, saturnjp, saturneu, ...") parser.add_argument("--cpu", default="master", choices=sorted(CPUS)) parser.add_argument("--frames", type=int, default=0, help="trace this many 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 (it must hold saturn.zip)", 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}-{args.cpu if trace else 'snap'}" out.mkdir(parents=True, exist_ok=True) script = out / "run.lua" script.write_text(lua(args.cpu, frames, trace), 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(frames / 50) + 5), "-autoboot_script", str(script), ] # fmt: skip if trace: command += ["-nodrc", "-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") (out / "S.trace").unlink(missing_ok=True) # the disassembly; run.log has the state print(f"exit {result.returncode}; output in {out.relative_to(ROOT)}") return result.returncode if __name__ == "__main__": sys.exit(main())