# SPDX-License-Identifier: MIT """Run MAME 0.285 headless as a closed-box detector: trace one CPU over a short window. MAME_ROMPATH=... python -I scripts/mame_trace.py ridgerac --cpu master --start 20 --window 0.25 MAME_ROMPATH=... python -I scripts/mame_trace.py timecris --cpu main --start 20 --window 0.25 MAME_ROMPATH=... python -I scripts/mame_trace.py ridgerac --snap 5 --start 0 --window 30 MAME_ROMPATH=... python -I scripts/mame_trace.py ridgerac --maps # address maps only MAME runs unthrottled to `--start` emulated seconds, then the debugger's `trace` command writes every instruction of one CPU (no `noloop`, so loops are counted in full) to reference/mame/-/T.trace for `--window` emulated seconds, and MAME exits. The script then counts instructions, gives the rate, and lists the hottest program counters (where a CPU spins waiting, which is what an exact interpreter still pays for). --snap N saves a PNG every N emulated seconds instead. Only short runs: one MAME process at a time on this machine, under `nice` and `taskset -c 24-31`. Tags and state names were probed on MAME 0.285 (docs/mame-oracle.md); the DSPs are TMS320C25s (C71 is Namco's mask-ROM TMS320C25); their state names are PC ACC P T AR0-AR7 and so on. The 68020's are D0-D7 A0-A7 PC SR VBR CACR CAAR; the 7700-family MCUs' are A B X Y S PC PG DT DPR PS E. """ from __future__ import annotations import argparse import collections import os import re import shutil import subprocess import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] CPUS = { "main": ":maincpu", # MC68020 (System 22) or MC68EC020 (Super System 22) "master": ":master", # Namco C71: a mask-ROM TMS320C25 "slave": ":slave", # Namco C71 "mcu": ":mcu", # Namco C74 (M37702) on System 22; M37710S4 on Super System 22 "iomcu": ":iomcu", # the second C74 (I/O board), System 22 only } FPS = 59.904060 # MAME's System 22 refresh (listxml) MAPS_LUA = ROOT / "scripts" / "mame_maps.lua" LOOP = re.compile(r"\(loops for (\d+) instructions\)") def lua(tag: str | None, start: float, window: float, snap: int | None, fps: float) -> str: f0 = int(round(start * fps)) f1 = f0 + max(1, int(round(window * fps))) out = ["frames = 0", "tap = emu.add_machine_frame_notifier(function()", " frames = frames + 1"] if tag: out += [ f" if frames == {f0} then", " local dbg = manager.machine.debugger", f' dbg.visible_cpu = manager.machine.devices["{tag}"]', f' dbg:command("trace T.trace,{tag}")', ' dbg:command("go")', " end", f" if frames == {f1} then", ' manager.machine.debugger:command("trace off")', " manager.machine:exit()", " end", ] if snap: out += [f" if frames % {int(round(snap * fps))} == 0 then manager.machine.video:snapshot() end", f" if frames == {f1} then manager.machine:exit() end"] out += ["end)"] if tag: out += ['manager.machine.debugger:command("go")'] return "\n".join(out) + "\n" def count(trace: Path, top: int) -> None: n = 0 looped = 0 pcs: collections.Counter[str] = collections.Counter() with trace.open(errors="replace") as f: for line in f: m = LOOP.search(line) if m: n += int(m.group(1)) looped += int(m.group(1)) continue if ":" not in line: continue pc = line.split(":", 1)[0].strip() if pc: n += 1 pcs[pc] += 1 print(f"instructions {n}; inside loops MAME's tracer folded (spins) {looped} " f"({100 * looped / max(n, 1):.1f} %)") hot = sum(c for _, c in pcs.most_common(top)) print(f"distinct pcs {len(pcs)}; top {top} pcs hold {hot} ({100 * hot / max(n, 1):.1f} %)") for pc, c in pcs.most_common(top): print(f" {pc} {c}") def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("game") ap.add_argument("--cpu", help="one of: " + " ".join(CPUS) + " (or a raw :tag)") ap.add_argument("--start", type=float, default=0.0, help="emulated seconds before tracing") ap.add_argument("--window", type=float, default=1.0, help="emulated seconds traced") ap.add_argument("--snap", type=int, help="save a PNG every N emulated seconds") ap.add_argument("--maps", action="store_true", help="print the address maps and exit") ap.add_argument("--fps", type=float, default=FPS) ap.add_argument("--top", type=int, default=8) a = ap.parse_args() rompath = os.environ.get("MAME_ROMPATH") or sys.exit("set MAME_ROMPATH") mame = os.environ.get("MAME") or shutil.which("mame") or sys.exit("put mame on PATH or set MAME") tag = CPUS.get(a.cpu, a.cpu) if a.cpu else None label = "maps" if a.maps else (a.cpu or "snap").strip(":").replace(":", "_") work = ROOT / "reference" / "mame" / f"{a.game}-{label}" work.mkdir(parents=True, exist_ok=True) for stale in ("error.log", "T.trace"): 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 = MAPS_LUA if a.maps else work / "run.lua" if not a.maps: script.write_text(lua(tag, a.start, a.window, a.snap, a.fps)) limit = int(a.start + a.window + 5) cmd = ["nice", "taskset", "-c", "24-31", mame, a.game, "-rompath", rompath, "-homepath", str(work), "-snapshot_directory", str(work / "snap"), "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-seconds_to_run", str(limit), "-autoboot_script", str(script)] cmd += ["-video", "none"] if not a.snap else ["-video", "none", "-window"] if tag: cmd += ["-debug", "-debugger", "none"] t0 = time.time() r = subprocess.run(cmd, cwd=work, capture_output=a.maps, text=True) if a.maps: lines = [x for x in r.stdout.splitlines() if x.startswith("MAP ")] (work / "maps.txt").write_text("\n".join(lines) + "\n") print(f"{len(lines)} map entries -> {work / 'maps.txt'}") print(f"{a.game} {label}: host {time.time() - t0:.1f} s", file=sys.stderr) trace = work / "T.trace" if tag and trace.exists(): print(f"{a.game} {a.cpu} from {a.start} s for {a.window} s -> {trace}") count(trace, a.top) return r.returncode if __name__ == "__main__": raise SystemExit(main())