# SPDX-License-Identifier: MIT """The minimal harness: a host that is not a GBA, for test ROMs that need only memory. It maps what jsmolka's and alyosha-tas's CPU tests touch (docs/handoff-brief.md "The minimal harness"): the cartridge ROM at ``0x08000000`` (mirrored through ``0x0DFFFFFF``), 256 KiB at ``0x02000000``, 32 KiB at ``0x03000000``, I/O at ``0x04000000`` as plain RAM except DISPSTAT (``0x04000004``), whose VBlank bit toggles on every read so a wait for VBlank completes, palette, VRAM and OAM as RAM, and 64 KiB of SRAM at ``0x0E000000``. Like the GBA's bus it ignores the low address bits a width does not use. There is no BIOS: a fetch below ``0x00004000`` (an SWI or any exception) stops the run with an error. It starts as the GBA's BIOS leaves a cartridge: System mode, ARM state, PC ``0x08000000``, SP_sys ``0x03007F00``, SP_irq ``0x03007FA0``, SP_svc ``0x03007FE0`` (GBATEK "BIOS RAM Usage"), and stops when the next instruction is a branch to itself. """ from __future__ import annotations import struct from collections.abc import Callable from dataclasses import dataclass from arm7tdmi_python.cpu import ARM7TDMI from arm7tdmi_python.state import CPUState SYS, SVC_BANK, IRQ_BANK = 0x1F, 2, 4 Observer = Callable[[str, int, int, int, int], None] # kind, address, width, access, value ARM_BRANCH_TO_SELF = 0xEAFFFFFE THUMB_BRANCH_TO_SELF = 0xE7FE DISPSTAT = 0x04000004 def elf_image(data: bytes) -> tuple[list[tuple[int, bytes]], int]: """The loadable segments of a 32-bit little-endian ARM ELF executable, as (physical address, bytes), and its entry point (bit 0 set for Thumb). The physical address is where a GBA image's ``.data`` sits in ROM before its start-up code copies it to RAM.""" if data[:4] != b"\x7fELF" or data[4] != 1 or data[5] != 1: raise ValueError("not a 32-bit little-endian ELF file") machine, entry = int.from_bytes(data[18:20], "little"), int.from_bytes(data[24:28], "little") if machine != 40: raise ValueError(f"ELF machine {machine} is not ARM (40)") table = int.from_bytes(data[28:32], "little") size, count = int.from_bytes(data[42:44], "little"), int.from_bytes(data[44:46], "little") segments = [] for n in range(count): header = data[table + n * size : table + (n + 1) * size] kind, offset, _, physical, file_size = struct.unpack_from("<5I", header) if kind == 1 and file_size: # PT_LOAD segments.append((physical, data[offset : offset + file_size])) return segments, entry class EnteredBIOS(RuntimeError): """The program fetched from the BIOS region: an SWI or an exception, which this host has no BIOS for. jsmolka's result screen divides with SWI 6 only when a test failed, so this is how such a failure ends; ``r12`` holds the result register at that point.""" r12: int = 0 @dataclass class Region: memory: bytearray mask: int # address bits that select a byte inside the region (its mirror) class Harness: def __init__(self, rom: bytes, *, observer: Observer | None = None) -> None: size = 1 << max(len(rom) - 1, 1).bit_length() self.rom = bytearray(rom) + bytearray(size - len(rom)) self.regions: dict[int, Region] = { 0x02: Region(bytearray(0x40000), 0x3FFFF), 0x03: Region(bytearray(0x8000), 0x7FFF), 0x04: Region(bytearray(0x400), 0x3FF), 0x05: Region(bytearray(0x400), 0x3FF), 0x06: Region(bytearray(0x20000), 0x1FFFF), 0x07: Region(bytearray(0x400), 0x3FF), 0x0E: Region(bytearray(0x10000), 0xFFFF), } rom_region = Region(self.rom, size - 1) for page in range(0x08, 0x0E): self.regions[page] = rom_region # one Region, so a resize reaches every mirror self.vblank = False self.observer = observer self.cpu = ARM7TDMI(self.read, self.write, self.idle) self.cycles = 0 banks = [[0] * 7 for _ in range(6)] banks[SVC_BANK][5] = 0x03007FE0 banks[IRQ_BANK][5] = 0x03007FA0 registers = [0] * 16 registers[13] = 0x03007F00 self.cpu.restore_state(CPUState(registers=registers, banks=banks, cpsr=SYS)) self.cpu.start_at(0x08000000) # ------------------------------------------------------------------ the bus def _locate(self, address: int, width: int) -> tuple[Region | None, int]: region = self.regions.get(address >> 24) address &= ~(width // 8 - 1) # the bus ignores the low bits the width does not use return region, (address & region.mask) if region else 0 def read(self, address: int, width: int, access: int) -> int: if address < 0x4000: raise EnteredBIOS(f"fetch or read at {address:08x}: no BIOS in the harness") if address & ~3 == DISPSTAT: self.vblank = not self.vblank self.regions[0x04].memory[4] = (self.regions[0x04].memory[4] & ~1) | self.vblank region, offset = self._locate(address, width) value = ( int.from_bytes(region.memory[offset : offset + width // 8], "little") if region else 0 ) self.cycles += 1 if self.observer: self.observer("read", address, width, access, value) return value def write(self, address: int, width: int, value: int, access: int) -> None: region, offset = self._locate(address, width) if region and region.memory is not self.rom: region.memory[offset : offset + width // 8] = value.to_bytes(width // 8, "little") self.cycles += 1 if self.observer: self.observer("write", address, width, access, value) def idle(self, address: int) -> None: self.cycles += 1 if self.observer: self.observer("internal", address, 0, 0, 0) def peek(self, address: int) -> int: """The byte at ``address`` without a bus cycle or any side effect (DISPSTAT does not toggle): for disassembly and memory views. Unmapped addresses read 0.""" region = self.regions.get((address >> 24) & 0xFF) return region.memory[address & region.mask] if region else 0 def load(self, address: int, data: bytes) -> None: """Copy ``data`` into memory at ``address``, cartridge ROM included (it grows, to the next power of two, if the image runs past its end); no bus cycles.""" if (address >> 24) in range(0x08, 0x0E): end = (address & 0x01FFFFFF) + len(data) if end > len(self.rom): size = 1 << max(end - 1, 1).bit_length() self.rom.extend(bytearray(size - len(self.rom))) self.regions[0x08].mask = size - 1 # every ROM page shares this Region for offset, byte in enumerate(data): target = (address + offset) & 0xFFFFFFFF region = self.regions.get(target >> 24) if region is None: raise ValueError(f"nothing is mapped at {target:08X}") region.memory[target & region.mask] = byte def start(self, address: int, *, thumb: bool = False) -> None: """Start running at ``address``, in Thumb state if ``thumb`` (two refill fetches).""" state = self.cpu.capture_state() state.cpsr = (state.cpsr & ~0x20) | (0x20 if thumb else 0) self.cpu.restore_state(state) self.cpu.start_at(address) # ------------------------------------------------------------------ running def at_branch_to_self(self) -> bool: cpu = self.cpu if cpu.thumb: return cpu.pipeline[0] == THUMB_BRANCH_TO_SELF return cpu.pipeline[0] == ARM_BRANCH_TO_SELF def run(self, max_cycles: int = 50_000_000) -> int: """Run until a branch to itself; return R12, the jsmolka/alyosha-tas result register (0 = all passed, otherwise the first failing test's number).""" cpu = self.cpu while not self.at_branch_to_self(): if self.cycles >= max_cycles: raise TimeoutError(f"no branch to itself within {max_cycles:,} cycles") try: cpu.step() except EnteredBIOS as error: error.r12 = cpu.r[12] raise return cpu.r[12]