# SPDX-License-Identifier: MIT """Shared helpers: a GSU over a small program, and the BYOR oracles (read in place, never copied). ``KROM`` is krom's ``CHIP/GSU`` checkout in a sibling snes-python checkout (``../snes-python/tests/test_roms/krom/CHIP/GSU``; ``GSU_KROM`` overrides it); the MAME traces are ``tests/mame_traces//gsu.log.gz`` (gitignored; scripts/mame_gsu_trace.py). Tests that need an absent oracle skip. """ from __future__ import annotations import os from pathlib import Path import pytest from gsu_python import GSU, GSU2, Model ROOT = Path(__file__).resolve().parents[1] KROM = Path(os.environ.get("GSU_KROM", ROOT.parent / "snes-python/tests/test_roms/krom/CHIP/GSU")) TRACES = ROOT / "tests" / "mame_traces" STAR_FOX = TRACES / "Star_Fox_(USA)_(Rev_2)" #: SCMR with RON and RAN (the GSU owns both buses), 4 colours, 128 high. SCMR_BUSES = 0x18 def make_gsu( code: bytes | list[int], *, origin: int = 0x8000, ram_size: int = 0x10000, model: Model = GSU2, cls: type[GSU] = GSU, rom_size: int = 0x20000, ) -> GSU: """A core over a LoROM image holding ``code`` at ``00:origin`` (``origin`` >= 8000h).""" rom = bytearray(rom_size) offset = origin - 0x8000 rom[offset : offset + len(code)] = bytes(code) return cls(bytes(rom), bytearray(ram_size), model=model) def start( gsu: GSU, address: int = 0x8000, *, clsr: int = 1, scmr: int = SCMR_BUSES, cfgr: int = 0x80, pbr: int | None = 0, ) -> None: """Set the clock, mode and bank as krom's tests do, and start the GSU at ``address``.""" gsu.write_io(0x3039, clsr) gsu.write_io(0x3037, cfgr) gsu.write_io(0x303A, scmr) if pbr is not None: # a PBR write also invalidates the cache (U15) gsu.write_io(0x3034, pbr) gsu.write_io(0x301E, address & 0xFF) gsu.write_io(0x301F, address >> 8) def run_to_stop(gsu: GSU, limit: int = 1_000_000) -> int: """Run until STOP; return the input clocks it took.""" used = 0 while gsu.running: used += gsu.step() assert used < limit, "the program did not stop" return used def execute(code: bytes | list[int], **registers: int) -> GSU: """Run ``code`` (which must end in STOP) from 00:8000 at CLSR = 1 with the given registers (``r0=...``) preset; return the stopped core.""" gsu = make_gsu(code) for name, value in registers.items(): gsu.r[int(name[1:])] = value start(gsu) run_to_stop(gsu) return gsu def require(path: Path) -> Path: if not path.exists(): pytest.skip(f"BYOR: {path} is absent") return path