#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Record MAME 0.285's per-instruction Super FX trace and the S-CPU's accesses to the GSU. 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; MAME's header heuristics pick ``lorom_gsu1`` or ``lorom_gsu2`` (the ``superfx1``/``superfx2`` device). Nothing is copied anywhere else: a ``.7z``/``.zip`` cartridge is extracted into the run directory, and a ROM smaller than 512 KiB is written there **mirrored up to 1 MiB** (the LoROM board's own decode does the same), because MAME 0.285 crashes with SIGSEGV under ``-debug`` on a 32 KiB GSU cartridge (trap 1). python -I scripts/mame_gsu_trace.py CART --start-frame 300 --frames 10 python -I scripts/mame_gsu_trace.py CART --host-only --frames 3600 # where does it talk to the GSU python -I scripts/mame_gsu_trace.py KROM.sfc --krom --frames 900 # krom's PASS/FAIL rows The trace (``gsu.log.gz``) holds, in order: - ``G pc r0 .. r11 cycles`` and ``H r12 r13 r14 r15 sfr pbr rombr rambr cbr colr por ramaddr cycles``: one GSU instruction, **before** it executes (hex; two lines because MAME's ``logerror`` drops arguments past 14). ``pc`` is MAME's ``(PBR << 16 | R15) - 1``, the address of the opcode in the pipeline; ``cycles`` is the GSU's ``totalcycles``, which MAME 0.285 advances by **one per instruction** whatever the instruction costs (docs/mame-oracle.md); - ``L n``: the previous G/H pair repeated ``n`` more times but for the cycle; - ``R addr value cycles`` / ``W addr value cycles``: an S-CPU read or write of the GSU's registers and cache (``$3000-$34FF``), and with ``--ram`` its writes to the Game Pak RAM (``$70-71:0000-FFFF``, ``$00-3F/$80-BF:6000-7FFF``), stamped with the **GSU's** ``totalcycles`` (actions are evaluated with the visible CPU's symbols: snes-python docs/mame-oracle.md trap 1, used here on purpose); - ``V addr value cycles``: with ``--krom``, the S-CPU's writes of ``$2116-$2118`` (VRAM address and low byte), from which ``summary.json`` counts krom's PASS and FAIL tokens. Host accesses are logged from power-on; the GSU trace starts at ``--start-frame`` and the run ends ``--frames`` later. ``--dasm BANK:ADDR:LEN`` writes MAME's disassembly of that range of the GSU's program space and stops. Keep windows short (docs/mame-oracle.md "Cost"). """ from __future__ import annotations import argparse import gzip import json import os import re import subprocess import sys import time from collections import Counter from pathlib import Path ROOT = Path(__file__).resolve().parents[1] MAME = "/usr/games/mame" # MAME's -rompath: ';'-separated folders holding snes.zip (the S-SMP IPL, needed by the # driver, read in place), from MAME_ROMPATH. DEFAULT_ROMPATH = os.environ.get("MAME_ROMPATH", "") FPS = 60.0988 # NTSC SNES frame rate, for -seconds_to_run MIRROR_BELOW = 0x80000 # pad smaller ROMs to 1 MiB (trap 1) PRINT = re.compile(r"PrintText\((Pass|Fail), \$([0-9A-F]{4}), 4\)") LUA = """\ local dbg = manager.machine.debugger local gsu_tag = nil for tag, dev in pairs(manager.machine.devices) do if dev.shortname == "superfx1" or dev.shortname == "superfx2" then gsu_tag = tag end end if gsu_tag == nil then print("NOGSU"); manager.machine:exit(); return end print("GSU " .. gsu_tag .. " " .. manager.machine.devices[gsu_tag].shortname) dbg.visible_cpu = manager.machine.devices[gsu_tag] if {dasm} then dbg:command('dasm {dasm_path},{dasm_start},{dasm_length},1,' .. gsu_tag) for _, line in ipairs(dbg.consolelog) do print("CON " .. line) end manager.machine:exit() return end local function watch(start, length, kind, cond, tag) dbg:command('wpset ' .. start .. ':maincpu,' .. length .. ',' .. kind .. ',' .. cond .. ',{{logerror "' .. tag .. ' %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}') end -- The GSU's registers and cache RAM in the banks the S-CPU uses (all of -- 00-3F/80-BF with --all-banks: slower, every ROM read there meets the tap). for _, bank in ipairs({banks}) do watch(bank .. "3000", "500", "r", "1", "R") watch(bank .. "3000", "500", "w", "1", "W") end if {all_banks} then watch("013000", "3F0500", "r", "(wpaddr & ffff) >= 3000 && (wpaddr & ffff) < 3500 && (wpaddr & ff0000) != 0", "R") watch("013000", "3F0500", "w", "(wpaddr & ffff) >= 3000 && (wpaddr & ffff) < 3500 && (wpaddr & ff0000) != 0", "W") watch("813000", "3F0500", "r", "(wpaddr & ffff) >= 3000 && (wpaddr & ffff) < 3500 && (wpaddr & ff0000) != 800000", "R") watch("813000", "3F0500", "w", "(wpaddr & ffff) >= 3000 && (wpaddr & ffff) < 3500 && (wpaddr & ff0000) != 800000", "W") end if {ram} then watch("700000", "20000", "w", "1", "W") watch("006000", "400000", "w", "(wpaddr & e000) == 6000", "W") watch("806000", "400000", "w", "(wpaddr & e000) == 6000", "W") end if {krom} then watch("002116", "3", "w", "1", "V") end local function start() dbg.visible_cpu = manager.machine.devices[gsu_tag] dbg:command('trace /dev/null,' .. gsu_tag .. ',noloop,{{' .. 'logerror "G %X %X %X %X %X %X %X %X %X %X %X %X %X %d\\\\n",pc,r0,r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,totalcycles; ' .. 'logerror "H %X %X %X %X %X %X %X %X %X %X %X %X %d\\\\n",r12,r13,r14,r15,sfr,pbr,rombr,rambr,cbr,colr,por,ramaddr,totalcycles}}') for _, line in ipairs(dbg.consolelog) do print("CON " .. line) end end -- --arm-on-start: begin at the S-CPU's first $301F write (a GSU start) at or after the -- start frame, so the trace opens with the GSU idle, and dump the Game Pak RAM (the GSU's -- 70:0000-71:FFFF) at that moment for the replay (rung 4). A Lua write tap sees the write. local armed_taps = {{}} local armed_frame = nil local screen = manager.machine.screens[":screen"] local function arm() local space = manager.machine.devices[":maincpu"].spaces["program"] local gsu_space = manager.machine.devices[gsu_tag].spaces["program"] local function fire(offset, data, mask) if #armed_taps == 0 then return data end local out = io.open("{ram_dump}", "wb") local chunk = {{}} for a = 0x700000, 0x71FFFF do chunk[#chunk + 1] = string.char(gsu_space:read_u8(a)) if #chunk == 4096 then out:write(table.concat(chunk)); chunk = {{}} end end out:close() for _, tap in ipairs(armed_taps) do tap:remove() end armed_taps = {{}} print("ARMED " .. screen:frame_number()) armed_frame = screen:frame_number() start() return data end armed_taps[#armed_taps + 1] = space:install_write_tap(0x00301F, 0x00301F, "arm00", fire) armed_taps[#armed_taps + 1] = space:install_write_tap(0x80301F, 0x80301F, "arm80", fire) end local started = {host_only} local function begin() if {arm_on_start} then arm() else start() end end if not started and {start_frame} == 0 then begin(); started = true end for _, line in ipairs(dbg.consolelog) do print("CON " .. line) end dbg:command("go") -- 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; begin() end if {snap_every} > 0 and frame % {snap_every} == 0 then manager.machine.video:snapshot() end -- With --arm-on-start the window is --frames long from the start that armed it; the -- search for one gives up {arm_timeout} frames after --start-frame. if {arm_on_start} then if armed_frame ~= nil and frame >= armed_frame + {frames} then manager.machine:exit() end if armed_frame == nil and frame >= {start_frame} + {arm_timeout} then manager.machine:exit() end elseif frame >= {end_frame} then manager.machine:exit() end end) """ 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 prepare(cart: Path, run: Path) -> tuple[Path, int]: """The cartridge MAME loads: extracted, and mirrored to 1 MiB when small (trap 1).""" 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"}) found = [p for p in found if not p.name.startswith("mirrored-")] if not found: raise SystemExit(f"no .sfc/.smc inside {cart}") cart = found[0] data = cart.read_bytes() size = len(data) if size < MIRROR_BELOW: mirrored = run / f"mirrored-{cart.stem}.sfc" mirrored.write_bytes(data * (0x100000 // size)) return mirrored, size return cart, size def collapse(source, out: Path, counts: Counter, vram: list[tuple[str, int, int]]) -> None: """Read MAME's logerror stream; write gsu.log.gz with identical G/H runs collapsed.""" previous = None pending = None # a G line waiting for its H line repeats = 0 with gzip.open(out, "wt", encoding="utf-8", compresslevel=6) as sink: def flush() -> None: nonlocal repeats if repeats: sink.write(f"L {repeats}\n") counts["collapsed"] += repeats repeats = 0 for line in source: kind = line[:2] if kind == "G ": pending = line elif kind == "H " and pending is not None: counts["instructions"] += 1 body = pending.rsplit(" ", 1)[0] + "|" + line.rsplit(" ", 1)[0] if body == previous: repeats += 1 else: flush() previous = body sink.write(pending) sink.write(line) pending = None elif kind in ("R ", "W ", "V "): flush() previous = None # a host access always breaks a run counts[kind.strip()] += 1 if kind == "V ": _, address, value, _ = line.split() vram.append(("V", int(address, 16), int(value, 16))) sink.write(line) else: counts["other"] += 1 if line.startswith("[:snsslot]"): sink.write("# " + line) flush() def krom_tokens(vram: list[tuple[str, int, int]]) -> dict[str, int]: """PASS/FAIL tokens in the S-CPU's VRAM low-byte stream (VMAIN = 0: +1 word per $2118).""" address = 0 text = [] # (word address, byte) for _, port, value in vram: port &= 0xFFFF if port == 0x2116: address = address & 0xFF00 | value elif port == 0x2117: address = address & 0x00FF | value << 8 elif port == 0x2118: text.append((address, value)) address = address + 1 & 0x7FFF found = Counter() for word in (b"PASS", b"FAIL"): for index in range(len(text) - 3): run = text[index : index + 4] if bytes(v for _, v in run) == word and all( a == run[0][0] + k for k, (a, _) in enumerate(run) ): found[word.decode()] += 1 return dict(found) def krom_expected(cart: Path) -> int | None: """Rows in krom's source beside the ROM (PrintText(Pass, ...) lines), if it is there.""" sources = [p for p in cart.parent.glob("*.asm") if not p.name.endswith("_gsu.asm")] rows = sum(len(PRINT.findall(p.read_text(errors="replace"))) // 2 for p in sources) return rows or None 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 run after the start") parser.add_argument( "--host-only", action="store_true", help="log the S-CPU's GSU accesses only, no GSU trace (fast: for finding a window)", ) # fmt: skip parser.add_argument( "--krom", action="store_true", help="host-only, plus krom's PASS/FAIL count" ) parser.add_argument( "--ram", action="store_true", help="also log the S-CPU's Game Pak RAM writes" ) parser.add_argument( "--all-banks", action="store_true", help="watch $3000-$34FF in every bank 00-3F/80-BF (default: banks 00 and 80)", ) # fmt: skip parser.add_argument( "--dasm", metavar="ADDR:LEN", help="write MAME's disassembly of GSU program space ADDR (24-bit hex) for LEN bytes and stop", ) # fmt: skip 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; repeatable', ) # fmt: skip 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( "--arm-on-start", action="store_true", help="begin the GSU trace at the first GSU start at/after --start-frame (searching " "600 frames), run --frames from there, and dump the Game Pak RAM at that start " "(RUN/ram_at_start.bin, 128 KiB) for the replay", ) # fmt: skip parser.add_argument( "--driver", default="snes", help="MAME driver: snes (NTSC) or snespal (a PAL cartridge such as Winter Gold " "(Europe), which shows its region screen on snes and never starts the GSU)", ) # fmt: skip parser.add_argument( "--rompath", default=DEFAULT_ROMPATH, help="MAME -rompath (default: $MAME_ROMPATH)" ) parser.add_argument("--out", type=Path, help="run directory (default tests/mame_traces/)") args = parser.parse_args() if not args.rompath: raise SystemExit("set MAME_ROMPATH (or --rompath) to the folders holding snes.zip") host_only = args.host_only or args.krom run = args.out or ROOT / "tests" / "mame_traces" / args.cart.stem.replace(" ", "_") run.mkdir(parents=True, exist_ok=True) cart, size = prepare(args.cart, run) dasm_start, dasm_length = (args.dasm or "0:0").split(":") lua = run / "trace.lua" lua.write_text( LUA.format( banks='{"00", "80"}', all_banks="true" if args.all_banks else "false", ram="true" if args.ram else "false", krom="true" if args.krom else "false", start_frame=args.start_frame, end_frame=args.start_frame + args.frames, host_only="true" if 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", dasm_start=dasm_start, dasm_length=dasm_length, arm_on_start="true" if args.arm_on_start else "false", frames=args.frames, arm_timeout=600, ram_dump=run / "ram_at_start.bin", ), encoding="utf-8", ) counts: Counter = Counter() vram: list[tuple[str, int, int]] = [] # -seconds_to_run is an integer option (upd7725-python trap 1): the Lua # exits at the end frame, and this is only the backstop. fps = 50.007 if args.driver == "snespal" else FPS seconds = int((args.start_frame + args.frames + (600 if args.arm_on_start else 0)) / fps) + 2 command = [ "nice", "-n", "19", MAME, args.driver, "-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 / "gsu.log.gz", counts, vram) returncode = mame.wait() wall = time.monotonic() - began console = [ ln for ln in stdout_path.read_text(encoding="utf-8", errors="replace").splitlines() if ln.startswith(("GSU", "CON", "NOGSU", "INPUT", "NOINPUT", "ARMED")) ] # fmt: skip summary = { "cart": args.cart.name, "rom_size": size, "mirrored": cart.name.startswith("mirrored-"), "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 if args.krom: summary["krom_tokens"] = krom_tokens(vram) summary["krom_rows_in_source"] = krom_expected(args.cart) (run / "summary.json").write_text(json.dumps(summary, indent=1) + "\n", encoding="utf-8") print(json.dumps(summary, indent=1)) ok = returncode == 0 and (counts["instructions"] or host_only or args.dasm) return 0 if ok else 1 if __name__ == "__main__": sys.exit(main())