#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Run krom's GSU test ROMs on Mesen2 headless and count their PASS/FAIL rows. A detector (docs/validation.md "Mesen2"): the family's Mesen2 tool, mesen2-runner (a GPL tool, kept outside this repository), is run as a separate program at its documented path, ``$EMU_TOOLS_GPL/tools/mesen2/run.py``, with machine ``snes``; nothing of it is imported or copied; only its exit status and ``script-log.txt`` are read (``manifest.json``, kept with ``--out``, records the run: tag values OBSERVED with its Mesen2 commit). Our Lua script, passed with ``--lua``, logs the S-CPU's writes of ``$2116-$2118`` (VRAM address, low byte), and the PASS and FAIL tokens krom prints are counted from that stream (the same reader as ``mame_gsu_trace.py --krom``), against the rows in krom's source. python -I scripts/mesen_krom.py # all 31 GSUTest ROMs, 900 frames each python -I scripts/mesen_krom.py --only ADD --frames 600 The library is the tool's own build unless ``--lib`` or ``MESEN_CORE`` names another (docs/validation.md built famicom-python's); the manifest says which. Exit status 3 when ``EMU_TOOLS_GPL`` is unset or the tool is not at its path (emu-tools' contract, section 5). Mesen2 needs no BIOS. One tool process per ROM; ~1 s of wall per 200 frames. """ from __future__ import annotations import argparse import json import os import re import subprocess import sys import tempfile import time from collections import Counter from pathlib import Path #: A snes-python checkout: SNES_PYTHON, else the sibling of this repository. SNES_PYTHON = Path( os.environ.get("SNES_PYTHON", Path(__file__).resolve().parents[2] / "snes-python") ) KROM = SNES_PYTHON / "tests/test_roms/krom/CHIP/GSU/GSUTest" PRINT = re.compile(r"PrintText\((Pass|Fail), \$([0-9A-F]{4}), 4\)") DONE = "MESEN-DONE" # Mesen2 keeps a bounded script log, so the token search runs here, in Lua: # only the PASS/FAIL hits are logged (as "T word address"). LUA = """\ local frames = 0 local vaddr = 0 local last = {{}} emu.addMemoryCallback(function(address, value) local port = address & 0xFFFF if port == 0x2116 then vaddr = (vaddr & 0xFF00) | value elseif port == 0x2117 then vaddr = (vaddr & 0x00FF) | (value << 8) else table.insert(last, {{vaddr, value}}) if #last > 4 then table.remove(last, 1) end vaddr = (vaddr + 1) & 0x7FFF if #last == 4 then local s = string.char(last[1][2], last[2][2], last[3][2], last[4][2]) local seq = last[2][1] == last[1][1] + 1 and last[3][1] == last[1][1] + 2 and last[4][1] == last[1][1] + 3 if seq and (s == "PASS" or s == "FAIL") then emu.log(string.format("T %s %X", s, last[1][1])) end end end end, emu.callbackType.write, 0x2116, 0x2118) emu.addEventCallback(function() frames = frames + 1 if frames == {frames} then emu.log("{done}") end end, emu.eventType.endFrame) """ def runner() -> Path: """mesen2-runner's run.py at its documented path under EMU_TOOLS_GPL.""" root = os.environ.get("EMU_TOOLS_GPL") path = Path(root or "$EMU_TOOLS_GPL") / "tools/mesen2/run.py" if not root or not path.is_file(): print(f"mesen2-runner not found at {path}: set EMU_TOOLS_GPL to a checkout of " "emu-tools-gpl (a GPL tool kept outside this repository)", file=sys.stderr) # fmt: skip sys.exit(3) return path def run_tool( run_py: Path, rom: Path, frames: int, out: Path, lib: Path | None ) -> tuple[str, float, int]: """One Mesen2 run of ``rom`` with our Lua; its script log, the wall and the exit status.""" out.mkdir(parents=True, exist_ok=True) lua = out / "krom.lua" lua.write_text(LUA.format(frames=frames, done=DONE), encoding="utf-8") # The system's python3, as the tool's README runs it (the tool brings its own dependencies). command = ["python3", "-I", str(run_py), "--machine", "snes", "--rom", str(rom), "--out", str(out / "run"), "--frames", str(frames), "--lua", str(lua), "--timeout", "300"] # fmt: skip if lib: command += ["--lib", str(lib)] start = time.perf_counter() done = subprocess.run(command, capture_output=True, text=True, check=False) wall = time.perf_counter() - start log_path = out / "run" / "script-log.txt" log = log_path.read_text(errors="replace") if log_path.exists() else "" if done.returncode not in (0, 1): sys.stderr.write(done.stderr) return log, wall, done.returncode def tokens(log: str) -> dict[str, int]: """The Lua's "T PASS addr" / "T FAIL addr" hits, counted.""" found: Counter = Counter(line.split()[1] for line in log.splitlines() if line.startswith("T ")) return dict(found) def rows(directory: Path) -> int: sources = [p for p in directory.glob("*.asm") if not p.name.endswith("_gsu.asm")] return sum(len(PRINT.findall(p.read_text(errors="replace"))) // 2 for p in sources) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--frames", type=int, default=900) parser.add_argument("--only", action="append", default=[], help="test directory name") parser.add_argument( "--out", type=Path, help="keep the tool's outputs here (default: a temporary folder)" ) parser.add_argument( "--lib", type=Path, help="MesenCore.so (else MESEN_CORE, else the tool's build)" ) parser.add_argument("--json", type=Path) args = parser.parse_args() run_py = runner() tests = [ p for p in sorted(KROM.iterdir()) if p.is_dir() and (not args.only or p.name in args.only) ] results = {} with tempfile.TemporaryDirectory(prefix="mesen-krom-") as scratch: base = args.out or Path(scratch) for directory in tests: rom = next(directory.glob("GSU*.sfc")) log, wall, code = run_tool(run_py, rom, args.frames, base / directory.name, args.lib) if code not in (0, 1): results[directory.name] = {"verdict": "crash", "rc": code} else: found = tokens(log) expected = rows(directory) verdict = ( "pass" if found.get("PASS", 0) == expected and not found.get("FAIL") else "FAIL" ) # done: the run completed all its frames (the tool's exit status 0; it stops # at the end of the last frame, before our script's DONE line can be logged). results[directory.name] = {"tokens": found, "rows": expected, "verdict": verdict, "wall": round(wall, 1), "done": code == 0} # fmt: skip print(f"{directory.name:<12} {results[directory.name]}", flush=True) if args.json: args.json.write_text(json.dumps(results, indent=1) + "\n", encoding="utf-8") passed = sum(r.get("verdict") == "pass" for r in results.values()) print(f"{passed} of {len(results)} tests pass") return 3 if any(r.get("rc") == 3 for r in results.values()) else 0 if __name__ == "__main__": sys.exit(main())