#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Record MAME 0.285's per-instruction trace of the N64's VR4300 (or its RSP). MAME is a detector here, never a judge (docs/mame-oracle.md, tier 5). Its value is register state after every instruction of real boot code, from a machine that runs a cartridge deterministically. python -I scripts/mame_trace.py reference/src/krom-n64/CPUTest/CPU/ADD/CPUADD.N64 python -I scripts/mame_trace.py game.z64 --frames 3 --cpu rsp The run boots MAME's ``n64`` driver, which needs the MAME romset ``n64.zip`` (Nintendo's PIF boot ROM ``pifntsc.bin`` and two 128-byte RDP tables) in the folder named by ``MAME_ROMPATH``. That romset is read in place; nothing from it is copied. Output goes to a fresh directory under ``tests/mame_traces/`` (ignored): ``error.log`` holds one line per instruction, ``T pc r1 .. r31 hi lo totalcycles``, collapsed by ``noloop``. The trace stops after ``--frames`` emulated frames (default 1: about 1.56 M VR4300 cycles at 93.75 MHz), then MAME exits. A file-size cap (``--max-mb``) stops a runaway trace. """ from __future__ import annotations import argparse import os import resource import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] MAME = "/usr/games/mame" CPUS = {"maincpu": ":maincpu", "rsp": ":rsp"} # MAME 0.285's mips3 state symbols are the ABI names (r1 is "at"); checked by listing # manager.machine.devices[":maincpu"].state. Lower-case "r1" names do not exist and # make the trace action print nothing (the first run's trap). REGISTERS = ( "at,v0,v1,a0,a1,a2,a3,t0,t1,t2,t3,t4,t5,t6,t7," "s0,s1,s2,s3,s4,s5,s6,s7,t8,t9,k0,k1,gp,sp,fp,ra" ) def lua_script(cpu: str, frames: int, entry: int | None) -> str: # The RSP's symbols are R1-R31 (and V0-V31, 128 bits wide, not printable here). rsp = ",".join(f"R{n}" for n in range(1, 32)) fields = f"pc,{REGISTERS},hi,lo" if cpu == "maincpu" else f"pc,{rsp}" count = fields.count(",") + 1 fmt = " ".join(["T"] + ["%X"] * count + ["%d"]) trace = f"trace T.trace,{CPUS[cpu]},noloop,{{logerror \"{fmt}\\\\n\",{fields},totalcycles}}" if entry is None: start = [f"dbg:command('{trace}')"] else: # Start at the cartridge's entry point, after IPL1-3: the boot code before it # is Nintendo's (the PIF ROM, and the IPL3 most cartridges carry) and is # neither traced nor read. start = [f"dbg:command('bpset {entry:X},1,{{{trace};go}}')"] return "\n".join([ "local dbg = manager.machine.debugger", f'dbg.visible_cpu = manager.machine.devices["{CPUS[cpu]}"]', *start, "dbg:command('go')", "frames = 0", "subscription = emu.add_machine_frame_notifier(function()", " frames = frames + 1", f" if frames >= {frames} then", " dbg:command('trace off')", " manager.machine:exit()", " end", "end)", ]) + "\n" def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("cart", type=Path) parser.add_argument("--cpu", choices=sorted(CPUS), default="maincpu") parser.add_argument("--frames", type=int, default=1) parser.add_argument("--max-mb", type=int, default=400) parser.add_argument("--driver", default="n64") parser.add_argument("--from-reset", action="store_true", help="trace from reset (includes Nintendo's PIF boot code: never commit or read it)") args = parser.parse_args() rompath = os.environ.get("MAME_ROMPATH") if not rompath: print("set MAME_ROMPATH to the folder holding n64.zip") return 2 out = ROOT / "tests" / "mame_traces" / f"{args.cart.stem}-{args.cpu}" out.mkdir(parents=True, exist_ok=False) entry = None if args.cpu == "maincpu" and not args.from_reset: with args.cart.open("rb") as handle: header = handle.read(0x40) entry = int.from_bytes(header[8:12], "big") # MAME's program space is 32-bit (out / "trace.lua").write_text(lua_script(args.cpu, args.frames, entry), encoding="utf-8") command = [ "nice", MAME, args.driver, "-cart", str(args.cart.resolve()), "-rompath", rompath, "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-debug", "-debugger", "none", "-log", "-autoboot_script", "trace.lua", "-seconds_to_run", "5", ] cap = args.max_mb << 20 def limit() -> None: resource.setrlimit(resource.RLIMIT_FSIZE, (cap, cap)) result = subprocess.run(command, cwd=out, preexec_fn=limit, check=False) log = out / "error.log" lines = sum(1 for line in log.open(encoding="latin-1") if line.startswith("T ")) if log.exists() else 0 print(f"exit {result.returncode}; {lines} trace lines in {log}") return 0 if __name__ == "__main__": sys.exit(main())