# SPDX-License-Identifier: MIT """Milestone 1(a): instruction-order lockstep against a MAME 0.285 trace (a detector). Reads the ``error.log`` that ``scripts/mame_trace.py`` leaves (one line per instruction: ``PC A X Y P SP totalcycles VCOUNT``), runs the board from reset on the same cartridge and BIOS, and compares PC, A, X, Y, P & $CF and S per instruction, through the BIOS to the first N cartridge instructions. MAME's ANTIC lumps each line's stolen cycles together (docs/mame-oracle.md), so a loop that polls VCOUNT or waits for an interrupt can run a different number of times on the two sides. Such a divergence is listed, not fixed: the comparison then resynchronises at the next point where 32 consecutive instructions agree on both sides, within a search window, and goes on. The report gives each divergence with its PC and both sides' context. python scripts/lockstep_mame.py TRACE_DIR CART [--cart-instructions 10000] """ from __future__ import annotations import argparse import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) from sixfiveohtwo.debug import BoundaryKind, next_boundary from a5200_python.system import Console RUN = 32 # instructions that must agree to call the streams resynchronised WINDOW = 4000 def mame_stream(log: Path, cart_limit: int): out = [] seen_cart = 0 with log.open("r", encoding="utf-8-sig", errors="replace") as handle: for line in handle: parts = line.split() if len(parts) != 8 or line.startswith("["): continue try: pc, a, x, y, p, s = (int(v, 16) for v in parts[:6]) except ValueError: continue out.append((pc, a, x, y, p & 0xCF, s & 0xFF)) if 0x4000 <= pc < 0xC000: seen_cart += 1 if seen_cart >= cart_limit + 2 * WINDOW: break return out def board_stream(cart: str, count: int, machine: str): console = Console(cart, machine) cpu = console.board.cpu out = [] step = cpu.step while len(out) < count: kind = next_boundary(cpu.capture_state()) if kind is BoundaryKind.INSTRUCTION: out.append((cpu.pc, cpu.a, cpu.x, cpu.y, cpu.p & 0xCF, cpu.s)) step() return out, console def resync(ours, theirs, i, j): """The nearest (a, b) past a divergence where RUN instructions agree.""" index: dict[tuple, int] = {} for b in range(j, min(j + WINDOW, len(theirs) - RUN)): index.setdefault(tuple(theirs[b : b + RUN]), b) best = None for a in range(i, min(i + WINDOW, len(ours) - RUN)): if best is not None and a - i >= (best[0] - i) + (best[1] - j): break b = index.get(tuple(ours[a : a + RUN])) if b is not None and (best is None or (a - i) + (b - j) < (best[0] - i) + (best[1] - j)): best = (a, b) return best def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("trace_dir", type=Path) parser.add_argument("cart") parser.add_argument("--cart-instructions", type=int, default=10000) parser.add_argument("--machine", default="a5200") args = parser.parse_args() theirs = mame_stream(args.trace_dir / "error.log", args.cart_instructions) ours, _console = board_stream(args.cart, len(theirs) + WINDOW, args.machine) i = j = 0 cart_compared = 0 agreed = 0 divergences = [] while j < len(theirs) - RUN and i < len(ours) - RUN and cart_compared < args.cart_instructions: if ours[i] == theirs[j]: agreed += 1 if 0x4000 <= ours[i][0] < 0xC000: cart_compared += 1 i += 1 j += 1 continue found = resync(ours, theirs, i, j) divergences.append((i, j, ours[i], theirs[j], found)) if found is None: break i, j = found print(f"cartridge: {args.cart}") print(f"MAME instructions read: {len(theirs):,}; board instructions run: {len(ours):,}") print(f"agreeing instructions: {agreed:,}; cartridge instructions compared: {cart_compared:,}") print(f"divergences: {len(divergences)}") # Classify: an interrupt entered at a different instruction (one side is at # the BIOS's NMI or IRQ entry), the power-on registers, or anything else. vectors = {0xFCA2, 0xFC00, 0xFC03} classes = {"interrupt position": 0, "power-on registers": 0, "other": 0} others = [] for item in divergences: _, _, a, b, _ = item if a[0] in vectors or b[0] in vectors: classes["interrupt position"] += 1 elif item is divergences[0] and a[0] == b[0] == 0xFD23: classes["power-on registers"] += 1 else: classes["other"] += 1 others.append(item) print("by class:", ", ".join(f"{k} {v}" for k, v in classes.items())) if others: print("unclassified divergences (first 20):") for i, j, a, b, found in others[:20]: fmt = "PC=%04X A=%02X X=%02X Y=%02X P=%02X S=%02X" print(f" board #{i:,} {fmt % a} | MAME #{j:,} {fmt % b}") print("first 12:") for i, j, a, b, found in divergences[:12]: fmt = "PC=%04X A=%02X X=%02X Y=%02X P=%02X S=%02X" skip = ( "no resync" if found is None else f"resync +{found[0] - i} board / +{found[1] - j} MAME" ) print(f" board #{i:,} {fmt % a} | MAME #{j:,} {fmt % b} -> {skip}") ok = cart_compared >= args.cart_instructions and (not divergences or divergences[-1][4]) print( "RESULT:", "reached" if ok else "NOT reached", f"{args.cart_instructions:,} cartridge instructions", ) return 0 if ok else 1 if __name__ == "__main__": raise SystemExit(main())