#!/usr/bin/env python3 """Run the whole system (CPU + board) in lockstep with a MAME trace. The log comes from ``scripts/mame_trace.py``: MAME's Z80 state before each instruction, with its cycle count. We step our system until its cycle count reaches each logged instruction's, then compare PC, AF, BC, DE, HL, IX, IY, SP, AF', I, R and the cycle count itself. The first disagreement stops the run and is reported with the instructions before it. MAME is a detector (docs/validation.md): a divergence is a question for a higher-tier source. python scripts/lockstep_mame.py tests/mame_traces/sg1000-flicky/error.log --driver sg1000 python scripts/lockstep_mame.py tests/mame_traces/sms-sonic/error.log --driver sms \\ --cartridge "$SMS/Sonic The Hedgehog (USA, Europe, Brazil) (En).zip" (``$SMS`` being your No-Intro Master System folder, ``romsets.py``.) The cartridge defaults to the image ``mame_trace.py`` extracted next to the log, or must be given. ``--phase`` is the VDP phase; by default it is solved as ``replay_mame_io.py`` does. """ from __future__ import annotations import argparse import sys import time import zipfile from collections import deque from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) sys.path.insert(0, str(Path(__file__).resolve().parent)) from replay_mame_io import DRIVERS, compare_frame, refine_phase, solve_phase from romsets import MAME_ROMPATH from sms_python.board import MACHINES from sms_python.cartridge import Cartridge from sms_python.mame_log import Instruction, PortAccess, read_log from sms_python.png import write_png from sms_python.system import System from sms_python.vdp import MCLOCKS_PER_LINE CLOCK = 3_579_545 ROMPATH = MAME_ROMPATH # MAME's power-on VDP phase per driver, in mclocks (kept equal to compat_sweep.SYSTEMS). POWER_ON_PHASE = {"sg1000": 139460, "sms": 142245, "gamegear": 114877} # The BIOS each MAME driver boots through (docs/mame-oracle.md, "Driver facts"). BIOS = {"sms": ("sms.zip", "mpr-12808.ic2"), "sf7000": ("sf7000.zip", "ipl.rom")} def phase_from_interrupts(log: Path, height: int = 192, lines_per_frame: int = 262) -> int: """The VDP phase that explains when MAME accepted its frame interrupts. An IM 1 entry takes 13 T-states and lands on $0038 with SP two lower, so the INT line rose no later than the entry's start: an *upper* bound, always valid. (The matching lower bound, "after the previous instruction began", fails whenever interrupts were disabled then, so it is not used.) Our frame IRQ rises at line ``height``, m = 680 (sms_python.vdp). Expressed as an offset within the frame, the tightest upper bound is the assertion time; entries far from the median (an RST 38h instruction, not an interrupt) are dropped first. """ frame_cycles = MCLOCKS_PER_LINE * lines_per_frame // 3 uppers: list[int] = [] previous = None for event in read_log(log): if not isinstance(event, Instruction): continue if previous is not None and event.pc == 0x0038 and event.sp == (previous.sp - 2) & 0xFFFF: uppers.append(event.cycles - 13) previous = event if not uppers: raise ValueError("no interrupt entries in the log") base = uppers[0] offsets = sorted((((u - base) + frame_cycles // 2) % frame_cycles) - frame_cycles // 2 for u in uppers) # fmt: skip median = offsets[len(offsets) // 2] assertion = base + min(o for o in offsets if abs(o - median) <= 64) irq_m = height * MCLOCKS_PER_LINE + 680 return (irq_m - assertion * 3) % (frame_cycles * 3) def load_bios(driver: str) -> Cartridge | None: if driver not in BIOS: return None archive, member = BIOS[driver] with zipfile.ZipFile(ROMPATH / archive) as bundle: return Cartridge(bundle.read(member)) def cpu_state(cpu) -> tuple[int, ...]: state = cpu.capture_state() return ( state.pc, state.a << 8 | state.f, state.b << 8 | state.c, state.d << 8 | state.e, state.h << 8 | state.l, state.ix, state.iy, state.sp, state.af_alt, state.i, state.r, ) def mame_state(line: Instruction) -> tuple[int, ...]: return (line.pc, line.af, line.bc, line.de, line.hl, line.ix, line.iy, line.sp, line.af2, line.i, line.r) # fmt: skip NAMES = ("PC", "AF", "BC", "DE", "HL", "IX", "IY", "SP", "AF'", "I", "R") def set_cpu(cpu, line: Instruction) -> None: """MAME's power-on registers (undefined on a real Z80, so copied, not compared).""" cpu.pc, cpu.sp, cpu.ix, cpu.iy, cpu.i, cpu.r = ( line.pc, line.sp, line.ix, line.iy, line.i, line.r, ) # fmt: skip cpu.a, cpu.f = line.af >> 8, line.af & 0xFF cpu.b, cpu.c = line.bc >> 8, line.bc & 0xFF cpu.d, cpu.e = line.de >> 8, line.de & 0xFF cpu.h, cpu.l = line.hl >> 8, line.hl & 0xFF cpu.af_ = line.af2 def dump_vdp(vdp) -> None: """The VDP state behind a differing read: line, m, registers, sprites on the line.""" regs = vdp.registers print(f"VDP line {vdp.line} m {vdp.m} status {vdp.status:02X} " f"frame_pending {vdp.frame_pending} overflow_pending {vdp.overflow_pending} " f"collision_at {vdp.collision_at}") # fmt: skip print("registers", " ".join(f"{r:02X}" for r in regs[:11])) if vdp.mode4: sat = (regs[5] & 0x7E) << 7 size = (16 if regs[1] & 2 else 8) * (2 if regs[1] & 1 else 1) for line in (vdp.line - 1, vdp.line, vdp.line + 1): hits = [] for index in range(64): y = vdp.vram[sat + index] if y == 0xD0 and vdp.height == 192: break if ((line - (y + 1)) & 0xFF) < size: hits.append((index, y, vdp.vram[sat + 0x80 + 2 * index])) print(f"line {line}: {len(hits)} sprites (index, y, x): {hits}") def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("log", type=Path) parser.add_argument("--driver", choices=sorted(DRIVERS), default="sms") parser.add_argument("--cartridge", type=Path) parser.add_argument("--phase", type=int) parser.add_argument( "--solve-phase", action="store_true", help="solve the VDP phase from this log instead" ) parser.add_argument("--limit", type=int, help="stop after this many MAME instructions") parser.add_argument( "--patch-reads", action="store_true", help="when a port read differs from MAME's, report it and continue with MAME's value", ) parser.add_argument( "--dump", action="store_true", help="print the VDP's state at the first differing read" ) parser.add_argument( "--frame", type=Path, help="render throughout, run on to --seconds as the sweep does, and save the " "frame completed after it here as a PNG, compared with MAME's exit snapshot " "if the log's run kept one", ) parser.add_argument("--seconds", type=int, default=10, help="the log's run time (--frame)") args = parser.parse_args() machine = MACHINES[DRIVERS[args.driver]] cart_path = args.cartridge or next( (p for p in args.log.parent.iterdir() if p.suffix in (".sms", ".sg", ".gg")), None ) if cart_path is None: parser.error("no cartridge image next to the log: pass --cartridge") cartridge = Cartridge.from_file(cart_path) phase = args.phase if phase is None and not args.solve_phase: # MAME starts every run from the same power-on state: one phase per driver, # fitted over the compatibility sweep (compat_sweep.SYSTEMS, fit_phase.py). phase = POWER_ON_PHASE.get(args.driver) if phase is None and machine.decode == "sg1000": phase = phase_from_interrupts(args.log) if phase is None: accesses = [e for e in read_log(args.log) if isinstance(e, PortAccess)] phase = solve_phase(accesses, 0) if isinstance(phase, list): lines = sorted({p - p % MCLOCKS_PER_LINE for p in phase}) coarse = refine_phase(accesses, machine, 0, lines) window = [p for p in phase if coarse <= p < coarse + MCLOCKS_PER_LINE] phase = refine_phase(accesses, machine, 0, window) print(f"{machine.name}: {cart_path.name}; VDP phase {phase} mclocks") system = System(machine, cartridge, load_bios(args.driver), audio=False) vdp = system.board.vdp vdp.render = args.frame is not None lines_in, remainder = divmod(phase, MCLOCKS_PER_LINE) vdp.line, vdp.m = lines_in % vdp.lines_per_frame, remainder # Interrupts are taken where MAME took them: MAME's acceptance point wanders by # up to about ten cycles from frame to frame (docs/mame-oracle.md, trap 7), so it # cannot judge our INT timing to the cycle. Our VDP's INT is still measured # against each MAME entry and reported as a spread. cpu, board = system.cpu, system.board recent: deque[str] = deque(maxlen=8) compared = 0 rise_at = None # our last INT rising edge, in cycles was_high = False irq_offsets: list[int] = [] started = time.time() previous = None # MAME's port reads, in order, for the instruction being stepped: each of our reads # is checked against the next one (the log lists them after their instruction). mame_reads: deque[PortAccess] = deque() read_differences: list[str] = [] board_read_port = board.read_port def read_port(port: int) -> int: value = board_read_port(port) if not mame_reads: return value theirs = mame_reads.popleft() if (theirs.port, theirs.value) != (port & 0xFF, value): read_differences.append( f"cycle {system.cycles}: IN ${port & 0xFF:02X} ours {value:02X}, " f"MAME ${theirs.port:02X} {theirs.value:02X}" ) if args.dump and len(read_differences) == 1: dump_vdp(board.vdp) if args.patch_reads: return theirs.value return value cpu.read_port = read_port # --frame: the first frame completed after the run's time, as compat_sweep.py # compares; MAME's log itself goes on to the end of that frame. frame_after = args.seconds * CLOCK kept_frame = None def step(take_irq: bool) -> None: nonlocal rise_at, was_high, kept_frame if take_irq: cpu.request_maskable_interrupt(0xFF) else: cpu.clear_maskable_interrupt() cycles = cpu.step() board.advance(cycles) system.cycles += cycles if board.vdp.frame_ready: board.vdp.frame_ready = False if kept_frame is None and system.cycles >= frame_after: kept_frame = board.vdp.frame high = board.vdp.irq if high and not was_high: rise_at = system.cycles was_high = high for event in read_log(args.log): if isinstance(event, PortAccess): if not event.write: mame_reads.append(event) continue if compared == 0: set_cpu(cpu, event) system.cycles = event.cycles # MAME lands on $0038 after an instruction that is not RST 38h: an IM 1 # entry (SP need not be two lower: the instruction itself may push or pop). irq_entry = ( previous is not None and event.pc == 0x0038 and board.read_byte(previous.pc) != 0xFF ) entry_at = event.cycles - 13 if irq_entry else None while system.cycles < event.cycles: step(take_irq=system.cycles == entry_at) if irq_entry and rise_at is not None: irq_offsets.append(entry_at - rise_at) ours, theirs = cpu_state(cpu), mame_state(event) recent.append(f" cycle {event.cycles}: PC {event.pc:04X}") if system.cycles != event.cycles or ours != theirs: print(f"DIVERGED after {compared:,} instructions, at MAME cycle {event.cycles}" f" (ours {system.cycles}):") # fmt: skip for name, a, b in zip(NAMES, ours, theirs, strict=True): if a != b: print(f" {name}: ours {a:04X}, MAME {b:04X}") print("recent MAME instructions:", *recent, sep="\n") print("port reads that differed:", *read_differences[-5:], sep="\n") return 1 compared += 1 previous = event if args.limit and compared >= args.limit: break if irq_offsets: # An entry within one instruction (23 T-states, the longest) of our INT rising # is timing agreement; later ones are the program holding interrupts off. prompt = sorted(o for o in irq_offsets if 0 <= o <= 23) early = sum(o < 0 for o in irq_offsets) print(f"{len(irq_offsets)} interrupt entries: {len(prompt)} within one instruction of " f"our INT rising (median {prompt[len(prompt) // 2] if prompt else '-'} cycles), " f"{len(irq_offsets) - len(prompt) - early} later (interrupts held off), " f"{early} before it") # fmt: skip print(f"{len(read_differences)} port reads differed from MAME's" + (" (MAME's value used)" if args.patch_reads else "")) # fmt: skip for line in read_differences[:10]: print(" " + line) if args.frame is not None: if kept_frame is None: # The log ended short of that frame (the program halted): finish it as # compat_sweep.py does, on our own interrupts. cpu.read_port = board_read_port system.run_cycles(frame_after - system.cycles) system.run_frame() else: board.vdp.frame = kept_frame snapshots = sorted(args.log.parent.glob("snap/*/*.png")) if snapshots: wrong, total, at = compare_frame(board, snapshots[-1], args.frame) print(f"our last frame vs MAME's snapshot at {at}: {wrong}/{total} pixels differ") else: write_png(args.frame, board.vdp.visible_frame()) elapsed = time.time() - started print(f"{compared:,} instructions identical (registers and cycle counts), " f"{system.cycles:,} cycles, {elapsed:,.0f} s") # fmt: skip return 0 if __name__ == "__main__": sys.exit(main())