# SPDX-License-Identifier: MIT """A minimal SNES-shaped host for CPU test ROMs: enough machine to run them, no PPU. Not a SNES (that is snes-python's job): a LoROM or HiROM cartridge, 128 KiB of WRAM at $7E-$7F mirrored at $0000-$1FFF of banks $00-$3F/$80-$BF, and the few registers CPU test ROMs touch on their way to drawing a verdict (docs/validation.md, "The minimal harness"): - the VRAM port ($2115-$2119) into a 64 KiB array, so the text a ROM prints can be read back with :meth:`Harness.screen`; - the WRAM port ($2180-$2183), the multiplier and divider ($4202-$4206, results at once), and general-purpose DMA ($420B, $43x0-$43x6), done instantly between two cycles; - a "frame" of ``frame_cycles`` CPU cycles whose last eighth is vblank: $4210 bit 7 sets as it starts and clears when read, $4212 bit 7 is high through it, and an NMI is raised there when $4200 bit 7 enables it; - the APU ports ($2140-$2143) read $AA, $BB, 0, 0 until written, then echo what was written, which satisfies the IPL handshake's wait loops; - open bus elsewhere: the last value on the data bus. Timing is the CPU's cycle count only: every callback is one cycle whatever the region's speed, no DRAM refresh, no DMA cycles. Only the order of events matters to the ROMs this runs. """ from __future__ import annotations import subprocess import tempfile import zipfile from collections.abc import Callable from dataclasses import dataclass from pathlib import Path from w65c816.cpu import W65C816 #: Bytes moved to B-bus addresses $21xx + offset, per DMA transfer mode ($43x0 bits 0-2). DMA_PATTERNS = ( (0,), (0, 1), (0, 0), (0, 0, 1, 1), (0, 1, 2, 3), (0, 1, 0, 1), (0, 0), (0, 0, 1, 1), ) VRAM_STEPS = (1, 32, 128, 128) WRAM_SIZE = 0x20000 #: Jump-to-self opcodes: BRA, JMP a, JML al. A ROM that has finished spins on one. SPIN_OPCODES = frozenset((0x80, 0x4C, 0x5C)) @dataclass class RunResult: """Why :meth:`Harness.run` stopped, and when.""" reason: str # "spin", "stopped", "condition" or "cycles" cycles: int pc: int # 24-bit, PBR:PC def lorom_offset(bank: int, offset: int) -> int | None: if offset >= 0x8000 or 0x40 <= bank & 0x7F < 0x7E: return (bank & 0x7F) << 15 | offset & 0x7FFF return None def hirom_offset(bank: int, offset: int) -> int | None: # Banks $C0-$FF are ROM throughout; only $7E-$7F are WRAM, not $FE-$FF. if offset >= 0x8000 or 0x40 <= bank & 0x7F < 0x7E or bank >= 0xFE: return (bank & 0x3F) << 16 | offset return None def load_rom(path: str | Path) -> bytes: """A cartridge image from ``.sfc``/``.smc``, or the first one inside a ``.zip`` or ``.7z`` (7z through the ``7z`` program), without the 512-byte copier header some dumps carry.""" path = Path(path) suffix = path.suffix.lower() if suffix == ".zip": with zipfile.ZipFile(path) as archive: names = sorted(n for n in archive.namelist() if n.lower().endswith((".sfc", ".smc"))) if not names: raise ValueError(f"no .sfc/.smc in {path}") data = archive.read(names[0]) elif suffix == ".7z": with tempfile.TemporaryDirectory() as scratch: subprocess.run(["7z", "e", "-y", f"-o{scratch}", str(path)], check=True, stdout=subprocess.DEVNULL) # fmt: skip inside = sorted( p for p in Path(scratch).iterdir() if p.suffix.lower() in (".sfc", ".smc") ) if not inside: raise ValueError(f"no .sfc/.smc in {path}") data = inside[0].read_bytes() else: data = path.read_bytes() return data[512:] if len(data) % 0x8000 == 512 else data def detect_mapping(rom: bytes) -> str: """'lorom' or 'hirom', by which header's checksum complement adds up.""" for name, base in (("lorom", 0x7FC0), ("hirom", 0xFFC0)): if len(rom) >= base + 0x20: checksum = rom[base + 0x1E] | rom[base + 0x1F] << 8 complement = rom[base + 0x1C] | rom[base + 0x1D] << 8 if checksum ^ complement == 0xFFFF: return name return "lorom" class Harness: """Run a ROM on a W65C816 with WRAM, a cartridge and the registers above. ``cpu`` is the core, reset and ready to :meth:`run`; ``wram`` and ``vram`` are bytearrays the ROM's results can be read from. """ def __init__(self, rom: bytes, mapping: str | None = None, frame_cycles: int = 30_000) -> None: self.rom = bytes(rom) self.mapping = mapping or detect_mapping(self.rom) self._rom_offset = lorom_offset if self.mapping == "lorom" else hirom_offset self.wram = bytearray(WRAM_SIZE) self.vram = bytearray(0x10000) self.frame_cycles = frame_cycles self.cycles = 0 self.open_bus = 0 self.vram_address = 0 self.vram_control = 0 self.wram_address = 0 self.nmi_enable = 0 self.nmi_flag = False self.apu_ports = bytearray((0xAA, 0xBB, 0, 0)) self.math = bytearray(8) # $4202-$4206 written, results at $4214-$4217 self.dma = bytearray(0x80) # $4300-$437F self.cpu = W65C816(self.read_byte, self.write_byte, self.idle) self.cpu.request_reset() # -- the bus --------------------------------------------------------- def _tick(self) -> None: self.cycles += 1 position = self.cycles % self.frame_cycles if position == self.frame_cycles - self.frame_cycles // 8: self.nmi_flag = True if self.nmi_enable & 0x80: self.cpu.request_non_maskable_interrupt() def in_vblank(self) -> bool: return self.cycles % self.frame_cycles >= self.frame_cycles - self.frame_cycles // 8 def read_byte(self, address: int) -> int: self._tick() value = self.peek(address) self.open_bus = value return value def write_byte(self, address: int, value: int) -> None: self._tick() self.open_bus = value self.poke(address, value) def idle(self, address: int) -> None: self._tick() def peek(self, address: int) -> int: """Read ``address`` as the bus would, without a cycle (DMA's A-bus side).""" bank, offset = address >> 16, address & 0xFFFF if bank & 0xFE == 0x7E: return self.wram[(bank & 1) << 16 | offset] if bank & 0x7F < 0x40 and offset < 0x8000: if offset < 0x2000: return self.wram[offset] return self.io_read(offset) rom = self._rom_offset(bank, offset) if rom is not None and self.rom: return self.rom[rom % len(self.rom)] return self.open_bus def inspect(self, address: int) -> int: """Read ``address`` with no side effects at all, for a debugger: WRAM and ROM as :meth:`peek` reads them; I/O registers as the open bus, since reading one can change it ($4210, $2180).""" bank, offset = address >> 16, address & 0xFFFF if bank & 0x7F < 0x40 and 0x2000 <= offset < 0x8000: return self.open_bus return self.peek(address) def poke(self, address: int, value: int) -> None: bank, offset = address >> 16, address & 0xFFFF if bank & 0xFE == 0x7E: self.wram[(bank & 1) << 16 | offset] = value elif bank & 0x7F < 0x40 and offset < 0x8000: if offset < 0x2000: self.wram[offset] = value else: self.io_write(offset, value) # -- registers ------------------------------------------------------- def io_read(self, offset: int) -> int: if 0x2140 <= offset < 0x2180: return self.apu_ports[offset & 3] if offset == 0x2180: value = self.wram[self.wram_address] self.wram_address = (self.wram_address + 1) % WRAM_SIZE return value if offset == 0x4210: value = 0x82 if self.nmi_flag else 0x02 # bit 7 NMI flag, version 2 self.nmi_flag = False return value | self.open_bus & 0x70 if offset == 0x4211: return self.open_bus & 0x7F if offset == 0x4212: return (0x80 if self.in_vblank() else 0) | self.open_bus & 0x3E if 0x4214 <= offset <= 0x4217: return self.math[offset - 0x4214 + 4] if 0x4218 <= offset <= 0x421F: return 0 # no buttons held if 0x4300 <= offset < 0x4380: return self.dma[offset - 0x4300] return self.open_bus def io_write(self, offset: int, value: int) -> None: if offset == 0x2115: self.vram_control = value elif offset == 0x2116: self.vram_address = self.vram_address & 0xFF00 | value elif offset == 0x2117: self.vram_address = value << 8 | self.vram_address & 0xFF elif offset in (0x2118, 0x2119): high = offset == 0x2119 self.vram[(self.vram_address << 1 | high) & 0xFFFF] = value if high == bool(self.vram_control & 0x80): step = VRAM_STEPS[self.vram_control & 3] self.vram_address = (self.vram_address + step) & 0xFFFF elif 0x2140 <= offset < 0x2180: self.apu_ports[offset & 3] = value elif offset == 0x2180: self.wram[self.wram_address] = value self.wram_address = (self.wram_address + 1) % WRAM_SIZE elif 0x2181 <= offset <= 0x2183: shift = (offset - 0x2181) * 8 address = self.wram_address & ~(0xFF << shift) | value << shift self.wram_address = address % WRAM_SIZE elif offset == 0x4200: self.nmi_enable = value elif 0x4202 <= offset <= 0x4206: self.math[offset - 0x4202] = value self._arithmetic(offset) elif offset == 0x420B: for channel in range(8): if value >> channel & 1: self._dma(channel) elif 0x4300 <= offset < 0x4380: self.dma[offset - 0x4300] = value def _arithmetic(self, offset: int) -> None: """$4203 starts an 8x8 multiply, $4206 a 16/8 divide; both finish at once.""" multiplicand, multiplier, dividend_low, dividend_high, divisor = self.math[:5] if offset == 0x4203: product = multiplicand * multiplier self.math[4:8] = bytes((dividend_low, dividend_high, product & 0xFF, product >> 8)) elif offset == 0x4206: dividend = dividend_low | dividend_high << 8 quotient, remainder = (dividend // divisor, dividend % divisor) if divisor else ( 0xFFFF, dividend) # fmt: skip self.math[4:8] = bytes( (quotient & 0xFF, quotient >> 8, remainder & 0xFF, remainder >> 8) ) def _dma(self, channel: int) -> None: """One general-purpose DMA channel, all at once (A-bus to B-bus or back).""" registers = self.dma[channel * 16 : channel * 16 + 16] control, b_address = registers[0], registers[1] a_offset = registers[2] | registers[3] << 8 a_bank = registers[4] count = registers[5] | registers[6] << 8 or 0x10000 pattern = DMA_PATTERNS[control & 7] a_step = 0 if control & 0x08 else -1 if control & 0x10 else 1 for index in range(count): b_target = 0x2100 | (b_address + pattern[index % len(pattern)]) & 0xFF a_target = a_bank << 16 | a_offset if control & 0x80: self.poke(a_target, self.io_read(b_target)) else: self.io_write(b_target, self.peek(a_target)) a_offset = (a_offset + a_step) & 0xFFFF base = channel * 16 self.dma[base + 2], self.dma[base + 3] = a_offset & 0xFF, a_offset >> 8 self.dma[base + 5] = self.dma[base + 6] = 0 # -- running --------------------------------------------------------- def screen(self, map_word: int, rows: int = 32) -> list[str]: """The text of a 32-column tilemap at VRAM word ``map_word``, one line per row: each entry's low byte as ASCII, anything unprintable as a space.""" lines = [] for row in range(rows): base = (map_word + row * 32) * 2 codes = self.vram[base : base + 64 : 2] lines.append("".join(chr(c) if 0x20 <= c < 0x7F else " " for c in codes).rstrip()) return lines def run( self, max_cycles: int, until: Callable[[Harness], bool] | None = None, step: Callable[[], object] | None = None, ) -> RunResult: """Step until the ROM spins on a jump to itself, STP, ``until(self)`` (checked after each instruction) or ``max_cycles`` more cycles. ``step`` replaces ``cpu.step`` (a debug session's, to trace the run).""" cpu = self.cpu step = cpu.step if step is None else step limit = self.cycles + max_cycles reason = "cycles" while self.cycles < limit: before = cpu.pbr << 16 | cpu.pc step() if cpu.stopped: reason = "stopped" break if (cpu.pbr << 16 | cpu.pc) == before and self.peek(before) in SPIN_OPCODES: reason = "spin" break if until is not None and until(self): reason = "condition" break return RunResult(reason, self.cycles, cpu.pbr << 16 | cpu.pc)