# SPDX-License-Identifier: MIT """The minimal harness: the core, the ROM and a RAM bytearray, and a scripted S-CPU. No 65C816, no cartridge decode, no clock ratio (those are the board's): the host writes the register file and the cache window through :meth:`GSU.write_io`, starts the GSU, runs it until GO = 0 or a clock budget, and reads results through :meth:`GSU.read_io`. **krom's GSUTest** (rung 2; validation.md "krom's tests": test-author tier). Each of the 31 ROMs runs a block of GSU code per row, reads R0/R1 and SFR after STOP, and compares them with ``ResultCheck``/``SFRResultCheck`` words in the ROM. :func:`krom_script` reads the S-CPU's side of that protocol **from the ROM's own 65C816 code** (BYOR: the bytes are read in place, nothing is assembled or copied): the GSU register stores (``LDA #``/``STA``/``STZ`` to ``$30xx``), the starts (``LDX #addr``/``LDX $301E`` then ``STX $301E``), the cache upload (``MVN`` to ``$3100``), the result reads (``LDX $30nn``) and the two compares (``CPX abs`` against the result word, ``CMP abs`` against SFR's low byte, 8-bit). :func:`run_krom` replays it on the core and returns one verdict per row. """ from __future__ import annotations from dataclasses import dataclass, field from gsu_python.core import GSU from gsu_python.model import GSU1, Model #: Clocks the host lets pass after GO = 0 before it reads (the S-CPU's polling loop takes #: longer than this; a pending ROM buffer read must not show in SFR.R). SETTLE_CLOCKS = 64 class HostTimeout(RuntimeError): """The GSU did not stop within the budget.""" class Harness: """A GSU with a host that is not a SNES.""" def __init__( self, rom: bytes, *, ram_size: int = 0x8000, model: Model = GSU1, gsu: GSU | None = None ) -> None: self.gsu = gsu if gsu is not None else GSU(rom, bytearray(ram_size), model=model) self.instructions = 0 def write(self, address: int, value: int) -> None: self.gsu.write_io(address, value) def read(self, address: int) -> int: value = self.gsu.read_io(address) return 0 if value is None else value def write_word(self, address: int, value: int) -> None: """A 16-bit S-CPU store: low byte first (U8).""" self.write(address, value & 0xFF) self.write(address + 1, value >> 8 & 0xFF) def read_word(self, address: int) -> int: low = self.read(address) return self.read(address + 1) << 8 | low def run_to_stop(self, budget: int = 50_000_000) -> int: """Step until GO = 0; return the input clocks used. Raises HostTimeout.""" gsu = self.gsu used = 0 while gsu.sfr & 0x20: used += gsu.step() self.instructions += 1 if used > budget: raise HostTimeout(f"no STOP within {budget} clocks (R15 = {gsu.r[15]:04X}h)") gsu.run(SETTLE_CLOCKS) return used def start(self, address: int, budget: int = 50_000_000) -> int: """Write R15 (its high byte starts the GSU) and run to STOP.""" self.write_word(0x301E, address) return self.run_to_stop(budget) # ----- krom's GSUTest ------------------------------------------------------------------------ @dataclass(frozen=True, slots=True) class KromRow: """One PASS/FAIL row: the register read, its value, the ROM's expectation, and SFR's low byte against its expectation.""" index: int register: int value: int expected: int sfr: int expected_sfr: int @property def passed(self) -> bool: return self.value == self.expected and self.sfr == self.expected_sfr @dataclass(slots=True) class KromResult: rows: list[KromRow] = field(default_factory=list) instructions: int = 0 @property def passed(self) -> int: return sum(row.passed for row in self.rows) @property def failed(self) -> list[KromRow]: return [row for row in self.rows if not row.passed] def _word(rom: bytes, address: int) -> int: offset = address - 0x8000 return rom[offset] | rom[offset + 1] << 8 def krom_script(rom: bytes) -> list[tuple]: """The S-CPU's GSU accesses in the order its code makes them, read from bank 0's code. Events: ``("w", address, value)``, ``("start", address)``, ``("restart",)`` (R15 read back and written), ``("upload", source, length)``, ``("result", register)``, ``("sfr",)``, ``("cpx", address)`` or ``("cpx#", value)``, ``("cmp", address)``. """ bank = rom[:0x8000] checks = [ i + 1 for i in range(len(bank) - 4) if bank[i] == 0xEC and bank[i + 3] == 0xF0 and bank[i + 2] >= 0x80 ] end = min(_word_at(bank, c) for c in checks) - 0x8000 if checks else len(bank) events: list[tuple] = [] wide = False # the 65C816's M flag: 16-bit accumulator stores write two registers a = 0 i = 0 while i < end - 2: op = bank[i] if op == 0xC2 and bank[i + 1] & 0x20: # REP #$20 wide, i = True, i + 2 elif op == 0xE2 and bank[i + 1] & 0x20: # SEP #$20 wide, i = False, i + 2 elif op == 0xA9: # LDA #imm a = bank[i + 1] | (bank[i + 2] << 8 if wide else 0) i += 3 if wide else 2 elif op in (0x8D, 0x9C) and bank[i + 2] == 0x30: # STA/STZ $30xx value = a if op == 0x8D else 0 events.append(("w", 0x3000 | bank[i + 1], value & 0xFF)) if wide: events.append(("w", 0x3001 | bank[i + 1], value >> 8 & 0xFF)) i += 3 elif op == 0xA2 and bank[i + 3 : i + 6] == b"\x8e\x1e\x30": # LDX #addr; STX $301E events.append(("start", bank[i + 1] | bank[i + 2] << 8)) i += 6 elif bank[i : i + 6] == b"\xae\x1e\x30\x8e\x1e\x30": # LDX $301E; STX $301E events.append(("restart",)) i += 6 elif op == 0xAE and bank[i + 2] == 0x30 and bank[i + 3] == 0x86: # LDX $30nn; STX dp if bank[i + 1] == 0x30: events.append(("sfr",)) else: events.append(("result", bank[i + 1] >> 1)) i += 3 elif op == 0xEC and i + 1 in checks: # CPX ResultCheck events.append(("cpx", bank[i + 1] | bank[i + 2] << 8)) i += 3 elif op == 0xE0 and bank[i + 3] == 0xF0: # CPX #value; BEQ (the macros' loops use BNE) events.append(("cpx#", bank[i + 1] | bank[i + 2] << 8)) i += 3 elif op == 0xCD and bank[i + 2] >= 0x80 and events and events[-1][0] in ("cpx", "cpx#"): events.append(("cmp", bank[i + 1] | bank[i + 2] << 8)) # CMP SFRResultCheck i += 3 elif op == 0x54 and i >= 9 and bank[i - 3] == 0xA0 and bank[i - 1] == 0x31: # LDA #len-1; LDX #src; LDY #$3100; MVN: the cache upload (krom CACHEINJECT) length = _word_at(bank, i - 8) + 1 events.append(("upload", _word_at(bank, i - 5), length)) i += 3 else: i += 1 return events def _word_at(bank: bytes, offset: int) -> int: return bank[offset] | bank[offset + 1] << 8 def run_krom(rom: bytes, *, gsu: GSU | None = None, model: Model = GSU1) -> KromResult: """Replay a krom GSUTest ROM's protocol on the core; one :class:`KromRow` per row.""" harness = Harness(rom, model=model, gsu=gsu) result = KromResult() value = register = sfr = 0 pending_value = None for event in krom_script(rom): kind = event[0] if kind == "w": harness.write(event[1], event[2]) elif kind == "start": harness.start(event[1]) elif kind == "restart": harness.start(harness.read_word(0x301E)) elif kind == "upload": source, length = event[1], event[2] for k in range(length): harness.write(0x3100 + k, rom[source - 0x8000 + k]) elif kind == "result": register = event[1] value = harness.read_word(0x3000 + 2 * register) elif kind == "sfr": sfr = harness.read_word(0x3030) & 0xFF elif kind == "cpx": pending_value = (value, _word(rom, event[1])) elif kind == "cpx#": pending_value = (value, event[1]) elif kind == "cmp" and pending_value is not None: got, expected = pending_value result.rows.append( KromRow(len(result.rows), register, got, expected, sfr, rom[event[1] - 0x8000]) ) pending_value = None result.instructions = harness.instructions return result __all__ = [ "SETTLE_CLOCKS", "Harness", "HostTimeout", "KromResult", "KromRow", "krom_script", "run_krom", ]