#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Record MAME 0.285's per-instruction SPC700 trace of a SNES ROM, and audit it. 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 needs the S-SMP's 64-byte IPL ROM (``spc700.rom``, CRC 44bb3a40). Nothing is downloaded for it: the script writes the 64 bytes that anomie's pinned SPC700 doc prints (reference/docs/anomie-spc700.txt, "IPL BOOT ROM") into the run directory and checks CRC-32 and SHA-1 against MAME's own ``-listroms`` values before starting. The file never leaves the gitignored run directory. python -I scripts/mame_trace.py reference/roms/snes-tests/spctest/spctest.sfc --seconds 25 python -I scripts/mame_trace.py ROM.sfc --no-trace --seconds 10 python -I scripts/mame_trace.py ROM.sfc --io --seconds 25 # for the rung 4 replay ``error.log`` then holds one line per S-SMP instruction, before it executes, all hex except the last: ``PC opcode A X Y SP PSW totalcycles``. ``totalcycles`` counts the S-SMP's 2.048 MHz input clock: one SPC700 bus cycle is 2 of them (``MOV X,#$EF`` advances it by 4). After the run the script compares every instruction's cycle delta with anomie's ``Cyc`` column (tests/anomie_opcodes.json, from scripts/anomie_opcodes.py), which is how docs/validation.md's MAME numbers were made. MAME saves a PNG of the screen under ``snap/snes/`` at frame ``--snapshot`` (default: the last whole frame of ``--seconds`` at 60.1 frames a second). """ from __future__ import annotations import argparse import json import re import os import shutil import subprocess import sys import time import zlib from collections import Counter from hashlib import sha1 from itertools import pairwise from pathlib import Path ROOT = Path(__file__).resolve().parents[1] MAME = os.environ.get("MAME", shutil.which("mame") or "mame") # MAME 0.285 on the path ANOMIE_DOC = ROOT / "reference" / "docs" / "anomie-spc700.txt" ANOMIE_TABLE = ROOT / "tests" / "anomie_opcodes.json" IPL_CRC32 = 0x44BB3A40 IPL_SHA1 = "97e352553e94242ae823547cd853eecda55c20f0" # A logerror action silently drops lines past 14 values (found on the Z80 # boards); 8 here. MAME 0.285's spc700 state symbols: PC S P A X Y (no YA). # b@pc reads the opcode byte through the visible CPU's program space. TRACE_LUA = """\ local dbg = manager.machine.debugger dbg.visible_cpu = manager.machine.devices[":soundcpu"] dbg:command('trace spc.trace,:soundcpu,noloop,{logerror "%X %X %X %X %X %X %X %d\\\\n",\ pc,b@pc,a,x,y,s,p,totalcycles}') dbg:command("go") """ # --ports: only the S-SMP's writes to $F4 (CPUIO0), where PeterLemon's tests # report each sub-test ($0n pass, $8n fail) and gilyon's spctest its state. PORTS_LUA = """\ local dbg = manager.machine.debugger dbg.visible_cpu = manager.machine.devices[":soundcpu"] dbg:command('wpset f4,1,w,1,{logerror "F4 %X %d\\\\n",wpdata,totalcycles; g}') dbg:command("go") """ # --io: the trace plus every S-SMP read and write of $F0-$FF, for the rung 4 replay # (src/spc700_python/replay.py): `R addr data cycles`, `W addr data cycles`, in bus order between # instruction lines. wpdata for a read is the value the device returned. IO_LUA = """\ local dbg = manager.machine.debugger dbg.visible_cpu = manager.machine.devices[":soundcpu"] dbg:command('wpset f0,10,r,1,{logerror "R %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}') dbg:command('wpset f0,10,w,1,{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}') dbg:command('trace spc.trace,:soundcpu,noloop,{logerror "%X %X %X %X %X %X %X %d\\\\n",\ pc,b@pc,a,x,y,s,p,totalcycles}') dbg:command("go") """ # 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 ipl_rom() -> bytes: text = ANOMIE_DOC.read_text(encoding="latin-1") block = text.split("IPL BOOT ROM", 1)[1].split(".ORG", 1)[0] data = bytes(int(h, 16) for h in re.findall(r"\$([0-9A-F]{2})", block)) if len(data) != 64 or zlib.crc32(data) != IPL_CRC32 or sha1(data).hexdigest() != IPL_SHA1: raise SystemExit("the IPL ROM bytes in anomie's doc do not match MAME's spc700.rom") return data def audit(log: Path) -> None: table = {e["opcode"]: e for e in json.loads(ANOMIE_TABLE.read_text(encoding="utf-8"))} rows = [] with log.open("rb") as handle: for line in handle: fields = line.split() if len(fields) == 8 and fields[0][:1].isalnum(): try: rows.append((int(fields[0], 16), int(fields[1], 16), int(fields[7]))) except ValueError: continue agree = Counter() differ: Counter = Counter() for (pc, opcode, cycles), (next_pc, _, next_cycles) in pairwise(rows): delta = next_cycles - cycles if delta % 2: differ[(opcode, f"odd delta {delta}")] += 1 continue expected = table[opcode]["cycles"] if not expected: continue sequential = next_pc == (pc + table[opcode]["bytes"]) & 0xFFFF want = expected[1] if len(expected) == 2 and not sequential else expected[0] if delta // 2 == want: agree[opcode] += 1 else: differ[(opcode, delta // 2)] += 1 pairs = len(rows) - 1 print( f" {len(rows):,} instructions; cycle delta == anomie on {sum(agree.values()):,}" f" of {pairs:,} measurable (an instruction's delta needs its successor)" ) print(f" opcodes seen: {len({r[1] for r in rows})}") for (opcode, got), n in differ.most_common(20): entry = table[opcode] print( f" differs: {opcode:02X} {entry['mnemonic']} {entry['operands']}: " f"MAME {got}, anomie {entry['cycles']} ({n:,}x)" ) 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=10, help="emulated seconds") parser.add_argument("--no-trace", action="store_true", help="no debugger: result only") parser.add_argument("--ports", action="store_true", help="log only S-SMP writes to $F4") parser.add_argument("--io", action="store_true", help="trace plus every I/O read and write") parser.add_argument("--snapshot", type=int, metavar="FRAME") 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).resolve() if out.exists(): shutil.rmtree(out) (out / "roms" / "snes").mkdir(parents=True) (out / "roms" / "snes" / "spc700.rom").write_bytes(ipl_rom()) shutil.copyfile(rom, out / "cart.sfc") lua = "" if args.no_trace else PORTS_LUA if args.ports else IO_LUA if args.io else TRACE_LUA lua += SNAP_LUA.format(frame=args.snapshot or int(args.seconds * 60.1) - 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, "snes", "-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}, snes, {wall:.1f} s wall: {out / 'error.log'}") if args.ports: writes = [ line.split()[1].decode() for line in (out / "error.log").open("rb") if line.startswith(b"F4 ") and len(line.split()) == 3 ] print(f" $F4 writes: {' '.join(writes)}") elif not args.no_trace: audit(out / "error.log") for snap in sorted((out / "snap").rglob("*.png")): print(f" snapshot: {snap}") return 0 if __name__ == "__main__": sys.exit(main())