# SPDX-License-Identifier: MIT """Replay a MAME 0.285 GSU trace on the core (validation.md rung 4; mame-oracle.md "The replay"). MAME is an emulator-tier **value** detector, one lineage with ares (byuu's model); its time is not the chip's (C17). The log (``scripts/mame_gsu_trace.py --ram --arm-on-start``) holds every S-CPU access to the register file and to Game Pak RAM since power-on, and, from the first GSU start at or after the start frame, one ``G``/``H`` pair per GSU instruction (``L n`` repeats the previous pair); ``ram_at_start.bin`` is the GSU's 70:0000-71:FFFF at that start. Two cores run in lockstep from that start, seeded from the first ``G``/``H`` pair (R0-R15, SFR, PBR, ROMBR, RAMBR, CBR, COLR, POR, RAMADDR), the dumped RAM and the last S-CPU writes of CFGR, SCBR, CLSR, SCMR and BRAMR before it; the pipeline holds NOP (a start after STOP): - the **MAME-switched** core: every contested switch at MAME's choice (:class:`MameCore`, with MAME's VCR 4 and no register mirrors). It must match every ``G``/``H`` pair and every host read; a difference is a *finding* (or a new C/U entry): it is recorded and the core is resynchronised to MAME's values. SFR is compared without bit 6 (R: MAME's ROM buffer time is its own) and host reads of SFR likewise. - the **default** core, the documented defaults, compared with the MAME-switched core after every instruction and at every host read. A difference is re-run from the saved pre-state with one switch at a time at MAME's value; the switch that explains it names the entry it is counted under, then the default core is resynchronised. Host accesses apply in log order (the stamps are MAME's instruction counts: a check, not a clock). An S-CPU RAM write while the GSU owns RAM is dropped, as MAME drops it. """ from __future__ import annotations import argparse import gzip import sys from collections import Counter from collections.abc import Iterator from dataclasses import dataclass, field, replace from pathlib import Path from gsu_python.core import GSU from gsu_python.model import GSU1, MIRRORS_GSU2, MODELS, Model from gsu_python.state import CPUState #: SFR bits compared: Z CY S OV GO, ALT1 ALT2 IL IH B, IRQ (not R: C17). SFR_MASK = 0x9F3E H_FIELDS = ("r12", "r13", "r14", "r15", "sfr", "pbr", "rombr", "rambr", "cbr", "colr", "por", "ramaddr") # fmt: skip class MameCore(GSU): """The core with every contested switch at MAME 0.285's choice (mame-oracle.md).""" REGISTER_WRITE_LATCH = False # C6: bytes written straight into the register RESTRICT_ACCESS_WHILE_RUNNING = False # C7 FMULT_R4_UNCHANGED = False # C9 CPU_R14_WRITE_PREFETCH = False # U9 WAIT_ON_BUS = False # MAME never waits on RON/RAN CACHE_WINDOW_BY_ADDRESS = False # U14: MAME's CBR-relative window TRANSPARENCY_BY_DEPTH = False # U20: ares' 4-colour test (core.cpp l.20) #: One switch at a time, for naming a default-core divergence: (entry, attribute, MAME's value). SWITCHES = ( ("C6", "REGISTER_WRITE_LATCH", False), ("C7", "RESTRICT_ACCESS_WHILE_RUNNING", False), ("C9", "FMULT_R4_UNCHANGED", False), ("U9", "CPU_R14_WRITE_PREFETCH", False), ("U14", "CACHE_WINDOW_BY_ADDRESS", False), ("U20", "TRANSPARENCY_BY_DEPTH", False), ) def mame_model(model: Model) -> Model: """MAME answers VCR 4 on both devices and implements no register mirrors (U12, U23).""" return replace(model, vcr=4, mirrors=MIRRORS_GSU2) @dataclass(frozen=True, slots=True) class Finding: instruction: int where: str detail: str @dataclass(slots=True) class ReplayResult: instructions: int = 0 reads_compared: int = 0 writes_applied: int = 0 ram_writes_dropped: int = 0 stops: int = 0 findings: list[Finding] = field(default_factory=list) classified: Counter = field(default_factory=Counter) unexplained: list[Finding] = field(default_factory=list) forms: Counter = field(default_factory=Counter) #: Instructions per code bank (PBR): 70h/71h is code running from Game Pak RAM. banks: Counter = field(default_factory=Counter) #: Instructions fetched from a valid cache line. from_cache: int = 0 def summary(self) -> str: lines = [ f"{self.instructions} instructions, {self.stops} STOPs, {self.reads_compared} host " f"reads compared, {self.writes_applied} host writes ({self.ram_writes_dropped} RAM " "writes dropped while the GSU owned RAM)", "code banks: " + ", ".join(f"{b:02X}h {n}" for b, n in sorted(self.banks.items())) + f"; next fetch from a valid cache line {self.from_cache}; " f"{len(self.forms)} instruction forms", f"MAME-switched core: {len(self.findings)} findings", "default core divergences by entry: " + (", ".join(f"{k} {v}" for k, v in sorted(self.classified.items())) or "none"), f"default core unexplained: {len(self.unexplained)}", ] for label, found in (("finding", self.findings), ("default", self.unexplained)): lines += [f" {label} {f.instruction}: {f.where}: {f.detail}" for f in found[:20]] return "\n".join(lines) def read_log(path: Path) -> Iterator[list[str]]: with gzip.open(path, "rt", encoding="utf-8", errors="replace") as stream: for line in stream: if line[:1] in "GHLRW" and line[1:2] == " ": yield line.split() def _ram_offset(address: int) -> int | None: """Where an S-CPU address lands in the GSU's 70:0000-71:FFFF (fullsnes "Memory Map").""" bank, offset = address >> 16 & 0x7F, address & 0xFFFF if bank in (0x70, 0x71): return (bank & 1) << 16 | offset if bank <= 0x3F and 0x6000 <= offset <= 0x7FFF: return offset & 0x1FFF return None def _io(address: int) -> int | None: bank, offset = address >> 16 & 0x7F, address & 0xFFFF if bank <= 0x3F and 0x3000 <= offset <= 0x34FF: return offset return None def _expected(g: list[str], h: list[str]) -> dict[str, int]: values = {"pc": int(g[1], 16)} for i in range(12): values[f"r{i}"] = int(g[2 + i], 16) for name, text in zip(H_FIELDS, h[1:13], strict=True): values[name] = int(text, 16) return values def _actual(core: GSU) -> dict[str, int]: values = {"pc": ((core.pbr << 16 | core.r[15]) - 1) & 0xFFFFFF} for i in range(16): values[f"r{i}"] = core.r[i] for name in ("sfr", "pbr", "rombr", "rambr", "cbr", "colr", "por", "ramaddr"): values[name] = getattr(core, name) return values def _differences(expected: dict[str, int], actual: dict[str, int]) -> list[str]: out = [] for name, value in expected.items(): mine = actual[name] if name == "sfr": value &= SFR_MASK mine &= SFR_MASK if mine != value: out.append(f"{name} {mine:X} (MAME {value:X})") return out def _seed(core: GSU, values: dict[str, int], shadow: dict[int, int], ram: bytes) -> None: core.ram[:] = ram[: len(core.ram)] state = CPUState( r=tuple(values[f"r{i}"] for i in range(16)), sfr=values["sfr"] & ~0x40, pbr=values["pbr"], rombr=values["rombr"], rambr=values["rambr"], cbr=values["cbr"], colr=values["colr"], por=values["por"], ramaddr=values["ramaddr"], pipeline=0x01, scbr=shadow.get(0x3038, 0), scmr=shadow.get(0x303A, 0) & 0x3F, cfgr=shadow.get(0x3037, 0) & 0xA0, clsr=shadow.get(0x3039, 0) & 1, bramr=shadow.get(0x3033, 0) & 1, ) core.restore_state(state) core.romdr = core._read(core.rombr, core.r[14]) core.pipeline_address = values["pc"] def _registers(core: GSU) -> tuple: return (tuple(core.r), core.sfr & SFR_MASK, core.pbr, core.rombr, core.rambr, core.cbr, core.colr, core.por, core.ramaddr) # fmt: skip def replay( log: Path, rom: bytes, ram_dump: bytes, *, model: Model = GSU1, ram_size: int = 0x20000, limit: int | None = None, default_class: type[GSU] = GSU, ) -> ReplayResult: """Replay ``log`` from its first GSU start; see the module docstring.""" result = ReplayResult() mame = MameCore(rom, bytearray(ram_size), model=mame_model(model)) default = default_class(rom, bytearray(ram_size), model=model) shadow: dict[int, int] = {} pending_g: list[str] | None = None last: dict[str, int] | None = None seeded = False count = 0 def step_both() -> None: nonlocal count pre = mame.capture_state() form = mame._dispatch[mame.sfr >> 8 & 3 | mame.sfr >> 10 & 4][mame.pipeline][0] result.forms[form.__name__[4:]] += 1 result.banks[mame.pipeline_address >> 16] += 1 r15 = mame.r[15] if (r15 - mame.cbr) & 0xFFFF < 512 and mame.cache_loaded[(r15 & 0x1FF) >> 4] == 16: result.from_cache += 1 was_running = mame.running mame.step() default.step() count += 1 if was_running and not mame.running: result.stops += 1 if mame.ram != default.ram: _divergence(f"RAM at STOP {result.stops}", None) if _registers(mame) != _registers(default): _divergence("registers", pre) def _divergence(where: str, pre: CPUState | None) -> None: explained = None if pre is not None: target = _registers(mame) base = default_class(rom, bytearray(mame.ram), model=model) base.restore_state(pre) base.step() if _registers(base) == target: # The instruction itself agrees: the cores already differed in state a host # access left (the C6 latch, U9's R14 prefetch). explained = "host (C6/U9)" if pre is not None and explained is None: for entry, attribute, value in SWITCHES: trial_class = type("Trial", (default_class,), {attribute: value}) trial = trial_class(rom, bytearray(mame.ram), model=model) trial.restore_state(pre) trial.step() if _registers(trial) == target: explained = entry break if explained: result.classified[explained] += 1 else: result.unexplained.append(Finding(count, where, _describe(default, mame))) default.restore_state(mame.capture_state()) default.ram[:] = mame.ram for fields in read_log(log): kind = fields[0] if kind == "G": pending_g = fields continue if kind == "H" and pending_g is not None: expected = _expected(pending_g, fields) pending_g = None if not seeded: _seed(mame, expected, shadow, ram_dump) _seed(default, expected, shadow, ram_dump) seeded = True if _check(result, mame, expected, count): default.restore_state(mame.capture_state()) default.ram[:] = mame.ram last = expected step_both() elif kind == "L" and last is not None: for _ in range(int(fields[1])): if _check(result, mame, last, count): default.restore_state(mame.capture_state()) default.ram[:] = mame.ram step_both() elif kind in ("R", "W"): address, value = int(fields[1], 16), int(fields[2], 16) io = _io(address) if not seeded: if kind == "W" and io is not None: shadow[io] = value continue if kind == "W": result.writes_applied += 1 if io is not None: mame.write_io(io, value) default.write_io(io, value) else: offset = _ram_offset(address) if offset is not None: if mame.cpu_owns_ram: mame.ram[offset % ram_size] = value default.ram[offset % ram_size] = value else: result.ram_writes_dropped += 1 elif io is not None: result.reads_compared += 1 mine = mame.read_io(io) theirs = default.read_io(io) mask = 0xBF if io == 0x3030 else 0xFF if mine is None or (mine ^ value) & mask: result.findings.append( Finding(count, f"read {io:04X}", f"core {mine} MAME {value:02X}") ) if theirs is None or (theirs ^ value) & mask: result.classified[_classify_read(io, default)] += 1 if limit is not None and count >= limit: break result.instructions = count return result def _classify_read(address: int, core: GSU) -> str: if 0x3100 <= address <= 0x32FF: return "C7" if core.running else "U14" if core.running and address not in (0x3030, 0x3031, 0x303B): return "C7" return "U12/U23" def _describe(default: GSU, mame: GSU) -> str: return ", ".join(_differences(_actual(mame), _actual(default))) or "RAM differs" def _check(result: ReplayResult, core: GSU, expected: dict[str, int], count: int) -> bool: """Compare before an instruction; on a difference record it, take MAME's values, and return True.""" differences = _differences(expected, _actual(core)) if differences: result.findings.append(Finding(count, "G/H", "; ".join(differences))) values = expected core.r[:] = [values[f"r{i}"] for i in range(16)] core.sfr = values["sfr"] & ~0x40 for name in ("pbr", "rombr", "rambr", "cbr", "colr", "por", "ramaddr"): setattr(core, name, values[name]) return True return False 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_gsu_trace.py run directory") parser.add_argument("--rom", type=Path, help="default: the .sfc in the run directory") parser.add_argument("--model", choices=sorted(MODELS), default="gsu1") parser.add_argument("--limit", type=int, help="stop after this many instructions") args = parser.parse_args(argv) rom_path = args.rom or next( p for p in sorted(args.run.glob("*.sfc")) if not p.name.startswith("mirrored-") ) result = replay( args.run / "gsu.log.gz", rom_path.read_bytes(), (args.run / "ram_at_start.bin").read_bytes(), model=MODELS[args.model], limit=args.limit, ) print(result.summary()) return 0 if not result.findings and not result.unexplained else 1 if __name__ == "__main__": sys.exit(main()) __all__ = ["SWITCHES", "Finding", "MameCore", "ReplayResult", "mame_model", "replay"]