# SPDX-License-Identifier: MIT """Rung 0 detector: the decoder against MAME 0.285's ``dasm`` at every traced Star Fox PC. MAME's disassembler is a linear sweep with no prefix state (mame-oracle.md trap 4), so the comparison is of the plain (ALT0, B = 0) form at each PC the Star Fox trace executed that is also a line of the sweep: mnemonic, length and operands. MAME's *disassembler* keeps BK2's names for 06/07 (BLT/BGE) while its *execution* is fullsnes' (C2), so 06 and 07 are compared by condition. Emulator tier: it detects, BK2 and fullsnes judge (test_decode.py). Needs the BYOR runs ``tests/mame_traces/StarFox_dasm_01``/``_06`` (``--dasm 018000:8000``, ``--dasm 068000:8000``) and the Star Fox trace. """ from __future__ import annotations import gzip import re import pytest from conftest import STAR_FOX, TRACES, require from gsu_python._decode import decode from gsu_python.disasm import disassemble LINE = re.compile(r"^([0-9A-F]{8}): ((?:[0-9A-F]{2} )+)\s*(\S+)\s*(.*)$") MAME_C2 = {"BLT": "BGE", "BGE": "BLT"} # MAME dasm names (BK2) -> condition (fullsnes) def load_dasm(bank: int) -> dict[int, tuple[bytes, str, str]]: path = require(TRACES / f"StarFox_dasm_{bank:02X}" / "program.dasm") lines = {} for text in path.read_text().splitlines(): match = LINE.match(text) if match: address = int(match.group(1), 16) raw = bytes.fromhex(match.group(2)) lines[address] = (raw, match.group(3), match.group(4)) return lines def traced_pcs() -> set[int]: path = require(STAR_FOX / "gsu.log.gz") pcs = set() with gzip.open(path, "rt") as stream: for line in stream: if line.startswith("G "): pcs.add(int(line.split()[1], 16)) return pcs @pytest.mark.slow def test_plain_forms_match_mame_at_traced_pcs(): sweeps = {bank: load_dasm(bank) for bank in (0x01, 0x06)} pcs = traced_pcs() compared = 0 for pc in sorted(pcs): bank = pc >> 16 if bank not in sweeps or pc not in sweeps[bank]: continue raw, mnemonic, operands = sweeps[bank][pc] padded = raw + bytes(4) ours = disassemble(lambda a, p=padded, s=pc: p[(a - s) & 0xFFFF], pc & 0xFFFF) opcode = raw[0] form = decode(opcode, 0, False) if form.keeps_prefix and form.key in ("alt1", "alt2", "alt3", "to", "from", "with"): assert mnemonic == form.key.upper(), hex(pc) continue assert len(raw) == form.length, (hex(pc), raw.hex(), mnemonic) assert ours.text.split()[0].rstrip(";") == MAME_C2.get(mnemonic, mnemonic), ( hex(pc), ours.text, mnemonic, ) numbers = [int(v, 16) if v.startswith("0x") else int(v) for v in re.findall(r"0x[0-9a-fA-F]+|-?\d+", operands.replace("#", " 0x"))] # fmt: skip if form.key == "branch": assert numbers[-1] == (raw[1] - 256 if raw[1] & 0x80 else raw[1]) elif form.key == "iwt": assert numbers == [form.n, raw[2] << 8 | raw[1]] elif form.key == "ibt": assert numbers == [form.n, raw[1]] compared += 1 print(f"compared {compared} of {len(pcs)} traced PCs") assert compared > 3000