#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Compare the board's master (or slave) SH-2 with MAME 0.285's, instruction by instruction: a detector for the first divergence (docs/validation.md; MAME is no judge for the 32X). MAME's trace comes from sh2-python's ``scripts/mame_trace.py`` (one ``S pc sr pr gbr vbr mach macl r0-r15 totalcycles`` line before each instruction). The board runs the same cartridge with the user's boot ROMs and records the same registers before each step of that chip; the two streams are walked together and the first instruction whose registers differ is printed with the ones before it. Expect a divergence early in any polling loop: the two machines' timing differs (MAME's SH-2 has no cache and charges about a cycle per instruction), so the count of a wait loop's iterations is the first thing to differ. python scripts/sh2_lockstep.py CART MAME_TRACE/master.log --bios-dir DIR --frames 30 """ from __future__ import annotations import argparse import collections import sys from pathlib import Path from megadrive_python.cartridge import Cartridge, load_image from sega32x_python.console import build NAMES = ["pc", "sr", "pr", "gbr", "vbr", "mach", "macl"] + [f"r{n}" for n in range(16)] def mame_states(path: Path): with path.open() as log: for line in log: if line.startswith("S "): fields = line.split() yield [int(value, 16) for value in fields[1:24]] def board_state(chip) -> list[int]: return [chip.pc, chip.sr, chip.pr, chip.gbr, chip.vbr, chip.mach, chip.macl, *chip.R] def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("cartridge", type=Path) parser.add_argument("trace", type=Path) parser.add_argument("--bios-dir", type=Path, required=True) parser.add_argument("--cpu", choices=("master", "slave"), default="master") parser.add_argument("--frames", type=int, default=30) parser.add_argument("--context", type=int, default=12) args = parser.parse_args() system, device = build("genesis", Cartridge.from_image(load_image(args.cartridge)), args.bios_dir) # fmt: skip system.board.fm.enabled = False chip = device.sh2.chips[0 if args.cpu == "master" else 1] # type: ignore[union-attr] expected = mame_states(args.trace) history: collections.deque = collections.deque(maxlen=args.context) count = 0 result: dict[str, object] = {} original = chip.step def step() -> int: nonlocal count if "done" not in result: ours = board_state(chip) theirs = next(expected, None) if theirs is None: result["done"] = f"MAME's trace ended after {count:,} instructions" elif ours != theirs: diff = [f"{n}: board ${a:08X} MAME ${b:08X}" for n, a, b in zip(NAMES, ours, theirs, strict=True) if a != b] # fmt: skip result["done"] = (f"first divergence after {count:,} identical instructions, " f"at PC ${ours[0]:08X} (MAME ${theirs[0]:08X}): " + "; ".join(diff)) # fmt: skip else: count += 1 history.append(ours[0]) return original() chip.step = step for _frame in range(args.frames): system.run_frame() if "done" in result: break print(result.get("done", f"{count:,} instructions identical, no divergence")) print("PCs before it:", " ".join(f"${pc:08X}" for pc in history)) return 0 if __name__ == "__main__": sys.exit(main())