# SPDX-License-Identifier: GPL-3.0-or-later """Mesen2's exported C functions, as the runner declares them for ctypes, and finding the library. The declarations follow the C API that Mesen2's own test runner calls (the library's exported entry points and the structures they take by value). They were written once per emulator repository before 2026-11-23 (famicom-, snes-, pcengine-, huc6280- and hg51b-python, MIT, by alewman; ``notices/MIT-emulator-family.txt``) and are gathered here. """ from __future__ import annotations import ctypes import os from pathlib import Path # EmulationFlags (bits for SetEmulationFlag). MAXIMUM_SPEED, CONSOLE_MODE = 0x04, 0x10 # CpuType values the trace logger takes. CPU_TYPES = {"snes": 0, "cx4": 5, "nes": 8, "pce": 9} # Where a build may be: this tool's own build first, then the place each emulator repository's # documents built it before the regrouping (relative to that checkout). TOOL_DIR = Path(__file__).resolve().parents[1] OWN_BUILD = TOOL_DIR / "upstream" / "Mesen2" / "InteropDLL" / "obj.linux-x64" / "MesenCore.so" #: Each pinned core's own build (``build.sh --core NAME``) and the record ``build.sh`` writes #: beside it (Mesen2's keeps its 0.1.0 name). OWN_BUILDS = { "mesen2": OWN_BUILD, "mesence": TOOL_DIR / "upstream" / "MesenCE" / "InteropDLL" / "obj.linux-x64" / "MesenCore.so", } BUILD_RECORDS = { "mesen2": TOOL_DIR / "upstream" / "build-info.json", "mesence": TOOL_DIR / "upstream" / "build-info-mesence.json", } CHECKOUT_BUILD = Path("reference/build-mesen2/Mesen2/InteropDLL/obj.linux-x64/MesenCore.so") class TraceLoggerOptions(ctypes.Structure): """The trace logger's options, by value: enabled, indent, labels, condition, format.""" _fields_ = [ ("Enabled", ctypes.c_bool), ("IndentCode", ctypes.c_bool), ("UseLabels", ctypes.c_bool), ("Condition", ctypes.c_char * 1000), ("Format", ctypes.c_char * 1000), ] class Pad(ctypes.Structure): """A controller's state for SetInputOverrides, by value (fourteen buttons).""" _fields_ = [ (n, ctypes.c_bool) for n in ( "a", "b", "x", "y", "l", "r", "u", "d", "up", "down", "left", "right", "select", "start", ) ] # fmt: skip class DebugConfig(ctypes.Structure): """Mesen2 2.1.1's DebugConfig by value: 56 bytes, every field false except the script timeout (1 second), as the header's defaults have it. Measured with offsetof() against the pinned settings header (2026-11-24): ScriptAllowIoOsAccess at 48, ScriptAllowNetworkAccess at 49, ScriptTimeout (uint32) at 52.""" _fields_ = [("raw", ctypes.c_ubyte * 56)] DEBUG_CONFIG_SCRIPT_IO = 48 DEBUG_CONFIG_SCRIPT_TIMEOUT = 52 def debug_config(script_io: bool) -> DebugConfig: """The header's defaults, with Lua's io and os libraries allowed if ``script_io`` (the runner's full script log writes through io; network access stays off).""" config = DebugConfig() config.raw[DEBUG_CONFIG_SCRIPT_IO] = int(script_io) config.raw[DEBUG_CONFIG_SCRIPT_TIMEOUT : DEBUG_CONFIG_SCRIPT_TIMEOUT + 4] = [1, 0, 0, 0] return config #: Batch mode (``run.py --batch``): keep the emulator between runs. The library cannot start #: twice in one process (``Release`` drops the emulator and a second ``InitDll`` crashes, #: OBSERVED), so a batch calls ``InitDll`` once, ``InitializeEmu`` with each run's home, and #: ``Stop`` (which drops the debugger and its scripts) between runs, ``Release`` never. KEEP = False _loaded: dict[str, ctypes.CDLL] = {} _initialised = False def start(m: ctypes.CDLL, home: Path) -> None: """``InitDll`` (once per process in batch mode) and ``InitializeEmu`` with ``home``.""" global _initialised if not (KEEP and _initialised): m.InitDll() _initialised = True m.InitializeEmu(str(home.resolve()).encode(), None, None, True, True, True, True) def finish(m: ctypes.CDLL) -> None: """``Stop``, then ``Release`` unless in batch mode.""" global _initialised m.Stop() if not KEEP: m.Release() _initialised = False def declare(m: ctypes.CDLL) -> ctypes.CDLL: """Give the entry points every adapter uses their argument and result types.""" 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.IsRunning.restype = ctypes.c_bool m.GetStopCode.restype = ctypes.c_int32 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.SetTraceOptions.argtypes = [ctypes.c_uint8, TraceLoggerOptions] m.StartLogTraceToFile.argtypes = [ctypes.c_char_p] m.SetDebugConfig.argtypes = [DebugConfig] return m def load(lib: Path | str) -> ctypes.CDLL: """The library at ``lib`` with the common declarations (loaded once per process).""" key = str(lib) if key not in _loaded: _loaded[key] = ctypes.CDLL(key) return declare(_loaded[key]) def candidates(checkout: Path | None = None) -> list[Path]: """Places a MesenCore.so may be, in the order the runner tries them: ``MESEN_CORE``, this tool's own build (``build.sh``), then ``checkout``'s ``reference/build-mesen2``.""" found = [] if os.environ.get("MESEN_CORE"): found.append(Path(os.environ["MESEN_CORE"])) found.append(OWN_BUILD) if checkout is not None: found.append(checkout / CHECKOUT_BUILD) return found def find_library( explicit: Path | None = None, checkout: Path | None = None, core: str | None = None ) -> Path | None: """``explicit`` if given; else, with ``core`` (``--core``), that core's own build, whether or not it exists (``MESEN_CORE`` does not override a core asked for by name); else the first of ``candidates`` that exists.""" if explicit is not None: return explicit if core is not None: return OWN_BUILDS[core] return next((p for p in candidates(checkout) if p.exists()), None) def poll_log(m: ctypes.CDLL, script: int, size: int) -> tuple[ctypes.Array, str]: """A buffer of ``size`` bytes and the script's log read into it.""" buf = ctypes.create_string_buffer(size) m.GetScriptLog(script, buf, len(buf)) return buf, buf.value.decode(errors="replace")