#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Milestone 1's MAME lockstep: the board's instruction stream against MAME 0.285's. MAME is a closed box (docs/restart.md rule 5): ``scripts/mame_trace.py`` runs it and leaves ``error.log`` (docs/mame-oracle.md). This script runs the board on the same cartridge, records the same fields per instruction, and aligns the two streams. python scripts/mame_trace.py snes "$NO_INTRO_DIR/.../Super Mario World (USA).zip" \\ --seconds 3 --out tests/mame_traces/lockstep-Super_Mario_World .venv-pypy/bin/python scripts/mame_lockstep.py \\ "$NO_INTRO_DIR/.../Super Mario World (USA).zip" tests/mame_traces/lockstep-Super_Mario_World The IPL ROM is bring-your-own (``SNES_IPL`` or ``snes.zip`` in ``MAME_ROMPATH``), as for the milestone 3 tests: games wait on the S-SMP. **What is compared** (handoff-brief.md milestone 1): per instruction, before it runs, PC (24 bit), A, X, Y, P, S, D, DB, E, and the master clocks it took. MAME does not model the refresh pause, the short line, DMA/HDMA cycles or mul/div latency (docs/mame-oracle.md "What MAME does not model"), so: - the clock comparison is per instruction, and the board's cost has its refresh (40 clocks) and its DMA/HDMA clocks taken off first; what remains is a residual, counted by opcode; - the two streams drift apart in time, so wait loops (on NMI, on the S-SMP's ports, on HVBJOY) run different numbers of iterations and interrupts arrive at different instructions. The aligner re-synchronises on the PC stream (the smallest skip on either side after which ``--k`` PCs agree) and classifies each divergence by the last register read whose value differed (``$2140-3``: the S-SMP; ``$4210-2``: NMI, IRQ, HVBJOY; ``$2137-3F``: the counters; ``$4214-7``: mul/div) or by an interrupt vector at the start of the skipped stretch. A difference that none of the named causes explains is a finding. Each register read and write in bank $00 ($2100-$21FF, $4200-$43FF: MAME's watchpoints cover exactly that) is logged on both sides, so the classification compares like with like. """ from __future__ import annotations import argparse import hashlib import os import sys import time import zipfile from collections import Counter from pathlib import Path ROOT = Path(__file__).resolve().parents[1] IPL_SHA1 = "97e352553e94242ae823547cd853eecda55c20f0" # MAME's spc700.rom FIELDS = ("pc", "a", "x", "y", "p", "s", "d", "db", "e") def ipl_rom() -> bytes: data = None if os.environ.get("SNES_IPL"): data = Path(os.environ["SNES_IPL"]).read_bytes() elif os.environ.get("MAME_ROMPATH"): path = Path(os.environ["MAME_ROMPATH"]) / "snes.zip" if path.exists(): data = zipfile.ZipFile(path).read("spc700.rom") if data is None or hashlib.sha1(data).hexdigest() != IPL_SHA1: raise SystemExit("no IPL ROM: set SNES_IPL or MAME_ROMPATH (snes.zip)") return data def cart_image(path: Path) -> bytes: if path.suffix.lower() == ".zip": z = zipfile.ZipFile(path) names = [n for n in z.namelist() if n.lower().endswith((".sfc", ".smc"))] return z.read(names[0]) return path.read_bytes() class Trace: """One side's stream: parallel lists, plus register accesses per instruction.""" def __init__(self) -> None: self.state: list[tuple] = [] # (pc, a, x, y, p, s, d, db, e) self.clock: list[int] = [] self.taken: list[int] = [] # board: clocks MAME does not charge (refresh, DMA) self.reads: dict[int, list[tuple[int, int]]] = {} self.writes: dict[int, list[tuple[int, int]]] = {} self.polls: dict[int, int] = {} # board: register reads in other banks def _norm(pc, a, x, y, p, s, d, db, e): # In emulation mode P bits 4-5 read as set (MAME shows them so; the core keeps them). if e: p |= 0x30 return (pc, a, x, y, p, s, d, db, e) def parse_mame(log: Path, limit: int) -> Trace: t = Trace() n = -1 with log.open("rb") as f: for raw in f: k = raw[:2] if k == b"C ": n += 1 if n >= limit + 1: break v = raw.split() pc, a, x, y, p, s, d, db, e = (int(w, 16) for w in v[1:10]) t.state.append(_norm(pc, a, x, y, p, s, d, db, e)) t.clock.append(int(v[10])) elif (k == b"R " or k == b"W ") and n >= 0: v = raw.split() store = t.reads if k == b"R " else t.writes store.setdefault(n, []).append((int(v[1], 16), int(v[2], 16))) t.taken = [0] * len(t.clock) return t def record_board(image: bytes, ipl: bytes, limit: int) -> Trace: """Run the board for ``limit`` + 1 instructions, recording as MAME's lua does.""" from snes_python.board import SNES from snes_python.cartridge import Cartridge snes = SNES(Cartridge(image), ipl=ipl) cpu = snes.cpu t = Trace() state, clock, taken = t.state, t.clock, t.taken box = {"n": -1, "taken": 0, "in_dma": 0} execute = cpu._execute def traced_execute() -> int: if box["n"] >= 0: taken.append(box["taken"]) box["n"] += 1 box["taken"] = 0 state.append( _norm(cpu.pbr << 16 | cpu.pc, cpu.a, cpu.x, cpu.y, cpu.p, cpu.s, cpu.d, cpu.dbr, cpu.e) ) clock.append(snes.clock) return execute() step = snes.step def traced_step(clocks: int) -> None: before = snes.refreshed step(clocks) if not before and snes.refreshed and not box["in_dma"]: box["taken"] += 40 dma_edge = snes.dma_edge def traced_dma_edge() -> None: # HDMA can run inside a DMA (dma.py calls dma_edge between bytes): only the # outermost call counts its clocks. c0 = snes.clock box["in_dma"] += 1 dma_edge() box["in_dma"] -= 1 if not box["in_dma"]: box["taken"] += snes.clock - c0 bus_read = snes.bus_read bus_write = snes.bus_write def _logged(address: int) -> bool: return address >> 16 == 0 and (address & 0xFF00 == 0x2100 or 0x4200 <= address < 0x4400) def traced_read(address: int, mdr: int) -> int: value = bus_read(address, mdr) # DMA's B-bus accesses are logged too: MAME's watchpoints see them (measured). if _logged(address): t.reads.setdefault(box["n"], []).append((address & 0xFFFF, value)) elif not address & 0x400000 and ( address & 0xFF00 == 0x2100 or 0x4200 <= address & 0xFFFF < 0x4400 ): # Banks $01-$3F and $80-$BF: outside MAME's watchpoints, so only used to # name a polling loop, never compared. t.polls.setdefault(box["n"], address & 0xFFFF) return value def traced_write(address: int, value: int) -> None: if _logged(address): t.writes.setdefault(box["n"], []).append((address & 0xFFFF, value)) bus_write(address, value) cpu._execute = traced_execute snes.step = traced_step snes.dma_edge = traced_dma_edge snes.bus_read = traced_read snes.bus_write = traced_write while box["n"] < limit + 1: cpu.step() taken.append(box["taken"]) del state[limit + 1 :], clock[limit + 1 :], taken[limit + 1 :] def peek(address: int) -> int: bank, offset = address >> 16, address & 0xFFFF if bank & 0xFE == 0x7E or (not bank & 0x40 and offset < 0x2000): return snes.wram[address & 0x1FFFF if bank & 0xFE == 0x7E else offset] return snes.cart.read(address, 0) t.peek = peek # type: ignore[attr-defined] t.vectors = { # type: ignore[attr-defined] "nmi": _vector(snes, 0xFFEA), "irq": _vector(snes, 0xFFEE), "nmi-e": _vector(snes, 0xFFFA), "irq-e": _vector(snes, 0xFFFE), } return t def _vector(snes, at: int) -> int: return snes.cart.read(at, 0) | snes.cart.read(at + 1, 0) << 8 # Which register a differing read points at. def cause_of(address: int) -> str: if 0x2140 <= address < 0x2180: return "S-SMP port $2140-3 (APU timing)" if address in (0x4210, 0x4211): return "NMI/IRQ flag $4210/$4211 (frame timing)" if address == 0x4212: return "HVBJOY $4212 (line timing, auto-joypad busy)" if 0x2137 <= address <= 0x213F: return "H/V counters $2137-$213F (dot timing)" if 0x4214 <= address <= 0x4217: return "mul/div result $4214-7 (MAME: no latency)" if 0x4218 <= address <= 0x421F: return "auto-joypad $4218-F" return f"register ${address:04X}" # Indexed absolute addressing (WDC W65C816S datasheet table 5-7: reads add a cycle when # the index crosses a page or X is 16 bit; writes and read-modify-writes always have it). ABS_X = { 0x1D: "ORA", 0x3D: "AND", 0x5D: "EOR", 0x7D: "ADC", 0xBD: "LDA", 0xDD: "CMP", 0xFD: "SBC", 0xBC: "LDY", 0x3C: "BIT", 0x9D: "STA", 0x9E: "STZ", 0x1E: "ASL", 0x3E: "ROL", 0x5E: "LSR", 0x7E: "ROR", 0xDE: "DEC", 0xFE: "INC", } ABS_Y = { 0x19: "ORA", 0x39: "AND", 0x59: "EOR", 0x79: "ADC", 0xB9: "LDA", 0xD9: "CMP", 0xF9: "SBC", 0xBE: "LDX", 0x99: "STA", } OPCODES = {0xEB: "XBA", 0x40: "RTI", 0x7C: "JMP (abs,X)", 0xFC: "JSR (abs,X)"} READS = { 0x1D, 0x3D, 0x5D, 0x7D, 0xBD, 0xDD, 0xFD, 0xBC, 0x3C, 0x19, 0x39, 0x59, 0x79, 0xB9, 0xD9, 0xF9, 0xBE, } def residual_cause(b: Trace, sm: tuple, to_vector: bool, m: Trace, i: int) -> str: """A name for a per-instruction clock difference left after refresh and DMA.""" if to_vector: return "interrupt entry (MAME charges the entry no clocks)" op = b.peek(sm[0]) # type: ignore[attr-defined] if op in ABS_X or op in ABS_Y: name = ABS_X[op] + " abs,X" if op in ABS_X else ABS_Y[op] + " abs,Y" index = sm[2] if op in ABS_X else sm[3] pc = sm[0] base = ( b.peek(pc & 0xFF0000 | (pc + 1) & 0xFFFF) | b.peek(pc & 0xFF0000 | (pc + 2) & 0xFFFF) << 8 ) # type: ignore[attr-defined] crossed = (base & 0xFF00) != ((base + index) & 0xFF00) kind = "read" if op in READS else "write/RMW" return ( f"{name} ({kind}), X/Y {'16' if not sm[4] & 0x10 else '8'}-bit, " f"page {'crossed' if crossed else 'not crossed'}" ) return OPCODES.get(op, f"opcode ${op:02X}") def _match_len(a: list, i: int, b: list, j: int, k: int) -> bool: if i + k > len(a) or j + k > len(b): return False return a[i : i + k] == b[j : j + k] def resync(pa: list[int], i: int, pb: list[int], j: int, k: int) -> tuple[int, int] | None: """The smallest di + dj after which ``k`` PCs agree, in growing windows.""" for window in (256, 4096, 65536, 1 << 20): best = None positions: dict[int, list[int]] = {} for q in range(j, min(j + window, len(pb))): positions.setdefault(pb[q], []).append(q) for di in range(min(window, len(pa) - i)): if best is not None and di >= best[0] + best[1]: break for q in positions.get(pa[i + di], ()): dj = q - j if best is not None and di + dj >= best[0] + best[1]: break if _match_len(pa, i + di, pb, q, k): best = (di, dj) break if best is not None: return best return None def compare(m: Trace, b: Trace, k: int, limit: int, detail: int) -> dict: pa = [s[0] for s in m.state] pb = [s[0] for s in b.state] na, nb = min(len(pa), limit), min(len(pb), limit + len(pb)) i = j = 0 exact = pc_only = 0 reg_diffs: Counter = Counter() residual: Counter = Counter() residual_ex: dict = {} cost_ok = cost_n = 0 causes: Counter = Counter() skipped_m = skipped_b = 0 events = [] last_read_diff = None # (instruction index on MAME's side, address) runs = [] # where a stretch of PC-only matches starts: (i, j, fields, cause) run_causes: Counter = Counter() was_exact = True vec = set(b.vectors.values()) # type: ignore[attr-defined] while i < na and j < nb: if pa[i] == pb[j]: sm, sb = m.state[i], b.state[j] if sm == sb: exact += 1 was_exact = True else: pc_only += 1 fields = [f for f, x, y in zip(FIELDS, sm, sb) if x != y] for f in fields: reg_diffs[f] += 1 if was_exact: if i == 0 and fields == ["s"]: cause = "S after reset (core: $01FF less the reset sequence's 3 stack cycles; MAME: $01FF)" elif fields == ["p"] and sm[0] in vec and sm[4] | 4 == sb[4]: cause = "MAME traces a handler's first instruction before setting P.I" elif last_read_diff is not None and i - last_read_diff[0] < 64: cause = cause_of(last_read_diff[1]) else: cause = ( "after a resync" if i and pa[i - 1] != pb[j - 1] else "unattributed: a memory value differs (power-on WRAM/SRAM, or game state that drifted)" ) run_causes[cause] += 1 if len(runs) < 20: runs.append((i, j, fields, cause)) was_exact = False rm, rb = m.reads.get(i, []), b.reads.get(j, []) if rm != rb: for (am, vm), (ab, vb) in zip(rm, rb): if am != ab or vm != vb: last_read_diff = (i, am) break else: last_read_diff = (i, (rm or rb)[0][0]) if i + 1 < len(pa) and j + 1 < len(pb) and pa[i + 1] == pb[j + 1]: cm = m.clock[i + 1] - m.clock[i] cb = b.clock[j + 1] - b.clock[j] - b.taken[j] cost_n += 1 if cm == cb: cost_ok += 1 else: key = (residual_cause(b, sm, pa[i + 1] in vec, m, i), cb - cm) residual[key] += 1 residual_ex.setdefault(key, (i, j, cm, cb, b.taken[j])) i += 1 j += 1 continue found = resync(pa, i, pb, j, k) if found is None: events.append((i, j, None, None, "no resync")) break di, dj = found skipped_m += di skipped_b += dj head = set(pa[i : i + di + 1]) | set(pb[j : j + dj + 1]) returned = i and b.peek(pa[i - 1]) == 0x40 # RTI if any(b.peek(pc) == 0xCB for pc in head): # WAI cause = ( "WAI with /IRQ held and P.I set: the board resumes at once (DOC: WDC " "datasheet, WAI), MAME sleeps to the next NMI" ) elif (head & vec and (pa[i] in vec or pb[j] in vec)) or returned: cause = "interrupt taken at another instruction" elif last_read_diff is not None and i - last_read_diff[0] < 64: cause = cause_of(last_read_diff[1]) else: # A polling loop whose extra iterations are the skipped stretch itself. polled = [m.reads[q][0][0] for q in range(i, i + di) if q in m.reads] polled += [b.reads[q][0][0] for q in range(j, j + dj) if q in b.reads] polled += [b.polls[q] for q in range(j - 64, j + dj) if q in b.polls] polled += [b.polls[q] for q in range(j - 64, j + 64) if q in b.polls] cause = ( cause_of(polled[0]) + " (polled in the skipped stretch)" if polled else "unexplained" ) causes[cause] += 1 if len(events) < detail or cause == "unexplained": events.append((i, j, di, dj, cause)) i += di j += dj return { "compared_mame": i, "compared_board": j, "exact": exact, "pc_only": pc_only, "reg_diffs": reg_diffs, "skipped_mame": skipped_m, "skipped_board": skipped_b, "causes": causes, "events": events, "runs": runs, "run_causes": run_causes, "cost_n": cost_n, "cost_ok": cost_ok, "residual": residual, "residual_ex": residual_ex, } def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("cart", type=Path) parser.add_argument("run", type=Path, help="mame_trace.py's output directory (error.log)") parser.add_argument("--instructions", type=int, default=2_000_000) parser.add_argument( "--board-factor", type=float, default=1.1, help="board instructions to run, as a multiple of --instructions", ) parser.add_argument("--k", type=int, default=32, help="PCs that must agree to resync") parser.add_argument("--detail", type=int, default=12) args = parser.parse_args() began = time.monotonic() m = parse_mame(args.run / "error.log", args.instructions) if len(m.state) <= args.instructions: raise SystemExit(f"MAME's trace has only {len(m.state):,} instructions: run it longer") t_parse = time.monotonic() - began began = time.monotonic() # The board runs further than MAME, so a lagging stream still covers MAME's 2M. b = record_board(cart_image(args.cart), ipl_rom(), int(args.instructions * args.board_factor)) t_board = time.monotonic() - began r = compare(m, b, args.k, args.instructions, args.detail) print( f"{args.cart.name}: MAME {len(m.state) - 1:,} instructions parsed in {t_parse:.0f} s; " f"board {len(b.state) - 1:,} in {t_board:.0f} s ({sys.implementation.name})" ) print(f" compared: MAME {r['compared_mame']:,}, board {r['compared_board']:,}") aligned = r["exact"] + r["pc_only"] print( f" aligned {aligned:,}: all registers equal {r['exact']:,} " f"({100 * r['exact'] / max(aligned, 1):.3f} %), PC only {r['pc_only']:,} " f"(fields: {dict(r['reg_diffs'])})" ) print( f" skipped: MAME {r['skipped_mame']:,}, board {r['skipped_board']:,}; " f"divergences {sum(r['causes'].values()):,}" ) for cause, n in r["causes"].most_common(): print(f" {n:6,} {cause}") print( f" clocks per instruction (board less refresh and DMA): {r['cost_ok']:,} of " f"{r['cost_n']:,} equal" ) for (name, delta), n in r["residual"].most_common(12): i, j, cm, cb, tk = r["residual_ex"][(name, delta)] print( f" {n:6,} x {name}: board {delta:+d} (MAME {cm}, board {cb} + {tk} taken; " f"first MAME #{i:,} board #{j:,})" ) print(f" stretches of PC-only matches: {sum(r['run_causes'].values()):,}") for cause, n in r["run_causes"].most_common(): print(f" {n:6,} {cause}") for i, j, fields, cause in r["runs"][: args.detail]: print(f" #{i:,} / #{j:,} at {m.state[i][0]:06X}: {','.join(fields)}: {cause}") print(" first divergences (MAME index, board index, MAME skip, board skip, cause):") for e in r["events"][: args.detail + 8]: i, j, di, dj, cause = e pc = m.state[i][0] if i < len(m.state) else 0 print(f" #{i:,} / #{j:,} at {pc:06X}: skip {di} / {dj}: {cause}") return 0 if __name__ == "__main__": sys.exit(main())