#!/usr/bin/env python3 """Run a ROM here and on NanoBoyAdvance 1.8.3 instruction by instruction; report where they part. NanoBoyAdvance is a detector (docs/validation.md), so a divergence is a question, not a verdict: it points at the instruction where the two disagree about the cycle count, and the hardware test that covers that behaviour decides. Each side lists, per executed instruction, the system-clock cycle at which it starts and R15 (its address + 8, or + 4 in Thumb), after any IRQ entry. ``scripts/nba_driver/trace.cc`` (``nba_trace``, built by ``scripts/build_referees.py --nba``) prints NBA's. python scripts/nba_lockstep.py ROM.gba --skip 0 --count 2000000 python scripts/nba_lockstep.py ROM.gba --bios BIOS.bin --context 8 python scripts/nba_lockstep.py GAME.zip --skip-bios --nba-model all # a smoke entry """ from __future__ import annotations import argparse import subprocess import sys import tempfile from collections import deque from collections.abc import Iterator from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) from gba_python import GBA, trace # noqa: E402 from gba_python import bios as bios_module # noqa: E402 from gba_python.testrom import read_rom # noqa: E402 NBA_TRACE = ROOT / "reference" / "build" / "nba" / "nba_trace" FRAME = 280896 def nba_lines( rom: Path, bios: Path, skip: int, count: int, keys: list[str], regs: bool = False, binary: Path = NBA_TRACE, skip_bios: bool = False, ) -> Iterator[tuple[int, ...]]: command = [ str(binary), str(rom), "--bios", str(bios), "--skip", str(skip), "--count", str(count), ] for key in keys: command += ["--keys", key] if regs: command.append("--regs") if skip_bios: command.append("--skip-bios") with subprocess.Popen(command, stdout=subprocess.PIPE, text=True, bufsize=1 << 20) as process: assert process.stdout is not None for line in process.stdout: yield tuple(int(field, 16) for field in line.split()) process.stdout.close() process.kill() def board_lines( gba: GBA, skip: int, count: int, keys: dict[int, int], regs: bool = False ) -> Iterator[tuple[int, ...]]: cpu = gba.cpu scheduler = gba.scheduler executed = 0 frame = 0 next_frame = FRAME if 0 in keys: gba.keypad.set_pressed(keys[0]) while executed < skip + count: if scheduler.now >= next_frame: frame += 1 next_frame += FRAME if frame in keys: gba.keypad.set_pressed(keys[frame]) if gba.halted: gba._run_halted(scheduler.now + 1 << 40) continue if (cpu.irq and not cpu._irq_masked) or (cpu.fiq and not cpu._fiq_masked): cpu.step() # the IRQ entry: NBA counts it with the handler's first instruction continue if executed >= skip: if regs: yield scheduler.now, cpu.r[15], *cpu.r[:15] else: yield scheduler.now, cpu.r[15] executed += 1 cpu.step() def nba_prefetch(gba: GBA) -> None: """Swap the board's prefetch buffer for NBA 1.8.3's (``Bus::Prefetch``, ``StopPrefetch``, ``Step``): opcodes, not halfwords (an ARM word is one entry); a full buffer keeps counting and hands out opcodes it never fetched; no stop at a 128 KiB boundary; an opcode in flight is waited for whatever the buffer holds and however the CPU got there. For looking past those differences only (docs/validation.md).""" scheduler = gba.scheduler state = {"thumb": True} def step(cycles: int) -> None: target = scheduler.now + cycles if target >= scheduler.next_time: scheduler.run_until(target) else: scheduler.now = target if gba.pf_active: gba.pf_countdown -= cycles while gba.pf_countdown <= 0: gba.pf_count += 1 if gba.prefetch_enabled and gba.pf_count < gba.pf_capacity: gba.pf_last += gba.pf_width gba.pf_countdown += gba.pf_duty else: break def stop() -> None: if gba.pf_active: if 0x08000000 <= gba.cpu.r[15] <= 0x0DFFFFFF: countdown = gba.pf_countdown if countdown == 1 or (not state["thumb"] and countdown == (gba.pf_duty >> 1) + 1): step(1) gba.pf_active = False def rom_access(address: int, code: bool, sequential: bool, cycles: int) -> None: if not code: stop() step(cycles) return if gba.pf_active: if gba.pf_count and address == gba.pf_head: gba.pf_count -= 1 gba.pf_head += gba.pf_width step(1) return if gba.pf_countdown > 0 and address == gba.pf_last: step(gba.pf_countdown) gba.pf_head = gba.pf_last gba.pf_count = 0 return stop() if gba.prefetch_was_disabled: region = (address >> 25) - 4 n16, s16 = gba.rom_n[0], gba.rom_s[region] if cycles == s16: cycles = n16 elif cycles == 2 * s16: cycles = gba.rom_n[0] + gba.rom_s[0] gba.prefetch_was_disabled = False step(cycles) if gba.prefetch_enabled: region = (address >> 25) - 4 thumb = state["thumb"] = gba.cpu.thumb gba.pf_active = True gba.pf_count = 0 if thumb: gba.pf_width, gba.pf_capacity = 2, 8 gba.pf_duty = gba.rom_s[region] else: gba.pf_width, gba.pf_capacity = 4, 4 gba.pf_duty = 2 * gba.rom_s[region] gba.pf_countdown = gba.pf_duty gba.pf_last = gba.pf_head = address + gba.pf_width gba.step = step gba._stop_prefetch = stop gba._rom_access = rom_access #: Where the board knowingly differs from NBA 1.8.3, each with the evidence the board follows #: (docs/undocumented-behavior.md). ``--nba-model`` swaps them for NBA's, to look past them. NBA_PARTS = { "irq": "the CPU looks at its IRQ input at the start of an access, a cycle after the " "synchronizer, which waits with the CPU for a DMA; NBA: at the instruction boundary, two " "cycles, no wait (quirks 10, 23; alyosha-tas irq/halt_pc, Interactions/*)", "data-bus": "open bus after a CPU data access to IWRAM, OAM or the Game Pak is that data " "(quirk 24; alyosha-tas Bus/*); NBA: always the prefetched opcode", "prefetch": "the prefetch buffer: halfwords, pauses when full or at a 128 KiB boundary, " "flushes on a branch past what it holds (alyosha-tas prefetcher/*)", "rom-mirror": "Game Pak reads past the ROM's end (quirk 7; mGBA suite ROM out-of-bounds)", "flash-id": "the Flash chip's ID: board Panasonic/Sanyo, NBA SST/Macronix (C7)", "sio": "SIODATA32/SIOMULTI0-3/SIOMLT_SEND read as stored (GBATEK); NBA: open bus", "joy": "the JOY bus registers read as stored (GBATEK); NBA: open bus", "obj-free": "the OBJ engine's HBlank-free window: 960 cycles; NBA 964 (C17)", "fifo-delay": "a sound FIFO's DMA request takes 3 cycles; NBA 2 (C28; alyosha-tas fifo_2-4)", } def nba_irq(gba: GBA) -> None: """NBA's IRQ line: two cycles after IE & IF & IME whatever the CPU is doing, seen by the CPU at the next instruction boundary; a HALT wake-up always costs its cycle.""" from gba_python import irq as irq_module class NBAIRQ(type(gba.irq)): # type: ignore[misc] @property def level(self) -> bool: return bool(self.cpu.irq) @level.setter def level(self, value: bool) -> None: self.cpu.irq = value @property def available_at(self) -> int: return 1 << 62 # never "during a DMA" @available_at.setter def available_at(self, value: int) -> None: pass irq_module.SYNC_CYCLES = 2 state = vars(gba.irq) state.pop("level", None) state.pop("available_at", None) gba.irq.__class__ = NBAIRQ gba.irq.cpu_cycles = lambda: gba.scheduler.now gba.irq.cpu_waiting = lambda: False gba.irq.overlapping = lambda: False def nba_model(gba: GBA, parts: set[str]) -> None: """Swap the named parts of the board for NBA 1.8.3's behaviour (``NBA_PARTS``).""" if "irq" in parts: nba_irq(gba) if "prefetch" in parts: nba_prefetch(gba) if "data-bus" in parts: from gba_python import board board.ON_BUS = 0 if "flash-id" in parts and gba.cartridge.sram is not None: from gba_python.cartridge.backup import FLASH_IDS, Flash chip = gba.cartridge.sram if isinstance(chip, Flash): name = "sst" if len(chip.data) == 0x10000 else "macronix" chip.manufacturer, chip.device = FLASH_IDS[name] if "sio" in parts: for offset in (0x120, 0x122, 0x124, 0x126, 0x12A): gba.io.readers.pop(offset, None) if "joy" in parts: for offset in (0x140, 0x150, 0x152, 0x154, 0x156, 0x158): gba.io.readers.pop(offset, None) if "rom-mirror" in parts: nba_rom_mirror(gba) if "fifo-delay" in parts: from gba_python import dma dma.FIFO_DELAY = 2 if "obj-free" in parts: from gba_python.ppu import objects start = objects.Engine.__init__ def nba_window(engine: objects.Engine, source: object, line: int, mosaic_y: int) -> None: start(engine, source, line, mosaic_y) if source.registers[0] & 0x20: # type: ignore[attr-defined] engine.steps = 964 // 2 objects.Engine.__init__ = nba_window # type: ignore[method-assign] def nba_rom_mirror(gba: GBA) -> None: """NBA reads past the ROM's end through a power-of-two mask: the ROM mirrors.""" cart = gba.cartridge data, size = cart.rom, cart.size mask = 1 while mask < size: mask <<= 1 mask -= 1 read16, read32 = cart.read16, cart.read32 def mirrored16(address: int, sequential: bool) -> int: offset = address & 0x01FFFFFE value = read16(address, sequential) if offset < size or offset & mask >= size or cart._is_eeprom(address): return value # (NBA asks its EEPROM before its ROM, as the board does) offset &= mask return data[offset] | data[offset + 1] << 8 def mirrored32(address: int, sequential: bool) -> int: offset = address & 0x01FFFFFC value = read32(address, sequential) if offset < size or offset & mask >= size or cart._is_eeprom(address): return value # (NBA asks its EEPROM before its ROM, as the board does) offset &= mask return int.from_bytes(data[offset : offset + 4], "little") cart.read16, cart.read32 = mirrored16, mirrored32 def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("rom", type=Path) parser.add_argument("--bios", help="a BIOS file or .zip (default: gba_python.bios.find)") parser.add_argument("--skip", type=int, default=0) parser.add_argument("--count", type=int, default=1_000_000) parser.add_argument("--keys", action="append", default=[], help="FRAME:MASK") parser.add_argument("--context", type=int, default=6) parser.add_argument( "--nba-trace", type=Path, default=NBA_TRACE, help="another nba_trace build (e.g. one patched for an experiment)", ) parser.add_argument( "--nba-model", default="", help="comma-separated parts to run as NBA does, or 'all': " + ", ".join(NBA_PARTS), ) parser.add_argument( "--skip-bios", action="store_true", help="start both at 8000000 (NBA's SkipBootScreen; the smoke set's skip entries)", ) parser.add_argument( "--regs", action="store_true", help="also compare R0-R14, to catch a value that differs" ) parser.add_argument( "--trace-from", type=int, help="print the board's bus accesses (gba_python.trace) from this instruction on", ) parser.add_argument( "--adopt", action="store_true", help="with --regs: where only registers differ, list it, take NBA's and carry on", ) args = parser.parse_args() bios = bios_module.find(args.bios) keys = {int(f): int(m, 0) for f, m in (k.split(":") for k in args.keys)} with tempfile.TemporaryDirectory() as scratch: bios_file = Path(scratch) / "bios.bin" bios_file.write_bytes(bios.data) # a temporary file for NBA only, removed after rom_file = Path(scratch) / "rom.gba" rom_file.write_bytes(read_rom(args.rom)) # NBA starts from reset with two never-executed opcodes in its pipeline, which it # "executes" to fill it (fetches at 0 and 4); this core makes the same two fetches # inside reset(). Skip those two lines so instruction numbers line up. theirs = nba_lines( rom_file, bios_file, args.skip + 2, args.count, args.keys, args.regs, args.nba_trace, args.skip_bios, ) gba = GBA(bios, read_rom(args.rom), skip_bios=args.skip_bios) if args.skip_bios: # NBA's SkipBootScreen sets only the stacks and PC; its resets give PA = PD = 100h # and SOUNDBIAS 200h. Undo the rest of what the BIOS leaves (C19) to start alike. for offset in (0x000, 0x082, 0x134): gba.io.write(0x04000000 + offset, 16, 0) gba.cpu.r[14] = 0 parts = ( set(NBA_PARTS) if args.nba_model == "all" else set(filter(None, args.nba_model.split(","))) ) unknown = parts - set(NBA_PARTS) if unknown: parser.error(f"unknown --nba-model parts: {', '.join(sorted(unknown))}") nba_model(gba, parts) ours = board_lines(gba, args.skip, args.count, keys, args.regs) # Stream both: a long run holds only the last --context lines of each side. recent: deque[tuple[tuple[int, ...], tuple[int, ...]]] = deque(maxlen=args.context) compared = adopted = stamps = 0 adopted_at: dict[int, int] = {} pairs = zip(ours, theirs, strict=False) for mine, nba in pairs: if args.trace_from is not None and args.skip + compared == args.trace_from: trace.attach(gba, sys.stdout) if args.adopt and mine[:2] == nba[:2] and mine != nba: adopted += 1 pc = mine[1] adopted_at[pc] = adopted_at.get(pc, 0) + 1 if adopted_at[pc] == 1: # the first at each address; counts at the end changed = ", ".join( f"r{r} {x:08x}->{y:08x}" for r, (x, y) in enumerate(zip(mine[2:], nba[2:], strict=True)) if x != y ) frame = mine[0] // FRAME print( f"adopt {args.skip + compared:>12,} frame {frame} pc {pc:08x}: {changed}", flush=True, ) gba.cpu.r[:15] = list(nba[2:]) mine = nba held = [] if mine != nba and mine[1:] == nba[1:]: # Only the start cycle differs. If the next instruction starts on the same # cycle on both, the two ran a DMA on either side of this one's start: the # same cycles, stamped differently. Not a difference. held = [pair for pair, _ in zip(pairs, range(1), strict=False)] if held and held[0][0] == held[0][1]: stamps += 1 recent.append((mine, nba)) recent.append(held[0]) compared += 2 continue if mine != nba: print( f"BIOS {bios.label}; first difference at instruction {args.skip + compared:,}" ) rows = [*recent, (mine, nba), *held] after = zip(pairs, range(args.context), strict=False) rows += [pair for pair, _ in after] for k, (a, b) in enumerate(rows): n = args.skip + compared - len(recent) + k (t1, p1), (t2, p2) = a[:2], b[:2] mark = " " if a == b else "!!" print( f"{mark} {n:>12,} here {t1:>12} {p1:08x} nba {t2:>12} {p2:08x}" f" delta {t1 - t2:+d} frame {t1 // FRAME} line {t1 % FRAME // 1232}" ) for r, (x, y) in enumerate(zip(a[2:], b[2:], strict=True)): if x != y: print(f"{'':>17}r{r}: here {x:08x} nba {y:08x}") break recent.append((mine, nba)) compared += 1 else: print(f"BIOS {bios.label}; compared {compared:,} instructions: no difference") if stamps: print(f"{stamps:,} starts stamped on the other side of a DMA (same cycles in all)") for pc, count in sorted(adopted_at.items()): print(f"adopted NBA's registers at {pc:08x}: {count:,} times") return 0 if compared >= args.count else 1 if __name__ == "__main__": sys.exit(main())