#!/usr/bin/env python3 """Record MAME 0.285's per-instruction trace of the Jaguar's GPU or DSP. Runs the recipe in docs/mame-oracle.md in a fresh directory (default ``tests/mame_traces/-``, gitignored) and leaves ``error.log`` there. MAME reads the ROM sets in place (``-rompath``); nothing is copied. python -I scripts/mame_trace.py jaguar --cpu gpu --seconds 2 python -I scripts/mame_trace.py jaguar --cpu dsp --seconds 4 --cart "/path/Game (World).j64" python -I scripts/mame_trace.py area51 --cpu gpu --seconds 2 # a CoJag board (needs its CHD) The run ends at ``--seconds`` of emulated time or when error.log reaches ``--max-mb`` (default 48), whichever is first: a DSP that never idles logs about 2.7 million lines per emulated second. ``error.log`` then holds one line per instruction, before it executes, all hex: ``PC FLAGS R0 ... R31`` with ``--registers``, or ``PC FLAGS`` without. PC is MAME's ``curpc`` (the address of the instruction). FLAGS is MAME's ``m_flags``: Z C N in bits 0-2, the enables and REGPAGE as written; IMASK is kept elsewhere by MAME and is NOT in this value (docs/mame-oracle.md). R0-R31 are the registers of the bank selected at that moment. MAME's jaguargpu/jaguardsp cost one count per instruction (plus 3 for a taken jump); there is no pipeline in it, so the trace order is an instruction-level record only. Emulator tier: a detector. """ from __future__ import annotations import argparse import os import subprocess import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] MAME = "/usr/games/mame" # MAME's ROM sets and (for the CoJag boards) its CHDs, from the environment. ROMPATHS = [p for p in (os.environ.get("MAME_ROMPATH"), os.environ.get("MAME_CHDS")) if p] # The trace runs on the debugger's "visible" CPU, so point it at the device # first. `trace` without `noloop` folds repeated loops into one line, which # hides how many times a loop ran. The CPU is halted (GO clear) until the # 68000 starts it, so the log begins when the boot ROM sets the GO bit. TRACE_LUA = """\ local dbg = manager.machine.debugger dbg.visible_cpu = manager.machine.devices[":{cpu}"] dbg:command('trace cpu.trace,,noloop,{{logerror "{fmt}\\\\n",{args}}}') dbg:command("go") """ STOP_LUA = """\ local frames = 0 stop_sub = emu.add_machine_frame_notifier(function() frames = frames + 1 if frames == {frames} then manager.machine:exit() end end) """ def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("machine", help="MAME machine: jaguar, jaguarcd, area51, maxforce, ...") parser.add_argument("--cpu", choices=("gpu", "dsp"), default="gpu") parser.add_argument("--seconds", type=float, default=2.0, help="emulated seconds") parser.add_argument("--cart", type=Path, help="a cartridge image (.j64, or a .zip/.7z of one)") parser.add_argument("--registers", action="store_true", help="log R0-R31 on every line") parser.add_argument("--max-mb", type=int, default=48, help="stop MAME when error.log reaches this size") parser.add_argument("--out", type=Path) args = parser.parse_args() if not ROMPATHS: raise SystemExit("set MAME_ROMPATH to the MAME ROM folder (and MAME_CHDS for the CHDs)") out = args.out or ROOT / "tests" / "mame_traces" / f"{args.machine}-{args.cpu}" out.mkdir(parents=True, exist_ok=True) names = ["curpc", "flags"] + ([f"r{n}" for n in range(32)] if args.registers else []) lua = TRACE_LUA.format(cpu=args.cpu, fmt=" ".join(["%X"] * len(names)), args=",".join(names)) lua += STOP_LUA.format(frames=max(1, round(args.seconds * 60))) (out / "trace.lua").write_text(lua, encoding="utf-8") command = [ MAME, args.machine, "-rompath", ";".join(ROMPATHS), "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-debug", "-debugger", "none", "-log", "-autoboot_script", "trace.lua", "-seconds_to_run", str(int(args.seconds) + 2), ] if args.cart: command += ["-cart", str(args.cart.resolve())] log = out / "error.log" started = time.monotonic() launched = time.time() # A running GPU or DSP logs millions of lines per emulated second (the DSP # of a game with sound never idles), and MAME under the debugger's trace # runs far below real time, so the log is capped by size as well as by # emulated time: whichever comes first ends the run. The cap asks MAME to # stop with SIGTERM first; MAME 0.285 with `-debug -debugger none` has been # seen to ignore it (2026-11-11: two runs kept writing for minutes), so # SIGKILL follows after five seconds. An error.log left by an earlier run # is ignored until MAME has rewritten it. capped = False with subprocess.Popen( command, cwd=out, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True ) as mame: while mame.poll() is None: time.sleep(0.25) if not log.exists(): continue status = log.stat() if status.st_mtime >= launched and status.st_size > args.max_mb << 20: capped = True mame.terminate() try: mame.wait(timeout=5) print("mame stopped on SIGTERM") except subprocess.TimeoutExpired: mame.kill() print("mame ignored SIGTERM for 5 s; sent SIGKILL") break stderr = mame.stderr.read() if mame.stderr else "" result = mame elapsed = time.monotonic() - started lines = 0 if log.exists(): with log.open("rb") as handle: lines = sum(1 for _ in handle) how = f"stopped at the {args.max_mb} MB cap" if capped else f"exit {result.returncode}" print(f"mame {how} after {elapsed:.1f} s; {log} has {lines:,} lines") if result.returncode and not capped: print(stderr.strip()[-2000:]) return result.returncode return 0 if __name__ == "__main__": sys.exit(main())