# SPDX-License-Identifier: MIT """Replay a MAME 0.285 DSP trace on the core (validation.md rung 4; mame-oracle.md "The replay"). MAME is an emulator-tier detector, one lineage with ares (byuu's model). The log (``scripts/mame_dsp_trace.py``) holds every host access to the DSP from power-on, stamped in DSP instructions, and from the start frame one ``D`` line per instruction (``L n`` repeats the previous one). An access stamped ``N`` lands after instruction ``N`` and is first seen by instruction ``N + 1`` (measured, mame-oracle.md). Two cores run in lockstep from MAME's power-on state (every register and the RAM zero; no reset, which in MAME leaves RP alone: C6): - the **MAME-switched** core: this core with each contested switch flipped to MAME's choice (C1 comparison carry, C4 bit-reversed serial register, C5 a 16-deep stack, C11 the stored DRS bit, C16 DPL clearing DP bits 10-8). It must match every ``D`` line and every host read; any difference is a *finding* against the core (or a new C-entry) and stops the run. MAME keeps DP and RP 16 bits wide (C9): a ``D`` value that differs only above the chip's width is counted as C9, not a finding. - the **default** core, the documented defaults. It is compared with the MAME-switched core after every instruction; when they differ, the instruction is re-executed from the saved pre-state with one switch at a time flipped to name the C-entry that explains it, the divergence is counted under that entry, and the default core is resynchronised to the MAME-switched one. A difference no single switch explains is a finding. """ from __future__ import annotations import argparse import gzip import json import sys from collections import Counter from collections.abc import Iterable, Iterator from dataclasses import dataclass, field, replace from pathlib import Path from upd7725_python._fields import CALL, HCALL, JP, LD, alu, brch, dpl, dst, kind, src from upd7725_python.cpu import UPD7725 from upd7725_python.disasm import disassemble from upd7725_python.images import load_image, model_for from upd7725_python.model import Model from upd7725_python.rompath import find_set from upd7725_python.state import CPUState D_FIELDS = ("pc", "a", "b", "k", "l", "tr", "trb", "dp", "rp", "sp", "dr") class MameSwitches(UPD7725): """The core with every contested switch at MAME 0.285's choice (mame-oracle.md).""" CARRY_BY_COMPARISON = True # C1 SERIAL_BIT_REVERSE = True # C4 RESET_SETS_RP = False # C6 DRS_READS_ZERO_IN_8BIT_MODE = False # C11 DPL_CLEARS_DP_BITS_10_8 = True # C16 def mame_model(model: Model) -> Model: """MAME's ``stack[16]`` with a 4-bit pointer on both chips (C5).""" return replace(model, stack_depth=16) # One switch at a time, for naming a divergence: (C-entry, attribute, MAME's value). SWITCHES = ( ("C1", "CARRY_BY_COMPARISON", True), ("C4", "SERIAL_BIT_REVERSE", True), ("C16", "DPL_CLEARS_DP_BITS_10_8", True), ) # The host side: which port an address selects, per cartridge wiring (fullsnes "DSP # Mapping"; MAME bus/snes/upd.cpp chip_read/chip_write, dataram_r/w). WIRINGS = ("a14", "a12", "seta") def port_of(address: int, wiring: str) -> str: """``"DR"``, ``"SR"`` or ``"RAM"`` for a host address.""" if wiring == "seta": if 0x68 <= (address >> 16 & 0x7F) <= 0x6F: return "RAM" return "SR" if address & 1 else "DR" if wiring == "a12": return "SR" if address & 0x1000 else "DR" return "SR" if address & 0x4000 else "DR" def parse_log(lines: Iterable[str]) -> Iterator[tuple]: """Yield ``("D", cycle, values)``, ``("L", n)``, ``("R"|"W", address, value, stamp)``.""" for line in lines: head = line[:2] if head == "D ": parts = line.split() yield ("D", int(parts[12]), tuple(int(v, 16) for v in parts[1:12])) elif head == "L ": yield ("L", int(line[2:])) elif head in ("R ", "W "): parts = line.split() yield (parts[0], int(parts[1], 16), int(parts[2], 16), int(parts[3])) class Finding(Exception): """A difference no C-entry explains.""" @dataclass class ReplayResult: instructions: int = 0 traced: int = 0 accesses: int = 0 reads_checked: int = 0 divergences: Counter = field(default_factory=Counter) examples: dict = field(default_factory=dict) c9: Counter = field(default_factory=Counter) # D-line fields equal only in the chip's width max_sp: int = 0 distinct_pcs: int = 0 unmapped_reads: int = 0 underflows: int = 0 power_on_stack: list = field(default_factory=list) finding: str | None = None def as_dict(self) -> dict: return { "instructions": self.instructions, "traced": self.traced, "accesses": self.accesses, "reads_checked": self.reads_checked, "divergences": dict(self.divergences), "examples": self.examples, "c9_width_only": dict(self.c9), "max_stack_depth": self.max_sp, "distinct_pcs_traced": self.distinct_pcs, "mame_unmapped_reads": self.unmapped_reads, "rt_on_empty_stack": self.underflows, "mame_power_on_stack": self.power_on_stack, "finding": self.finding, } _COMPARED = ("pc", "a", "b", "k", "l", "tr", "trb", "dp", "rp", "sp", "dr", "sr", "so") _COMPARED += ("flaga", "flagb", "si", "m", "n") class Replay: """The lockstep of a MAME log, the MAME-switched core and the default core.""" def __init__( self, program: list[int], data_rom: list[int], model: Model, wiring: str, *, default_class: type[UPD7725] = UPD7725, unmapped_dsp_reads: bool = False, ) -> None: if wiring not in WIRINGS: raise ValueError(f"wiring must be one of {WIRINGS}") self.wiring = wiring # MAME 0.285 leaves the ST011's DR/SR reads in banks 60-6F (not E0-EF) unmapped # (nintendo/snes.cpp snes20_lo_r: "why does this break moritash?"): the S-CPU reads # open bus and the DSP sees no read. Those reads are skipped and counted. self.unmapped_dsp_reads = unmapped_dsp_reads self.model = model self.mame = MameSwitches(program, data_rom, model=mame_model(model)) self.core = default_class(program, data_rom, model=model) self.default_class = default_class self.executed = 0 self.result = ReplayResult() self._depth_mask = model.stack_depth - 1 self._sensitive = bytearray(self._is_sensitive(word) for word in self.mame.program) self._seen = bytearray(model.program_words) self._tracing = False self._underflow_at = -1 @staticmethod def _is_sensitive(word: int) -> int: """Words where a switch can make the two cores differ (and need a saved pre-state): 0 none, 1 an OP/LD, 2 a CALL (records the nesting, C5), 3 an RT (C5, U10).""" k = kind(word) if k == JP: return 2 if brch(word) in (CALL, HCALL) else 0 if k == LD: return 1 if dst(word) == 8 else 0 # @SOL (C4) if k == 1: return 3 return int( alu(word) in (6, 7) # SBB, ADC: the carry (C1) or src(word) == 12 # SIL (C4) or dst(word) == 8 # @SOL (C4) or dpl(word) != 0 # C16 on the uPD96050 ) # ----- stepping both cores ------------------------------------------------------------ def _differs(self) -> bool: core, mame = self.core, self.mame return ( core.pc != mame.pc or core.a != mame.a or core.b != mame.b or core.flaga != mame.flaga or core.flagb != mame.flagb or core.sp != (mame.sp & self._depth_mask) or core.dp != mame.dp or core.rp != mame.rp or core.k != mame.k or core.l != mame.l or core.tr != mame.tr or core.trb != mame.trb or core.sr != mame.sr or core.dr != mame.dr or core.so != mame.so ) def advance(self, count: int) -> None: """Run both cores ``count`` instructions, comparing after each.""" core, mame = self.core, self.mame sensitive, seen = self._sensitive, self._seen tracing = self._tracing result = self.result for _ in range(count): pc = mame.pc what = sensitive[pc] pre = mame.capture_state() if what else None if tracing: seen[pc] = 1 mame.step() core.step() if what == 2 and mame.sp > result.max_sp: result.max_sp = mame.sp # the deepest nesting a CALL reached (C5) elif what == 3 and pre.sp == 0: result.underflows += 1 # an RT on an empty stack (U10) self._underflow_at = self.executed + 1 if self._differs() or (pre is not None and core.ram != mame.ram): self._classify(pc, pre) self.executed += 1 def _to_default(self, state: CPUState) -> CPUState: """A MAME-switched state as the default core holds it (its stack depth).""" depth = self.model.stack_depth sp = state.sp & self._depth_mask stack = list(state.stack[:depth]) if state.sp > depth: # deeper than the chip: keep the innermost entries (C5) for i in range(depth): stack[(state.sp - depth + i) & self._depth_mask] = state.stack[state.sp - depth + i] return replace(state, sp=sp, stack=tuple(stack)) def _classify(self, pc: int, pre: CPUState | None) -> None: word = self.mame.program[pc] text = disassemble(word, pc).text entry = None after = self._to_default(self.mame.capture_state()) if pre is not None: depth = self.model.stack_depth if (kind(word) == JP and brch(word) in (CALL, HCALL) and pre.sp >= depth) or ( kind(word) == 1 and pre.sp > depth ): entry = "C5" # nesting deeper than the chip's stack elif kind(word) == 1 and pre.sp == 0: entry = "U10" # RT on an empty stack: each core pops its own last entry for name, attribute, value in SWITCHES if entry is None else (): trial_class = type("Trial", (self.default_class,), {attribute: value}) trial = trial_class(self.core.program, self.core.data_rom, model=self.model) trial.restore_state(self._to_default(pre)) trial.step() if trial.capture_state() == after: entry = name break if entry is None: diff = { name: (getattr(self.core, name), getattr(self.mame, name)) for name in _COMPARED if getattr(self.core, name) != getattr(self.mame, name) } raise Finding( f"default core differs from the MAME-switched core after {pc:04X} {text} " f"(instruction {self.executed}): {diff}" ) self.result.divergences[entry] += 1 self.result.examples.setdefault(entry, f"{pc:04X} {text} (instruction {self.executed})") self.core.restore_state(after) # resynchronise and go on # ----- the log ------------------------------------------------------------------------ def _check_d(self, cycle: int, values: tuple[int, ...]) -> None: mame = self.mame for name, expected in zip(D_FIELDS, values, strict=True): actual = getattr(mame, name) if actual == expected: continue if name == "pc" and self._underflow_at == cycle: # U10/U18: an RT on an empty stack popped MAME's stack[15], which MAME's # device_start never initialises (it zeroes SP, not the array): undefined # power-on memory. Adopt MAME's value in both cores and go on. self.mame.stack[15] = self.mame.pc = expected self.core.pc = expected self.result.power_on_stack.append(f"cycle {cycle}: popped {expected:X}") continue mask = { "pc": self.model.pc_mask, # MAME's PC is 16 bits too (a JMPSO to SO > 3FFFh) "dp": self.model.dp_mask, "rp": self.model.rp_mask, }.get(name) if mask is not None and expected & mask == actual: self.result.c9[name] += 1 # C9: MAME keeps PC, DP, RP 16 bits wide continue raise Finding( f"MAME-switched core differs from MAME at cycle {cycle}: {name} = " f"{actual:X}, MAME {expected:X} (pc {mame.pc:04X} " f"{disassemble(mame.program[mame.pc], mame.pc).text})" ) def _access(self, direction: str, address: int, value: int) -> None: port = port_of(address, self.wiring) self.result.accesses += 1 if port == "RAM": index = address >> 1 & (len(self.mame.ram) - 1) for dsp in (self.mame, self.core): word = dsp.ram[index] if direction == "W": if address & 1: dsp.ram[index] = value << 8 | (word & 0xFF) else: dsp.ram[index] = (word & 0xFF00) | value else: got = word >> 8 if address & 1 else word & 0xFF if got != value: raise Finding(f"RAM read {address:06X} = {got:02X}, MAME {value:02X}") self.result.reads_checked += direction == "R" return if direction == "R" and self.unmapped_dsp_reads and address < 0x800000: self.result.unmapped_reads += 1 return if direction == "W": if port == "DR": self.mame.write_dr(value) self.core.write_dr(value) return # SR writes are "Inhibit" (DS (20)); MAME logs and ignores them if port == "DR": got, ours = self.mame.read_dr(), self.core.read_dr() else: got, ours = self.mame.read_sr(), self.core.read_sr() self.result.reads_checked += 1 if got != value: raise Finding( f"host read of {port} ({address:06X}) after instruction {self.executed - 1}: " f"core {got:02X}, MAME {value:02X}" ) if ours != got: if port == "SR" and (ours ^ got) == 0x10: self.result.divergences["C11"] += 1 self.result.examples.setdefault("C11", f"SR read {got:02X} vs {ours:02X}") else: raise Finding(f"default core read {port} {ours:02X}, MAME {got:02X}") def run(self, events: Iterable[tuple]) -> ReplayResult: result = self.result last_cycle = None last_values = None try: for event in events: tag = event[0] if tag == "D": _, cycle, values = event if not self._tracing: self._tracing = True self.advance(cycle - self.executed) self._check_d(cycle, values) last_cycle, last_values = cycle, values result.traced += 1 elif tag == "L": for _ in range(event[1]): last_cycle += 1 self.advance(last_cycle - self.executed) self._check_d(last_cycle, last_values) result.traced += 1 else: direction, address, value, stamp = event self.advance(stamp + 1 - self.executed) self._access(direction, address, value) except Finding as finding: result.finding = str(finding) result.instructions = self.executed result.distinct_pcs = sum(self._seen) return result def slot_details(summary: dict) -> tuple[str, str]: """(MAME device set, wiring) from ``summary.json``'s DSP line.""" for line in summary.get("console", []): if line.startswith("DSP "): slot = line.split()[-1] break else: raise ValueError("summary.json names no DSP slot") if "st10" in slot: return "sns_seta10leg", "seta" if "st11" in slot: return "sns_seta11leg", "seta" name = slot.split("_", 1)[1].removesuffix("_hi") return f"sns_{name}", "a12" if slot.startswith("hirom") else "a14" def replay_run(run_dir: Path, rompath: str | None = None, **kwargs) -> ReplayResult: """Replay ``run_dir/dsp.log.gz`` with the image its ``summary.json`` names. The device set is looked up on ``rompath`` (``;``-separated folders; default ``$MAME_ROMPATH``). ``FileNotFoundError`` when it is not there. """ summary = json.loads((run_dir / "summary.json").read_text(encoding="utf-8")) device_set, wiring = slot_details(summary) image = find_set(device_set, rompath) if image is None: raise FileNotFoundError(f"{device_set}.zip is not on the rompath (MAME_ROMPATH)") program, data_rom = load_image(image) kwargs.setdefault("unmapped_dsp_reads", device_set == "sns_seta11leg") replay = Replay(program, data_rom, model_for(program), wiring, **kwargs) with gzip.open(run_dir / "dsp.log.gz", "rt", encoding="utf-8") as log: return replay.run(parse_log(log)) def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("run", type=Path, help="a mame_dsp_trace.py run directory") parser.add_argument( "--rompath", default=None, help="';'-separated folders holding MAME's DSP device sets (default: $MAME_ROMPATH)", ) args = parser.parse_args(argv) result = replay_run(args.run, args.rompath) print(json.dumps(result.as_dict(), indent=1)) return 0 if result.finding is None else 1 if __name__ == "__main__": sys.exit(main()) __all__ = [ "Finding", "MameSwitches", "Replay", "ReplayResult", "mame_model", "parse_log", "port_of", "replay_run", "slot_details", ]