#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Run the probe suite (probes/suite) on an emulator and keep its battery RAM. EMU_TOOLS_GPL=... python3 -I scripts/suite_run.py SUITE.sfc --on mesen --out mesen.srm python -I scripts/suite_run.py SUITE.sfc --on board --out board.srm python -I scripts/suite_run.py SUITE.sfc --on mame --out mame.srm The console writes its .srm through the EverDrive; this gives the detectors' and the board's equivalents, for scripts/suite_results.py to set side by side. A run ends when the suite's run state (battery RAM byte $0009) reads 2, or at --frames. B on pad 1 is held while the running test's flags (WRAM $1E10) ask for it, as the tester would. ``--on board`` runs the restarted board (docs/restart.md; re-pointed 2026-11-19). ``--machine sfc-v1`` is the console's own revision row. The board run is the reference board in this process: slow (well under real time), so --frames bounds it. Mesen2 runs as mesen2-runner (``$EMU_TOOLS_GPL/tools/mesen2/run.py --machine snes --lua``, a GPL tool run as a separate program; scripts/emu_tools.py), which gives every run its own Mesen2 home, so no earlier save is loaded; the run ends at the end of the frame the suite finishes in (``--until``, the script's done line; --frames is the most it runs), the save being read then. Its values are OBSERVED (Mesen2 b9fa69d via mesen2-runner 0.3.0). With --only TAGS --base SAVE the board runs just those tests on top of a finished save of the same build (their statuses and slots cleared): seconds, not minutes. MAME 0.285 runs headless with a Lua script that reads battery RAM through the CPU's address space ($70:0000) and exits; it needs the snes.zip IPL ROM (scripts/mame_trace.py, --rompath). """ from __future__ import annotations import argparse import os import sys import tempfile import time from pathlib import Path ROOT = Path(__file__).resolve().parent sys.path.insert(0, str(ROOT)) sys.path.insert(0, str(ROOT.parent / "src")) SRAM_SIZE = 0x8000 #: The script's last line once it has reported (our own marker, read from script-log.txt). MESEN_DONE = "SUITE RUN DONE" STATE = 9 PROMPT = 0x1E10 HOLD_B = 0x01 MESEN_LUA = """\ local frames = 0 local finished = false emu.addEventCallback(function() if finished then return end frames = frames + 1 if emu.read({state}, emu.memType.snesSaveRam) == 2 or frames >= {frames} then finished = true local parts = {{}} for i = 0, {size} - 1 do parts[#parts + 1] = string.format("%02x", emu.read(i, emu.memType.snesSaveRam)) end emu.log("SRAM " .. table.concat(parts)) emu.log("FRAMES " .. frames) emu.log("{done}") end end, emu.eventType.endFrame) emu.addEventCallback(function() if (emu.read({prompt}, emu.memType.snesWorkRam) & {hold_b}) ~= 0 then emu.setInput({{b = true}}, 0, 0) end end, emu.eventType.inputPolled) """ def run_mesen(rom: Path, frames: int, timeout: float) -> tuple[bytes, int]: """The suite on mesen2-runner (``run.py --machine snes --lua``), run as a separate program. The script reports the battery RAM at the frame the suite finishes (or at ``frames``) and logs ``MESEN_DONE``; ``--until log:MESEN_DONE`` (mesen2-runner 0.3.0) ends the run at the end of that frame, so ``frames`` is only the most it runs (until 2026-11-24 the runner ran all ``frames`` and the rest of the run was idle). Every line the script logs arrives in ``script-log.txt``.""" import subprocess import emu_tools runner = emu_tools.require(emu_tools.MESEN2_RUN) lua = MESEN_LUA.format( state=STATE, frames=frames, size=SRAM_SIZE, done=MESEN_DONE, prompt=PROMPT, hold_b=HOLD_B, ) with tempfile.TemporaryDirectory() as tmp: script = Path(tmp) / "suite.lua" script.write_text(lua, encoding="utf-8") out = Path(tmp) / "run" subprocess.run( [sys.executable, "-I", str(runner), "--machine", "snes", "--rom", str(rom.resolve()), "--out", str(out), "--frames", str(frames), "--lua", str(script), "--until", f"log:{MESEN_DONE}", "--region", "auto", "--timeout", str(timeout)], capture_output=True, check=False, ) # fmt: skip log_file = out / "script-log.txt" log = log_file.read_text(encoding="utf-8") if log_file.exists() else "" if MESEN_DONE not in log: raise SystemExit("Mesen2 run did not finish (mesen2-runner: see its manifest's status)") lines = log.splitlines() sram = bytes.fromhex(next(x for x in lines if x.startswith("SRAM ")).split()[1]) ran = int(next(x for x in lines if x.startswith("FRAMES ")).split()[1]) return sram, ran MAME_LUA = """\ local space = manager.machine.devices[":maincpu"].spaces["program"] local frames = 0 local hold_b = {{}} for _, port in pairs(manager.machine.ioport.ports) do for name, field in pairs(port.fields) do if name == "P1 B" or name == "B" or name == "P1 Button 1" then hold_b[#hold_b + 1] = field end end end notifier = emu.add_machine_frame_notifier(function() frames = frames + 1 local want = (space:read_u8(0x7E0000 + {prompt}) & {hold_b_bit}) ~= 0 for _, field in ipairs(hold_b) do field:set_value(want and 1 or 0) end if space:read_u8(0x700000 + {state}) == 2 or frames >= {frames} then local f = io.open("{out}", "wb") for i = 0, {size} - 1 do f:write(string.char(space:read_u8(0x700000 + i))) end f:close() print("FRAMES " .. frames) manager.machine:exit() end end) """ def run_mame(rom: Path, frames: int, rompath: str) -> tuple[bytes, int]: import subprocess import mame_trace with tempfile.TemporaryDirectory() as tmp: out = Path(tmp) / "sram.bin" script = Path(tmp) / "suite.lua" script.write_text( MAME_LUA.format( prompt=PROMPT, hold_b_bit=HOLD_B, state=STATE, frames=frames, size=SRAM_SIZE, out=out, ) ) done = subprocess.run( [mame_trace.MAME, "snes", "-cart", str(rom.resolve()), "-rompath", rompath, "-homepath", tmp, "-nvram_directory", tmp, "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-seconds_to_run", str(frames // 60 + 10), "-autoboot_script", str(script)], cwd=tmp, capture_output=True, text=True, check=False, ) # fmt: skip if not out.exists(): raise SystemExit( f"MAME wrote no battery RAM:\n{done.stdout[-2000:]}{done.stderr[-2000:]}" ) ran = next( (int(x.split()[1]) for x in done.stdout.splitlines() if x.startswith("FRAMES ")), 0 ) return out.read_bytes(), ran def only(base: bytes, tags: list[str]) -> bytes: """A finished save with only ``tags`` to run again: their statuses and slots cleared, the run marked in progress, so a board run takes seconds.""" sram = bytearray(base) for i in range(sram[14]): o = 0x200 + 8 * i if sram[o : o + 4].decode("ascii", "replace") in tags: sram[0x10 + i] = 0 slot, size = ( int.from_bytes(sram[o + 4 : o + 6], "little"), int.from_bytes(sram[o + 6 : o + 8], "little"), ) sram[slot : slot + size] = bytes(size) sram[STATE] = 1 return bytes(sram) def run_board( rom: Path, frames: int, sram: bytes | None = None, machine: str = "ntsc", ipl: bytes | None = None, ) -> tuple[bytes, int]: # The restarted board (docs/restart.md). Until milestone 3 it has the # port stub, which echoes writes: IPLS and CLKR then measure nothing. from snes_python.board import SNES from snes_python.cartridge import Cartridge from snes_python.machines import MACHINES del ipl snes = SNES(Cartridge(rom.read_bytes()), MACHINES[machine.replace("-", "_")]) if sram is not None: snes.cart.sram[:] = sram ran = 0 while ran < frames: if snes.wram[PROMPT] & HOLD_B: snes.ports[0].pressed.add("B") else: snes.ports[0].pressed.discard("B") snes.run_frames(1) ran += 1 if snes.cart.sram[STATE] == 2: break return bytes(snes.cart.sram), ran def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("rom", type=Path) parser.add_argument("--on", choices=("mesen", "board", "mame"), required=True) parser.add_argument("--out", type=Path, required=True) parser.add_argument("--frames", type=int, default=20000) parser.add_argument("--timeout", type=float, default=600.0, help="Mesen2 wall-clock seconds") parser.add_argument("--rompath", default=None, help="MAME rompath holding snes.zip") parser.add_argument("--machine", default="ntsc", help="board: ntsc or sfc-v1") parser.add_argument( "--ipl", type=Path, default=Path( os.environ.get("SNES_IPL", ROOT.parents[1] / "spc700-python/reference/build/iplrom.bin") ), help="board: the S-SMP IPL ROM ($SNES_IPL; the S-SMP runs only with it)", ) parser.add_argument("--only", help="board: run just these tags (comma-separated) ...") parser.add_argument( "--base", type=Path, help="... on top of this finished save of the same build" ) args = parser.parse_args() began = time.monotonic() if args.on == "mesen": sram, ran = run_mesen(args.rom, args.frames, args.timeout) elif args.on == "mame": import mame_trace sram, ran = run_mame(args.rom, args.frames, args.rompath or mame_trace.DEFAULT_ROMPATH) else: preload = None if args.only: if args.base is None: raise SystemExit("--only needs --base") preload = only(args.base.read_bytes(), args.only.split(",")) ipl = args.ipl.read_bytes() if args.ipl.exists() else None if ipl is None: print(f"no IPL ROM at {args.ipl}: the S-SMP is a port stub", file=sys.stderr) sram, ran = run_board(args.rom, args.frames, preload, args.machine, ipl) args.out.write_bytes(sram) state = "complete" if sram[STATE] == 2 else f"state {sram[STATE]}" print(f"{args.on}: {ran} frames in {time.monotonic() - began:.1f} s, run {state} -> {args.out}") return 0 if __name__ == "__main__": raise SystemExit(main())