#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Milestone 1 gate: instruction-level lockstep with MAME 0.285 through the boot ROM. MAME is a closed box (restart rules): its per-instruction trace (PC, A, X, Y, P, S; ``scripts/mame_trace.py``) is compared with this board on the Lynx I row (MAME's only row is a G65SC02) from ``$FF80`` until the first difference, which is then classified. P is compared under mask ``$CF`` (MAME shows bits 4 and 5 set). A difference is expected where time first matters (a timer or a vertical-blank read): MAME's CPU runs flat 250 ns cycles and this board charges 4/5-tick cycles, so the first time-dependent read is the end of what MAME can judge. python -I scripts/m1_lockstep.py "Zaku (World) (Unl)" ... # titles under $NO_INTRO_DIR """ from __future__ import annotations import argparse import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) from lynx_python import bootrom, romsets from lynx_python.board import Lynx from lynx_python.cart import load from lynx_python.cart.port import CartPort from lynx_python.machine import LYNX1 DEFAULT_TITLES = ( "Zaku (World) (Unl)", "California Games (World)", "Chip's Challenge (World)", "Blue Lightning (World).", "Shanghai (World)", ) def mame_trace(cart: Path, seconds: int, out: Path) -> list[tuple[int, ...]]: log = out / "error.log" if not log.exists(): subprocess.run( [sys.executable, "-I", str(ROOT / "scripts" / "mame_trace.py"), str(cart), "--seconds", str(seconds), "--out", str(out)], check=True, capture_output=True, ) # fmt: skip rows = [] with log.open(encoding="utf-8", errors="replace") as handle: for line in handle: parts = line.split() if len(parts) != 7: continue try: pc, a, x, y, p, s = (int(v, 16) for v in parts[:6]) except ValueError: continue rows.append((pc, a, x, y, p & 0xCF, s & 0xFF)) return rows def lockstep(cart: Path, rows: list[tuple[int, ...]], fault=None) -> tuple[int, str]: description = load(cart) board = Lynx(description.payload, description.bank0_block, machine=LYNX1, boot_rom=bootrom.find()) # fmt: skip if fault: fault(board) board.reset() board.step() # the reset sequence; MAME's first line is the vector's target cpu = board.cpu # Power-on register contents are undefined (U15): MAME's own start values (X=$80, # P=$36) are taken from its first line, so the comparison starts from one state. _pc, cpu.a, cpu.x, cpu.y, p, cpu.s = rows[0] cpu.p = (p & 0xCF) | 0x20 # Recorded difference D1 (docs/validation.md "M1"): the G65SC02 row's reset writes # PCH, PCL, P to page one (w65c02-python, captured on a G65SC12); MAME's reset does # not, and the boot ROM's first PLAs read those bytes back. Explained, then aligned: for address in range(0x100, 0x200): board.ram[address] = 0 for n, expected in enumerate(rows): ours = (cpu.pc, cpu.a, cpu.x, cpu.y, cpu.p & 0xCF, cpu.s) if ours != expected: names = ("PC", "A", "X", "Y", "P", "S") diff = ", ".join( f"{names[i]} ours {ours[i]:02X} MAME {expected[i]:02X}" for i in range(6) if ours[i] != expected[i] ) prev = rows[n - 1][0] if n else 0 return n, f"instruction {n:,} after PC ${prev:04X}: {diff}" board.step() return len(rows), "no difference in the whole trace" class _LeadingEdgePort(CartPort): __slots__ = () def read(self, bank: int) -> int: if not self.strobe: self.counter = (self.counter + 1) & 0x7FF data = self.banks[bank] address = self.address(bank) return data[address] if address < len(data) else 0xFF def _fault_counter_edge(board: Lynx) -> None: """Seeded fault: the cart counter advances on the leading edge (before the byte is taken) instead of the trailing edge (Spec ยง9).""" board.port.__class__ = _LeadingEdgePort FAULTS = {"counter-edge": _fault_counter_edge} def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("titles", nargs="*", default=list(DEFAULT_TITLES)) parser.add_argument("--seconds", type=int, default=4) parser.add_argument("--fault", choices=sorted(FAULTS), help="run with a seeded fault") args = parser.parse_args() for title in args.titles: cart = romsets.find_cart(title) if cart is None: print(f"{title}: not found under $NO_INTRO_DIR") continue stem = title.split(" (")[0].replace(" ", "_").replace("'", "") out = ROOT / "tests" / "mame_traces" / f"{stem}-{args.seconds}s" rows = mame_trace(cart, args.seconds, out) stage2 = next((n for n, row in enumerate(rows) if row[0] == 0x0200), None) n, why = lockstep(cart, rows, FAULTS.get(args.fault)) print(f"{title}: {n:,} of {len(rows):,} instructions agree " f"(MAME reaches $0200 at instruction {stage2}); first difference: {why}") # fmt: skip return 0 if __name__ == "__main__": sys.exit(main())