#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Rung 1's second half: the core's internal cycles against the NBA referee's, case by case. The corpus records only reads and writes. NanoBoyAdvance's ARM core, built as a referee (``reference/build/nba_sst``, scripts/build_referees.py) and run as a closed box, reports every I cycle through the referee's bus shim, so its full sequence shows where the I cycles fall. This compares, for every corpus case the gate does not exclude, the core's sequence of cycle kinds (code read, data read, write, internal) with NBA's. NBA is an emulator: a detector, and where the core follows the TRM against it the difference is expected and counted by class: - C5: the undefined trap has an I cycle before the vector fetch (TRM table 6-21). - C11: Thumb POP and LDMIA with an empty list have an I cycle before the refill, as every LDM that loads R15 does in the TRM's table 6-12; NBA has none there. Anything else is printed and fails the run. python scripts/referee_icycles.py python scripts/referee_icycles.py --files thumb_push_pop --limit 5000 """ from __future__ import annotations import argparse import os import subprocess import sys import time from collections import Counter from concurrent.futures import ProcessPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path[:0] = [str(ROOT / "src"), str(ROOT)] from tests.sst_runner import ( # noqa: E402 CORPUS, EXCLUDED_FILES, Bench, corpus_files, cp14_case, load, writes_back_r15, ) REFEREE = ROOT / "reference" / "build" / "nba_sst" KIND = {0: "C", 1: "R", 2: "W"} def referee_kinds(path: Path, count: int) -> list[str]: """NBA's cycle kinds per case, e.g. 'CRWI', from ``nba_sst --seq``.""" result = subprocess.run( [str(REFEREE), str(path), "--seq", str(count)], capture_output=True, text=True, check=True ) return [ "".join(token[0] for token in line.split(":", 1)[1].split()) for line in result.stderr.splitlines() ] def core_kinds(log: list[tuple]) -> str: return "".join("I" if entry[0] == "I" else KIND[entry[0]] for entry in log) def expected_difference(core: str, nba: str, case, name: str, bench: Bench) -> str | None: """The class that explains a difference, or None.""" if core.replace("I", "", 1) == nba or core[:1] + core[2:] == nba: trap = any(e[0] == 0 and e[2] == 0x04 for e in bench.log) if trap and core[1] == "I": return "C5" op = case.opcode pop_empty = name == "thumb_push_pop" and op & 0x01FF == 0 ldmia_empty = name == "thumb_ldm_stm" and op & 0x00FF == 0 if (pop_empty or ldmia_empty) and op & 0x0800: return "C11" return None def job(args: tuple[str, int | None]): path, limit = Path(args[0]), args[1] name = path.name.removesuffix(".json.bin") start = time.perf_counter() counts: Counter = Counter() problems: list[str] = [] if name in EXCLUDED_FILES: return name, counts, problems, 0.0 cases = load(path, limit) nba = referee_kinds(path, len(cases)) bench = Bench() for number, (case, theirs) in enumerate(zip(cases, nba, strict=True)): if writes_back_r15(name, case) or cp14_case(name, case): counts["excluded"] += 1 continue bench.run(case) ours = core_kinds(bench.log) if ours == theirs: counts["agree"] += 1 continue why = expected_difference(ours, theirs, case, name, bench) if why: counts[why] += 1 else: counts["unexplained"] += 1 if len(problems) < 5: problems.append( f"{name} case {number} opcode {case.opcode:08x}: core {ours} nba {theirs}" ) return name, counts, problems, time.perf_counter() - start def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--limit", type=int) parser.add_argument("--files", nargs="*") parser.add_argument("--jobs", type=int, default=os.cpu_count()) args = parser.parse_args() if not REFEREE.exists(): print("no referee; run scripts/build_referees.py", file=sys.stderr) return 1 paths = [CORPUS / f"{n}.json.bin" for n in args.files] if args.files else corpus_files() total: Counter = Counter() with ProcessPoolExecutor(args.jobs) as pool: for name, counts, problems, seconds in pool.map(job, [(str(p), args.limit) for p in paths]): total += counts print(f"{name:32} {dict(sorted(counts.items()))} {seconds:5.1f}s") for line in problems: print(" ", line) print(f"\nall: {dict(sorted(total.items()))}") return 0 if not total["unexplained"] else 1 if __name__ == "__main__": sys.exit(main())