# SPDX-License-Identifier: MIT AND BSD-3-Clause """Rung 4: replay MAME 0.285's trace of a real game through the core. ``scripts/mame_trace.py GAME --io`` leaves an ``error.log`` holding one line per instruction, before it runs (``PC PB A X Y S D DB P E totalcycles``), and after each line the I/O and cartridge-RAM reads that instruction made (``R address value``; docs/mame-oracle.md). :class:`Replay` runs the core in the minimal harness from the same reset and answers those reads from the log in order, so the core sees what MAME's board gave MAME's CPU. After every instruction it compares the registers with MAME's next line, and the instruction's length in master clocks with MAME's ``totalcycles`` delta. MAME is emulator-derived (validation.md): a difference is a lead, never a verdict. What this replay knows about MAME and adjusts for, each counted: - **interrupts** come from MAME's board, not the harness's: when MAME's next line is at the NMI (or IRQ) vector's target with the entry's bytes pushed, the replay requests that interrupt and steps the entry before comparing. The harness's own frame NMI is off. - **MAME's NMI entry leaves I clear** (``g65816i_interrupt_nmi`` has no ``g65816i_set_flag_i``, unlike its IRQ entry and DS section 7.5): after an NMI entry the core's I flag is set to MAME's (``nmi_i``). - **reads MAME's watchpoints did not log**: only banks $00 and $80 of the I/O area are watched (mame_trace.py). An instruction that reads I/O elsewhere is answered by the harness and then the core takes MAME's registers after it (``adopted``), so a wrong guess cannot spread. - **power-on WRAM** is MAME's $55 in every byte (``snes_init_ram``). - **MVN/MVP's A** goes below zero unmasked in MAME and is traced as $FFFFFFFF: A, X and Y are read as 16 bits. - **reset** leaves A, X, Y and S's low byte undefined (DS section 2.25): the core takes MAME's values for those at the first instruction. The clocks of a step are the 5A22's for the core's own cycles: 6 per cycle, plus MAME's ``bus_5A22_cycle_burst`` for each read and write (2 for a slow region, 6 for $4000-$41FF, none for FastROM in banks $80-$FF with MEMSEL set). Steps whose MAME delta also holds DMA (a write to $420B) or an interrupt entry are compared as a whole; the remaining differences are tallied by the instruction's opcode for docs/validation.md. """ from __future__ import annotations import re from collections import Counter, deque from collections.abc import Iterator from dataclasses import dataclass, field from pathlib import Path from w65c816.harness import Harness REGISTERS = ("pc", "pbr", "a", "x", "y", "s", "d", "dbr", "p", "e") I_FLAG = 0x04 @dataclass(frozen=True, slots=True) class Line: """One instruction of MAME's trace: the registers before it, the master clock count before it, and the logged reads it made.""" registers: tuple[int, ...] # in REGISTERS order clocks: int reads: tuple[tuple[int, int], ...] @property def address(self) -> int: return self.registers[1] << 16 | self.registers[0] def read_log(path: Path) -> Iterator[Line]: """MAME's trace lines with their reads, lazily, from an ``error.log``.""" registers: tuple[int, ...] | None = None clocks = 0 reads: list[tuple[int, int]] = [] with path.open("rb") as log: for raw in log: fields = raw.split() if len(fields) == 3 and fields[0] == b"R": reads.append((int(fields[1], 16), int(fields[2], 16))) continue if len(fields) != 11 or raw.startswith(b"["): continue try: values = tuple(int(f, 16) for f in fields[:10]) # MAME's "pc" is PB:PC, 24 bits; the core's is 16. MAME's MVN # and MVP count A below zero without a mask (REGISTER_A--, # g65816op.ipp), which shows as $FFFFFFFF until the next # instruction that rebuilds A: registers are 16 bits. pc, pb, a, x, y, *rest = values values = (pc & 0xFFFF, pb, a & 0xFFFF, x & 0xFFFF, y & 0xFFFF, *rest) total = int(fields[10]) except ValueError: continue if registers is not None: yield Line(registers, clocks, tuple(reads)) registers, clocks, reads = values, total, [] if registers is not None: yield Line(registers, clocks, tuple(reads)) def burst(address: int, fast_rom: bool) -> int: """MAME 0.285's ``bus_5A22_cycle_burst``: the clocks a read or write adds to the 6 every cycle costs, by region. Transcribed from MAME 0.285 ``src/devices/cpu/g65816/g65816.cpp`` (license: BSD-3-Clause; copyright-holders: Karl Stenerud).""" if address & 0x408000: return 0 if address & 0x800000 and fast_rom else 2 if (address + 0x6000) & 0x4000: return 2 if (address - 0x4000) & 0x7E00: return 0 return 6 DEFAULT_BANKS = frozenset((0x00, 0x80)) def watched_banks(trace_lua: Path) -> frozenset[int]: """The banks whose I/O reads mame_trace.py had MAME log (its trace.lua).""" if not trace_lua.is_file(): return DEFAULT_BANKS found = re.findall(r"wpset ([0-9A-F]*)2000,6000,", trace_lua.read_text(encoding="utf-8")) return frozenset(int(bank or "0", 16) for bank in found) or DEFAULT_BANKS def logged(address: int, banks: frozenset[int] = DEFAULT_BANKS) -> bool: """Whether MAME's watchpoints log reads of ``address`` (mame_trace.py).""" bank, offset = address >> 16, address & 0xFFFF if bank in banks: return 0x2000 <= offset < 0x8000 if 0x20 <= bank < 0x40: return 0x6000 <= offset < 0x8000 return 0x70 <= bank <= 0x7D and offset < 0x8000 def unmodelled(address: int) -> bool: """Reads the harness cannot answer as MAME's board would: I/O and cartridge RAM (LoROM's banks $70-$7D, HiROM's $6000-$7FFF).""" bank, offset = address >> 16, address & 0xFFFF if bank & 0x7F < 0x40: return 0x2000 <= offset < 0x8000 return 0x70 <= bank <= 0x7D and offset < 0x8000 # MAME's cycle counts, where they are not the datasheet's (g65816op.ipp, # g65816.cpp; the core follows DS Table 5-7, rung 0). Indexed addressing adds # one cycle only when the index carries out of the page (EA_AX, EA_AY, # EA_DIY), whatever the index width; the datasheet adds one for a carry *or* # 16-bit index registers on reads, and always (one, not two) on writes and # read-modify-writes. MAME's a,x and a,y store and RMW constants (CLK_W_AX = # 3) already include that cycle, so a carry makes two; its (d),y store # constant does not (CLK_W_DIY = CLK_DIY), so without a carry it is one short. # Each rule was found by a replay below and read in MAME's source after. INDEXED_READS = { # opcode: "x" (a,x), "y" (a,y) or "dy" ((d),y) **dict.fromkeys((0x1D, 0x3D, 0x5D, 0x7D, 0xBD, 0xBC, 0xDD, 0xFD, 0x3C), "x"), **dict.fromkeys((0x19, 0x39, 0x59, 0x79, 0xB9, 0xBE, 0xD9, 0xF9), "y"), **dict.fromkeys((0x11, 0x31, 0x51, 0x71, 0xB1, 0xD1, 0xF1), "dy"), } INDEXED_WRITES = { # stores, and read-modify-writes, whose a,x constants are alike **dict.fromkeys((0x9D, 0x9E, 0x1E, 0x3E, 0x5E, 0x7E, 0xDE, 0xFE), "x"), 0x99: "y", 0x91: "dy", } XBA = 0xEB # CLK_OP + CLK_IMPLIED: 2 cycles with M = 1 (3 with M = 0); DS 3 RTI = 0x40 # CLK(7) emulation, CLK(8) native; DS 6 and 7 JMP_AXI = 0x7C # CLK_OP + CLK_AXI: 5 cycles; DS 6 def mame_extra_cycles(harness: Harness, registers: tuple[int, ...]) -> int: """How many CPU cycles more than the datasheet MAME 0.285 charges for the instruction about to run from ``registers`` (negative: fewer).""" pc, pbr, _, x, y, _, d, _, p, _ = registers opcode = harness.peek(pbr << 16 | pc) if opcode == XBA: return -1 if p & 0x20 else 0 if opcode == RTI: return 1 if opcode == JMP_AXI: return -1 mode = INDEXED_READS.get(opcode) or INDEXED_WRITES.get(opcode) if mode is None: return 0 operand = pbr << 16 | (pc + 1) & 0xFFFF if mode == "dy": pointer = (d + harness.peek(operand)) & 0xFFFF base = harness.peek(pointer) | harness.peek((pointer + 1) & 0xFFFF) << 8 else: base = harness.peek(operand) | harness.peek(operand + 1) << 8 index = x if mode == "x" else y crossed = bool((base ^ (base + index)) & 0xFF00) if opcode in INDEXED_WRITES: return int(crossed) - (mode == "dy") return -1 if not p & 0x10 and not crossed else 0 @dataclass class Divergence: index: int # MAME line number (0 = the first instruction) address: int # 24-bit address of the instruction that was stepped opcode: int differences: dict[str, tuple[int, int]] # register: (core, MAME) @dataclass class Report: instructions: int = 0 nmi: int = 0 irq: int = 0 nmi_i: int = 0 #: Interrupts MAME took at a boundary where the core's poll (bsnes's rule) #: waits one more instruction: after CLI/PLP/REP cleared I, or an entry. forced: Counter[str] = field(default_factory=Counter) adopted: int = 0 adopted_addresses: Counter[int] = field(default_factory=Counter) unread: int = 0 # logged reads the core did not make (DMA's B-bus side) unread_addresses: Counter[int] = field(default_factory=Counter) divergences: list[Divergence] = field(default_factory=list) clocks_equal: int = 0 clocks_mame_rule: int = 0 # differ exactly as mame_extra_cycles predicts clocks_skipped: int = 0 # DMA and interrupt entries clock_differences: Counter[tuple[int, int]] = field(default_factory=Counter) # (opcode, delta) #: The first few steps of each (opcode, delta): (line, registers before). clock_samples: dict[tuple[int, int], list[tuple[int, tuple[int, ...]]]] = field( default_factory=dict ) @property def unexplained(self) -> int: """Steps whose clocks differ from MAME's other than by its cycle rules.""" return sum(self.clock_differences.values()) def summary(self) -> str: compared = self.clocks_equal + self.clocks_mame_rule + sum(self.clock_differences.values()) lines = [ ( f"instructions {self.instructions:,}; NMI {self.nmi:,}, IRQ {self.irq:,}" f" (I flag set to MAME's after {self.nmi_i:,} NMIs); taken a boundary" f" earlier than the core's poll would: NMI {self.forced['nmi']:,}," f" IRQ {self.forced['irq']:,}" ), ( f"register divergences {len(self.divergences):,}; adopted MAME's registers" f" after {self.adopted:,} unlogged reads; {self.unread:,} logged reads not made" ), ( f"clocks equal {self.clocks_equal:,} of {compared:,}, MAME's cycle rules" f" {self.clocks_mame_rule:,}, unexplained {self.unexplained:,}" f" ({self.clocks_skipped:,} steps with DMA, WAI or an interrupt entry skipped)" ), ] by_opcode: Counter[int] = Counter() for (opcode, _), count in self.clock_differences.items(): by_opcode[opcode] += count for opcode, count in by_opcode.most_common(20): deltas = sorted((d, n) for (o, d), n in self.clock_differences.items() if o == opcode) text = ", ".join(f"{d:+d} x{n:,}" for d, n in deltas) lines.append(f" opcode {opcode:02X}: {count:,} differ (MAME - core: {text})") if self.unread_addresses: common = ", ".join(f"{a:06X} x{n:,}" for a, n in self.unread_addresses.most_common(8)) lines.append(f" logged reads not made: {common}") if self.adopted_addresses: common = ", ".join(f"{a:06X} x{n:,}" for a, n in self.adopted_addresses.most_common(8)) lines.append(f" unlogged reads: {common}") for divergence in self.divergences[:20]: diffs = ", ".join( f"{name} core {core:X} MAME {mame:X}" for name, (core, mame) in divergence.differences.items() ) lines.append( f" line {divergence.index:,} at {divergence.address:06X}" f" (opcode {divergence.opcode:02X}): {diffs}" ) return "\n".join(lines) class Replay(Harness): """The minimal harness with MAME's board behind its unmodelled reads.""" def __init__( self, rom: bytes, mapping: str | None = None, banks: frozenset[int] = DEFAULT_BANKS ) -> None: super().__init__(rom, mapping) self.banks = banks # MAME's power-on WRAM ("0x55 isn't exactly right but it's close", # snes_m.cpp snes_init_ram); the real chip powers up with a pattern # of its own, which the harness's zeros are no closer to. self.wram[:] = bytes((0x55,)) * len(self.wram) self.clocks = 0 self.fast_rom = False self.reads: deque[tuple[int, int]] = deque() self.guessed: int | None = None # an unlogged unmodelled read this step self.dma_started = False self.unread_addresses: Counter[int] = Counter() self.in_dma = False # The harness's frame and its NMI are MAME's to decide here. def _tick(self) -> None: self.cycles += 1 def read_byte(self, address: int) -> int: self._tick() self.clocks += 6 + burst(address, self.fast_rom) value = self.peek(address) # the harness's side effects ($2180, ...) if unmodelled(address): reads = self.reads if reads and reads[0][0] == address: value = reads.popleft()[1] elif logged(address, self.banks) and reads and address in (a for a, _ in reads): # MAME logged other reads first (a DMA's B-bus reads): skip them. while reads[0][0] != address: self.unread_addresses[reads.popleft()[0]] += 1 value = reads.popleft()[1] else: self.guessed = address self.open_bus = value return value def write_byte(self, address: int, value: int) -> None: self._tick() self.clocks += 6 + burst(address, self.fast_rom) self.open_bus = value self.poke(address, value) def idle(self, address: int) -> None: self._tick() self.clocks += 6 def _dma(self, channel: int) -> None: self.in_dma = True try: super()._dma(channel) finally: self.in_dma = False def io_read(self, offset: int) -> int: """A DMA's B-bus read (MAME logs it at $00:21xx): MAME's value.""" reads = self.reads value = super().io_read(offset) if self.in_dma and reads and reads[0][0] == offset: value = reads.popleft()[1] return value def io_write(self, offset: int, value: int) -> None: if offset == 0x420D: self.fast_rom = bool(value & 1) elif offset == 0x420B and value: self.dma_started = True super().io_write(offset, value) # -- the replay ------------------------------------------------------- def registers(self) -> tuple[int, ...]: cpu = self.cpu return (cpu.pc, cpu.pbr, cpu.a, cpu.x, cpu.y, cpu.s, cpu.d, cpu.dbr, cpu.p, cpu.e) def adopt(self, registers: tuple[int, ...]) -> None: cpu = self.cpu for name, value in zip(REGISTERS, registers, strict=True): setattr(cpu, name, value) def vector_target(self, kind: str) -> int: """The 16-bit handler address of "nmi" or "irq" for the core's mode.""" native = {"nmi": 0xFFEA, "irq": 0xFFEE}[kind] emulation = {"nmi": 0xFFFA, "irq": 0xFFFE}[kind] vector = emulation if self.cpu.e else native return self.peek(vector) | self.peek(vector + 1) << 8 def interrupt_before(self, line: Line) -> str | None: """Which interrupt MAME took before ``line``, if the core is not there.""" cpu = self.cpu if line.address == (cpu.pbr << 16 | cpu.pc) and not cpu.waiting: return None pushed = 3 if cpu.e else 4 if line.registers[1] != 0 or line.registers[5] != (cpu.s - pushed) & 0xFFFF: return None for kind in ("nmi", "irq"): if line.registers[0] == self.vector_target(kind): return kind return None def take(self, kind: str) -> bool: """Request ``kind`` and step the core into it, at this boundary as MAME did; True if the core's own poll would have waited one more instruction (after CLI, PLP or REP cleared I, or right after an entry), which this overrides.""" cpu = self.cpu if kind == "nmi": cpu.request_non_maskable_interrupt() else: cpu.request_maskable_interrupt() if cpu.waiting: cpu.step() # the IO cycle that ends WAI # The frame's poll memory (6502-python CPUFrame): the I flag or the # requests as the last instruction's poll saw them. forced = cpu._polled_i is not None or cpu._polled is not None cpu._polled_i = cpu._polled = None cpu.step() if kind == "irq": cpu.clear_maskable_interrupt() return forced def replay(rom: bytes, log: Path, limit: int | None = None, max_divergences: int = 50) -> Report: """Run the core against MAME's trace ``log`` of ``rom``; at a register divergence, record it and take MAME's registers (``max_divergences`` at most).""" harness = Replay(rom, banks=watched_banks(log.parent / "trace.lua")) cpu = harness.cpu report = Report() lines = read_log(log) first = next(lines) cpu.step() # reset if first.address != (cpu.pbr << 16 | cpu.pc): raise AssertionError(f"reset to {cpu.pbr:02X}:{cpu.pc:04X}, MAME {first.address:06X}") harness.adopt(first.registers) line = first for index, following in enumerate(lines): if limit is not None and index >= limit: break opcode = harness.peek(line.address) harness.reads = deque(line.reads) harness.guessed = None harness.dma_started = False extra = mame_extra_cycles(harness, line.registers) start = harness.clocks cpu.step() report.instructions += 1 whole = harness.dma_started or cpu.waiting kind = harness.interrupt_before(following) if kind is None and cpu.waiting: # WAI ended by an IRQ with I set: MAME runs on after it (U11). cpu.request_maskable_interrupt() cpu.step() cpu.clear_maskable_interrupt() elif kind is not None: if harness.take(kind): report.forced[kind] += 1 whole = True if kind == "nmi": report.nmi += 1 if bool(cpu.p & I_FLAG) != bool(following.registers[8] & I_FLAG): cpu.p = cpu.p & ~I_FLAG | following.registers[8] & I_FLAG report.nmi_i += 1 else: report.irq += 1 for address, _ in harness.reads: harness.unread_addresses[address] += 1 if harness.guessed is not None: report.adopted += 1 report.adopted_addresses[harness.guessed] += 1 harness.adopt(following.registers) else: got = harness.registers() if got != following.registers: differences = { name: (core, mame) for name, core, mame in zip(REGISTERS, got, following.registers, strict=True) if core != mame } report.divergences.append(Divergence(index, line.address, opcode, differences)) harness.adopt(following.registers) if len(report.divergences) >= max_divergences: break delta = following.clocks - line.clocks clocks = harness.clocks - start if whole: report.clocks_skipped += 1 elif clocks == delta and not extra: report.clocks_equal += 1 elif clocks + 6 * extra == delta: report.clocks_mame_rule += 1 else: key = opcode, delta - clocks report.clock_differences[key] += 1 samples = report.clock_samples.setdefault(key, []) if len(samples) < 5: samples.append((index, line.registers)) line = following report.unread_addresses = harness.unread_addresses report.unread = sum(harness.unread_addresses.values()) return report