# SPDX-License-Identifier: MIT """A host that is not a SNES, for the rungs and the command line. The core does not own the S-SMP's I/O page: this is a minimal copy of what the board's ``smp`` module does, enough to run test programs and sound drivers with no S-CPU and no S-DSP audio (docs /handoff-brief.md "The minimal harness"): 64 KiB RAM; $F0-$FF with RAM write-through (B4); the IPL ROM overlay; CONTROL; timers 0-2 at 128/16 cycles (B2); DSP ports as a 128-byte register file with no audio; $F4-$F7 as latches that a script drives; a ``.spc`` loader; and a stop on a branch to itself. TEST ($F0) is stored and otherwise ignored: wait states are the board's (B3). Rung 2's gilyon driver and rung 3's PeterLemon driver are at the end of this module. """ from __future__ import annotations from collections.abc import Callable, Iterable from dataclasses import dataclass, field from pathlib import Path from spc700_python.cpu import SPC700, CPUState SPC_SIGNATURE = b"SNES-SPC700 Sound File Data v0.30" SPC_MINIMUM_SIZE = 0x10180 # header, RAM and the DSP registers IPL_SIZE = 64 IPL_BASE = 0x10000 - IPL_SIZE REFERENCE_IPL = Path(__file__).resolve().parents[2] / "reference" / "build" / "iplrom.bin" #: The conditional branches, whose flags a branch to itself can never change, and BRA, JMP !a. _SELF_BRANCHES = frozenset((0x10, 0x30, 0x50, 0x70, 0x90, 0xB0, 0xD0, 0xF0, 0x2F, 0x5F)) def default_ipl() -> bytes | None: """The IPL ROM built by scripts/build_referees.py, if this checkout has one.""" return REFERENCE_IPL.read_bytes() if REFERENCE_IPL.exists() else None class Timer: """One S-SMP timer: stage 2 counts stage-1 ticks up to the target, stage 3 is 4-bit (B2).""" __slots__ = ("counter", "enabled", "output", "target") def __init__(self) -> None: self.enabled = False self.target = 0 # 0 means 256 self.counter = 0 self.output = 0 def tick(self) -> None: """One stage-1 tick.""" if self.enabled: self.counter = (self.counter + 1) & 0xFF if self.counter == self.target: self.counter = 0 self.output = (self.output + 1) & 0x0F def enable(self, on: bool) -> None: """Stages 2 and 3 reset on a 0 to 1 edge of the enable bit (anomie, B2).""" if on and not self.enabled: self.counter = self.output = 0 self.enabled = on @dataclass(frozen=True, slots=True) class RunResult: """How a bounded run ended.""" reason: str # "self-branch", "stopped", "finished" (the script said so) or "max-cycles" cycles: int instructions: int class Harness: """The core on 64 KiB RAM with a minimal S-SMP I/O page, the host of rungs 2 to 4.""" def __init__(self, ipl: bytes | None = None) -> None: if ipl is not None and len(ipl) != IPL_SIZE: raise ValueError("the IPL ROM is 64 bytes") self.ram = bytearray(0x10000) self.ipl = ipl self.ipl_mapped = ipl is not None self.cycles = 0 self.timers = (Timer(), Timer(), Timer()) self.dsp = bytearray(128) self.dsp_address = 0 self.ports_in = bytearray(4) # what the S-SMP reads at $F4-$F7: the S-CPU's last writes self.ports_out = bytearray(4) # what it wrote there: the S-CPU reads these self.port_log: list[tuple[int, int, int]] = [] # (cycle, port 0-3, value), every write #: The scripted S-CPU: called after each S-SMP port write with (port, value). self.on_port_write: Callable[[int, int], None] | None = None self.finished = False # a script sets this to end the run self.cpu = SPC700(self.read, self.write, self._tick) # ----- the clock -------------------------------------------------------- def _tick(self) -> None: """One SPC700 cycle: stage 1 is 128 cycles for timers 0 and 1, 16 for timer 2 (B2).""" self.cycles += 1 if not self.cycles & 15: self.timers[2].tick() if not self.cycles & 127: self.timers[0].tick() self.timers[1].tick() # ----- the bus ---------------------------------------------------------- def read(self, address: int) -> int: self._tick() if 0xF0 <= address <= 0xFF: return self._read_io(address) if address >= IPL_BASE and self.ipl_mapped: return self.ipl[address - IPL_BASE] # type: ignore[index] return self.ram[address] def write(self, address: int, value: int) -> None: self._tick() self.ram[address] = value # B4: even I/O writes reach the RAM beneath, and $FFC0+ is RAM if 0xF0 <= address <= 0xFF: self._write_io(address, value) def peek(self, address: int) -> int: """What a read would return, with no side effect and no cycle.""" if address >= IPL_BASE and self.ipl_mapped: return self.ipl[address - IPL_BASE] # type: ignore[index] return self.ram[address] def _read_io(self, address: int) -> int: match address: case 0xF0 | 0xF1 | 0xFA | 0xFB | 0xFC: return 0 # write-only case 0xF2: return self.dsp_address case 0xF3: return self.dsp[self.dsp_address & 0x7F] # B5: $80-$FF mirror $00-$7F case 0xF4 | 0xF5 | 0xF6 | 0xF7: return self.ports_in[address - 0xF4] case 0xF8 | 0xF9: return self.ram[address] case _: timer = self.timers[address - 0xFD] value = timer.output timer.output = 0 # B2: reading clears, a dummy read too return value def _write_io(self, address: int, value: int) -> None: match address: case 0xF1: self._write_control(value) case 0xF2: self.dsp_address = value case 0xF3: if self.dsp_address < 0x80: # B5: writes to the mirror are ignored self.dsp[self.dsp_address] = value case 0xF4 | 0xF5 | 0xF6 | 0xF7: port = address - 0xF4 self.ports_out[port] = value self.port_log.append((self.cycles, port, value)) if self.on_port_write is not None: self.on_port_write(port, value) case 0xFA | 0xFB | 0xFC: self.timers[address - 0xFA].target = value case _: pass # TEST, AUXIO and the read-only counters: the RAM write is all there is def _write_control(self, value: int) -> None: for bit, timer in enumerate(self.timers): timer.enable(bool(value >> bit & 1)) if value & 0x10: # every time a 1 is written, not on an edge (B1) self.ports_in[0] = self.ports_in[1] = 0 if value & 0x20: self.ports_in[2] = self.ports_in[3] = 0 self.ipl_mapped = bool(value & 0x80) and self.ipl is not None # ----- loading ---------------------------------------------------------- def load_program(self, data: bytes, org: int = 0x0300) -> None: """Put a raw program at ``org`` and enter it as the IPL ROM would: A = X = Y = 0, PSW = $02, SP = $EF (U12), the IPL ROM still mapped.""" self.ram[org : org + len(data)] = data[: 0x10000 - org] self.cpu.restore_state(CPUState(pc=org)) def load_spc(self, data: bytes) -> None: """Load a ``.spc`` snapshot: registers at $25-$2B, RAM at $100, DSP at $10100, the 64 bytes under the IPL ROM at $101C0 (the SPC file format document, "SNES-SPC700 Sound File Data v0.30").""" if data[:27] != SPC_SIGNATURE[:27] or len(data) < SPC_MINIMUM_SIZE: raise ValueError("not a SNES-SPC700 sound file") self.ram[:] = data[0x100:0x10100] self.dsp[:] = data[0x10100:0x10180] self.dsp_address = self.ram[0xF2] self.ports_in[:] = self.ram[0xF4:0xF8] for index, timer in enumerate(self.timers): timer.target = self.ram[0xFA + index] timer.output = self.ram[0xFD + index] & 0x0F timer.enabled = bool(self.ram[0xF1] >> index & 1) self.ipl_mapped = bool(self.ram[0xF1] & 0x80) and self.ipl is not None if self.ram[0xF1] & 0x80 and len(data) >= 0x10200: self.ram[IPL_BASE:] = data[0x101C0:0x10200] self.cpu.restore_state( CPUState( a=data[0x27], x=data[0x28], y=data[0x29], sp=data[0x2B], pc=data[0x26] << 8 | data[0x25], psw=data[0x2A], ) ) def load_file(self, data: bytes, org: int = 0x0300) -> None: """A ``.spc`` snapshot if it has the signature, otherwise a raw program at ``org``. (PeterLemon's per-test ``ADC/SPC700ADC.spc`` is a raw program for $0200 despite the extension; his top-level ``SPC700ADC.spc`` is a snapshot.)""" if data[:27] == SPC_SIGNATURE[:27]: self.load_spc(data) else: self.load_program(data, org) # ----- running ---------------------------------------------------------- def run( self, *, max_cycles: int = 100_000_000, step: Callable[[], int] | None = None ) -> RunResult: """Run until a branch to itself, a stopped CPU, a finished script, or ``max_cycles`` more cycles. ``step`` replaces ``cpu.step`` (a tracing session's).""" cpu = self.cpu step = step or cpu.step end = self.cycles + max_cycles start = self.cycles instructions = 0 reason = "max-cycles" while self.cycles < end: if self.finished: reason = "finished" break if cpu.stopped: reason = "stopped" break pc = cpu.pc step() instructions += 1 if cpu.pc == pc and cpu.opcode in _SELF_BRANCHES: reason = "self-branch" break return RunResult(reason, self.cycles - start, instructions) # ----- rung 2: gilyon's spctest --------------------------------------------------------------- @dataclass(slots=True) class SpcTestReport: """What the three programs of gilyon's spctest reported.""" tests: list[int] = field(default_factory=list) # every test number, in the order it started failure: tuple[int, int, int, int, int] | None = None # test, PSW, A, X, Y cycles: int = 0 instructions: int = 0 programs: int = 0 @property def passed(self) -> bool: return self.failure is None and self.tests == list(range(len(self.tests))) def run_spctest(programs: Iterable[bytes], *, max_cycles: int = 400_000_000) -> SpcTestReport: """Play the S-CPU side of spctest's port protocol (``spc_common.inc``, ``spctest.asm``). Each program loads at $0300 and waits for port 1 = 1, with ports 2/3 = one less than the first test number. It writes each test's number to ports 2/3, and port 0 = 1 at the end, or 2 then 3 with the failing test's result on ports 1 to 3. Test numbers are checked to run from 0 with no gap, so a skipped test cannot pass unseen. """ report = SpcTestReport() last_test = 0xFFFF # one less than test 0 for program in programs: harness = Harness() harness.load_program(program, 0x0300) harness.ports_in[1] = 1 harness.ports_in[2], harness.ports_in[3] = last_test & 0xFF, last_test >> 8 failing: list[int] = [] # the PSW the failing test left, once the program says it failed def on_write( port: int, value: int, host: Harness = harness, failing: list[int] = failing ) -> None: if port == 3 and not failing: # MOVW $F6,YA writes the low byte, then the high one report.tests.append(host.ports_out[2] | value << 8) elif port == 0 and value == 1: host.finished = True elif port == 0 and value == 2: failing.append(host.ports_out[1]) host.ports_in[1] = 2 # the program waits for this before giving A, X and Y elif port == 0 and value == 3: host.finished = True harness.on_port_write = on_write result = harness.run(max_cycles=max_cycles) report.cycles += result.cycles report.instructions += result.instructions report.programs += 1 final = harness.ports_out[0] if final == 3: out = harness.ports_out report.failure = (report.tests[-1], failing[0], out[1], out[2], out[3]) return report if result.reason != "finished" or final != 1: report.failure = (report.tests[-1] if report.tests else -1, -1, -1, -1, -1) return report last_test = report.tests[-1] return report # ----- rung 3: PeterLemon's CPU tests --------------------------------------------------------- @dataclass(frozen=True, slots=True) class CpuTestReport: """One PeterLemon CPU test: the codes it wrote to $F4 and how it ended.""" codes: tuple[int, ...] reason: str cycles: int instructions: int @property def passes(self) -> tuple[int, ...]: return tuple(code for code in self.codes if not code & 0x80) @property def failures(self) -> tuple[int, ...]: return tuple(code for code in self.codes if code & 0x80) def run_cpu_test(program: bytes, *, max_cycles: int = 400_000_000) -> CpuTestReport: """Run a PeterLemon program (raw, from its ``SPCRAM`` $0200, or a snapshot) until its final ``jmp Loop``, or its ``bra Fail`` loop, and collect the $F4 writes: $0n pass, $8n fail.""" harness = Harness() harness.load_file(program, 0x0200) result = harness.run(max_cycles=max_cycles) codes = tuple(value for _, port, value in harness.port_log if port == 0) return CpuTestReport(codes, result.reason, result.cycles, result.instructions) __all__ = [ "CpuTestReport", "Harness", "RunResult", "SpcTestReport", "Timer", "default_ipl", "run_cpu_test", "run_spctest", ]