# SPDX-License-Identifier: MIT AND ISC """A board-free harness: the core, a BYOR cartridge on its ROM bus, and a scripted S-CPU. No 65816, no PPU, no master-clock ratio (validation.md "The minimal harness"). The ROM is read in LoROM order (banks 00-3F/80-BF $8000-$FFFF, C0-FF $0000-$FFFF; ares ``hitachidsp/memory.cpp``), mirrored to its size, from bytes the caller read in place (``.zip`` or ``.sfc``: :func:`read_cartridge`). The scripted S-CPU writes what the games write and polls $7F5E bit 6 with ``poll_clocks`` chip clocks between reads, as the games' driver does (X2 ``00:CD07``, copied to WRAM at 7E:2680: wait idle, $7F4D/$7F4E = PB, $7F48 = cache page (a preload), wait, $7F4F = PC, wait). :func:`selftest` runs the games' own built-in Cx4 test (hold controller 2 B at power-on) in the harness, item by item, with the expected values **read from the cartridge's own test code** (X2 USA ``13:F8B7``-``13:FBDA``; found in every retail version by its code bytes): the interface register table (DB:A2F6 in X2 USA, DB = the bank of the "Cx4 TEST" string), the register file and data RAM patterns, the ROM checksum through DMA + 0E:40 (compared with the header's checksum at $00:FFDE), 0E:00-0E:3C (R0 = n), 0E:54 over R0 = FFFFFFh, EEEEEEh, ... 000000h (R1:R2 against the table the code compares with), 0E:5C (data RAM against the constants table), 0E:89 (R0 = 054336h). """ from __future__ import annotations import re import zipfile from dataclasses import dataclass, field from pathlib import Path from hg51b_python.cpu import HG51B #: The games' configuration (MAME host log; the test's INTERFACE REGISTER table). CONFIGURATION = ( (0x7F52, 0x00), (0x7F6E, 0xF3), (0x7F6F, 0x1F), (0x7F6A, 0xEF), (0x7F6B, 0x1F), (0x7F50, 0x44), (0x7F51, 0x01), (0x7F49, 0x00), (0x7F4A, 0x80), (0x7F4B, 0x02), (0x7F4C, 0x00), ) #: The test's eight items, in screen order. ITEMS = ( "INTERFACE REGISTER", "REGISTER FILE", "DATA RAM", "LDMAC", "DOWN LOAD", "MALU", "IMMEDIATE REGISTER", "IMMEDIATE ROM", ) class HostTimeout(RuntimeError): """The chip did not go idle within the budget.""" def read_cartridge(path: str | Path) -> bytes: """A cartridge image, read in place: a ``.zip`` (its ``.sfc``/``.smc``) or a loose file. A 512-byte copier header is dropped.""" path = Path(path) if path.suffix.lower() == ".zip": with zipfile.ZipFile(path) as archive: names = [n for n in archive.namelist() if n.lower().endswith((".sfc", ".smc"))] if not names: raise ValueError(f"{path}: no .sfc/.smc inside") data = archive.read(names[0]) else: data = path.read_bytes() if len(data) % 0x8000 == 512: data = data[512:] return data def mirror(address: int, size: int) -> int: """byuu's ``Bus::mirror`` (ares ``sfc/memory/inline.hpp``, ISC): fold an address past the end of a ROM whose size is not a power of two onto its last power-of-two part (1.5 MiB: 180000h-1FFFFFh -> 100000h).""" if size == 0: return 0 base, mask = 0, 1 << 23 while address >= size: while not address & mask: mask >>= 1 address -= mask if size > mask: size -= mask base += mask mask >>= 1 return base + address def lorom_offset(address: int, size: int) -> int: """The cartridge's LoROM decode (ares ``hitachidsp/memory.cpp`` ``addressROM``, Mapping = 0), mirrored: banks 00-3F/80-BF $8000-$FFFF and C0-FF $0000-$FFFF, linear = (bank & 3Fh) << 15 | A14-A0.""" return mirror((address & 0x3F0000) >> 1 | (address & 0x7FFF), size) class Harness: """The core on a cartridge ROM, driven by a scripted S-CPU.""" def __init__( self, rom: bytes, *, core: type[HG51B] = HG51B, data_rom: list[int] | None = None, poll_clocks: int = 16, ) -> None: self.rom = bytes(rom) self.cx = core(self.bus_read, None, data_rom) self.poll_clocks = poll_clocks self.polls = 0 def bus_read(self, address: int) -> int: return self.rom[lorom_offset(address, len(self.rom))] # ----- the S-CPU's side -------------------------------------------------------------- def write(self, address: int, value: int) -> None: self.cx.write(address, value) def read(self, address: int) -> int: return self.cx.read(address) def configure(self, values: tuple[tuple[int, int], ...] = CONFIGURATION) -> None: """The games' setup writes (X2's by default; :func:`selftest` uses the cartridge's own table, since X3's IRQ/NMI vectors differ).""" for address, value in values: self.write(address, value) def wait_idle(self, budget: int = 50_000_000) -> int: """Poll $7F5E bit 6 until clear, running the chip ``poll_clocks`` between reads.""" spent = 0 while self.read(0x7F5E) & 0x40: self.polls += 1 self.cx.run(self.poll_clocks) spent += self.poll_clocks if spent > budget: raise HostTimeout(f"still running after {spent} clocks") return spent def call(self, pb: int, pc: int, page: int = 0) -> None: """The games' start stub: PB, a preload into ``page``, PC; wait for the HALT.""" self.wait_idle() self.write(0x7F4D, pb & 0xFF) self.write(0x7F4E, pb >> 8) self.write(0x7F48, page) self.wait_idle() self.write(0x7F4F, pc) self.wait_idle() def dma(self, source: int, length: int, target: int) -> None: self.wait_idle() for i in range(3): self.write(0x7F40 + i, source >> (8 * i) & 0xFF) self.write(0x7F43, length & 0xFF) self.write(0x7F44, length >> 8) self.write(0x7F45, target & 0xFF) self.write(0x7F46, target >> 8 & 0xFF) self.write(0x7F47, target >> 16) self.wait_idle() def register(self, index: int) -> int: """R0-R15 through the S-CPU's bytes.""" base = 0x7F80 + 3 * index return self.read(base) | self.read(base + 1) << 8 | self.read(base + 2) << 16 def set_register(self, index: int, value: int) -> None: for i in range(3): self.write(0x7F80 + 3 * index + i, value >> (8 * i) & 0xFF) # ----- the built-in test ------------------------------------------------------------------ @dataclass(frozen=True, slots=True) class Expectations: """What the cartridge's test code compares with, found by its code bytes.""" interface: tuple[tuple[int, int], ...] # (register, value) the test reads back checksum: int # $00:FFDE double_from_bank: int | None # X2: banks >= this count twice (the 2 MiB mirror); X3: None banks: int malu: bytes # 16 x 6 bytes, R1:R2 for R0 = FFFFFFh ... 000000h, in table order constants: bytes # 48 bytes of data RAM after 0E:5C immediate_rom: int # R0 after 0E:89 def _snes(rom: bytes, address: int) -> int: return lorom_offset(address, len(rom)) def find_expectations(rom: bytes) -> Expectations: """Read the test's expected values out of its code (retail X2/X3, all regions).""" def one(pattern: bytes) -> re.Match[bytes]: found = list(re.finditer(pattern, rom, re.S)) if len(found) != 1: raise ValueError(f"the Cx4 test code is not where expected ({pattern!r})") return found[0] data_bank = one(rb"Cx4 TEST").start() >> 15 # the strings' bank is the test's DB table = int.from_bytes(one(rb"\xbe(..)\x30\x10\xb9").group(1), "little") at = _snes(rom, data_bank << 16 | table) interface = [] while True: # LDX table,Y (register; negative ends); LDA table+2,Y; CMP $0000,X register = rom[at] | rom[at + 1] << 8 if register & 0x8000: # BMI: a negative 16-bit X ends the table break interface.append((register, rom[at + 2])) at += 3 malu_at = int.from_bytes(one(rb"\xb9\x83\x7f\xdf(...)").group(1), "little") constants_at = int.from_bytes(one(rb"\xbd\x00\x60\xdd(..)").group(1), "little") match = one(rb"\xad\x80\x7f\xc9(.)\xd0\x0e\xad\x81\x7f\xc9(.)\xd0\x07\xad\x82\x7f\xc9(.)") immediate_rom = int.from_bytes(b"".join(match.groups()), "little") loop = one(rb"\xa9(.)\x8d\x83\x08\xa9(.)\x8d\x84\x08") double = one(rb"\xad\x81\x08\xc9\x00(.)\x90") # X2 compares 0885h + 0887h (the doubled upper half) with the header, X3 0885h alone doubled = bool(re.search(rb"\xad\x85\x08\x6d\x87\x08\xcf\xde\xff\x00", rom)) checksum_at = _snes(rom, 0x00FFDE) start = _snes(rom, malu_at) constants = _snes(rom, data_bank << 16 | constants_at) return Expectations( interface=tuple(interface), checksum=rom[checksum_at] | rom[checksum_at + 1] << 8, double_from_bank=double.group(1)[0] if doubled else None, banks=loop.group(1)[0], malu=rom[start : start + 0x60], constants=rom[constants : constants + 0x30], immediate_rom=immediate_rom, ) @dataclass class SelfTestResult: passed: dict[str, bool] = field(default_factory=dict) details: dict[str, str] = field(default_factory=dict) @property def ok(self) -> bool: return all(self.passed.get(item, False) for item in ITEMS) def lines(self) -> list[str]: return [ f"{item:<20} {'OK.' if self.passed.get(item) else 'ERROR!'}" + (f" {self.details[item]}" if item in self.details else "") for item in ITEMS if item in self.passed ] def selftest( rom: bytes, *, core: type[HG51B] = HG51B, items: tuple[str, ...] = ITEMS, harness: Harness | None = None, ) -> SelfTestResult: """The built-in Cx4 test, each item as the cartridge's code performs and checks it.""" expect = find_expectations(rom) h = harness or Harness(rom, core=core) h.configure((*expect.interface, (0x7F4C, 0x00))) result = SelfTestResult() def record(item: str, ok: bool, detail: str = "") -> None: result.passed[item] = ok if detail: result.details[item] = detail if "INTERFACE REGISTER" in items: # 13:F8B7: read back what the setup wrote bad = [(r, v, h.read(r)) for r, v in expect.interface if h.read(r) != v] record("INTERFACE REGISTER", not bad, " ".join(f"{r:04X}={g:02X}" for r, _, g in bad)) if "REGISTER FILE" in items: # 13:F8E9: 00h, 11h, ... into each R byte, read back ok = True for index in range(0, 0x30, 3): value = 0 for _ in range(16): for k in range(3): h.write(0x7F80 + index + k, value) ok &= all(h.read(0x7F80 + index + k) == value for k in range(3)) value = (value + 0x11) & 0xFF record("REGISTER FILE", ok) if "DATA RAM" in items: # 13:F92F: FFh, EEh, ... into every data RAM byte, read back ok = True for address in range(0xBFF, -1, -1): value = 0xFF for _ in range(16): h.write(0x6000 + address, value) ok &= h.read(0x6000 + address) == value value = (value - 0x11) & 0xFF record("DATA RAM", ok) if "LDMAC" in items: # 13:FAE0: DMA every 2 KiB of the ROM, 0E:40 sums it total = page = 0 for bank in range(expect.banks): for block in range(16): source = bank << 16 | 0x8000 | block << 11 h.dma(source, 0x800, 0x006000) h.call(0x0E, 0x40, page) page ^= 1 low = h.register(0) & 0xFFFF doubled = expect.double_from_bank is not None and bank >= expect.double_from_bank total += low * (2 if doubled else 1) total &= 0xFFFF record("LDMAC", total == expect.checksum, f"sum {total:04X}, header {expect.checksum:04X}") if "DOWN LOAD" in items: # 13:FB6D: 0E:00, 0E:04 ... 0E:3C set R0 = 0..15 ok, page = True, 0 for n in range(16): h.call(0x0E, 4 * n, page) page ^= 1 ok &= h.read(0x7F80) == n record("DOWN LOAD", ok) if "MALU" in items: # 13:F99C: R0 = vvvvvvh, 0E:54, R1:R2 against the table ok, value, offset = True, 0xFF, 0x5A while True: for k in range(3): h.write(0x7F80 + k, value) h.call(0x0E, 0x54, 0) got = bytes(h.read(0x7F83 + k) for k in range(6)) ok &= got == expect.malu[offset : offset + 6] if value == 0: break value -= 0x11 offset -= 6 record("MALU", ok) if "IMMEDIATE REGISTER" in items: # 13:F9EF: 0E:5C writes the 16 constants h.call(0x0E, 0x5C, 0) got = bytes(h.read(0x6000 + k) for k in range(0x30)) record("IMMEDIATE REGISTER", got == expect.constants) if "IMMEDIATE ROM" in items: # 13:FA1F: 0E:89 sums the data ROM h.call(0x0E, 0x89, 0) got = h.register(0) record("IMMEDIATE ROM", got == expect.immediate_rom, f"R0 {got:06X}") return result __all__ = [ "CONFIGURATION", "ITEMS", "Expectations", "Harness", "HostTimeout", "SelfTestResult", "find_expectations", "lorom_offset", "mirror", "read_cartridge", "selftest", ]