# SPDX-License-Identifier: MIT """Replay a MAME 0.285 trace of real SPC700 code on the core (validation.md rung 4). MAME is an emulator-derived detector (docs/mame-oracle.md). A real sound driver reads I/O registers whose values come from a board the core does not have, so the replay is board-free: every read of $F0-$FF is answered from MAME's own log (``scripts/mame_trace.py --io``), in order, and every write there is compared with the log. RAM and the IPL ROM are the replay's own; the core starts from the registers of MAME's first line, at the IPL ROM's entry. After each instruction the replay compares ``PC A X Y SP PSW`` with MAME's next line, and the cycles with the difference of MAME's ``totalcycles`` divided by 2. MAME's core is instruction-level: its stores do not read their destination (U1), and it makes no dummy read of PC (C2), so a dummy read here that MAME did not log is answered from RAM, not a divergence: on the core it is one more bus read, which only the board's timers can see (B2). The other way round, MAME's ``SUBOP_ADC`` macro evaluates its second argument twice, so its memory-destination ADC logs two reads of the destination where anomie (groups 10, 18, 19, verified by blargg) and SingleStepTests have one: the repeat, same address, same value, is dropped and counted (C10). The first divergence is a lead, not a verdict: look it up in docs/undocumented-behavior.md, then ask a higher tier. """ from __future__ import annotations from collections import deque from collections.abc import Callable, Iterable, Iterator from contextlib import suppress from dataclasses import dataclass, field from pathlib import Path from spc700_python._opcodes import OPCODES from spc700_python.cpu import SPC700, CPUState from spc700_python.disasm import disassemble from spc700_python.harness import IPL_BASE START_PC = 0xFFC0 REGISTER_NAMES = ("pc", "a", "x", "y", "sp", "psw") @dataclass(slots=True) class Line: """One MAME instruction line (state before the instruction) and the I/O it then made.""" pc: int opcode: int a: int x: int y: int sp: int psw: int cycles: int # MAME totalcycles: two per SPC700 cycle io: list[tuple[str, int, int]] = field(default_factory=list) # ("R" or "W", address, data) def parse_trace(lines: Iterable[bytes | str], start_pc: int = START_PC) -> Iterator[Line]: """Yield MAME instruction lines from the first at ``start_pc``, each with the I/O after it. MAME's own messages are skipped.""" current: Line | None = None started = False for raw in lines: text = raw.decode("latin-1") if isinstance(raw, bytes) else raw fields = text.split() if len(fields) == 4 and fields[0] in ("R", "W"): if started and current is not None: with suppress(ValueError): current.io.append((fields[0], int(fields[1], 16), int(fields[2], 16))) continue if len(fields) != 8: continue try: values = [int(f, 16) for f in fields[:7]] + [int(fields[7])] except ValueError: continue if not started: if values[0] != start_pc: continue started = True if current is not None: yield current current = Line(*values) if current is not None: yield current class ReplayHost: """RAM, the IPL ROM overlay, and I/O answered from and compared with the MAME log.""" def __init__(self, ipl: bytes) -> None: self.ram = bytearray(0x10000) self.ipl = ipl self.ipl_mapped = True self.io: deque[tuple[str, int, int]] = deque() self.problems: list[str] = [] self.unlogged_dummy_reads = 0 self.repeated_reads = 0 self.cpu = SPC700(self.read, self.write) def read(self, address: int) -> int: if 0xF0 <= address <= 0xFF: head = self.io[0] if self.io else None if head is not None and head[0] == "R" and head[1] == address: self.io.popleft() if self.io and self.io[0] == head and OPCODES[self.cpu.opcode].mnemonic == "ADC": self.io.popleft() self.repeated_reads += 1 return head[2] if self.cpu.dummy: self.unlogged_dummy_reads += 1 # U1, C2: MAME makes no such read return self.ram[address] self.problems.append(f"core read ${address:04X}, MAME logged {head}") return 0 if address >= IPL_BASE and self.ipl_mapped: return self.ipl[address - IPL_BASE] return self.ram[address] def write(self, address: int, value: int) -> None: self.ram[address] = value # B4 if 0xF0 <= address <= 0xFF: head = self.io.popleft() if self.io else None if head != ("W", address, value): self.problems.append(f"core wrote ${address:04X}=${value:02X}, MAME logged {head}") if address == 0xF1: self.ipl_mapped = bool(value & 0x80) def peek(self, address: int) -> int: if address >= IPL_BASE and self.ipl_mapped: return self.ipl[address - IPL_BASE] return self.ram[address] @dataclass(frozen=True, slots=True) class Divergence: """The first place the core and MAME disagree.""" position: int # index of the MAME line the replay was executing when it diverged line: Line problems: tuple[str, ...] history: tuple[str, ...] # the last few instructions, for context def describe(self) -> str: head = f"divergence at line {self.position}, MAME PC={self.line.pc:04X}" return "\n".join([head, *self.problems, "recent:", *self.history]) @dataclass(frozen=True, slots=True) class ReplayResult: compared: int # MAME instruction lines compared without a difference divergence: Divergence | None io_reads: int # I/O reads answered from the log io_writes: int # I/O writes compared with the log unlogged_dummy_reads: int # U1 and C2 reads of $F0-$FF that MAME's core does not make repeated_reads: int # MAME's second read of an ADC destination, dropped opcodes: frozenset[int] # distinct opcodes executed @property def ok(self) -> bool: return self.divergence is None def _describe(state: CPUState, host: ReplayHost) -> str: text = disassemble(host.peek, state.pc).text return ( f"{state.pc:04X} {text:<22} A={state.a:02X} X={state.x:02X} Y={state.y:02X} " f"SP={state.sp:02X} PSW={state.psw:02X}" ) def replay( lines: Iterable[Line], ipl: bytes, *, limit: int | None = None, observer: Callable[[int, CPUState, ReplayHost], None] | None = None, ) -> ReplayResult: """Run the core against MAME's lines; stop at the first divergence or the end or limit. ``observer`` is called before each instruction with (position, state, host).""" host = ReplayHost(ipl) cpu = host.cpu iterator = iter(lines) current = next(iterator, None) if current is None: raise ValueError("the trace has no line at the IPL ROM's entry") cpu.restore_state( CPUState( a=current.a, x=current.x, y=current.y, sp=current.sp, pc=current.pc, psw=current.psw ) ) history: deque[CPUState] = deque(maxlen=8) compared = reads = writes = 0 opcodes: set[int] = set() for position, following in enumerate(iterator): if limit is not None and compared >= limit: break before = cpu.capture_state() if observer is not None: observer(position, before, host) history.append(before) host.io = deque(current.io) host.problems = [] reads += sum(entry[0] == "R" for entry in current.io) writes += sum(entry[0] == "W" for entry in current.io) used = cpu.step() opcodes.add(cpu.opcode) state = cpu.capture_state() problems = list(host.problems) if host.io: problems.append(f"MAME logged {len(host.io)} more I/O cycle(s), first {host.io[0]}") for name in REGISTER_NAMES: want = getattr(following, name) if getattr(state, name) != want: problems.append(f"{name.upper()} = {getattr(state, name):X}, MAME {want:X}") delta, remainder = divmod(following.cycles - current.cycles, 2) if remainder or delta != used: problems.append(f"{used} cycles, MAME {(following.cycles - current.cycles) / 2:g}") if problems: recent = tuple(_describe(old, host) for old in history) divergence = Divergence(position, current, tuple(problems), recent) return ReplayResult( compared, divergence, reads, writes, host.unlogged_dummy_reads, host.repeated_reads, frozenset(opcodes), ) compared += 1 current = following return ReplayResult( compared, None, reads, writes, host.unlogged_dummy_reads, host.repeated_reads, frozenset(opcodes), ) def replay_file(path: Path, ipl: bytes, *, limit: int | None = None, observer=None) -> ReplayResult: """Replay a MAME ``error.log`` produced by ``scripts/mame_trace.py --io``.""" with path.open("rb") as stream: return replay(parse_trace(stream), ipl, limit=limit, observer=observer) __all__ = [ "Divergence", "Line", "ReplayHost", "ReplayResult", "parse_trace", "replay", "replay_file", ]