#!/usr/bin/env python3 """Show that the judges can fail: seed one fault per rule into a copy of src/, run its judge. Each fault below changes one line of the board (a copy; the tree is not touched) and names the judge that covers the rule. A fault the judge still passes means the judge does not cover the rule, and the report says so. Runs in parallel processes, with the BIOS ``gba_python.bios.find`` picks (the retail dump for a real verdict). python scripts/seeded_faults.py # every fault python scripts/seeded_faults.py --only irq """ from __future__ import annotations import argparse import json import shutil import subprocess import sys import tempfile from concurrent.futures import ThreadPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] # (name, file under src/gba_python, text, replacement, (suite, judge key)) FAULTS = [ ( "EWRAM 16-bit access 2 cycles, not 3", "board.py", "self.ewram16 = 1 + wait", "self.ewram16 = wait", ("mgba", "Timing tests"), ), ( "open bus reads 0, not the prefetched opcode", "board.py", "return word >> shift & ((1 << width) - 1)", "return 0", ("mgba", "Memory tests"), ), ( "a 16-bit IWRAM read puts only its own half on the bus", "board.py", "self.iwram_bus = self.iwram_bus & ~(0xFFFF << shift) | (value & 0xFFFF) << shift", "self.iwram_bus = (value & 0xFFFF) * 0x10001", ("alyosha", "reference/src/gba-tests-alyosha/Bus/DMA_IWRAM_Bus.gba"), ), ( "data the CPU moved does not stay on the bus (open bus is always the prefetch)", "board.py", "if last & ON_BUS and not last & CODE:", "if False:", ("alyosha", "reference/src/gba-tests-alyosha/Bus/DMA_OAM_Bus.gba"), ), ( "a Game Pak data read leaves nothing on the bus", "board.py", "self.rom_bus = value * 0x10001 # the Game Pak's 16 bits on both halves", "self.rom_bus = 0", ("alyosha", "reference/src/gba-tests-alyosha/Bus/LDRSH_misaligned.gba"), ), ( "the BIOS answers reads from outside it", "board.py", "if self.cpu.r[15] < 0x4000:", "if True:", ("jsmolka", "reference/src/gba-tests/bios/bios.gba"), ), ( # hw-test irq-delay does not see this one cycle (its wait loop absorbs it). "the IRQ synchronizer takes no cycle", "irq.py", "SYNC_CYCLES = 1", "SYNC_CYCLES = 0", ("mgba", "Timer IRQ tests"), ), ( "the CPU sees its IRQ input at once, not when it begins a bus cycle", "irq.py", " self.level = bool(packed & 1)\n elif self.cpu_waiting():", " self.level = self.cpu.irq = bool(packed & 1)\n elif self.cpu_waiting():", ("alyosha", "reference/src/gba-tests-alyosha/Interactions/Internal_Cycle_DMA_IRQ_ST.gba"), ), ( "the IRQ synchronizer runs while the CPU waits for a DMA", "board.py", "self.waited_cycles += self._run_dma()", "self._run_dma()", ("alyosha", "reference/src/gba-tests-alyosha/Interactions/Internal_Cycle_DMA_IRQ_ST.gba"), ), ( "the IRQ synchronizer stops for all of a DMA, overlapped internal cycles too", "board.py", "used = self._overlap - self._parallel", "used = 0", ("alyosha", "reference/src/gba-tests-alyosha/Interactions/Internal_Cycle_DMA_MUL_IRQ.gba"), ), ( "the CPU gets an access before a DMA that became ready as another ended", "board.py", "while self.dma.runnable and not self.halted:", "while False:", ("alyosha", "reference/src/gba-tests-alyosha/DMA/DMA_pause_timing_end_4.gba"), ), ( "a CPU woken from HALT during a DMA waits out the DMA's closing idle cycle", "dma.py", " if not (board.halted and self.irq.available):", " if True:", ("alyosha", "reference/src/gba-tests-alyosha/Interactions/Halt_DMA_IRQ.gba"), ), ( "a HALT wake-up during a DMA takes its cycle after the DMA", "board.py", " if not during:", " if True:", ("alyosha", "reference/src/gba-tests-alyosha/Interactions/Halt_DMA_IRQ.gba"), ), ( "DMA starts one cycle after its enable, not two", "dma.py", "self.channels[index].event = self.scheduler.add(2, self._activated, index)", "self.channels[index].event = self.scheduler.add(1, self._activated, index)", ("hwtest", "reference/src/hw-test/dma/start-delay/start-delay.gba"), ), ( "a timer reload write lands at once", "timer.py", "self.scheduler.add(1, self._reload_written, index, priority=1)", "self.scheduler.add(0, self._reload_written, index, priority=1)", ("hwtest", "reference/src/hw-test/timer/reload/reload.gba"), ), ( "no prefetch buffer", "board.py", " if self.prefetch_enabled:\n region", " if False:\n region", ("mgba", "Timing tests"), ), ( # The factory test is coarse: of the faults above it catches only this one and the # EWRAM wait (docs/validation.md, AGS). "no prefetch buffer, seen by Nintendo's aging cartridge", "board.py", " if self.prefetch_enabled:\n region", " if False:\n region", ("ags", "nointro:AGS Aging Cartridge (World) (Rev 3) (v9.0) (Test Program).zip"), ), ( # A block written once keeps its old bits: a rewrite ORs into it (no erase before the # write). The defaults land on a blank (FF) chip, so the automatic tests (`ags`) still # pass; changing the settings page clears bits, which the aging suite reads back. "an EEPROM rewrite ORs into the block instead of replacing it", "cartridge/backup.py", "self.data[self.address : self.address + 8] = bytes(8)", "self.data[self.address : self.address + 8] = (bytes(8) if self.data[self.address] == 0xFF" " else self.data[self.address : self.address + 8])", ("aging", "nointro:AGS Aging Cartridge (World) (v10.0) (Test Program).zip"), ), ( "a DMA's 128 KiB boundary by its own address (NanoBoyAdvance's rule)", "board.py", "sequential = access & SEQ and self.dma_rom_next & 0x1FFFF != 0", "sequential = access & SEQ and address & 0x1FFFF != 0", ("hwtest", "reference/src/hw-test/bus/128kb-boundary/128kb-boundary.gba"), ), ( "a Game Pak write does not move the cartridge's counter", "cartridge/__init__.py", "self.latch = (self.latch + 2) & ROM_MASK", "pass", ("hwtest", "reference/src/hw-test/dma/burst-into-tears/burst-into-tears.gba"), ), ( "HBlank flag at line cycle 1006, not 1007", "ppu/__init__.py", "HBLANK_START = 1007", "HBLANK_START = 1006", ("hwtest", "reference/src/hw-test/ppu/status-irq-dma/status-irq-dma.gba#0"), ), ( "a branch onto a fetch just starting, the buffer never ahead, waits for it", "board.py", "and (sequential or self.pf_count or not just_started or not self.pf_lockstep)", "and True", ("alyosha", "reference/src/gba-tests-alyosha/prefetcher/prefetcher_branch_thumb_2.gba"), ), ( "the buffer counts as ahead of the CPU from its start", "board.py", " self.pf_lockstep = True # no fetch of its own yet", " self.pf_lockstep = False # no fetch of its own yet", ("alyosha", "reference/src/gba-tests-alyosha/prefetcher/prefetcher_branch_thumb_6.gba"), ), ( "a branch past buffered halfwords still waits for the one in flight", "board.py", " if self.pf_active and address == self.pf_head:\n", " if self.pf_active and address == self.pf_last and self.pf_count and not sequential:\n" " self.pf_count, self.pf_head = 0, address\n" " if self.pf_active and address == self.pf_head:\n", ("alyosha", "reference/src/gba-tests-alyosha/prefetcher/prefetcher_branch_thumb_3.gba"), ), ( "the prefetch buffer holds opcodes, so Thumb after ARM loses each word's second half", "board.py", " halves = 1 if self.cpu.thumb else 2\n", " halves = 1 if self.cpu.thumb else 2\n if self.cpu.thumb and self.pf_head & 2 == 0 and self.pf_count > 1:\n self.pf_count = 0\n", ("alyosha", "reference/src/gba-tests-alyosha/prefetcher/prefetcher_branch_thumb_arm.gba"), ), ( "the prefetch buffer runs across a 128 KiB boundary", "board.py", " and (self.pf_last + 2) & 0x1FFFF\n", " and True\n", ("alyosha", "reference/src/gba-tests-alyosha/prefetcher/bounday_test_1.gba"), ), ( "a buffer stopped at a 128 KiB boundary loses its rhythm", "board.py", " and (self.scheduler.now - self.pf_paused_at) % self.pf_duty == self.pf_duty - 1", " and False", ("alyosha", "reference/src/gba-tests-alyosha/prefetcher/prefetcher_boundary_1.gba"), ), ( "an unfinished EEPROM command survives the end of its transfer (/CS high)", "cartridge/backup.py", " if not self.state & (READING | BUSY):\n self.state = ACCEPT_COMMAND", " if False:\n self.state = ACCEPT_COMMAND", ("backuplib", "eeprom#0000"), ), ( "a full prefetch buffer keeps counting (NanoBoyAdvance)", "board.py", " self.pf_paused = True\n", " pass\n", ("alyosha", "reference/src/gba-tests-alyosha/prefetcher/prefetcher_full_arm_2.gba"), ), ( "an unreadable I/O half in a readable word reads open bus", "io.py", " value = 0\n", " return self.board._open_bus(address, width)\n", ("mgba", "I/O read tests"), ), ( "SRAM reads not replicated across the word", "board.py", "value = byte * 0x01010101 & ((1 << width) - 1)", "value = byte", ("jsmolka", "reference/src/gba-tests/save/sram.gba"), ), ( "8-bit palette writes store one byte", "board.py", "self._palette16[offset >> 1] = value * 0x0101 # both bytes (quirk 4)", "self.ppu.palette[offset] = value", ("alyosha", "reference/src/gba-tests-alyosha/memory/PAL_8_bit_writes.gba"), ), # The picture (rung 3): each judge is a frame in tests/frames_pass.txt. ( "DISPCNT acts one line after a write, not two (no three-deep latch)", "ppu/__init__.py", "latch[0], latch[1], latch[2] = latch[1], latch[2], self.registers[0]", "latch[0], latch[1], latch[2] = latch[2], self.registers[0], self.registers[0]", ("frames", "reference/src/hw-test/ppu/dispcnt-latch/dispcnt-latch.gba@400"), ), ( "forced blank still draws the picture", "ppu/__init__.py", "if not (self.dispcnt_latch[0] | dispcnt) & 0x80:", "if True:", ("frames", "reference/src/hw-test/ppu/dispcnt-latch/dispcnt-latch.gba@400"), ), ( "affine reference points reload every line, not only after a write", "ppu/__init__.py", "if self.affine_dirty[bg][axis] or line == 0:", "if True:", ("frames", "reference/src/hw-test/ppu/bgpd/bgpd.gba@400"), ), # Not seeded: "the internal point does not step while the BG is disabled" (NBA, "confirmed # on real hardware"). No agreed frame here depends on it (docs/validation.md, rung 3). ( "OBJ mosaic: a pixel in front waits for the mosaic block", "ppu/compose.py", "or priority < held_priority", "or False", ("frames", "reference/src/hw-test/ppu/sprite-hmosaic/sprite-hmosaic.gba@400"), ), ( "JOYCNT keeps the event flags the BIOS writes to acknowledge", "serial.py", "flags = self.joy[0] & 7 & ~value", "flags = value & 7", ("mgba-score", "SIO register R/W tests"), ), ( "skip_bios leaves BG2/BG3 PA = PD = 0, not the BIOS's 100h", "board.py", " (0x020, 0x0100),\n", "", ("handoff", "reference/src/gba-tests/arm/arm.gba"), ), # The picture, dot-exact (rung 4). ( "register writes during a line reach the whole line (no dot engine)", "ppu/__init__.py", "self._start_dot(now) # the line changes while it is drawn: draw it dot by dot", "pass", ("frames", "reference/src/hw-test/ppu/greenswap/greenswap.gba@400"), ), ( "CPU accesses to OBJ VRAM never wait for the OBJ engine", "ppu/__init__.py", "return engine.last_vram >= 0 and self.obj_start + 2 * engine.last_vram == now - 1", "return False", ("alyosha", "reference/src/gba-tests-alyosha/ppu/Sprite_Last_VRAM_Access.gba"), ), ( "the HBlank-free OBJ window runs 964 cycles (NanoBoyAdvance)", "ppu/objects.py", "(960 if source.registers[0] & 0x20 else 1232)", "(964 if source.registers[0] & 0x20 else 1232)", ("alyosha", "reference/src/gba-tests-alyosha/ppu/Sprite_Last_VRAM_Access_Free.gba"), ), ( "keypad AND IRQ needs exactly the selected keys down (NanoBoyAdvance)", "keypad.py", "if selected & down == selected:", "if selected == down:", ("keyirq", "tests/test_roms/keyirq/keyirq.gba#2"), ), ( "BIOS reads take 2 cycles, not 1", "board.py", "elif page == 0x00:\n self.step(1)", "elif page == 0x00:\n self.step(2)", ("krom", "reference/src/PeterLemon-GBA/BIOS/Arithmetic/DIV/BIOSDIV.gba"), ), ( # The library verifies each sector as it writes it, so a bank switch that does nothing # (both banks aliased) passes it: not seeded against this judge. "Flash byte program does nothing", "cartridge/backup.py", "self.data[self._physical(address)] = value", "self.data[self._physical(address)] = 0xFF", ("backuplib", "flash128#INC"), ), # ----- rung 5: sound. The FIFO's DMA has a hardware judge; the mixer and the channels' # clock have none here (the comparison with NanoBoyAdvance is a detector over minutes of # music), so each of those rules is held by its unit test in tests/test_apu.py ("rule"). ( "a FIFO's DMA request takes two cycles, not three (NanoBoyAdvance)", "dma.py", "FIFO_DELAY = 3", "FIFO_DELAY = 2", ("alyosha", "reference/src/gba-tests-alyosha/fifo_dma/fifo_2.gba"), ), ( "a FIFO request during a refill is dropped (NanoBoyAdvance)", "dma.py", " self.channels[index].fifo_again = True", " pass", ("rule", "test_a_request_during_a_refill_reads_a_fifth_word_and_leaves_three"), ), ( "a request for a refill still waiting counts as one during it", "dma.py", "if self.channels[index].moving:", "if True:", ("rule", "test_a_request_for_a_refill_still_waiting_adds_nothing"), ), ( "the refill after a five-word one moves four words", "dma.py", " owed = 3", " owed = 4", ("rule", "test_a_request_during_a_refill_reads_a_fifth_word_and_leaves_three"), ), ( "a DMA's IRQ is raised with its last write, not a cycle later", "dma.py", "self.scheduler.add(1, self.irq.raise_, DMA0 + channel.id)", "self.irq.raise_(DMA0 + channel.id)", ("alyosha", "reference/src/gba-tests-alyosha/fifo_dma/fifo_6.gba"), ), ( "the Game Boy channels run at half the system clock", "apu.py", "target = self.scheduler.now >> 2", "target = self.scheduler.now >> 1", ("rule", "test_channels_run_at_a_quarter_of_the_system_clock"), ), ( "the frame sequencer steps every 65,536 cycles", "apu.py", "SEQUENCER_HALF = 4096", "SEQUENCER_HALF = 8192", ("rule", "test_frame_sequencer_steps_every_32768_cycles_from_power_on"), ), ( "the high register byte is written before the low one", "apu.py", "for byte in (offset, offset + 1):", "for byte in (offset + 1, offset):", ("rule", "test_channel_registers_reach_the_core_at_their_gba_offsets"), ), ( "master enable off leaves the FIFOs full", "apu.py", "if was_on and not psg.power:", "if False:", ("rule", "test_master_enable_off_clears_and_locks"), ), ( "PSG volume setting 0 is 50 %", "apu.py", "PSG_VOLUME = (1, 2, 4, 0)", "PSG_VOLUME = (2, 2, 4, 0)", ("rule", "test_psg_volume_is_25_50_100_percent_and_scaled_by_nr50"), ), ( "NR50's left volume scales the right side", "apu.py", "right = right * scale * ((nr50 & 7) + 1) >> 5", "right = right * scale * ((nr50 >> 4 & 7) + 1) >> 5", ("rule", "test_psg_volume_is_25_50_100_percent_and_scaled_by_nr50"), ), ( "NR51's right bits route to the left", "apu.py", "if nr51 & 0x10 << channel:", "if nr51 & 1 << channel:", ("rule", "test_nr51_routes_each_channel_to_a_side"), ), ( "FIFO A's 50 % is 100 %", "apu.py", "fifo_a = self.fifo[0].sample * (4 if cnt_h & 4 else 2)", "fifo_a = self.fifo[0].sample * 4", ("rule", "test_fifo_volume_sides_and_the_10_bit_clip"), ), ( "FIFO A's right enable feeds the left", "apu.py", "if cnt_h & 0x0100:\n right += fifo_a", "if cnt_h & 0x0100:\n left += fifo_a", ("rule", "test_fifo_volume_sides_and_the_10_bit_clip"), ), ( "the output does not clip at 10 bits", "apu.py", "min(max(left + bias, 0), 0x3FF) - 0x200,", "left + bias - 0x200,", ("rule", "test_fifo_volume_sides_and_the_10_bit_clip"), ), ( "SOUNDBIAS's level is always 200h", "apu.py", "bias = self.soundbias & 0x3FE", "bias = 0x200", ("rule", "test_soundbias_level_moves_the_clip"), ), ( "the faster SOUNDBIAS rates are not averaged down", "apu.py", "if self._summed >= 1 << (self.soundbias >> 14):", "if self._summed >= 1:", ("rule", "test_capture_gives_32768_stereo_samples_a_second_at_every_resolution"), ), # Not seeded: the BG engine's and the merge's waits (BG VRAM, palette). No hardware judge # here measures them (hw-test ppu/ram-access-timing draws its measurements and ships no # reference); NanoBoyAdvance's lockstep is the only check (docs/validation.md, rung 4). ] RUNNER = """ import json, sys sys.path[:0] = [{src!r}, {scripts!r}] import gba_python assert gba_python.__file__.startswith({src!r}), gba_python.__file__ from run_test_roms import run_one suite, key = {suite!r}, {key!r} if suite == "mgba-score": # A group the board passes only in part: the fault must lower its recorded score # (tests/mgba_scores.txt, the slow test's floor). result = run_one(("mgba", key), None, None) scores = dict(line.split("\t") for line in open({scores!r}).read().splitlines()) floor = int(scores[key].split("/")[0]) result["passed"] = result["passes"] is not None and result["passes"] >= floor result["detail"] += f", recorded {{scores[key]}}" else: result = run_one((suite, key), None, None) print(json.dumps({{"passed": result["passed"], "detail": result["detail"]}})) """ def run_fault(fault: tuple) -> dict: name, file, text, replacement, (suite, key) = fault with tempfile.TemporaryDirectory() as scratch: copy = Path(scratch) / "src" shutil.copytree(ROOT / "src", copy) target = copy / "gba_python" / file source = target.read_text() if source.count(text) != 1: return {"fault": name, "error": f"text found {source.count(text)} times in {file}"} target.write_text(source.replace(text, replacement)) if suite == "rule": out = subprocess.run( [sys.executable, "-m", "pytest", "-q", "-x", "-p", "no:cacheprovider", "-o", f"pythonpath={copy} .", "tests/test_apu.py", "-k", key], capture_output=True, text=True, check=False, cwd=ROOT, ) # fmt: skip if out.returncode not in (0, 1): return {"fault": name, "judge": key, "error": out.stdout.strip()[-400:]} passed = out.returncode == 0 return {"fault": name, "judge": key, "caught": not passed, "detail": "unit test"} code = RUNNER.format( src=str(copy), scripts=str(ROOT / "scripts"), suite=suite, key=key, scores=str(ROOT / "tests" / "mgba_scores.txt"), ) out = subprocess.run( [sys.executable, "-c", code], capture_output=True, text=True, check=False ) if out.returncode: return {"fault": name, "judge": key, "error": out.stderr.strip()[-400:]} result = json.loads(out.stdout.strip().splitlines()[-1]) return {"fault": name, "judge": key, "caught": not result["passed"], **result} def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--only", help="run only faults whose name contains this") parser.add_argument("--jobs", type=int, default=16) args = parser.parse_args() faults = [f for f in FAULTS if not args.only or args.only in f[0]] with ThreadPoolExecutor(max_workers=args.jobs) as pool: results = list(pool.map(run_fault, faults)) caught = 0 for result in results: if "error" in result: print(f"ERROR {result['fault']}: {result['error']}") continue caught += result["caught"] mark = "caught" if result["caught"] else "MISSED" print(f"{mark:6} {result['fault']:70} {result['judge'].split('/')[-1]} {result['detail']}") print(f"{caught} of {len(results)} seeded faults fail their judge") return 0 if caught == len(results) else 1 if __name__ == "__main__": sys.exit(main())