# SPDX-License-Identifier: MIT """Run MAME 0.285's Irem drivers headless, as a closed-box detector (docs/mame-oracle.md). python -I scripts/mame_trace.py rtype --frames 3 # trace the main V30 python -I scripts/mame_trace.py rtype --frames 3 --cpu sound # ... the Z80 python -I scripts/mame_trace.py nspirit --frames 3 --cpu mcu # ... the i8751 python -I scripts/mame_trace.py gunforce --frames 3 --cpu sound # ... the encrypted V35 python -I scripts/mame_trace.py inthunt --snap 20 # no trace: run, save a PNG python -I scripts/mame_trace.py rtype --maps # dump the address maps The romsets come from MAME_ROMPATH (non-merged sets read in place). Output goes to reference/mame/-/ (git-ignored): run.log with one line per instruction ("T "), and summary.txt with the instruction count per frame, the clocks per frame and the clocks per instruction. MAME is run as a binary only; its source is never fetched (docs/sources.md). One 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] TAGS = {"main": ":maincpu", "sound": ":soundcpu", "mcu": ":mcu"} # MAME's state names per CPU family (checked against `-debug` runs, docs/mame-oracle.md). FIELDS = { "nec": "ps,pc,aw,bw,cw,dw,sp,ss,ds0,ds1,psw", "z80": "pc,af,bc,de,hl,sp", "mcs51": "pc,acc,psw,sp", } FAMILY = {"main": "nec", "sound": "nec", "mcu": "mcs51"} def lua(tag: str, fields: str, start: int, frames: int, trace: bool, maps: bool) -> str: """The autoboot script: trace from frame `start` for `frames` frames, then exit. `noloop` turns off MAME's loop detection, which otherwise collapses a repeated loop into one line (and skips the logerror action), so every instruction is logged: the counts in docs/domains-and-speed.md need that (checked 2026-11-26 on `rtype`). """ if maps: return (ROOT / "scripts" / "mame_maps.lua").read_text(encoding="utf-8") on = "" if trace: names = fields.split(",") fmt = " ".join(["T %X"] + ["%X"] * len(names) + ["%d"]) on = (f"dbg:command('trace T.trace,{tag},noloop," f'{{logerror "{fmt}\\\\n",curpc,{fields},totalcycles}}\')') lines = [ "dbg = manager.machine.debugger", f'dbg.visible_cpu = manager.machine.devices["{tag}"]', "count = 0", ] if trace else ["count = 0"] if trace and start == 0: lines.append(on) if trace: lines.append('dbg:command("go")') lines += [ "notifier = emu.add_machine_frame_notifier(function()", " count = count + 1", ' manager.machine:logerror(string.format("FRAME %d\\n", count))', ] if trace and start > 0: lines += [f" if count == {start} then", f" {on}", " end"] lines += [ f" if count == {start + frames} then", " manager.machine.video:snapshot()", " manager.machine:exit()", " end", "end)", ] return "\n".join(lines) + "\n" def summarise(log: Path, out: Path) -> str: """Instructions and clocks per frame, from run.log's FRAME markers and T lines.""" frames, count, first, last = [], 0, None, None for line in log.read_text(encoding="utf-8", errors="replace").splitlines(): if line.startswith("T "): cycles = int(line.rsplit(" ", 1)[1]) first = cycles if first is None else first last = cycles count += 1 elif "FRAME" in line: frames.append((count, first, last)) count, first, last = 0, None, None rows = ["frame instructions clocks clocks/instruction"] for n, (ins, a, b) in enumerate(frames, 1): if not ins: continue clocks = (b - a) if a is not None and b is not None else 0 rows.append(f"{n} {ins} {clocks} {clocks / ins if ins else 0:.2f}") text = "\n".join(rows) + "\n" out.write_text(text, encoding="utf-8") return text def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("set", help="a MAME set: rtype, nspirit, gunforce, inthunt, ...") parser.add_argument("--cpu", default="main", choices=sorted(TAGS)) parser.add_argument("--frames", type=int, default=0, help="trace this many frames") parser.add_argument("--start", type=int, default=0, help="first traced frame") parser.add_argument("--snap", type=float, default=0, help="untraced run of N seconds") parser.add_argument("--maps", action="store_true", help="dump the address maps and exit") parser.add_argument("--z80", action="store_true", help="the sound CPU is a Z80 (M72, M90)") 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 (non-merged MAME sets)", file=sys.stderr) return 2 trace = args.frames > 0 and not args.maps family = "z80" if (args.cpu == "sound" and args.z80) else FAMILY[args.cpu] frames = args.frames if trace else max(1, round(args.snap * 55)) label = "maps" if args.maps else (args.cpu if trace else "snap") out = ROOT / "reference" / "mame" / f"{args.set}-{label}" out.mkdir(parents=True, exist_ok=True) script = out / "run.lua" script.write_text(lua(TAGS[args.cpu], FIELDS[family], args.start, frames, trace, args.maps), encoding="utf-8") # fmt: skip command = [ args.mame, args.set, "-rompath", args.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", "-verbose", "-seconds_to_run", str(int((args.start + frames) / 50) + 5), "-autoboot_script", str(script), ] # fmt: skip if trace: command += ["-debug", "-debugger", "none"] env = dict(os.environ, IREM_MAP_OUT=str(out / "maps.txt")) result = subprocess.run(["nice", "taskset", "-c", "24-31", *command], cwd=out, env=env, 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") # T lines and FRAME markers, in order (out / "T.trace").unlink(missing_ok=True) # the disassembly; run.log has the state print(f"exit {result.returncode}; output in {out.relative_to(ROOT)}") if trace and (out / "run.log").exists(): print(summarise(out / "run.log", out / "summary.txt"), end="") return result.returncode if __name__ == "__main__": sys.exit(main())