# SPDX-License-Identifier: MIT """Run SingleStepTests ARM7TDMI cases against the core (docs/validation.md, rung 1). Each case loads a state with two prefetched opcodes, runs one instruction and records the final state and the bus transactions (reads and writes; the corpus has no internal cycles). The corpus was generated from a NanoBoyAdvance fork, so it is **emulator-derived: a detector, not a judge** (user decision 2). ``tests/sst_overrides.json`` lists, class by class, where the core deliberately differs and what the comparison does about it: - C1 ``map``: the core reports the TRM's S on the fetch after an I cycle; the comparison passes every access through :func:`arm7tdmi_python.gba_access`, the same function gba-python uses. - C10 ``ignore``: LOCK on SWP's read (the TRM's; the corpus marks only the write). - C6 ``override``: CP14 MRC/MCR with the encodings alyosha-tas's hardware test exercises are compared to that test's behaviour (no trap) instead of the corpus's trap. - C2, C6 (other encodings), C7 ``exclude``: skipped and reported as a count, never as passes. The corpus's state layout is in :meth:`arm7tdmi_python.CPUState.from_sst`. """ from __future__ import annotations import json from collections import Counter from dataclasses import dataclass, field from pathlib import Path from struct import unpack_from from arm7tdmi_python import ARM7TDMI, CODE, LOCK, SEQ, CPUState, gba_access from arm7tdmi_python._modes import condition_passes ROOT = Path(__file__).resolve().parents[1] CORPUS = ROOT / "reference" / "src" / "SingleStepTests-ARM7TDMI" / "v1" OVERRIDES = json.loads((ROOT / "tests" / "sst_overrides.json").read_text(encoding="utf-8")) MAGIC = 0xD33DBAE0 NAMES = ( *(f"r{i}" for i in range(16)), *(f"fiq_r{i}" for i in range(8, 15)), "svc_r13", "svc_r14", "abt_r13", "abt_r14", "irq_r13", "irq_r14", "und_r13", "und_r14", "cpsr", "spsr_fiq", "spsr_svc", "spsr_abt", "spsr_irq", "spsr_und", "pipe0", "pipe1", "access", ) # fmt: skip EXCLUDED_FILES = {e["file"]: e["id"] for e in OVERRIDES if e["action"] == "exclude-file"} KIND_NAME = {0: "C", 1: "R", 2: "W"} @dataclass class Case: initial: tuple[int, ...] final: tuple[int, ...] transactions: list[tuple[int, int, int, int, int]] # kind, bytes, address, data, access opcode: int def corpus_files() -> list[Path]: return sorted(CORPUS.glob("*.json.bin")) def load(path: Path, limit: int | None = None) -> list[Case]: """Decode a ``.json.bin`` file (the format of the corpus's ``transcode_json.py``).""" buf = path.read_bytes() magic, count = unpack_from(" None: self.cpu = ARM7TDMI(self.read, self.write, self.idle) self.case: Case | None = None self.used: list[bool] = [] self.log: list[tuple] = [] def read(self, address: int, width: int, access: int) -> int: kind = 0 if access & CODE else 1 data = address if kind == 0 else 0 for index, t in enumerate(self.case.transactions): if not self.used[index] and t[0] == kind and t[2] == address: self.used[index] = True data = t[3] break data &= (1 << width) - 1 self.log.append((kind, width // 8, address, data, access)) return data def write(self, address: int, width: int, value: int, access: int) -> None: self.log.append((2, width // 8, address, value, access)) def idle(self, address: int) -> None: self.log.append(("I", address)) def run(self, case: Case) -> None: self.case = case self.used = [False] * len(case.transactions) self.log = [] self.cpu.restore_state(CPUState.from_sst(case.initial)) self.cycles = self.cpu.step() def bus_as_gba(log: list[tuple]) -> tuple[list[tuple], bool]: """The core's reads and writes with C1's mapping applied and LOCK dropped from reads (C10); and whether the last callback was an I cycle.""" out = [] after_idle = False for entry in log: if entry[0] == "I": after_idle = True continue kind, size, address, data, access = entry access = gba_access(access, after_idle) if kind != 2: access &= ~LOCK out.append((kind, size, address, data, access)) after_idle = False return out, after_idle def describe(transactions: list[tuple]) -> str: return " ".join( f"{KIND_NAME[k]}{'S' if a & SEQ else 'N'}{s * 8}@{addr:08x}" + (f"={d:x}" if k == 2 else "") for k, s, addr, d, a in transactions ) def executed(case: Case) -> bool: """Whether the case's instruction runs (Thumb always; ARM when its condition passes).""" cpsr = case.initial[31] return bool(cpsr & 0x20) or condition_passes(case.opcode >> 28, cpsr) # ----------------------------------------------------------------------------- classes def writes_back_r15(name: str, case: Case) -> bool: """C2: an ARM single, halfword or block transfer with Rn = R15 and write-back.""" op = case.opcode if not name.startswith("arm_") or (op >> 16) & 0xF != 15 or not executed(case): return False if name == "arm_ldm_stm": return bool(op & (1 << 21)) if name.startswith(("arm_ldr_str", "arm_ldrh_strh", "arm_ldrsb_ldrsh")): return bool(op & (1 << 21)) or not op & (1 << 24) return False def cp14_case(name: str, case: Case) -> str | None: """C6: 'tested' for the encodings alyosha-tas's Coprocessor_14 runs on hardware, 'other' for any other executed CP14 MRC/MCR, None otherwise.""" op = case.opcode if name != "arm_mcr_mrc" or (op >> 8) & 0xF != 14 or not executed(case): return None opc1, crn, crm, opc2 = (op >> 21) & 7, (op >> 16) & 0xF, op & 0xF, (op >> 5) & 7 load, rd = op & (1 << 20), (op >> 12) & 0xF if opc1 == 0 and crm == 0 and opc2 == 0: if load and crn in (0, 1): return "tested" # MRC p14,0,Rd,c0,c0,0 / c1,c0,0 (Rd = R15 sets the flags) if not load and crn == 1 and rd == 1: return "tested" # MCR p14,0,R1,c1,c0,0 return "other" def cp14_expected(case: Case) -> tuple[list[int], list[tuple]]: """What alyosha-tas's Coprocessor_14 shows a GBA doing (U17): no trap; the prefetch only on the bus; MRC puts the opcode that prefetch read into Rd (or its top four bits into N Z C V for R15); MCR changes nothing. The next fetch: MRC ends with an I cycle, so the GBA times it N (C1); MCR's is N (table 6-20).""" words = list(case.initial) fetch = case.transactions[0] words[37], words[38] = case.initial[38], fetch[3] words[15] = (case.initial[15] + 4) & 0xFFFFFFFF op = case.opcode if op & (1 << 20): rd = (op >> 12) & 0xF if rd == 15: words[31] = (words[31] & 0x0FFFFFFF) | (fetch[3] & 0xF0000000) else: words = _with_register(words, rd, fetch[3]) words[39] = CODE return words, [fetch] def _with_register(words: list[int], rd: int, value: int) -> list[int]: """Set Rd as the current mode sees it, in the corpus layout.""" from arm7tdmi_python._modes import BANK_FIQ, BANK_INVALID, BANK_USER, bank_of words = list(words) bank = bank_of(words[31]) if rd < 8 or rd == 15 or bank in (BANK_USER, BANK_INVALID): words[rd] = value elif bank == BANK_FIQ: words[16 + rd - 8] = value elif rd < 13: words[rd] = value else: offset = {2: 23, 3: 25, 4: 27, 5: 29}[bank] words[offset + rd - 13] = value return words # ----------------------------------------------------------------------------- comparison @dataclass class FileResult: name: str cases: int = 0 passed: int = 0 failed: int = 0 excluded: Counter = field(default_factory=Counter) overridden: Counter = field(default_factory=Counter) mapped: int = 0 # cases where C1 or C10 changed an access or the final next-fetch type fields: Counter = field(default_factory=Counter) examples: list[str] = field(default_factory=list) def check(bench: Bench, name: str, case: Case) -> list[str]: """Run one case; return its disagreements (empty when it passes).""" bench.run(case) problems: list[str] = [] if bench.cycles != len(bench.log): problems.append(f"step() returned {bench.cycles} but made {len(bench.log)} callbacks") ours, last_idle = bus_as_gba(bench.log) words = bench.cpu.capture_state().to_sst() words[39] = gba_access(words[39], last_idle) want_words, want_bus = list(case.final), case.transactions if cp14_case(name, case) == "tested": want_words, want_bus = cp14_expected(case) for index, (got, want) in enumerate(zip(words, want_words, strict=True)): if got != want: problems.append(f"{NAMES[index]} {got:08x} != {want:08x}") same = len(ours) == len(want_bus) and all( a[0] == b[0] and a[1] == b[1] and a[2] == b[2] and (a[0] != 2 or a[3] == b[3]) and a[4] & 0xB == b[4] & 0xB for a, b in zip(ours, want_bus, strict=False) ) if not same: problems.append(f"bus\n got {describe(ours)}\n want {describe(want_bus)}") return problems def run_file(path: Path, limit: int | None = None, examples: int = 3) -> FileResult: name = path.name.removesuffix(".json.bin") result = FileResult(name) cases = load(path, limit) result.cases = len(cases) if name in EXCLUDED_FILES: result.excluded[EXCLUDED_FILES[name]] = len(cases) return result bench = Bench() for number, case in enumerate(cases): if writes_back_r15(name, case): result.excluded["C2"] += 1 continue cp14 = cp14_case(name, case) if cp14 == "other": result.excluded["C6"] += 1 continue if cp14 == "tested": result.overridden["C6"] += 1 problems = check(bench, name, case) raw = [e for e in bench.log if e[0] != "I"] mapped, last_idle = bus_as_gba(bench.log) changed = any(a[4] != b[4] for a, b in zip(raw, mapped, strict=True)) if changed or (last_idle and bench.cpu.next_fetch_seq): result.mapped += 1 if problems: result.failed += 1 for p in problems: result.fields[p.split()[0]] += 1 if len(result.examples) < examples: result.examples.append( f"{name} case {number} opcode {case.opcode:08x} cpsr {case.initial[31]:08x}: " + "; ".join(problems) ) else: result.passed += 1 return result