# SPDX-License-Identifier: MIT # Contains the timing frame of endrift's mGBA test suite (MIT License, # Copyright (c) 2015 Jeffrey Pfau; reference/src/suite/LICENSE). """Tiny hand-assembled programs for the unit tests, run on a board without a BIOS boot. ``timed_arm`` and ``timed_thumb`` build the mGBA suite's timing frame (suite include/macros.s, MIT, Jeffrey Pfau: START is "ldr r0, =TM0CNT_LO; ldr r1, =0x800000; str r1, [r0]", END is "ldrh r2, [r0]"), with the code under test between, in Game Pak ROM. The value left in r2 is the timer's count, which the suite's "Calibration" row gives for an empty body (suite src/timing.c; TEST ROM). """ from __future__ import annotations import struct from gba_python.board import GBA from gba_python.cartridge.rom import GamePakROM ZERO_BIOS = bytes(0x4000) ARM_BRANCH_SELF = 0xEAFFFFFE THUMB_BRANCH_SELF = 0xE7FE def timed_arm(code: list[int]) -> bytes: words = [0, 0, 0xE5801000, *code, 0xE1D020B0, ARM_BRANCH_SELF] literals = len(words) * 4 words += [0x04000100, 0x00800000] words[0] = 0xE59F0000 | (literals - 8) # ldr r0, [pc, #...] words[1] = 0xE59F1000 | (literals + 4 - 4 - 8) # ldr r1, [pc, #...] return b"".join(struct.pack(" bytes: halves = [0, 0, 0x6001, *code, 0x8802, THUMB_BRANCH_SELF] while len(halves) % 2: halves.append(0x46C0) # mov r8, r8 literals = len(halves) * 2 halves[0] = 0x4800 | ((literals - 4) >> 2) # ldr r0, [pc, #...] halves[1] = 0x4900 | ((literals + 4 - 4) >> 2) # ldr r1, [pc, #...] return b"".join(struct.pack(" GBA: return GBA(GamePakROM(program + bytes(64)), bios=bios) def run_timed(program: bytes, waitcnt: int, thumb: bool = False) -> int: """Run a ``timed_*`` program from 08000000 and return r2 (the timer's count).""" board = board_for(program) board.bus.write_waitcnt(waitcnt) if thumb: board.cpu.cpsr |= 0x20 board.cpu.r[3] = 0x08000000 board.cpu.r[13] = 0x03007F00 board.cpu.start_at(0x08000000) for _ in range(500): board.step() width = 2 if board.cpu.thumb else 4 executing = (board.cpu.r[15] - 2 * width) & 0x1FFFFFF if board.cpu.thumb and board.rom.halfword(executing >> 1) == THUMB_BRANCH_SELF: break if not board.cpu.thumb and board.rom.halfword(executing >> 1) == 0xFFFE: break return board.cpu.r[2]