# SPDX-License-Identifier: MIT # First published under MIT by alewman in huc6280-python (validation/vanish_probe.py); the MIT # permission is kept (notices/MIT-emulator-family.txt). It runs inside this GPL-3.0-or-later tool. """huc6280-python's C18 closed-box probe (``tools/huc6280-python/vanish_probe.py`` loads this). Run huc6280-python's ``validation/vanish_rom.py`` cards on Mesen2, Mednafen and MAME. python -I "$HUC6280_GPL_TOOLS/vanish_probe.py" [--out DIR] [--mesen-core PATH] \ [--skip mesen|mednafen|mame ...] [--only VARIANT|t-entry ...] The emulators are run, never read: - **Mesen2** 2.1.1 (``b9fa69d``), driven through its exported C functions with ``ctypes`` and a Lua script that reads work RAM ($2000-$2007) after 30 frames (``--mesen-core``, else ``MESEN_CORE``, else mesen2-runner's own build from ``build.sh``). - **Mednafen** 1.32.1, the traced build (huc6280-python's ``scripts/mednafen_trace.py``). - **MAME** (huc6280-python's ``scripts/mame_trace.py``). The huc6280-python checkout is ``HUC6280_PYTHON_ROOT``, else the working directory (as parked on 2026-11-21 the file looked for it beside itself, where it is not, and stopped at import). Kept as it ran, including one defect found at the regrouping (2026-11-23): the PC Engine settings are declared as a bare ctypes array, which ctypes passes as a pointer (its documented rule for array arguments), where the library takes the structure by value, so the settings this probe meant (RAM powered on as zeros, no frame skipping) are not reliably the ones Mesen2 receives. ``--by-value`` passes them as the library takes them. OBSERVED 2026-11-23: all five cards give the same Mesen2 RAM answers either way, so huc6280-python's recorded results stand; the default stays as it was (``docs/consumer-migration.md``). """ from __future__ import annotations import argparse import ctypes import os import struct import subprocess import sys import time from pathlib import Path from ..api import OWN_BUILD from ..pce import PceConfig ROOT = Path(os.environ.get("HUC6280_PYTHON_ROOT", Path.cwd())).resolve() # The library: --mesen-core, else MESEN_CORE, else mesen2-runner's own build (build.sh), as # run.py finds it (the build fallback from 0.3.0). MESEN_LIBS = (*([Path(os.environ["MESEN_CORE"])] if os.environ.get("MESEN_CORE") else []), OWN_BUILD) MAXIMUM_SPEED, CONSOLE_MODE = 0x04, 0x10 LUA = """ local n = 0 emu.addEventCallback(function() n = n + 1 if n == 30 then local s = "RAM" for i = 0, 7 do s = s .. string.format(" %02X", emu.read(i, emu.memType.pceWorkRam)) end emu.log(s) emu.log("PROBE-DONE") end end, emu.eventType.endFrame) """ def mesen_config() -> bytes: raw = bytearray(8080) # PcEngineConfig; offsets measured by pcengine-python struct.pack_into(" str: m = ctypes.CDLL(str(lib)) config = PceConfig if by_value else ctypes.c_ubyte * 8080 m.InitializeEmu.argtypes = [ctypes.c_char_p, ctypes.c_void_p, ctypes.c_void_p] + [ ctypes.c_bool ] * 4 m.LoadRom.argtypes = [ctypes.c_char_p, ctypes.c_char_p] m.LoadRom.restype = ctypes.c_bool m.SetEmulationFlag.argtypes = [ctypes.c_uint32, ctypes.c_bool] m.LoadScript.argtypes = [ctypes.c_char_p] * 3 + [ctypes.c_int32] m.LoadScript.restype = ctypes.c_int32 m.GetScriptLog.argtypes = [ctypes.c_int32, ctypes.c_char_p, ctypes.c_uint32] m.SetPcEngineConfig.argtypes = [config] home.mkdir(parents=True, exist_ok=True) m.InitDll() m.InitializeEmu(str(home).encode(), None, None, True, True, True, True) m.SetPcEngineConfig(config.from_buffer_copy(mesen_config())) m.Pause() m.SetEmulationFlag(CONSOLE_MODE, True) if not m.LoadRom(str(rom).encode(), b""): raise SystemExit("Mesen2: LoadRom failed") m.InitializeDebugger() script = m.LoadScript(b"probe.lua", str(home).encode(), LUA.encode(), -1) m.SetEmulationFlag(MAXIMUM_SPEED, True) m.Resume() buf = ctypes.create_string_buffer(1 << 16) began = time.monotonic() while time.monotonic() - began < 60: time.sleep(0.05) m.GetScriptLog(script, buf, len(buf)) if b"PROBE-DONE" in buf.value: break line = next((x for x in buf.value.decode().splitlines() if x.startswith("RAM")), "RAM ?") return line[4:] def mesen_ram(lib, cart: Path, home: Path, by_value: bool = False) -> str: """Run one card on Mesen2 in its own process (the library does not survive a second start); a first start in a fresh home directory sometimes reports nothing, so try three times.""" for _ in range(3): command = [sys.executable, "-I", sys.argv[0], "--mesen-core", str(lib), *(["--by-value"] if by_value else []), "--mesen-one", str(cart), str(home)] # fmt: skip result = subprocess.run(command, capture_output=True, text=True, check=False) lines = result.stdout.strip().splitlines() if lines and lines[-1].strip() != "?": return lines[-1] return "?" def describe_ram(ram: str) -> str: b = [int(x, 16) for x in ram.split()] taken = [name for name, at, mark in (("TIQ", 0, 0x22), ("IRQ2", 5, 0x33), ("IRQ1", 6, 0x44)) if b[at] == mark] # fmt: skip if not taken: return "no entry; main line went on" if b[1] == 0x11 else "nothing happened" first = "before the main line" if b[2] == 0 else "after the main line" return f"{'+'.join(taken)} handler, {first}, return address {b[4]:02X}{b[3]:02X}" def follow(trace: Path, site: int, names: dict[int, str]) -> str: """What follows the first execution of ``site``: the next address, then the first handler.""" previous = seen = None after = 0 with trace.open("rb") as log: for line in log: if line.startswith((b"[", b"M ")): continue fields = line.split() if not fields: continue try: pc = int(fields[0], 16) except ValueError: continue if seen is None and previous == site: seen = names.get(pc, f"{pc:04X}") elif seen is not None: after += 1 if pc in names and "handler" in names[pc]: return f"{seen}; {names[pc]} entered {after} instructions later" if after == 20: break previous = pc if seen is None: return "site never reached" return f"{seen}; no handler within 20 instructions" def t_entry(args, out: Path, lib, build_t_entry) -> None: """C16: is T still set for the handler's first instruction when the entry follows SET?""" rom, labels = build_t_entry() cart = out / "t-entry.pce" cart.write_bytes(rom) print("t-entry (C16): the timer taken between SET and its target", flush=True) if "mesen" not in args.skip and lib: ram = mesen_ram(lib, cart, out / "mesen-home-t-entry", args.by_value) b = [int(x, 16) for x in ram.split()] print(f" Mesen2: RAM {ram}: handler ran {b[6] == 0x22}, A after ORA ${b[3]:02X}, " f"$2000 ${b[4]:02X}, pushed P ${b[5]:02X}") # fmt: skip if "mednafen" not in args.skip: subprocess.run( [sys.executable, "-I", str(ROOT / "scripts" / "mednafen_trace.py"), str(cart), "--count", "400000", "--out", str(out / "mednafen-t-entry")], check=True, stdout=subprocess.DEVNULL, ) # fmt: skip handler = labels["tiq_handler"] rows = [] with (out / "mednafen-t-entry" / "error.log").open() as log: for line in log: fields = line.split() if len(fields) >= 6 and not line.startswith(("M ", "[")): rows.append(fields) # The handler's first line (state before its ORA), the line before it (where the entry # came from) and the line after it (A and P after the ORA). at = next(n for n, row in enumerate(rows) if n and int(row[0], 16) == handler) came_from, after = int(rows[at - 1][0], 16), rows[at + 1] print(f" Mednafen: entered from ${came_from:04X}; A after the ORA " f"${int(after[1], 16):02X}, P ${int(after[5], 16):02X}") # fmt: skip def main() -> int: parser = argparse.ArgumentParser( description="C18 closed-box probe: run validation/vanish_rom.py's cards on Mesen2, " "Mednafen and MAME." ) parser.add_argument("--out", type=Path, default=ROOT / "scratch" / "vanish") parser.add_argument("--mesen-core", type=Path, default=os.environ.get("MESEN_CORE")) parser.add_argument( "--skip", action="append", default=[], choices=("mesen", "mednafen", "mame") ) parser.add_argument("--only", action="append", default=[], help="a variant, or t-entry (C16)") parser.add_argument( "--by-value", action="store_true", help="pass Mesen2 its PC Engine settings by value, as the library takes them", ) parser.add_argument("--mesen-one", nargs=2, type=Path, help=argparse.SUPPRESS) args = parser.parse_args() if args.mesen_one: # one card per process: the library does not survive a second start print(run_mesen(args.mesen_core, *args.mesen_one, by_value=args.by_value), flush=True) os._exit(0) # the library's teardown can crash; the answer is already out sys.path.insert(0, str(ROOT / "validation")) from vanish_rom import VARIANTS, build, build_t_entry out = args.out.resolve() out.mkdir(parents=True, exist_ok=True) lib = args.mesen_core or next((p for p in MESEN_LIBS if p.exists()), None) if "t-entry" in args.only or not args.only: t_entry(args, out, lib, build_t_entry) for variant in VARIANTS: if args.only and variant not in args.only: continue rom, labels = build(variant) cart = out / f"vanish-{variant}.pce" cart.write_bytes(rom) names = {labels["after"]: "main line (no entry)"} for name in ("tiq_handler", "irq1_handler", "irq2_handler"): names[labels[name]] = name.split("_")[0].upper() + " handler" print(f"{variant}: site ${labels['site']:04X}", flush=True) if "mesen" not in args.skip and lib: ram = mesen_ram(lib, cart, out / f"mesen-home-{variant}", args.by_value) print(f" Mesen2: RAM {ram}: {describe_ram(ram)}") if "mednafen" not in args.skip: subprocess.run( [sys.executable, "-I", str(ROOT / "scripts" / "mednafen_trace.py"), str(cart), "--count", "400000", "--out", str(out / f"mednafen-{variant}")], check=True, stdout=subprocess.DEVNULL, ) # fmt: skip trace = out / f"mednafen-{variant}" / "error.log" print(f" Mednafen: after the site: {follow(trace, labels['site'], names)}") if "mame" not in args.skip: subprocess.run( [sys.executable, "-I", str(ROOT / "scripts" / "mame_trace.py"), str(cart), "--seconds", "1", "--out", str(out / f"mame-{variant}")], check=True, stdout=subprocess.DEVNULL, ) # fmt: skip trace = out / f"mame-{variant}" / "error.log" print(f" MAME: after the site: {follow(trace, labels['site'], names)}") return 0