#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Instruction lockstep of the board against a MAME 0.285 trace (a detector, never a judge). Milestone 1's acceptance (docs/handoff-brief.md): run the board on the same cartridge MAME traced with ``scripts/mame_trace.py`` and compare, before every instruction, PC, A, X, Y, P (under $CF), S, the cycle count and INTIM. The board starts from :class:`a2600_python.machine.PowerOn`'s defaults, which match MAME's power-on state. python scripts/mame_trace.py a2600 "ROM.zip" --seconds 60 --out tests/mame_traces/x python scripts/lockstep_mame.py "ROM.zip" tests/mame_traces/x/error.log Three adaptations to MAME, all on this side and none in the board (docs/mame-oracle.md): - **Stamps.** MAME stamps each instruction one cycle after its opcode fetch (trap 2) and burns a WSYNC's cycles at the write, where the board halts inside the next opcode fetch; the compared count adds both. - **The timer is replayed, not compared** (docs/undocumented-behavior.md C21, C22). MAME's RIOT times a timer write as if made at the instruction's stamp (a 4-cycle STA TIM64T acts two cycles early, measured on Adventure), and its timer slips a further cycle against its own CPU within the first emulated second (Pitfall!, River Raid and Adventure all diverge on INTIM near cycle 1,191,875). So reads of INTIM/TIMINT return MAME's logged values and the INTIM column is not compared; the timer's detector is Stella, whose devices see each access's own cycle. ``--compare-timer`` compares it anyway. - **RSYNC is dropped.** MAME's RSYNC is a no-op (tia.cpp:1317-1320) where the board restarts the line (provisionally, C3), so RSYNC writes do not reach the board's TIA here. - **Collisions.** Milestone 1's TIA draws nothing, so its collision latches stay clear; MAME's draw. D7/D6 of every collision read are replayed from MAME's logged reads (the floating D5-D0 still come from the board's own bus). Prints the number of instructions that agreed, or the first divergence with the instructions before it. Exit status 0 only if the whole trace agreed. """ from __future__ import annotations import argparse import collections import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) from a2600_python import System # noqa: E402 FIELDS = ("PC", "A", "X", "Y", "P", "S", "cycle", "INTIM") MAME_STAMP_OFFSET = 1 # docs/mame-oracle.md trap 2 def is_timer_read(address: int) -> bool: """INTIM or TIMINT: A12 low, A9, A7 and A2 high (riot.py's decode).""" return address & 0x1284 == 0x284 def mame_steps(log: Path): """Per instruction: its state (PC, A, X, Y, P & $CF, S, cycle, INTIM) and the collision and timer reads logged with it, as (kind, address, value).""" state = None reads: list[tuple[str, int, int]] = [] with log.open(encoding="utf-8", errors="replace") as lines: for line in lines: parts = line.split() if len(parts) == 4 and parts[0] == "R": address, value = int(parts[1], 16), int(parts[2], 16) if address < 0x80 and address & 0x0F < 0x08: reads.append(("TIA", address & 0x0F, value)) elif is_timer_read(address): reads.append(("RIOT", address, value)) continue if len(parts) != 9: continue try: pc, a, x, y, p, sp = (int(v, 16) for v in parts[:6]) cycle, intim = int(parts[6]), int(parts[7], 16) except ValueError: continue if state is not None: yield state, reads reads = [] state = (pc, a, x, y, p & 0xCF, sp & 0xFF, cycle, intim) if state is not None: yield state, reads class MameAdapter: """The detector-side adaptations: replayed collision and timer reads.""" def __init__(self, system: System, replay_timer: bool) -> None: self.system = system self.queues = {"TIA": collections.deque(), "RIOT": collections.deque()} riot, tia = system.board.riot, system.board.tia tia_read, riot_read = tia.read, riot.read def replay(kind: str, address: int, own: int) -> int: queue = self.queues[kind] if queue and queue[0][0] == address: return queue.popleft()[1] return own def read_with_collisions(address: int) -> int: own = tia_read(address) if address & 0x0F < 0x08: return replay("TIA", address & 0x0F, own) & 0xC0 return own tia.read = read_with_collisions tia_step = tia.step def step_without_rsync(write=None): tia_step(None if write is not None and write[0] & 0x3F == 0x03 else write) tia.step = step_without_rsync if replay_timer: def read_with_timer(address: int, cycle: int) -> int: own = riot_read(address, cycle) # side effects still happen return replay("RIOT", address, own) if is_timer_read(address) else own riot.read = read_with_timer def take(self, reads) -> None: for kind, address, value in reads: self.queues[kind].append((address, value)) def state(self) -> tuple[int, ...]: cpu, board = self.system.cpu, self.system.board stamp = board.cycles + MAME_STAMP_OFFSET if not board.tia.rdy: # A WSYNC is pending: the board halts inside the coming opcode # fetch; MAME burnt the cycles at the write (tia.cpp:976-984). stamp += board.tia.clocks_to_line_end() // 3 intim = board.riot.timer_at(stamp) return (cpu.pc, cpu.a, cpu.x, cpu.y, cpu.p & 0xCF, cpu.s, stamp, intim) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("cart", type=Path) parser.add_argument("log", type=Path, help="error.log from scripts/mame_trace.py") parser.add_argument("--compare-timer", action="store_true", help="compare INTIM, no replay") parser.add_argument("--context", type=int, default=8) parser.add_argument("--max-instructions", type=int, help="stop after this many") args = parser.parse_args() system = System.from_rom(args.cart) system.step() # the reset sequence; MAME's first line is the first instruction adapter = MameAdapter(system, replay_timer=not args.compare_timer) loaded = system.loaded print( f"{loaded.title or args.cart.name}: {loaded.scheme} ({loaded.source}), sha1 {loaded.sha1}" ) compared = slice(0, 8) if args.compare_timer else slice(0, 7) recent: collections.deque = collections.deque(maxlen=args.context) began = time.monotonic() count = 0 for theirs, reads in mame_steps(args.log): ours = adapter.state() if ours[compared] != theirs[compared]: print(f"DIVERGED at instruction {count:,} (frame {system.board.tia.frame})") for state in recent: print(" both ", fmt(state)) print(" MAME ", fmt(theirs)) print(" board", fmt(ours)) bad = [f for f, a, b in zip(FIELDS, ours, theirs) if a != b] print(" fields:", ", ".join(bad)) for kind, queue in adapter.queues.items(): if queue: head = ", ".join(f"{a:03X}={v:02X}" for a, v in list(queue)[:4]) print(f" unreplayed {kind} reads: {len(queue)} ({head} ...)") return 1 if args.max_instructions is not None and count >= args.max_instructions: break recent.append(ours) adapter.take(reads) system.step() count += 1 wall = time.monotonic() - began print( f"AGREED on {count:,} instructions, {system.board.cycles:,} cycles, " f"{system.board.tia.frame} frames ({wall:.1f} s)" ) return 0 if count else 1 def fmt(state: tuple[int, ...]) -> str: pc, a, x, y, p, s, cycle, intim = state return f"PC={pc:04X} A={a:02X} X={x:02X} Y={y:02X} P={p:02X} S={s:02X} cyc={cycle} INTIM={intim:02X}" if __name__ == "__main__": sys.exit(main())