#!/usr/bin/env python3 """Record MAME 0.285's per-instruction 5A22 (65816) trace of a SNES ROM. Runs the recipe in docs/mame-oracle.md in a fresh directory (default ``tests/mame_traces/``, gitignored) and leaves ``error.log`` there. MAME's ``snes`` driver refuses to start without ``spc700.rom``, the S-SMP's 64-byte boot ROM (Nintendo's; none is fetched or committed here). It runs with a wrong-checksum substitute after a warning, so this script writes one: ``IPL`` below, a 54-byte SPC700 program written for this repository from the documented upload protocol (fullsnes "SNES APU Main CPU Communication Port"; docs/mame-oracle.md has the listing). With it MAME boots commercial games that upload their sound driver through the protocol; ROMs that never talk to the APU (krom's CPU tests) run with any substitute. python -I scripts/mame_trace.py reference/src/PeterLemon-SNES/CPUTest/CPU/ADC/CPUADC.sfc python -I scripts/mame_trace.py game.sfc --seconds 10 --no-trace --snapshot 590 python -I scripts/mame_trace.py game.7z --seconds 5 # first .sfc/.smc inside, via 7z ``error.log`` then holds one line per instruction, before it executes, all hex except the last: ``PC PB A X Y S D DB P E totalcycles``. ``PC`` is the 16-bit program counter (``PB`` the bank); ``totalcycles`` counts **master clocks** (21.477 MHz NTSC): MAME's 5A22 charges 6 per CPU cycle plus 2 for an access to a slow region and 6 for $4000-$41FF (g65816.cpp ``bus_5A22_cycle_burst``), so a NOP in FastROM-off ROM advances it by 14. MAME saves a PNG of the screen under ``snap/snes/`` at frame ``--snapshot`` (default: the last whole frame of ``--seconds``; NTSC runs 60.10 frames a second) and exits. """ from __future__ import annotations import argparse import shutil import subprocess import sys import time from pathlib import Path from w65c816.harness import load_rom ROOT = Path(__file__).resolve().parents[1] MAME = "/usr/games/mame" # A substitute S-SMP boot ROM: not Nintendo's code, written from the protocol. # It sets SP, signals $AA/$BB on ports 0/1, waits for $CC on port 0, then # serves blocks: ports 2-3 = destination, port 1 = 0 to jump there or nonzero # to transfer, port 0 = the kick value, echoed; then each byte arrives in port # 1 with its index in port 0 and the index is echoed. A port 0 value ahead of # the expected index (signed difference) starts the next block. Unlike # Nintendo's ROM it does not clear page zero. IPL_SOURCE = """\ FFC0 CD EF mov x,#$ef FFC2 BD mov sp,x FFC3 8F AA F4 mov $f4,#$aa FFC6 8F BB F5 mov $f5,#$bb FFC9 78 CC F4 wait: cmp $f4,#$cc FFCC D0 FB bne wait FFCE BA F6 next: movw ya,$f6 ; destination from ports 2-3 FFD0 DA 00 movw $00,ya FFD2 BA F4 movw ya,$f4 ; A = port 0 (kick), Y = port 1 (command) FFD4 C4 F4 mov $f4,a ; echo the kick FFD6 DD mov a,y FFD7 5D mov x,a FFD8 D0 03 bne xfer FFDA 1F 00 00 jmp [$0000+x] ; command 0: run at the destination FFDD 8D 00 xfer: mov y,#$00 FFDF 7E F4 first: cmp y,$f4 ; the first byte always has index 0 FFE1 D0 FC bne first FFE3 E4 F5 store: mov a,$f5 FFE5 D7 00 mov [$00]+y,a FFE7 CB F4 mov $f4,y ; echo the index FFE9 FC inc y FFEA D0 02 bne loop FFEC AB 01 inc $01 FFEE 7E F4 loop: cmp y,$f4 FFF0 F0 F1 beq store FFF2 10 FA bpl loop ; port 0 still holds the last index FFF4 2F D8 bra next ; port 0 ran ahead: a new block FFFE C0 FF reset vector """ def ipl() -> bytes: image = bytearray(64) for line in IPL_SOURCE.splitlines(): address, *rest = line.split() data = [] for word in rest: if len(word) != 2 or not all(c in "0123456789ABCDEF" for c in word): break data.append(int(word, 16)) start = int(address, 16) - 0xFFC0 image[start : start + len(data)] = bytes(data) return bytes(image) TRACE_LUA = """\ local dbg = manager.machine.debugger dbg.visible_cpu = manager.machine.devices[":maincpu"] dbg:command('trace cpu.trace,,noloop,{logerror "%X %X %X %X %X %X %X %X %X %X %d\\\\n",\ pc,pb,a,x,y,s,d,db,p,e,totalcycles}') dbg:command("go") """ # With --io: every read of the I/O area and expansion ($2000-$7FFF) of banks # $00 and $80, and of cartridge RAM (LoROM: $0000-$7FFF of banks $70-$7D; # HiROM: $6000-$7FFF of banks $20-$3F), logged as "R address value" right # after the trace line of the instruction (or DMA) that made it, for # tests/mame_replay.py to answer the core's reads with. MAME's watchpoints are # per address range: one per bank would cover every mirror, but MAME 0.285 # makes no progress with 128 of them (2026-10-23), so the replay adopts # MAME's registers after a read of another bank's mirror (counted, by # address) and --io-banks adds the banks a game turns out to use. Four # watchpoints cost about 2.3 times the wall time of the plain trace. IO_BANK_LUA = """\ dbg:command('wpset {bank:X}2000,6000,r,1,{{logerror "R %X %X\\\\n",wpaddr,wpdata; g}}') """ IO_LUA = """\ dbg:command('wpset 206000,1F2000,r,wpaddr%10000>=6000&&wpaddr%10000<8000,{logerror "R %X %X\\\\n",wpaddr,wpdata; g}') dbg:command('wpset 700000,E0000,r,wpaddr%10000<8000,{logerror "R %X %X\\\\n",wpaddr,wpdata; g}') """ # Notifier subscriptions are unsubscribed when garbage-collected: keep them in # globals, or the callbacks silently stop. SNAP_LUA = """\ local frames = 0 snap_sub = emu.add_machine_frame_notifier(function() frames = frames + 1 if frames == {frame} then manager.machine.video:snapshot() manager.machine:exit() end end) """ def cartridge(rom: Path, out: Path) -> Path: """Write the ROM in as cart.sfc: the first .sfc/.smc of a .zip or .7z, copier header dropped (w65c816.harness.load_rom).""" target = out / "cart.sfc" target.write_bytes(load_rom(rom)) return target def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("rom", type=Path) parser.add_argument("--seconds", type=int, default=3, help="emulated seconds") parser.add_argument("--no-trace", action="store_true", help="no debugger: result only") parser.add_argument("--io", action="store_true", help="also log I/O and SRAM reads") parser.add_argument("--io-banks", default="", metavar="B9,..", help="more banks (hex) whose I/O reads --io logs") # fmt: skip parser.add_argument("--snapshot", type=int, metavar="FRAME") parser.add_argument("--driver", default="snes", choices=("snes", "snespal")) parser.add_argument("--out", type=Path) parser.add_argument("--mame", default=MAME) args = parser.parse_args() rom = args.rom.resolve() out = (args.out or ROOT / "tests" / "mame_traces" / rom.stem.replace(" ", "_")).resolve() if out.exists(): shutil.rmtree(out) (out / "roms" / args.driver).mkdir(parents=True) (out / "roms" / args.driver / "spc700.rom").write_bytes(ipl()) cartridge(rom, out) fps = 60.0988 if args.driver == "snes" else 50.007 lua = "" if args.no_trace else TRACE_LUA if args.io and not args.no_trace: banks = sorted({0x00, 0x80, *(int(b, 16) for b in args.io_banks.split(",") if b)}) watches = "".join(IO_BANK_LUA.format(bank=bank) for bank in banks) + IO_LUA lua = lua.replace('dbg:command("go")', watches + 'dbg:command("go")') lua += SNAP_LUA.format(frame=args.snapshot or int(args.seconds * fps) - 1) (out / "trace.lua").write_text(lua, encoding="utf-8") version = subprocess.run( [args.mame, "-version"], capture_output=True, text=True, check=True ).stdout.strip() debug = [] if args.no_trace else ["-debug", "-debugger", "none"] began = time.monotonic() # error.log lands in the working directory, not under -homepath. subprocess.run( [args.mame, args.driver, "-rompath", "roms", "-cart", "cart.sfc", "-homepath", str(out), "-snapshot_directory", "snap", "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", *debug, "-log", "-seconds_to_run", str(args.seconds), "-autoboot_script", str(out / "trace.lua")], cwd=out, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) # fmt: skip wall = time.monotonic() - began print(f"MAME {version}, {args.driver}, {wall:.1f} s wall: {out / 'error.log'}") if not args.no_trace: instructions = 0 with (out / "error.log").open("rb") as log: for line in log: fields = line.split() if len(fields) == 11 and fields[0][:1].isalnum() and not line.startswith(b"["): instructions += 1 print(f" {instructions:,} instructions") for snap in sorted((out / "snap").rglob("*.png")): print(f" snapshot: {snap}") return 0 if __name__ == "__main__": sys.exit(main())