# SPDX-License-Identifier: MIT """A board-free test rig: the core on a 1 MiB LoROM image, programs placed as words.""" from __future__ import annotations from hg51b_python import HG51B BASE = 0x028000 # the games' cache base ($7F49-$7F4B) def linear(address: int) -> int: """LoROM: banks 00-3F/80-BF $8000-$FFFF and C0-FF $0000-$FFFF (ares ``hitachidsp/memory.cpp`` ``addressROM``).""" return ((address & 0x3F0000) >> 1 | (address & 0x7FFF)) & 0xFFFFF class Rig: def __init__(self, core: type[HG51B] = HG51B, *, configure: bool = True) -> None: self.rom = bytearray(0x100000) self.sram_writes: list[tuple[int, int]] = [] self.reads: list[int] = [] self.cx = core(self.bus_read, self.bus_write) if configure: # the games' setup (MAME host log): ROM wait 4, RAM wait 4, IRQ off for address, value in ((0x7F52, 0), (0x7F50, 0x44), (0x7F51, 1), (0x7F4C, 0)): self.cx.write(address, value) self.set_base(BASE) def bus_read(self, address: int) -> int: self.reads.append(address) return self.rom[linear(address)] def bus_write(self, address: int, value: int) -> None: self.sram_writes.append((address, value)) def set_base(self, base: int) -> None: for i in range(3): self.cx.write(0x7F49 + i, base >> (8 * i) & 0xFF) def poke(self, address: int, data: bytes) -> None: for offset, value in enumerate(data): self.rom[linear(address + offset)] = value def place(self, words: list[int], page: int = 0, pc: int = 0, base: int = BASE) -> None: """Put words at PB ``page``, PC ``pc`` of the program (base + page x 512).""" data = b"".join(word.to_bytes(2, "little") for word in words) self.poke(base + page * 512 + pc * 2, data) def start(self, pc: int = 0, pb: int = 0) -> None: self.cx.write(0x7F4D, pb & 0xFF) self.cx.write(0x7F4E, pb >> 8) self.cx.write(0x7F4F, pc) def finish(self, budget: int = 1_000_000) -> int: """Run until the chip is idle; returns the clocks it took.""" start = self.cx.clock while self.cx.running: # unit by unit, so the clock count is exact self.cx.step() if self.cx.clock - start > budget: raise AssertionError("the chip did not stop") return self.cx.clock - start def execute(self, words: list[int], *, pc: int = 0, pb: int = 0) -> HG51B: """Place ``words`` + HALT, start, run to the HALT. The rig forgets what the cache holds first (a test convenience: the chip cannot see the ROM change).""" self.place([*words, 0xFC00], page=pb, pc=pc) self.cx.cache_address[:] = [-1, -1] self.start(pc, pb) self.finish() return self.cx