# SPDX-License-Identifier: MIT """Run MAME 0.285's Data East 16-bit drivers headless, as a closed-box detector. python -I scripts/mame_trace.py robocop --frames 3 # trace the 68000 python -I scripts/mame_trace.py robocop --frames 3 --cpu sub # ... the HuC6280 (DEM-01) python -I scripts/mame_trace.py baddudes --frames 3 --cpu mcu # ... the i8751 python -I scripts/mame_trace.py midres --frames 3 --cpu sound # ... the sound CPU python -I scripts/mame_trace.py robocop --snap 20 # no trace: run, save a PNG MAME is run, never read (docs/mame-oracle.md). The romsets come from MAME_ROMPATH (non-merged sets: one zip holds the whole machine). Output goes to reference/mame/-/ (git-ignored): run.log with one line per instruction ("S pc totalcycles"), the writes any --watch watchpoint logs ("W address size data totalcycles"), and snap/*.png. One MAME process at a time, a few emulated seconds at most, under nice. CPU tags (mame -listdevices): maincpu (68000, or the HuC6280 on actfancr/triothep), audiocpu (R65C02 / 6502 / HuC6280 / Z80 by board), sub (the HuC6280 beside the MB8421 on robocop and hippodrm), mcu (i8751 on baddudes, hbarrel, birdtry, bandit, karnov ...). Register symbols differ per CPU type; --fields overrides the default. """ from __future__ import annotations import argparse import os import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] CPUS = {"main": ":maincpu", "sound": ":audiocpu", "sub": ":sub", "mcu": ":mcu"} # Defaults by the CPU usually behind each tag on these boards. # Trap: an unknown symbol that spells a hex number (a7, acc) is logged as that constant. FIELDS = {"main": "pc,sr,d0,sp", "sound": "pc,a,x,p", "sub": "pc,a,x,p", "mcu": "pc,a,sp,psw"} def lua(tag: str, fields: str, frames: int, trace: bool, watch: list[str]) -> str: lines = ["local dbg = manager.machine.debugger"] if trace else [] if trace: names = fields.split(",") fmt = " ".join(["S"] + ["%X"] * len(names) + ["%d"]) lines += [ f'dbg.visible_cpu = manager.machine.devices["{tag}"]', f"dbg:command('trace S.trace,{tag},noloop," f'{{logerror "{fmt}\\\\n",{fields},totalcycles}}\')', ] for spec in watch: # "start,length" on the traced CPU's program space, writes lines.append( f"dbg:command('wpset {spec},w,1," f'{{logerror "W %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("machine", help="a MAME machine name: robocop, baddudes, midres, cninja, ...") parser.add_argument("--cpu", default="main", choices=sorted(CPUS)) parser.add_argument("--fields", help="register symbols to log (default by --cpu)") 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("--watch", action="append", default=[], help="write watchpoint 'start,length' (hex) on the traced CPU, repeatable") # fmt: skip parser.add_argument("--mame", default="mame") args = parser.parse_args() rompath = os.environ.get("MAME_ROMPATH") if not rompath: print("set MAME_ROMPATH (it must hold the machine's zip)", file=sys.stderr) return 2 trace = args.frames > 0 frames = args.frames if trace else max(1, round(args.snap * 58)) out = ROOT / "reference" / "mame" / f"{args.machine}-{args.cpu if trace else 'snap'}" out.mkdir(parents=True, exist_ok=True) script = out / "run.lua" fields = args.fields or FIELDS[args.cpu] script.write_text(lua(CPUS[args.cpu], fields, frames, trace, args.watch), encoding="utf-8") command = [ args.mame, args.machine, "-rompath", rompath, "-homepath", str(out), "-cfg_directory", str(out / "cfg"), "-nvram_directory", str(out / "nvram"), "-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 += ["-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 debugger's 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())