#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Write the lockstep scenarios (rungs 4 and 5) into external/scenarios. Stdlib only. - ``rom-*.json``: each CPU test ROM of the reference's rungs 2-3 in the minimal harness, one slice per instruction, to its branch to itself (``$TEST_ROMS`` is expanded by both sides). - ``fuzz-*.json`` (with ``fuzz-*.bin``): random memory (1 KiB to 64 KiB, mirrored through the whole address space), a random starting state in a random mode (the six named modes, System, and some values that name no mode) in ARM or Thumb state, and the IRQ and FIQ lines raised and dropped at random between instructions. Random memory reaches what programs avoid: every encoding (undefined, coprocessor, NV, the doubleword encodings), exceptions and their vectors, mode changes by MSR and by ``S`` with R15, LDM^ and its glitch, unaligned transfers, interrupts taken in both states and under both masks. - ``mask-*.json``: U14 (MSR CPSR_c, #imm changing I and F, lines changed at almost every step). - ``msrt-*.json``: U16 (MSR CPSR_fc, Rm setting T: the prefetched ARM words run as Thumb). The scenario files are inputs, generated the same way every time (seeded), so the reference's cached traces stay valid. make_scenarios.py [--fuzz N] [--mask N] [--msrt N] [--steps N] """ from __future__ import annotations import argparse import json import random import struct from pathlib import Path ROOT = Path(__file__).resolve().parents[1] OUT = ROOT / "external" / "scenarios" ROMS = [ "jsmolka-gba-tests/arm/arm.gba", "jsmolka-gba-tests/thumb/thumb.gba", "alyosha-gba-tests/arm/arm.gba", "alyosha-gba-tests/thumb/blx.gba", "alyosha-gba-tests/thumb/cpy.gba", "alyosha-gba-tests/arm/Coprocessor_14.gba", "alyosha-gba-tests/thumb/Push_no_regs.gba", *( f"alyosha-gba-tests/LDM/{name}.gba" for name in ( "LDM_ALU", "LDM_ALU_IMM", "LDM_ALU_Store", "LDM_Bx", "LDM_LD", "LDM_MUL_UL_32", "LDM_MUL_UL_SL", "LDM_Swap", ) ), ] # fmt: skip MODES = [0x10, 0x11, 0x12, 0x13, 0x17, 0x1B, 0x1F] INVALID_MODES = [0x00, 0x05, 0x14, 0x1A, 0x1E] # Exception vectors that return to the interrupted code, CPSR restored from the SPSR (so # Thumb code stays in Thumb): MOVS PC, R14 for the undefined trap and SWI, SUBS PC, R14, #4 # for the aborts, IRQ and FIQ. VECTORS = [0xEAFFFFFE, 0xE1B0F00E, 0xE1B0F00E, 0xE25EF004, 0xE25EF008, 0xEAFFFFFE, 0xE25EF004, 0xE25EF004] def fuzz(index: int, steps: int) -> None: """Flavour by index: 0 raw random memory; 1 random memory with returning vectors and half the ARM words made unconditional; 2 the same, started in Thumb state.""" rng = random.Random(0xA7_0000 + index) flavour = index % 3 size = rng.choice([0x400, 0x1000, 0x4000, 0x10000]) memory = bytearray(rng.getrandbits(8) for _ in range(size)) if flavour: if flavour == 1: for at in range(0, size, 4): if rng.random() < 0.5: memory[at + 3] = 0xE0 | (memory[at + 3] & 0x0F) # condition AL if rng.random() < 0.01: # BX Rn, which random words almost never are memory[at : at + 4] = (0xE12FFF10 | rng.getrandbits(4)).to_bytes(4, "little") for n, word in enumerate(VECTORS): memory[4 * n : 4 * n + 4] = word.to_bytes(4, "little") memory = bytes(memory) mode = rng.choice(INVALID_MODES) if rng.random() < 0.08 else rng.choice(MODES) thumb = flavour == 2 or (flavour == 0 and rng.random() < 0.5) cpsr = rng.getrandbits(4) << 28 | rng.getrandbits(2) << 6 | (0x20 if thumb else 0) | mode if rng.random() < 0.05: cpsr |= rng.getrandbits(19) << 8 # reserved bits set (the corpus has such states) word = (lambda: rng.getrandbits(16)) if thumb else (lambda: rng.getrandbits(32)) pc = rng.getrandbits(32) & ~(1 if thumb else 3) state = { "registers": [rng.getrandbits(32) for _ in range(15)] + [pc], "banks": [[rng.getrandbits(32) for _ in range(7)] for _ in range(6)], "cpsr": cpsr, "spsr": [0] + [rng.getrandbits(32) for _ in range(5)], "pipeline": [word(), word()], "next_fetch_seq": rng.random() < 0.5, } # Lines: quiet stretches, single pulses, long assertions; IRQ more often than FIQ. lines, irq, fiq, step = [], 0, 0, 0 rate = rng.choice([0.002, 0.01, 0.05]) while step < steps: step += 1 + int(rng.expovariate(rate)) if step >= steps: break if rng.random() < 0.75: irq ^= 1 else: fiq ^= 1 lines.append([step, irq, fiq]) name = f"fuzz-{index:03d}" (OUT / f"{name}.bin").write_bytes(memory) scenario = { "kind": "fuzz", "memory": f"{name}.bin", "mask": size - 1, "state": state, "steps": steps, "slice": 16, "lines": lines, } (OUT / f"{name}.json").write_text(json.dumps(scenario) + "\n") def mask(index: int, steps: int) -> None: """``mask-*``: U14 under pressure. Code that is mostly MSR CPSR_c, #imm (random I and F, a random privileged mode, ARM state) between register moves, looping, with returning vectors, and both lines changed at random before almost every instruction: the line rises right after an MSR that set or cleared its mask, which random memory almost never arranges (the IRQ and FIQ masks' "one instruction late" and "at once" rules).""" rng = random.Random(0xA7_1000 + index) size = 0x1000 words = [] for _ in range(size // 4): pick = rng.random() # Only the immediate form, so these scenarios stay what they were: a register could # set T, which crashed the reference before its U16 fix (docs/status.md); the # ``msrt-*`` scenarios below are the register form. No R15 as a source. if pick < 0.5: imm = rng.getrandbits(2) << 6 | rng.choice(MODES[1:]) words.append(0xE321F000 | imm) # MSR CPSR_c, #imm else: words.append(0xE1A00000 | rng.randrange(13) << 12 | rng.randrange(15)) # MOV Rd, Rm words[: len(VECTORS)] = VECTORS words[-1] = 0xEA000000 | (((0x20 - (size - 4 + 8)) // 4) & 0xFFFFFF) # B 0x20 memory = b"".join(w.to_bytes(4, "little") for w in words) state = { "registers": [rng.getrandbits(32) & ~0x20 for _ in range(15)] + [0x28], "banks": [[rng.getrandbits(32) for _ in range(7)] for _ in range(6)], "cpsr": rng.getrandbits(2) << 6 | 0x13, "spsr": [0] + [rng.getrandbits(32) & ~0x20 for _ in range(5)], "pipeline": [words[8], words[9]], "next_fetch_seq": True, } lines, irq, fiq = [], 0, 0 for step in range(1, steps): if rng.random() < 0.3: irq ^= 1 if rng.random() < 0.3: fiq ^= 1 lines.append([step, irq, fiq]) name = f"mask-{index:03d}" (OUT / f"{name}.bin").write_bytes(memory) scenario = {"kind": "fuzz", "memory": f"{name}.bin", "mask": size - 1, "state": state, "steps": steps, "slice": 16, "lines": lines} (OUT / f"{name}.json").write_text(json.dumps(scenario) + "\n") def msrt(index: int, steps: int) -> None: """``msrt-*``: U16, an MSR that sets T. Code that is MSR CPSR_fc, Rm from registers whose control byte names a privileged mode with T set about half the time (and some MSR CPSR_c, #imm), between register moves, with returning vectors: after each T-setting MSR the two ARM words it prefetched run as Thumb (the reference's HYPOTHESIS: their bits 15:0; moves to R0-R7, whose low halfwords are Thumb shifts, adds, moves, ALU operations and transfers), then the halfwords of the word after them: BX PC, back to ARM (a word that in ARM state is MI-conditional undefined code, trapped and returned from). The lines change now and then.""" rng = random.Random(0xA7_2000 + index) size = 0x1000 veneer = 0x46C04778 # Thumb: BX PC (at a word address: ARM at + 4), MOV r8, r8 words: list[int] = [] while len(words) < size // 4: pick = rng.random() if pick < 0.3: words.append(0xE129F000 | rng.randrange(13)) # MSR CPSR_fc, Rm words += [0xE1A00000 | rng.randrange(8) << 12 | rng.randrange(13) for _ in range(2)] words.append(veneer) elif pick < 0.4: imm = rng.getrandbits(2) << 6 | rng.choice(MODES[1:]) words.append(0xE321F000 | imm) # MSR CPSR_c, #imm else: words.append(0xE1A00000 | rng.randrange(13) << 12 | rng.randrange(13)) # MOV Rd, Rm words = words[: size // 4] words[: len(VECTORS)] = VECTORS words[-1] = 0xEA000000 | (((0x20 - (size - 4 + 8)) // 4) & 0xFFFFFF) # B 0x20 def control() -> int: thumb = 0x20 if rng.random() < 0.5 else 0 return rng.getrandbits(4) << 28 | rng.getrandbits(2) << 6 | thumb | rng.choice(MODES[1:]) memory = b"".join(w.to_bytes(4, "little") for w in words) state = { "registers": [control() for _ in range(13)] + [rng.getrandbits(32), rng.getrandbits(32), 0x28], "banks": [[control() for _ in range(7)] for _ in range(6)], "cpsr": rng.getrandbits(2) << 6 | 0x13, "spsr": [0] + [rng.getrandbits(32) & ~0x20 for _ in range(5)], "pipeline": [words[8], words[9]], "next_fetch_seq": True, } lines, irq, fiq = [], 0, 0 for step in range(1, steps): if rng.random() < 0.02: irq ^= 1 if rng.random() < 0.01: fiq ^= 1 lines.append([step, irq, fiq]) name = f"msrt-{index:03d}" (OUT / f"{name}.bin").write_bytes(memory) scenario = {"kind": "fuzz", "memory": f"{name}.bin", "mask": size - 1, "state": state, "steps": steps, "slice": 16, "lines": lines} (OUT / f"{name}.json").write_text(json.dumps(scenario) + "\n") def elf(entry: int, address: int, code: bytes) -> bytes: """A minimal 32-bit little-endian ARM executable: one PT_LOAD segment of ``code`` at ``address`` (virtual and physical), entry ``entry``.""" header = struct.pack("<4sBBBB8sHHIIIIIHHHHHH", b"\x7fELF", 1, 1, 1, 0, bytes(8), 2, 40, 1, entry, 52, 0, 0x05000000, 52, 32, 1, 40, 0, 0) segment = struct.pack("<8I", 1, 84, address, address, len(code), len(code), 5, 4) return header + segment + code # The CLI's other paths (rung 3): raw images loaded with --at, in ARM and Thumb state, an ELF # file with a Thumb entry, an SWI into the absent BIOS, a run out of cycles. Each must give # the reference CLI's output, exit status and trace; they are not passes. CLI_IMAGES = { # MOV r12, #5; MOV r0, #1; ADD r0, r0, #1; B . "arm-raw.bin": struct.pack("<4I", 0xE3A0C005, 0xE3A00001, 0xE2800001, 0xEAFFFFFE), # MOV r0, #5; SUB r0, #1; B . (a 2-byte tail: the image is shorter than a word) "thumb-raw.bin": struct.pack("<3H", 0x2005, 0x3801, 0xE7FE), # MOV r0, #1; ADD r0, #2; MOV r12, r0; B . "thumb-entry.elf": elf(0x02000001, 0x02000000, struct.pack("<4H", 0x2001, 0x3002, 0x4684, 0xE7FE)), # MOV r12, #7; SWI 0 "swi.bin": struct.pack("<2I", 0xE3A0C007, 0xEF000000), # MOV r0, #0x08000000; MOV r1, #5; STR r1, [r0, #0x20]; LDR r12, [r0, #0x20]; B . # (the cartridge is read-only: R12 stays 0) "rom-write.bin": struct.pack("<5I", 0xE3A00302, 0xE3A01005, 0xE5801020, 0xE590C020, 0xEAFFFFFE), } CLI_CASES = [ ("arm-raw.bin", ["--at", "0x02000000"]), ("arm-raw.bin", []), ("thumb-raw.bin", ["--at", "0x03000000", "--thumb"]), ("thumb-entry.elf", []), ("swi.bin", []), ("swi.bin", ["--at", "0x06000000"]), ("rom-write.bin", []), ("$TEST_ROMS/jsmolka-gba-tests/arm/arm.gba", ["--max-cycles", "5000"]), ] def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--fuzz", type=int, default=96) parser.add_argument("--mask", type=int, default=16) parser.add_argument("--msrt", type=int, default=8) parser.add_argument("--steps", type=int, default=20_000) args = parser.parse_args() OUT.mkdir(parents=True, exist_ok=True) for rom in ROMS: name = "rom-" + rom.split("/", 1)[0].split("-")[0] + "-" + rom.split("/", 1)[1].replace("/", "-").removesuffix(".gba") scenario = {"kind": "rom", "rom": "$TEST_ROMS/" + rom, "slice": 1, "max_steps": 1_000_000} (OUT / f"{name}.json").write_text(json.dumps(scenario) + "\n") (OUT / "cli").mkdir(exist_ok=True) for name, data in CLI_IMAGES.items(): (OUT / "cli" / name).write_bytes(data) for index in range(args.fuzz): fuzz(index, args.steps) for index in range(args.mask): mask(index, args.steps) for index in range(args.msrt): msrt(index, args.steps) print(f"{len(ROMS)} ROM, {args.fuzz} fuzz, {args.mask} mask and {args.msrt} msrt scenarios in {OUT}") return 0 if __name__ == "__main__": raise SystemExit(main())