#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Instruction lockstep of the board against Stella's trace (a detector, never a judge). The second detector of milestone 1 (docs/handoff-brief.md), and the one for the RIOT timer: Stella's devices see each access at its own cycle, where MAME's timer slips (docs/undocumented-behavior.md C21, C22). Runs the pinned Stella SDL build headless (``scripts/stella_run.py --debugger --trace``) with a fixed seed and CPU/RAM randomisation off, reads the power-on INTIM from its first RIOT dump, powers the board on in Stella's state, and compares per instruction: A, X, Y, S, P (under $CF, ignoring I until the program first sets it: Stella powers on with I clear and runs no reset sequence) and the beam position. python scripts/lockstep_stella.py "ROM.zip" --frames 600 **Beam position.** Stella's trace gives each instruction's scanline, cycle and pixel at its start; the board's is its TIA colour clock within the line. Both stamp the instruction after a WSYNC before its halted fetch, and both release the halt as the line starts (observed in its traces), so the board is powered on at Stella's phase and the clocks are compared directly (``--offset`` shifts them if needed). A slip of one cycle anywhere, including a WSYNC stall of the wrong length, shows as a beam mismatch at once. One exception: after an RSYNC, Stella's trace keeps showing the old line's coordinates until that line ends (observed in its traces), so from an RSYNC write to the next line the beam is not compared (the registers still are). **Collisions end the run.** Milestone 1's TIA draws nothing, so its collision latches stay clear, and Stella's trace logs no reads to replay (its collision switch is a hotkey only). A divergence right after the board read a collision register is therefore reported as the end of the comparable stretch, with the count of instructions that agreed up to it; ``--strict`` makes it a failure. MAME's lockstep, which replays collision reads, covers the long runs. Stella's trace has no PC column in this build; the beam and registers are what is compared. Exit status 0 if every traced instruction agreed or the run ended at a collision read. """ from __future__ import annotations import argparse import collections import re import subprocess import sys import time from dataclasses import replace from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) from a2600_python import VCS_NTSC, System # noqa: E402 from a2600_python.cartridge import load # noqa: E402 TRACE = re.compile( r"^trace\s+(\d+)\s+(\d+)\s+(\d+)\s+(-?\d+)\s+\|\s+([NnVv-][Vv-]-[Bb][Dd][Ii][Zz][Cc])\s+" r"([0-9A-F]{2}) ([0-9A-F]{2}) ([0-9A-F]{2}) ([0-9A-F]{2})" ) INTIM = re.compile(r"INTIM=([0-9a-f]{2})") RESET_CYCLES = 7 # 6502-python's reset sequence; Stella starts at the vector def flags(text: str) -> int: """Stella's 'nv-BdIzc' (upper case = set) as P.""" value = 0x20 for bit, char in zip((0x80, 0x40, 0x10, 0x08, 0x04, 0x02, 0x01), text[:2] + text[3:]): if char.isupper(): value |= bit return value def stella_trace(cart: Path, frames: int, out: Path, seed: int) -> tuple[int, Path]: command = [ sys.executable, str(ROOT / "scripts" / "stella_run.py"), "--debugger", "--trace", "--frames", str(frames), "--out", str(out), "--stella-option", f"seed={seed}", "--stella-option", "plr.cpurandom=", "--stella-option", "plr.ramrandom=0", str(cart), ] # fmt: skip # The board's console: joysticks, both difficulties B, colour, no phosphor # (Stella's database otherwise sets them per game; milestone 4's sweep). for option in ("bc=JOYSTICK", "ld=B", "rd=B", "tv=COLOR", "sp=NO", "pp=NO"): command[-1:-1] = ["--stella-option", option] subprocess.run(command, check=True, stdout=subprocess.DEVNULL) report = (out / "run.script.output.txt").read_text(errors="replace") return int(INTIM.search(report).group(1), 16), out / "stella-stdout.txt" def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("cart", type=Path) parser.add_argument("--frames", type=int, default=600) parser.add_argument("--seed", type=int, default=1) parser.add_argument("--offset", type=int, default=0, help="Stella pixel+68 minus board clock") parser.add_argument("--out", type=Path) parser.add_argument("--context", type=int, default=8) parser.add_argument("--strict", action="store_true", help="a collision read is a failure") args = parser.parse_args() stem = args.cart.stem.split(" (")[0].replace(" ", "_") out = (args.out or ROOT / "tests" / "detector_runs" / f"stella-{stem}").resolve() began = time.monotonic() intim, log = stella_trace(args.cart, args.frames, out, args.seed) traced = time.monotonic() - began power = replace( VCS_NTSC.power_on, a=0, x=0, y=0, s=0, p=0x20, ram_fill=0, timer_value=intim, timer_divider=1024, # Stella's devices see time at the end of each CPU cycle and it runs no # reset sequence: its cycle 1024 is the board's cycle 1024 + 7 - 1. timer_first_decrement=1024 + RESET_CYCLES - 1, # Stella's first instruction starts a line (pixel -68); the board's # starts after its reset sequence, so it powers on that many cycles # before the line's first cycle (steps 455-4) on the cycle grid. hclock=((454 - 6 * RESET_CYCLES) % 456) // 2, ) # fmt: skip loaded = load(args.cart) system = System(loaded.cartridge, replace(VCS_NTSC, power_on=power)) system.step() # the reset sequence tia = system.board.tia rsync_line = [None] # the board's line in which RSYNC was last written tia_step = tia.step def step_noting_rsync(write=None) -> None: if write is not None and write[0] & 0x3F == 0x03: rsync_line[0] = tia.line tia_step(write) tia.step = step_noting_rsync collision_reads = [] # collision registers read by the last instruction system.board.bus_observers.append( lambda kind, address, value, cycle: ( collision_reads.append(address) if kind == "R" and not address & 0x1080 and address & 0x0F < 0x08 else None ) ) print( f"{loaded.title or args.cart.name}: {loaded.scheme} ({loaded.source}); Stella seed {args.seed}, INTIM ${intim:02X}" ) recent: collections.deque = collections.deque(maxlen=args.context) count = 0 i_known = False with log.open(errors="replace") as lines: for line in lines: m = TRACE.match(line) if not m: continue frame, line_no, cycle, pixel = (int(v) for v in m.group(1, 2, 3, 4)) p = flags(m.group(5)) a, x, y, s = (int(v, 16) for v in m.group(6, 7, 8, 9)) board, cpu = system.board, system.cpu # An instruction starts after a cycle's last step (≡ 4 mod 6); its # first cycle begins two steps on, in Stella's colour clocks. hclock = ((board.tia.step_in_line + 2) % 456) // 2 stella_clock = (pixel + 68 - args.offset) % 228 if rsync_line[0] is not None: if board.tia.line == rsync_line[0]: stella_clock = hclock # Stella shows pre-RSYNC coordinates here else: rsync_line[0] = None mask = 0xCF if i_known else 0xCB theirs = (a, x, y, s, p & mask, stella_clock) ours = (cpu.a, cpu.x, cpu.y, cpu.s, cpu.p & mask, hclock) if ours != theirs and collision_reads and not args.strict: print( f"AGREED on {count:,} instructions up to a collision read " f"(${collision_reads[-1]:02X}) in Stella frame {frame}: the end of what " f"milestone 1's TIA can compare" ) return 0 if ours != theirs: print( f"DIVERGED at instruction {count:,} (Stella frame {frame} line {line_no} cycle {cycle})" ) for state in recent: print(" both ", fmt(state)) print(" Stella", fmt(theirs)) print(" board ", fmt(ours), f"PC={cpu.pc:04X}") return 1 recent.append(ours) collision_reads.clear() i_known = i_known or bool(p & 0x04) system.step() count += 1 print( f"AGREED on {count:,} instructions, {system.board.cycles:,} cycles, " f"{args.frames} Stella frames (Stella {traced:.0f} s, compare {time.monotonic() - began - traced:.0f} s)" ) return 0 if count else 1 def fmt(state: tuple[int, ...]) -> str: a, x, y, s, p, h = state return f"A={a:02X} X={x:02X} Y={y:02X} S={s:02X} P={p:02X} clock={h}" if __name__ == "__main__": sys.exit(main())