"""Running test ROMs and reading their verdicts without looking at the screen. Three protocols (docs/validation.md): - **r12**: jsmolka's convention, shared by alyosha-tas's tests built on his library. The ROM leaves 0 in r12 when every test passed, else the first failed test's number, and then idles on a branch to itself. - **mGBA suite**: endrift's suite runs one of its 14 sub-suites when selected with the D-pad and A, and reports "END: passes/total" (and a "FAIL: ..." line per failure) through mGBA's debug port, which this board answers (``io.py``). - **frames**: anything else runs a fixed number of frames; the caller inspects the state. Keys are pressed at frame boundaries, as the referee drivers do (``scripts/referee_run.py``), so a run here and a run there see the same inputs. """ from __future__ import annotations import hashlib import re import struct import zipfile import zlib from dataclasses import dataclass, field from pathlib import Path from gba_python.bios import BIOS from gba_python.board import GBA from gba_python.keypad import DOWN, LEFT, RIGHT, START, UP, A, B, L, R ARM_BRANCH_TO_SELF = 0xEAFFFFFE THUMB_BRANCH_TO_SELF = 0xE7FE #: the order of suites[] in mgba-emu/suite src/main.c SUITES = ( "Memory tests", "I/O read tests", "Timing tests", "Timer count-up tests", "Timer IRQ tests", "Shifter tests", "Carry tests", "Multiply long tests", "BIOS math tests", "DMA tests", "SIO register R/W tests", "SIO timing tests", "Misc. edge case tests", "Video tests", ) BOOT_FRAMES = 300 # Nintendo's BIOS plays its logo for about 270 frames def screen_text(gba: GBA, layer: int = 0, offset: int = 0, rows: int = 20) -> list[str]: """The text on a text-mode background, read from its map (no picture needed). libgba's console (used by NanoBoyAdvance's ``hw-test`` and other suites) puts each character's ASCII code in the map entry's tile number, so the map *is* the text: 20 rows of 30 visible columns, trailing spaces removed. ``offset`` is added to each tile number (the AGS aging cartridge's font starts at the space: ``offset`` 20h). ``rows`` reads past the visible 20 when a program writes below them (krom's BIOS tests). """ control = gba.ppu.registers[4 + layer] base = (control >> 8 & 0x1F) * 0x800 vram = gba.ppu.vram text = [] for row in range(rows): entry = base + row * 64 chars = ((vram[entry + 2 * column] + offset) & 0xFF for column in range(30)) text.append("".join(chr(c) if 32 <= c < 127 else " " for c in chars).rstrip()) return text def screen_rgb(gba: GBA) -> bytes: """The current picture as 240x160 RGB bytes. Each 5-bit channel widens to 8 bits as ``c << 3 | c >> 2``, as NanoBoyAdvance's driver writes its PNGs, so the two compare pixel for pixel.""" widen = [c << 3 | c >> 2 for c in range(32)] out = bytearray() for color in gba.ppu.screen: out += bytes((widen[color & 31], widen[color >> 5 & 31], widen[color >> 10 & 31])) return bytes(out) def screen_hash(gba: GBA) -> str: """A short SHA-256 of ``screen_rgb``: what tests/frames_pass.txt records.""" return hashlib.sha256(screen_rgb(gba)).hexdigest()[:16] def screen_png(gba: GBA) -> bytes: """The current picture as a 240x160 RGB PNG (``screen_rgb``).""" return rgb_png(240, 160, screen_rgb(gba)) def rgb_png(width: int, height: int, rgb: bytes) -> bytes: """``width`` x ``height`` RGB bytes, row by row, as a PNG.""" rows = bytearray() stride = 3 * width for y in range(height): rows.append(0) # filter: none rows += rgb[y * stride : y * stride + stride] def chunk(kind: bytes, data: bytes) -> bytes: body = kind + data return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body)) header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0) # 8-bit RGB return ( b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", zlib.compress(bytes(rows), 9)) + chunk(b"IEND", b"") ) def run_frames(rom: bytes, bios: BIOS, frames: int) -> GBA: """The **frames** protocol for pictures: run exactly ``frames`` frames from power-on.""" gba = GBA(bios, rom) for _ in range(frames): gba.run_frame() return gba class _AtCartridge(Exception): pass def _handoff_state(gba: GBA) -> dict: cpu = gba.cpu.capture_state() return { "registers": cpu.registers[:15], "banks": cpu.banks, "cpsr": cpu.cpsr, "spsr": cpu.spsr, "ppu": list(gba.ppu.registers), "apu": list(gba.apu.registers), "serial": [gba.serial.siocnt, gba.serial.rcnt, *gba.serial.joy], "irq": [gba.io.read(0x04000200, 16), gba.io.read(0x04000208, 16)], "waitcnt": gba.waitcnt, "postflg": gba.postflg, "memory": [hashlib.sha256(m).hexdigest() for m in (gba.ewram, gba.iwram)], } def bios_handoff(rom: bytes, bios: BIOS) -> dict[str, tuple]: """Where ``skip_bios`` differs from the BIOS: boot ``rom`` through ``bios`` to its first opcode fetch from 8000000 and compare the registers it leaves with ``skip_bios``'s. Returns ``{field: (bios's, skip_bios's)}`` for the fields that differ. Not compared: the PPU's position (the BIOS leaves VCOUNT at 126) and timer 0's stopped counter (C19). """ gba = GBA(bios, rom) read = gba.bus_read def bus_read(address: int, width: int, access: int) -> int: if address == 0x08000000 and access & 2: raise _AtCartridge return read(address, width, access) gba.bus_read = bus_read # type: ignore[method-assign] try: for _ in range(400): gba.run_frame() except _AtCartridge: pass else: raise RuntimeError("the BIOS never reached the cartridge") booted, skipped = _handoff_state(gba), _handoff_state(GBA(bios, rom, skip_bios=True)) return {k: (booted[k], skipped[k]) for k in booted if booted[k] != skipped[k]} def read_rom(path: str | Path) -> bytes: """A ROM file, or the first ``.gba`` in a ``.zip`` (a No-Intro dump read in place).""" path = Path(path) if path.suffix.lower() == ".zip": with zipfile.ZipFile(path) as archive: name = next(n for n in archive.namelist() if n.lower().endswith(".gba")) return archive.read(name) return path.read_bytes() def at_branch_to_self(gba: GBA) -> bool: cpu = gba.cpu if cpu.thumb: return cpu.pipeline[0] == THUMB_BRANCH_TO_SELF return cpu.pipeline[0] == ARM_BRANCH_TO_SELF @dataclass class R12Result: r12: int | None # None: no branch to itself within the frame budget frames: int pc: int @property def passed(self) -> bool: return self.r12 == 0 def run_r12(rom: bytes, bios: BIOS, frames: int = 600, *, skip_bios: bool = False) -> R12Result: """Run until the ROM idles on a branch to itself, checking at the end of each frame.""" gba = GBA(bios, rom, skip_bios=skip_bios) for frame in range(1, frames + 1): gba.run_frame() if at_branch_to_self(gba): return R12Result(gba.cpu.r[12], frame, gba.cpu.r[15]) return R12Result(None, frames, gba.cpu.r[15]) @dataclass class SuiteResult: suite: str passes: int | None total: int | None fails: list[str] = field(default_factory=list) frames: int = 0 def run_suite( rom: bytes, bios: BIOS, index: int, frames: int = 4300, *, gba: GBA | None = None ) -> SuiteResult: """Select sub-suite ``index`` of the mGBA suite and run it to its END line.""" gba = gba or GBA(bios, rom) presses: dict[int, int] = {0: 0} frame = BOOT_FRAMES for _ in range(index): presses[frame], presses[frame + 2] = DOWN, 0 frame += 4 presses[frame], presses[frame + 2] = A, 0 log = gba.debug_log for current in range(frames): if current in presses: gba.keypad.set_pressed(presses[current]) gba.run_frame() for line in log: match = re.match(r"END: (\d+)/(\d+)", line) if match: fails = [entry[6:] for entry in log if entry.startswith("FAIL: ")] return SuiteResult( SUITES[index], int(match.group(1)), int(match.group(2)), fails, current + 1 ) return SuiteResult(SUITES[index], None, None, [], frames) @dataclass class TextResult: """A text-screen verdict: ``passed`` is None when the screen shows none.""" passed: bool | None detail: str text: list[str] def hwtest_verdict(text: list[str]) -> tuple[bool | None, str]: """NanoBoyAdvance ``hw-test``: "congratulations!" when every case passed, else "pass: n / total: m"; a test that prints no summary is judged by its PASS/FAIL lines.""" joined = "\n".join(text) if "congratulations!" in joined: return True, "congratulations!" match = re.search(r"pass:\s+(\d+)\s+total:\s+(\d+)", joined) if match: return False, f"{match.group(1)}/{match.group(2)}" passes, fails = joined.count(": PASS"), joined.count(": FAIL") if passes + fails == 0: return None, "no verdict on screen" return fails == 0, f"{passes}/{passes + fails} visible" def hades_verdict(text: list[str]) -> tuple[bool | None, str]: """Hades-Tests: "Total: n/m".""" match = re.search(r"Total: (\d+)/(\d+)", "\n".join(text)) if not match: return None, "no verdict on screen" return match.group(1) == match.group(2), f"{match.group(1)}/{match.group(2)}" def run_text( rom: bytes, bios: BIOS, frames: int, verdict, *, layer: int = 0, rows: int = 20, skip_bios: bool = False, ) -> TextResult: """Run a fixed number of frames, then read the console text and judge it.""" gba = GBA(bios, rom, skip_bios=skip_bios) for _ in range(frames): gba.run_frame() text = screen_text(gba, layer, rows=rows) passed, detail = verdict(text) return TextResult(passed, detail, text) AGS_TESTS = ("MEMORY", "LCD", "TIMER", "DMA", "KEY INPUT", "INTERRUPT") def ags_verdict(text: list[str]) -> tuple[bool | None, str]: """An aging cartridge's first screen: PASS or NG per automatic test, INTERRUPT last. COM needs a link cable and stays blank; the older AGB cartridge leaves KEY INPUT blank too (no keys pressed).""" results = {} for row in text: name = row.split(".")[0].strip() if name in AGS_TESTS and row.rstrip().endswith(("PASS", "NG")): results[name] = row.split()[-1] if "INTERRUPT" not in results: return None, f"{len(results)} results" failed = [name for name, result in results.items() if result != "PASS"] missing = [name for name in AGS_TESTS if name not in results and name != "KEY INPUT"] if failed or missing: return False, "NG: " + ", ".join(failed + [f"{name} (none)" for name in missing]) return True, f"{len(results)} PASS" def run_ags(rom: bytes, bios: BIOS, frames: int = 1200) -> TextResult: """The AGS aging cartridge's automatic tests, to their result screen. A fresh AGS cartridge (v7.0-v10.0) finds its EEPROM blank on the first power-on, shows "CHECK SUM ERROR! DEFAULT IS SAVED" and waits: the board is switched off and on with what it saved, as on hardware, and the tests then run. The older AGB cartridge opens on a "SELECT TARGET" menu instead: AGING CARTRIDGE is the third entry (DOWN, DOWN, A). """ save = None text: list[str] = [] for _power_on in range(2): gba = GBA(bios, rom, save) taps = [DOWN, DOWN, A] held = menu = 0 for _ in range(frames): gba.run_frame() text = screen_text(gba, 0, 0x20) if held: # four frames down, four up held -= 1 if held == 4: gba.keypad.set_pressed(0) elif taps and any("SELECT TARGET" in row for row in text): menu += 1 if menu > 30: # the menu takes no keys at first gba.keypad.set_pressed(taps.pop(0)) held = 8 if any("DEFAULT IS SAVED" in row for row in text): for _ in range(30): # let it finish writing gba.run_frame() save = gba.cartridge.save_data() break passed, detail = ags_verdict(text) if passed is not None: return TextResult(passed, detail, text) else: break return TextResult(None, "no result screen", text) def _ags_text(gba: GBA) -> list[str]: return [row.strip() for row in screen_text(gba, 0, 0x20)] def _ags_frames(gba: GBA, count: int) -> None: for _ in range(count): gba.run_frame() def _ags_press(gba: GBA, key: int, wait: int = 15) -> None: """Five frames down, then ``wait`` up: the menus read each press once.""" gba.keypad.set_pressed(key) _ags_frames(gba, 5) gba.keypad.set_pressed(0) _ags_frames(gba, wait) def _ags_until(gba: GBA, words: str, limit: int) -> bool: for _ in range(limit): gba.run_frame() if any(words in row for row in _ags_text(gba)): return True return False def _ags_setting(text: list[str], label: str) -> str | None: """The value under a CONFIGURATION item (``3.AGING TIME`` -> ``01:00:00``).""" for i, row in enumerate(text[:-1]): if row.startswith(label): return text[i + 1] return None def _ags_menu(rom: bytes, bios: BIOS, save: bytes | None) -> GBA: """Power on holding L and R: the AGS cartridges open their AGS TEST PROGRAM menu.""" gba = GBA(bios, rom, save) gba.keypad.set_pressed(L | R) _ags_until(gba, "CONFIGURATION", 900) gba.keypad.set_pressed(0) _ags_frames(gba, 20) return gba def run_ags_aging(rom: bytes, bios: BIOS, loops: int = 2) -> TextResult: """An aging cartridge's settings kept in its EEPROM across a power cycle, then ``loops`` rounds of the aging loop. The AGS cartridges (v7.0-v10.0) open a menu when powered on with L and R held. Its CONFIGURATION page is stored in the cartridge's EEPROM under a checksum, which the cartridge checks at every power-on ("CHECK SUM ERROR! DEFAULT IS SAVED" when it fails). The run moves AGING TIME back one step and, where the page has it (v9.0 on), sets AGING LOG to YES, then switches off and on: the page must come back as left. TEST PROGRAM, AGING CARTRIDGE then runs the automatic tests and waits on PUSH START TO AGING; START begins the aging loop, which draws test patterns and plays sound and, every round, reruns the MEMORY, LCD, DMA and INTERRUPT tests on its result screen. Each round must pass and no "ERROR OCCURED!!" may appear. With AGING LOG on, each round also writes a record to the EEPROM. The older AGB cartridge has no settings page: its loop starts from SELECT TARGET. """ gba = GBA(bios, rom) kept = "" if _ags_until(gba, "DEFAULT IS SAVED", 1200): _ags_frames(gba, 30) gba = _ags_menu(rom, bios, gba.cartridge.save_data()) _ags_press(gba, A) # CONFIGURATION if not _ags_until(gba, "AGING TIME", 120): return TextResult(None, "no CONFIGURATION page", _ags_text(gba)) before = _ags_setting(_ags_text(gba), "3.AGING TIME") _ags_press(gba, DOWN) _ags_press(gba, DOWN) _ags_press(gba, LEFT, 30) if _ags_setting(_ags_text(gba), "4.AGING LOG") is not None: _ags_press(gba, DOWN) _ags_press(gba, RIGHT, 30) text = _ags_text(gba) wanted = (_ags_setting(text, "3.AGING TIME"), _ags_setting(text, "4.AGING LOG")) if wanted[0] == before: return TextResult(None, f"AGING TIME did not move from {before}", text) _ags_press(gba, A, 30) # back to the menu, which writes the page gba = _ags_menu(rom, bios, gba.cartridge.save_data()) # off and on _ags_press(gba, A) _ags_until(gba, "AGING TIME", 120) text = _ags_text(gba) got = (_ags_setting(text, "3.AGING TIME"), _ags_setting(text, "4.AGING LOG")) if got != wanted: return TextResult(False, f"settings {wanted} came back as {got}", text) kept = "settings kept (" + ", ".join(v for v in got if v) + "); " _ags_press(gba, A, 30) _ags_press(gba, DOWN) _ags_press(gba, A) # TEST PROGRAM _ags_until(gba, "AGING CARTRIDGE", 120) _ags_press(gba, DOWN) _ags_press(gba, DOWN) _ags_press(gba, A) # AGING CARTRIDGE elif any("SELECT TARGET" in row for row in _ags_text(gba)): _ags_frames(gba, 30) # the menu takes no keys at first for key in (DOWN, DOWN, A): _ags_press(gba, key) if not _ags_until(gba, "PUSH START TO AGING", 1500): return TextResult(None, kept + "no PUSH START TO AGING", _ags_text(gba)) passed, detail = ags_verdict(_ags_text(gba)) if not passed: return TextResult(passed, kept + "automatic tests: " + detail, _ags_text(gba)) _ags_press(gba, START) rounds = 0 showing = False for frame in range(3000 * loops): gba.run_frame() if frame % 10: continue text = _ags_text(gba) if gba.ppu.registers[0] & 0x100 else [] if any("ERROR" in row for row in text): return TextResult(False, kept + f"ERROR in round {rounds + 1}", text) results = [row for row in text if row.endswith(("PASS", "NG"))] shown = any(row.startswith("INTERRUPT") for row in results) if shown and not showing: rounds += 1 failed = [row.split(".")[0] for row in results if row.endswith("NG")] if failed: return TextResult(False, kept + f"round {rounds} NG: {', '.join(failed)}", text) if rounds == loops: return TextResult(True, kept + f"{rounds} aging rounds PASS", text) showing = shown return TextResult(None, kept + f"{rounds} of {loops} aging rounds shown", _ags_text(gba)) def run_menu_text( rom: bytes, bios: BIOS, option: int, frames: int, verdict, *, done=None ) -> TextResult: """hw-test's menu ROMs: choose ``option`` (D-pad down, then A, released as the menu reads key releases), run until ``done(text)`` or ``frames``, then judge the console text.""" gba = GBA(bios, rom) presses: dict[int, int] = {} frame = BOOT_FRAMES for _ in range(option): presses[frame], presses[frame + 2] = DOWN, 0 frame += 4 presses[frame], presses[frame + 2] = A, 0 for current in range(frames): if current in presses: gba.keypad.set_pressed(presses[current]) gba.run_frame() if current > frame + 10 and current % 25 == 0: text = screen_text(gba) if (done is not None and done(text)) or (verdict(text)[0] is not None and done is None): break text = screen_text(gba) passed, detail = verdict(text) return TextResult(passed, detail, text) def bitmap_text(gba: GBA, font: bytes, first: int) -> list[tuple[int, int, str]]: """Text drawn into the mode 4 frame (page 0) with an 8x8, byte-per-pixel ``font`` whose glyph ``i`` is character ``first + i``: ``(y, x, text)`` per run of glyphs, in reading order. A glyph matches when the pixels it sets are exactly the non-zero ones in an 8x8 cell, whatever their colour; a gap of whole cells reads as spaces.""" glyphs: dict[bytes, str] = {} for index in range(len(font) // 64): mask = bytes(b != 0 for b in font[index * 64 : index * 64 + 64]) if any(mask): glyphs.setdefault(mask, chr(first + index)) vram = gba.ppu.vram lit = bytes(b != 0 for b in vram[: 240 * 160]) runs = [] for y in range(153): if not any(lit[y * 240 : y * 240 + 240]): continue x, run, start, last = 0, "", 0, 0 while x <= 232: cell = b"".join(lit[(y + r) * 240 + x : (y + r) * 240 + x + 8] for r in range(8)) char = glyphs.get(cell) if char is None: x += 1 continue if run and x - last >= 8: run += " " * ((x - last) // 8) elif not run: start = x run += char last = x + 8 x += 8 if run: runs.append((y, start, run)) return runs def _hold(gba: GBA, keys: int, frames: int) -> None: gba.keypad.set_pressed(keys) for _ in range(frames): gba.run_frame() #: ARMWrestler's menu entries and the pages each one steps through with START (its #: ``menulinks`` and ``jumptable``: the ARM entries share one run of five pages). ARMWRESTLER_PAGES = { "ARM ALU 1": (0, 0), "ARM ALU 2": (0, 1), "ARM LDR/STR 1": (1, 0), "ARM LDR/STR 2": (1, 1), "ARM LDM/STM": (2, 0), "THUMB ALU": (3, 0), "THUMB LDR/STR": (4, 0), "THUMB LDM/STM": (5, 0), } def run_armwrestler(rom: bytes, bios: BIOS, font: bytes, page: str) -> TextResult: """One ARMWrestler results page: choose its menu entry (D-pad, START), step to the page with START, then read the mode 4 text. Every result row ends in OK, or in BAD and what was wrong (``Rd``, ``Rn``, a flag, ``MEM``). Keys are held six frames: the program polls once per frame it finishes, and its loops take longer than a frame.""" item, steps = ARMWRESTLER_PAGES[page] gba = GBA(bios, rom, skip_bios=True) _hold(gba, 0, 60) for _ in range(item): _hold(gba, DOWN, 6) _hold(gba, 0, 8) for _ in range(1 + steps): _hold(gba, START, 6) _hold(gba, 0, 24) rows = [text for _, x, text in bitmap_text(gba, font, 0x25) if x == 16] results = [row for row in rows if " OK" in row or " BAD" in row] bad = [row for row in results if " BAD" in row] if not results: return TextResult(None, "no results on screen", rows) return TextResult(not bad, f"{len(results) - len(bad)}/{len(results)} OK", rows) def run_fuzzarm(rom: bytes, bios: BIOS, frames: int = 3000) -> TextResult: """FuzzARM: each failed test dumps its state to EWRAM (``AAAA`` or ``TTTT`` first) and waits for a key; press A, collect the dump, and run on to the program's final branch to itself. Passed when it got there with no dumps.""" gba = GBA(bios, rom, skip_bios=True) failures: list[str] = [] for _ in range(frames): gba.run_frame() if bytes(gba.ewram[:4]) in (b"AAAA", b"TTTT"): dump = bytes(gba.ewram[:64]) for _ in range(4): # the dump is written a word at a time, with text drawn between gba.run_frame() if bytes(gba.ewram[:64]) == dump: break dump = bytes(gba.ewram[:64]) words = struct.unpack("<16I", dump) name = dump[4:16].decode("latin1").strip() failures.append(f"{name}: " + " ".join(f"{w:08X}" for w in words[4:])) gba.ewram[0:4] = bytes(4) _hold(gba, A, 3) gba.keypad.set_pressed(0) continue if at_branch_to_self(gba): detail = f"{len(failures)} failed" if failures else "end of testing" return TextResult(not failures, detail, failures) return TextResult(None, f"no end within {frames} frames ({len(failures)} failed)", failures) def krom_verdict(text: list[str]) -> tuple[bool | None, str]: """krom's (Peter Lemon's) BIOS tests: a PASS or FAIL at the end of each checked line, results and Timer 0 cycle counts both.""" passes = sum(row.endswith("PASS") for row in text) fails = sum(row.endswith("FAIL") for row in text) if passes + fails == 0: return None, "no verdict on screen" return fails == 0, f"{passes}/{passes + fails} PASS" def run_retaddr(rom: bytes, bios: BIOS, frames: int = 60) -> TextResult: """GBA-Test-Collection ``exception/retAddr``: an IRQ taken in ARM and in Thumb state each leave the offset of LR_irq from the right return address in EWRAM words 0 and 1 (0 = right). The program reaches its final branch to itself only after both IRQs.""" gba = GBA(bios, rom, skip_bios=True) for _ in range(frames): gba.run_frame() if at_branch_to_self(gba): arm, thumb = struct.unpack_from("<2i", gba.ewram, 0) text = [f"ARM IRQ: {arm:+d}", f"Thumb IRQ: {thumb:+d}"] return TextResult(arm == thumb == 0, ", ".join(text), text) return TextResult(None, f"no end within {frames} frames", []) #: The keys mGBA's keyirq asks for, by prompt. KEYIRQ_KEYS = { "Hold A...": A, "Hold A+B...": A | B, "Release everything...": 0, "Release B, keep holding A..": A, } def keyirq_steps(rom: bytes, bios: BIOS, frames: int = 300) -> list[str]: """mGBA's ``keyirq``, built against ``scripts/libgba_shim`` (its console is text at 2000000h): hold what each prompt asks, changing keys only when the prompt changes, and return its PASS/FAIL per step, in order.""" gba = GBA(bios, rom, skip_bios=True) held = None text = "" for _ in range(frames): gba.run_frame() text = bytes(gba.ewram[:0x1000]).split(b"\0")[0].decode("latin1") prompts = [line.split("PASS")[0].split("FAIL")[0].strip() for line in text.splitlines()] prompts = [p for p in prompts if p in KEYIRQ_KEYS] if prompts and KEYIRQ_KEYS[prompts[-1]] != held: held = KEYIRQ_KEYS[prompts[-1]] gba.keypad.set_pressed(held) if "Test complete" in text: break return re.findall(r"(PASS|FAIL) ", text) # "PASS " per step; the intro ends in "FAIL\n" #: Nintendo's "Backup LIB sample" (No-Intro, v1.04): its menu entry per chip, and the pattern #: keys (UP twice selects 00FF, DOWN twice INC; none leaves 0000). BACKUP_LIB_MENU = {"sram": 0, "flash64": 1, "flash128": 1, "eeprom": 2} BACKUP_LIB_PATTERNS = {"0000": (), "00FF": (UP, UP), "INC": (DOWN, DOWN)} def run_backup_lib( rom: bytes, bios: BIOS, save_type: str, pattern: str = "0000", frames: int = 900 ) -> TextResult: """Nintendo's backup library sample on one save chip: choose the chip's test, select a pattern, press A to write it through the library, and read the library's own verify: "WRITE COMPLETE." or an error. The ROM carries all four libraries' ID strings, so the chip is chosen with ``save_type``; DACS (a development flash chip) is not run.""" gba = GBA(bios, rom, save_type=save_type, skip_bios=True) _hold(gba, 0, 50) for _ in range(BACKUP_LIB_MENU[save_type]): _hold(gba, DOWN, 4) _hold(gba, 0, 2) _hold(gba, A, 4) _hold(gba, 0, 16) for key in BACKUP_LIB_PATTERNS[pattern]: _hold(gba, key, 4) _hold(gba, 0, 4) _hold(gba, A, 4) gba.keypad.set_pressed(0) text: list[str] = [] for frame in range(frames): gba.run_frame() if frame % 10: continue text = [row for row in screen_text(gba) if row.strip()] joined = "\n".join(text) shown = next((row.split(":")[1] for row in text if "PATTERN:" in row), "?") if shown != pattern: # the pattern keys did not land return TextResult(None, f"pattern {shown} on screen, not {pattern}", text) if "WRITE COMPLETE." in joined: return TextResult(True, f"{pattern}: write complete", text) if "ERROR" in joined: error = next(row.strip() for row in text if "ERROR" in row) return TextResult(False, f"{pattern}: {error} {text[-1].strip()}", text) return TextResult(None, f"{pattern}: no verdict within {frames} frames", text)