#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Rung 3: the reference's CPU test ROMs (its rungs 2 and 3), run by this crate's CLI and by the reference's (``python -m arm7tdmi_python ROM --trace FILE``): R12 must be 0 (every test passed), and the printed line, the exit status and the whole JSON Lines bus trace (every bus cycle) must be byte for byte the reference's. The CLI's other paths (``make_scenarios.py`` ``CLI_CASES``: raw images with ``--at`` and ``--thumb``, an ELF, the BIOS stop, a run out of cycles) must match the reference the same way. The reference's outputs are cached. Stdlib only. rom_cli.py [--reference-cache DIR] [--rust BINARY] [--traces DIR] """ from __future__ import annotations import argparse import hashlib import os import subprocess import sys from concurrent.futures import ThreadPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "scripts")) from make_scenarios import CLI_CASES, OUT, ROMS # noqa: E402 NICE = ["nice", "-n", "19"] def one(case: tuple[str, list[str], bool], python: str, rust: Path, cache: Path, traces: Path): rom, extra, must_pass = case path = Path(rom.replace("$TEST_ROMS", os.environ["TEST_ROMS"])) if not path.is_absolute(): path = Path(os.environ["TEST_ROMS"]) / rom tag = (rom.replace("/", "_").removesuffix(".gba") + "".join(extra)).replace("$", "") key = hashlib.sha256(path.read_bytes() + " ".join(extra).encode()).hexdigest()[:12] ref_out, ref_trace = cache / f"{tag}.{key}.out", cache / f"{tag}.{key}.jsonl" if not ref_out.is_file(): part = ref_trace.with_suffix(".part") done = subprocess.run([*NICE, python, "-m", "arm7tdmi_python", str(path), *extra, "--trace", str(part)], capture_output=True, text=True, cwd="/") part.rename(ref_trace) ref_out.write_text(f"{done.returncode}\n{done.stdout}{done.stderr}") ours_trace = traces / f"{tag}.rust.jsonl" done = subprocess.run([*NICE, str(rust), str(path), *extra, "--trace", str(ours_trace)], capture_output=True, text=True) ours = f"{done.returncode}\n{done.stdout}{done.stderr}" want = ref_out.read_text() if ours != want: return rom, False, f"output differs: reference {want!r}, rust {ours!r}" if ref_trace.read_bytes() != ours_trace.read_bytes(): return rom, False, "the bus traces differ" lines = ours_trace.read_bytes().count(b"\n") ours_trace.unlink() passed = done.returncode == 0 or not must_pass shown = (done.stdout + done.stderr).strip().replace("\n", " ") return " ".join([rom, *extra]), passed, f"{shown}; trace identical ({lines:,} bus cycles)" + ("" if passed else " (R12 != 0)") def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--reference-cache", type=Path, default=Path(os.environ.get("REFCACHE", ROOT / "external" / "refcache")) / "roms") parser.add_argument("--rust", type=Path, default=ROOT / "target" / "release" / "arm7tdmi") parser.add_argument("--python", default=os.environ.get("REFERENCE_PYTHON")) parser.add_argument("--traces", type=Path, default=ROOT / "external" / "traces") args = parser.parse_args() args.reference_cache.mkdir(parents=True, exist_ok=True) traces = args.traces traces.mkdir(parents=True, exist_ok=True) cases = [(rom, [], True) for rom in ROMS] cases += [(rom if rom.startswith("$") else str(OUT / "cli" / rom), extra, False) for rom, extra in CLI_CASES] failed = [0, 0] with ThreadPoolExecutor(4) as pool: for index, (rom, ok, text) in enumerate(pool.map(lambda c: one(c, args.python, args.rust, args.reference_cache, traces), cases)): print(f"{rom}: {text}") failed[index >= len(ROMS)] += not ok print(f"{len(ROMS) - failed[0]} of {len(ROMS)} ROMs pass, and {len(CLI_CASES) - failed[1]} of {len(CLI_CASES)} other CLI cases" " (--at, --thumb, ELF, the BIOS stop, --max-cycles), with output and trace identical to the reference's") return 1 if sum(failed) else 0 if __name__ == "__main__": sys.exit(main())