#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Trace the Nintendo DS's CPUs in MAME 0.285 (a closed-box detector, tier 5). MAME's ``nds`` machine (driver "DS", MACHINE_NOT_WORKING) has two CPUs, ``:arm9`` (MAME's "ARM946ES" device at 67.02 MHz) and ``:arm7`` (ARM7, little endian, 33.51 MHz), and boots the BIOS and firmware from its ``nds`` ROM set (biosnds9.rom, biosnds7.rom, firmware.bin; found through MAME_ROMPATH, never copied). It has no cartridge slot, so what can be traced is the BIOS and firmware boot. The debugger's instruction trace is switched on from reset for one CPU (with the registers named by --regs before each line) and the machine exits after --frames frames. ``--state`` prints the CPUs' state symbol names instead of tracing. One CPU per run, made the visible CPU first (OBSERVED 2026-11-26): with ``trace file,:arm9,noloop,{tracelog ...}`` MAME writes the ARM9's instructions but drops the tracelog action, while the same command for ``:arm7`` (MAME's default visible CPU) keeps it; ``dbg.visible_cpu = `` then ``trace file,,noloop,{...}`` works for both. MAME_ROMPATH=... python -I scripts/mame_trace.py --cpu arm9 --frames 1 \ --regs CPSR,R0,R13 --out tests/mame_traces/arm9-boot.trace All output lands in tests/mame_traces/ (git-ignored), which is the run's cwd. MAME's ``noloop`` option does not fold the BIOS's two-instruction delay loops (seen 2026-11-26), so a frame of ARM9 boot is millions of lines: keep --frames small. """ from __future__ import annotations import argparse import os import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] RUNS = ROOT / "tests" / "mame_traces" LUA = """ dbg = manager.machine.debugger if {state} then for _, tag in ipairs({{':arm9', ':arm7'}}) do local names = {{}} for k, _ in pairs(manager.machine.devices[tag].state) do names[#names + 1] = k end table.sort(names) print('STATE ' .. tag .. ' ' .. table.concat(names, ' ')) end manager.machine:exit() else {start} dbg:command('go') frames = 0 sub = emu.add_machine_frame_notifier(function() frames = frames + 1 if frames == {stop} then {finish} print(string.format('TIME %.6f s', manager.machine.time:as_double())) manager.machine:exit() end end) end """ def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--cpu", choices=["arm9", "arm7"], default="arm9", help="the CPU to trace (one per run, see the docstring)") parser.add_argument("--frames", type=int, default=1) parser.add_argument("--regs", default="", help="comma-separated MAME state symbols") parser.add_argument("--state", action="store_true", help="print state symbols, trace nothing") parser.add_argument("--out", type=Path, default=RUNS / "boot.trace") parser.add_argument("--mame", default="mame") args = parser.parse_args() rompath = os.environ.get("MAME_ROMPATH") if not rompath: print("set MAME_ROMPATH (MAME's ';'-separated rompath holding nds.zip)", file=sys.stderr) return 2 RUNS.mkdir(parents=True, exist_ok=True) regs = [r for r in args.regs.split(",") if r] action = "" if regs: fmt = " ".join(f"{r}=%08X" for r in regs) + " " action = ',{tracelog "' + fmt + '",' + ",".join(regs) + "}" outs = {args.cpu: args.out.resolve()} start = (f"dbg.visible_cpu = manager.machine.devices[':{args.cpu}']\n " f"dbg:command('trace {outs[args.cpu].as_posix()},,noloop{action}')") finish = "dbg:command('trace off')" script = RUNS / "trace.lua" script.write_text(LUA.format(state="true" if args.state else "false", start=start, finish=finish, stop=args.frames), encoding="utf-8") command = [ "nice", args.mame, "nds", "-rompath", rompath, "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-debug", "-debugger", "none", "-autoboot_script", str(script), "-seconds_to_run", str(args.frames // 60 + 5), ] result = subprocess.run(command, cwd=RUNS, capture_output=True, text=True, check=False) for line in result.stdout.splitlines(): if line.startswith(("STATE", "TIME")): print(line) if args.state: return 0 for cpu, out in outs.items(): if not out.exists(): print(result.stdout[-2000:], result.stderr[-2000:], sep="\n", file=sys.stderr) return 1 with out.open("rb") as handle: count = sum(1 for _ in handle) print(f"{cpu}: {count} instructions traced to {out.relative_to(ROOT)}") return 0 if __name__ == "__main__": sys.exit(main())