#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Record MAME 0.285's per-instruction uPD7725/uPD96050 trace and the host's DR/SR/RAM accesses. The detector recipe of docs/mame-oracle.md, in a fresh run directory (default ``tests/mame_traces/``, gitignored). MAME runs the ``snes`` driver with the cartridge; the DSP program comes from MAME's device sets (``sns_dsp1leg.zip`` ... ``sns_seta11leg.zip``), read in place from the folders on ``MAME_ROMPATH`` (bring your own; ``--rompath`` overrides it). Nothing is copied anywhere else; the ``.7z``/``.zip`` cartridge is extracted into the run directory with ``7z``. python -I scripts/mame_dsp_trace.py "path/to/Pilotwings (USA).7z" \ --start-frame 0 --frames 120 MAME writes one line per DSP instruction (8 million per emulated second at MAME's 8 MHz DSP-1 clock), almost all of them the program's one-instruction RQM wait loop, so MAME logs to stderr (``-oslog``) and this script reads it as a stream, collapses each run of lines identical but for the cycle stamp, and writes ``dsp.log.gz``: - ``D pc a b k l tr trb dp rp sp dr cycles``: a DSP instruction, before it executes (hex; ``cycles`` is the DSP's ``totalcycles``, decimal). MAME's upd7725 registers no SR or flag symbols for the debugger, so neither is in the trace; M and N follow from K and L; - ``L n``: the previous ``D`` line repeated ``n`` more times (same registers, consecutive cycles); - ``R addr value cycles`` / ``W addr value cycles``: a 5A22 read or write of the DSP's ports (and, for the ST010/ST011, its data RAM), stamped with the **DSP's** ``totalcycles`` (the visible CPU's symbols are used for every action: snes-python docs/mame-oracle.md trap 1, used here on purpose), so each host access lands between two DSP instructions. Host accesses are logged from power-on; the DSP trace starts at ``--start-frame`` (a frame notifier issues the command) and the run ends ``--frames`` later, so a replay runs the core from reset on the host stream alone and compares from the first ``D`` line. ``--host-only`` never starts the trace (MAME then runs at about full speed), to find where a game talks to its DSP before paying for a trace. ``--dasm`` writes MAME's disassembly of the whole program (``program.dasm``: ``PC: word disassembly``, moves printed ``mov src,dst``) and stops. Keep windows short: a traced emulated second costs about a minute of one core (measured 2026-11-05). """ from __future__ import annotations import argparse import gzip import json import os import shutil import subprocess import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] #: MAME 0.285: $MAME, else ``mame`` on the PATH. MAME = os.environ.get("MAME") or shutil.which("mame") or "mame" #: snes.zip (the S-SMP IPL, needed by the driver) and the DSP device sets, read in place: #: one or more folders separated by ';', as MAME's -rompath. DEFAULT_ROMPATH = os.environ.get("MAME_ROMPATH", "") FPS = 60.0988 # NTSC SNES frame rate, for -seconds_to_run # The host-side windows, by the slot MAME chose (src/mame/nintendo/snes.cpp # l.1218-1262 and bus/snes/upd.cpp): one read and one write watchpoint per # (start, length) range with a condition on the low 16 bits. WINDOWS = { "lorom_dsp": [ ("208000", "200000", "(wpaddr & 8000) != 0"), ("a08000", "200000", "(wpaddr & 8000) != 0"), ], "lorom_dsp4": [ ("308000", "100000", "(wpaddr & 8000) != 0"), ("b08000", "100000", "(wpaddr & 8000) != 0"), ], "lorom_dsp_2mb": [ ("600000", "100000", "(wpaddr & 8000) == 0"), ("e00000", "100000", "(wpaddr & 8000) == 0"), ], "hirom_dsp": [ ("006000", "200000", "(wpaddr & e000) == 6000"), ("806000", "200000", "(wpaddr & e000) == 6000"), ], "seta": [ ("600000", "100000", "(wpaddr & ffff) < 4000"), ("680000", "080000", "(wpaddr & ffff) < 8000"), ], } LUA = """\ local dbg = manager.machine.debugger local dsp_tag = nil for tag, dev in pairs(manager.machine.devices) do if dev.shortname == "upd7725" or dev.shortname == "upd96050" then dsp_tag = tag end end if dsp_tag == nil then print("NODSP"); manager.machine:exit(); return end local slot = dsp_tag:match(":snsslot:([^:]+):dsp") print("DSP " .. dsp_tag .. " " .. manager.machine.devices[dsp_tag].shortname .. " " .. slot) local windows = {windows} local function pick() -- MAME names the Seta slots lorom_st10leg / lorom_st11leg (measured) if slot:find("st1") or slot:find("seta") then return windows.seta end if slot:find("hi") then return windows.hirom_dsp end if slot:find("dsp4") then return windows.lorom_dsp4 end -- the slot name does not say 1 MB or 2 MB LoROM (snes.cpp SNES_DSP / SNES_DSP_2MB): watch both local both = {{}} for _, w in ipairs(windows.lorom_dsp) do table.insert(both, w) end for _, w in ipairs(windows.lorom_dsp_2mb) do table.insert(both, w) end return both end dbg.visible_cpu = manager.machine.devices[dsp_tag] if {dasm} then -- MAME's disassembly of the whole program space (rung 0's detector), then stop. local words = manager.machine.devices[dsp_tag].shortname == "upd96050" and "4000" or "800" dbg:command('dasm {dasm_path},0,' .. words .. ',1,' .. dsp_tag) for _, line in ipairs(dbg.consolelog) do print("CON " .. line) end manager.machine:exit() return end -- Host accesses from power-on, so a replay can bring the core to the traced -- window by itself (the trace carries no flags, data RAM or stack). for _, w in ipairs(pick()) do dbg:command('wpset ' .. w[1] .. ':maincpu,' .. w[2] .. ',r,' .. w[3] .. ',{{logerror "R %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}') dbg:command('wpset ' .. w[1] .. ':maincpu,' .. w[2] .. ',w,' .. w[3] .. ',{{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}') end local function start() dbg.visible_cpu = manager.machine.devices[dsp_tag] dbg:command('trace /dev/null,' .. dsp_tag .. ',noloop,{{logerror "D %X %X %X %X %X %X %X %X %X %X %X %d\\\\n",' .. 'pc,a,b,k,l,tr,trb,dp,rp,sp,dr,totalcycles}}') for _, line in ipairs(dbg.consolelog) do print("CON " .. line) end end local started = {host_only} if not started and {start_frame} == 0 then start(); started = true end for _, line in ipairs(dbg.consolelog) do print("CON " .. line) end dbg:command("go") local screen = manager.machine.screens[":screen"] -- Button presses: {{frame, field name, frames held}}, matched against every input field's name. local presses = {presses} local fields = {{}} for ptag, port in pairs(manager.machine.ioport.ports) do for fname, fld in pairs(port.fields) do fields[fname] = fld if {list_inputs} then print("INPUT " .. ptag .. " | " .. fname) end end end for _, p in ipairs(presses) do if fields[p[2]] == nil then print("NOINPUT " .. p[2]) end end sub = emu.add_machine_frame_notifier(function() local frame = screen:frame_number() for _, p in ipairs(presses) do local fld = fields[p[2]] if fld ~= nil then if frame == p[1] then fld:set_value(1) end if frame == p[1] + p[3] then fld:clear_value() end end end if not started and frame >= {start_frame} then started = true; start() end if {snap_every} > 0 and frame % {snap_every} == 0 then manager.machine.video:snapshot() end if frame >= {end_frame} then manager.machine:exit() end end) """ def windows_lua() -> str: parts = [] for name, ranges in WINDOWS.items(): rows = ", ".join(f'{{"{a}", "{n}", "{c}"}}' for a, n, c in ranges) parts.append(f"{name} = {{{rows}}}") return "{" + ", ".join(parts) + "}" def presses_lua(presses: list[str]) -> str: """``FRAME:FIELD[:HOLD]`` options as a Lua table (HOLD frames, default 6).""" rows = [] for press in presses: parts = press.split(":") frame, name = int(parts[0]), parts[1] hold = int(parts[2]) if len(parts) > 2 else 6 rows.append(f'{{{frame}, "{name}", {hold}}}') return "{" + ", ".join(rows) + "}" def extract(cart: Path, run: Path) -> Path: if cart.suffix.lower() in {".7z", ".zip"}: subprocess.run(["7z", "x", "-y", f"-o{run}", str(cart)], check=True, capture_output=True) found = sorted(p for p in run.iterdir() if p.suffix.lower() in {".sfc", ".smc"}) if not found: raise SystemExit(f"no .sfc/.smc inside {cart}") return found[0] return cart def collapse(source, out: Path, counts: dict) -> None: """Read MAME's logerror stream; write dsp.log.gz with identical runs collapsed.""" previous = None repeats = 0 with gzip.open(out, "wt", encoding="utf-8", compresslevel=6) as sink: for line in source: kind = line[:2] if kind == "D ": counts["instructions"] += 1 body = line.rsplit(" ", 1)[0] if body == previous: repeats += 1 continue if repeats: sink.write(f"L {repeats}\n") counts["collapsed"] += repeats repeats = 0 previous = body sink.write(line) elif kind in ("R ", "W "): if repeats: sink.write(f"L {repeats}\n") counts["collapsed"] += repeats repeats = 0 previous = None # a host access always breaks a run counts[kind.strip()] += 1 sink.write(line) else: counts["other"] += 1 if line.startswith("[:snsslot]"): sink.write("# " + line) if repeats: sink.write(f"L {repeats}\n") counts["collapsed"] += repeats def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("cart", type=Path) parser.add_argument("--start-frame", type=int, default=0) parser.add_argument("--frames", type=int, default=60, help="frames traced after the start") parser.add_argument( "--host-only", action="store_true", help="log the host's accesses only, no DSP trace (fast: for finding a window)", ) parser.add_argument( "--dasm", action="store_true", help="write MAME's disassembly of the DSP program to program.dasm and stop", ) parser.add_argument( "--press", action="append", default=[], metavar="FRAME:FIELD[:HOLD]", help='press an input field (MAME\'s name, e.g. "P1 Start") at FRAME for HOLD frames (default 6); repeatable', ) parser.add_argument( "--list-inputs", action="store_true", help="print every input port and field name" ) parser.add_argument( "--snapshots", type=int, default=0, metavar="N", help="save a screen snapshot every N frames (in RUN/snap), to see where a game is", ) # fmt: skip parser.add_argument("--rompath", default=DEFAULT_ROMPATH, help="default: $MAME_ROMPATH") parser.add_argument("--out", type=Path, help="run directory (default tests/mame_traces/)") args = parser.parse_args() if not args.rompath: parser.error( "set MAME_ROMPATH (or pass --rompath): the folders holding snes.zip and the DSP sets" ) run = args.out or ROOT / "tests" / "mame_traces" / args.cart.stem.replace(" ", "_") run.mkdir(parents=True, exist_ok=True) cart = extract(args.cart, run) lua = run / "trace.lua" lua.write_text( LUA.format( windows=windows_lua(), start_frame=args.start_frame, end_frame=args.start_frame + args.frames, host_only="true" if args.host_only else "false", presses=presses_lua(args.press), list_inputs="true" if args.list_inputs else "false", snap_every=args.snapshots, dasm="true" if args.dasm else "false", dasm_path=run / "program.dasm", ), encoding="utf-8", ) counts = {"instructions": 0, "collapsed": 0, "R": 0, "W": 0, "other": 0} # -seconds_to_run is an integer option ("0.998" runs forever, measured): the # Lua exits at the end frame, and this is only the backstop. seconds = int((args.start_frame + args.frames) / FPS) + 2 # -oslog sends logerror to stderr, which this process reads as a stream: no # error.log (MAME replaces a FIFO put in its place, measured), nothing large on disk. command = [ "nice", "-n", "19", MAME, "snes", "-cart", str(cart), "-rompath", args.rompath, "-homepath", str(run), "-snapshot_directory", str(run / "snap"), "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-debug", "-debugger", "none", "-oslog", "-seconds_to_run", str(seconds), "-autoboot_script", str(lua), ] # fmt: skip began = time.monotonic() stdout_path = run / "mame.stdout" with stdout_path.open("w", encoding="utf-8") as stdout: mame = subprocess.Popen( command, cwd=run, stdout=stdout, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace", ) # fmt: skip collapse(mame.stderr, run / "dsp.log.gz", counts) returncode = mame.wait() wall = time.monotonic() - began result_stdout = stdout_path.read_text(encoding="utf-8", errors="replace") console = [ ln for ln in result_stdout.splitlines() if ln.startswith(("DSP", "CON", "NODSP", "INPUT", "NOINPUT")) ] # fmt: skip summary = {"cart": args.cart.name, "start_frame": args.start_frame, "frames": args.frames, "presses": args.press, "seconds_to_run": seconds, "wall_seconds": round(wall, 1), "mame_exit": returncode, "console": console, **counts} # fmt: skip (run / "summary.json").write_text(json.dumps(summary, indent=1) + "\n", encoding="utf-8") print(json.dumps(summary, indent=1)) return 0 if returncode == 0 and (counts["instructions"] or args.host_only or args.dasm) else 1 if __name__ == "__main__": sys.exit(main())