#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Rung 7: a gate that cannot fail proves nothing. Seed one fault at a time into a copy of the crate and show that the ladder catches each, and which rungs do. Each fault is one exact text replacement (the text must occur exactly once) in a fresh copy of ``src/``, ``tests/``, ``Cargo.toml``, ``Cargo.lock`` and ``README.md`` (the doctest), written anew so every file has a new timestamp and cargo cannot reuse a stale build (the methodology's lesson of 2026-11-13), built in its worker's own target directory. Then every judge runs on it against the reference's cached results (the ladder fills the caches; run it first): - rung 0: ``gen_tables.py --check`` on the copy's tables and ``cargo test``; - rung 1: the SingleStepTests gate's per-file counts against the reference's; - rung 2: every corpus case's hash against the reference's; - rung 3: the 15 ROMs through the CLI, output and bus trace against the reference's; - rung 4: the 15 ROMs in per-instruction lockstep; - rung 5: the 96 random-memory, 16 mask and 8 msrt scenarios in lockstep; - rung 6: the 7,000,000 multiplies against zaydlang's model. The control run (no fault) must pass every judge, or nothing is concluded. A fault no rung catches is reported as a blind spot (or, if it cannot change anything observable, an equivalent mutant), never counted as caught. seeded_faults.py [--only WORD] [--jobs N] [--json OUT] """ from __future__ import annotations import argparse import json import os import shutil import subprocess import sys from concurrent.futures import ThreadPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] WORK = ROOT / "external" / "faults" NICE = ["nice", "-n", "19"] # (name, file, exact text, replacement) FAULTS = [ # -- ALU and shifter ------------------------------------------------------------------------ ("SUB's carry is a borrow off by one (>= becomes >)", "src/alu.rs", "if a as u64 >= b as u64 + borrow as u64 {", "if a as u64 > b as u64 + borrow as u64 {"), ("ADD's overflow uses a ^ b instead of NOT (a ^ b)", "src/alu.rs", "if !(a ^ b) & (b ^ result) & FLAG_N != 0 {", "if (a ^ b) & (b ^ result) & FLAG_N != 0 {"), ("a shift by register makes no internal cycle", "src/alu.rs", " self.r[15] = self.r[15].wrapping_add(4);\n self.idle(self.r[15]);\n return shift_by_register", " self.r[15] = self.r[15].wrapping_add(4);\n return shift_by_register"), ("LSR by register keeps C = 0 (U10)", "src/alu.rs", "((value as u64) >> amount) as u32,\n (value >> (amount - 1)) & 1,", "((value as u64) >> amount) as u32,\n 0,"), ("RRX rotates C into bit 30", "src/alu.rs", "return ((value >> 1) | (carry << 31), value & 1);", "return ((value >> 1) | (carry << 30), value & 1);"), ("a test operation with Rd = R15 and S does not restore the CPSR (U13)", "src/alu.rs", " if rd == 15 {\n if op & S_BIT != 0 {\n self.restore_cpsr_from_spsr();\n }", " if rd == 15 {\n if op & S_BIT != 0 && result.is_some() {\n self.restore_cpsr_from_spsr();\n }"), ("a rotated immediate never sets the shifter carry", "src/alu.rs", " if (op >> 8) & 0xF != 0 {\n value >> 31", " if (op >> 8) & 0xF == 16 {\n value >> 31"), ("Thumb ADD Rd, PC does not clear bit 1", "src/alu.rs", "(self.r[15] & !2).wrapping_add((op & 0xFF) << 2);\n self.thumb_next();", "self.r[15].wrapping_add((op & 0xFF) << 2);\n self.thumb_next();"), ("Thumb hi-register forms take H1 from bit 6", "src/alu.rs", "let rd = ((op & 7) | ((op >> 4) & 8)) as usize;", "let rd = ((op & 7) | ((op >> 3) & 8)) as usize;"), # -- PSR transfers -------------------------------------------------------------------------- ("MSR does not force M4 (alyosha-tas psr)", "src/psr.rs", " new |= 0x10; // M4", " new |= 0x00; // M4"), ("MSR in User mode writes the control field", "src/psr.rs", " mask &= FIELD_MASKS[3];", " mask &= 0xFFFF_FFFF;"), # -- multiplies ----------------------------------------------------------------------------- ("UMULL stops early on ones too (U11)", "src/multiply.rs", "if top == 0 || (signed && top == u32::MAX >> shift) {", "if top == 0 || top == u32::MAX >> shift {"), ("the four-iteration MUL carry reads bit 7", "src/multiply.rs", "let bit = if flavor == SHORT { 6 } else { 38 };", "let bit = if flavor == SHORT { 7 } else { 38 };"), ("MLA makes no extra internal cycle", "src/multiply.rs", " }\n self.idle(self.r[15]);\n }\n self.r[15] = self.r[15].wrapping_add(4);", " }\n }\n self.r[15] = self.r[15].wrapping_add(4);"), ("MLA's R15 as Rn reads pc+8 (U12)", "src/multiply.rs", " rn = rn.wrapping_add(4); // R15", " rn = rn.wrapping_add(0); // R15"), ("a long multiply's N comes from bit 31", "src/multiply.rs", "self.multiply_flags(result >> 63 != 0, result == 0, carry);", "self.multiply_flags(result >> 31 & 1 != 0, result == 0, carry);"), # -- single transfers ----------------------------------------------------------------------- ("a misaligned word load does not rotate (U1)", "src/transfer.rs", "return ror32(self.read(address, 32, false, false), (address & 3) * 8);", "return ror32(self.read(address, 32, false, false), 0);"), ("a misaligned LDRSH sign-extends the halfword (C4)", "src/transfer.rs", " sign_extend_from(value >> 8, 8)\n", " sign_extend_from(value, 16)\n"), ("a store's next fetch is S", "src/transfer.rs", "self.next_fetch_seq = false; // two N cycles back to back", "self.next_fetch_seq = true; // two N cycles back to back"), ("write-back wins over the loaded base (U6)", "src/transfer.rs", " let pc_written = self.write_back(op, rn, offset);\n self.idle(self.r[15]); // data to Rd: I cycle at pc+3L\n self.set_reg(rd, value);", " self.set_reg(rd, value);\n let pc_written = self.write_back(op, rn, offset);\n self.idle(self.r[15]); // data to Rd: I cycle at pc+3L"), ("Thumb LDR Rd, [PC] does not clear bit 1", "src/transfer.rs", "let address = (self.r[15] & !2).wrapping_add((op & 0xFF) << 2);", "let address = self.r[15].wrapping_add((op & 0xFF) << 2);"), ("LDRD makes one internal cycle (U21)", "src/transfer.rs", "self.doubleword_encoding(op, 2);", "self.doubleword_encoding(op, 1);"), # -- block transfers ------------------------------------------------------------------------ ("an empty ARM list moves the base by 0x3C", "src/block.rs", " 0x40\n };\n if registers.len == 0 {\n registers.push(15);\n }\n let base = self.reg(rn);", " 0x3C\n };\n if registers.len == 0 {\n registers.push(15);\n }\n let base = self.reg(rn);"), ("STM writes the base back after its second transfer", "src/block.rs", " self.write(address, 32, value, seq, false);\n if index == 0 && write_back {", " self.write(address, 32, value, seq, false);\n if index == 1 && write_back {"), ("no LDM^ glitch (U7)", "src/block.rs", " self.glitch_next = true; // U7", " self.glitch_next = false; // U7"), ("the glitch replaces instead of OR-ing (U7)", "src/block.rs", " value |= self.bank[BANK_USER][n - 8];", " value = self.bank[BANK_USER][n - 8];"), ("LDM^ with R15 does not restore the CPSR", "src/block.rs", " if s_bit {\n self.restore_cpsr_from_spsr();\n }", " if s_bit && false {\n self.restore_cpsr_from_spsr();\n }"), ("POP {PC} keeps bit 0 of the loaded PC (U20)", "src/block.rs", "self.block_thumb(13, registers, true, false, op & 0x100 == 0);", "self.block_thumb(13, registers, true, false, true);"), # -- branches ------------------------------------------------------------------------------- ("Thumb BL leaves bit 0 of LR clear", "src/branch.rs", "let link = self.r[15].wrapping_sub(2) | 1;", "let link = self.r[15].wrapping_sub(2);"), ("Thumb BL's first half shifts by 11", "src/branch.rs", "(signed(op & 0x7FF, 11) << 12) as u32", "(signed(op & 0x7FF, 11) << 11) as u32"), ("BX to ARM clears bit 1 of R15 (U20)", "src/branch.rs", " self.cpsr &= !THUMB;\n self.set_pc(target);", " self.cpsr &= !THUMB;\n self.set_pc(target & !2);"), # -- exceptions ----------------------------------------------------------------------------- ("the undefined trap makes no internal cycle (C5)", "src/exception.rs", " fn undefined(&mut self, length: u32) {\n self.idle(self.r[15]);", " fn undefined(&mut self, length: u32) {"), ("MRC p14 to R15 leaves the flags alone (U17)", "src/exception.rs", "self.cpsr = (self.cpsr & 0x0FFF_FFFF) | (value & 0xF000_0000);", "self.cpsr &= 0xFFFF_FFFF;"), ("Thumb SWI links to pc+4 less 4", "src/exception.rs", "self.enter_exception(0x08, SVC, self.r[15].wrapping_sub(2), false);", "self.enter_exception(0x08, SVC, self.r[15].wrapping_sub(4), false);"), ("MCR p14 makes an internal cycle, not a coprocessor cycle", "src/exception.rs", " self.coprocessor_cycle(self.r[15]);\n self.next_fetch_seq = false;", " self.idle(self.r[15]);\n self.next_fetch_seq = false;"), # -- the core: interrupts, modes, pipeline, Rust's own forms --------------------------------- ("setting F masks FIQ at once (U14)", "src/core.rs", "if self.fiq && !(self.fiq_masked && cpsr & MASK_F != 0) {\n self.take_interrupt", "if self.fiq && cpsr & MASK_F == 0 {\n self.take_interrupt"), ("clearing I acts one instruction late (U14)", "src/core.rs", "} else if self.irq && !(self.irq_masked && cpsr & MASK_I != 0) {", "} else if self.irq && !(self.irq_masked || cpsr & MASK_I != 0) {"), ("FIQ entry keeps the interrupted instruction's masks (U14)", "src/core.rs", " self.irq_masked = self.cpsr & MASK_I != 0;\n self.fiq_masked = self.cpsr & MASK_F != 0;\n } else if self.irq", " } else if self.irq"), ("a Thumb refill fetches at R15 with bit 0 (C3)", "src/core.rs", " let fetch = pc & !1;", " let fetch = pc;"), ("a mode that names no mode banks R13-R14 as Supervisor's", "src/core.rs", " let slot = if old == BANK_INVALID { BANK_USER } else { old };", " let slot = if old == BANK_INVALID { BANK_FIQ + 1 } else { old };"), ("restore_state gives a mode that names no mode no SPSR (unlike the reference)", "src/core.rs", " self.spsr_bank = if current == BANK_USER {\n", " self.spsr_bank = if current == BANK_USER || current == BANK_INVALID {\n"), ("the LDM^ glitch lasts two cycles into the next instruction", "src/core.rs", "if self.glitch && self.cycles >= 2 {", "if self.glitch && self.cycles >= 3 {"), ("the condition table is built from the wrong flag bits", "src/core.rs", "condition_passes(cond as u32, (flags as u32) << 28);", "condition_passes(cond as u32, (flags as u32) << 27);"), ("width_mask treats 32 bits as 31", "src/core.rs", " if width >= 32 {\n MASK32", " if width > 32 {\n MASK32"), ("ARM IRQ entry links to pc+8", "src/core.rs", " self.r[15].wrapping_sub(4) // pc + 4", " self.r[15] // pc + 4"), ("an unexecuted ARM instruction's next fetch is N", "src/core.rs", " self.next_fetch_seq = true;\n self.r[15] = self.r[15].wrapping_add(4);\n }\n }\n\n fn execute_thumb", " self.next_fetch_seq = false;\n self.r[15] = self.r[15].wrapping_add(4);\n }\n }\n\n fn execute_thumb"), ("a Thumb step mixes bits 31:16 into an ARM word an MSR left in the pipeline (U16)", "src/core.rs", "let op = self.pipeline[0] & 0xFFFF;", "let op = (self.pipeline[0] ^ (self.pipeline[0] >> 16)) & 0xFFFF;"), # -- swap, state, tables, harness ----------------------------------------------------------- ("SWP reads Rm before its read cycle (U7)", "src/swap.rs", " value = ror32(self.read(address, 32, false, true), (address & 3) * 8);\n let rm = self.reg((op & 0xF) as usize);", " let rm = self.reg((op & 0xF) as usize);\n value = ror32(self.read(address, 32, false, true), (address & 3) * 8);"), ("SWP's write is not locked", "src/swap.rs", "self.write(address, 32, rm, false, true);", "self.write(address, 32, rm, false, false);"), ("from_sst does not load the FIQ bank into R8-R14", "src/state.rs", " registers[8..15].copy_from_slice(&banks[BANK_FIQ]);\n", "\n"), ("one decode-table entry: MUL's encoding runs MLA", "src/tables.rs", " // 0x000\n ArmAnd, ArmAnd, ArmAnd, ArmAnd, ArmAnd, ArmAnd, ArmAnd, ArmAnd, ArmAnd, ArmMul,", " // 0x000\n ArmAnd, ArmAnd, ArmAnd, ArmAnd, ArmAnd, ArmAnd, ArmAnd, ArmAnd, ArmAnd, ArmMla,"), ("the harness's DISPSTAT never toggles", "src/harness.rs", " self.vblank = !self.vblank;", " self.vblank = self.vblank;"), ("the harness lets the program write its ROM", "src/harness.rs", " if index != self.rom {", " if index != usize::MAX {"), ] # fmt: skip RUNGS = ["r0", "r1", "r2", "r3", "r4", "r5", "r6"] def env() -> dict[str, str]: return {**os.environ, "PYPY_GC_NURSERY": "1M"} def run(command: list[str], **kwargs) -> subprocess.CompletedProcess: return subprocess.run([*NICE, *command], capture_output=True, text=True, env=env(), **kwargs) def faulted_tree(slot: int, fault: tuple | None) -> Path: tree = WORK / f"tree-{slot}" if tree.exists(): shutil.move(str(tree), str(WORK / f"old-{slot}-{os.getpid()}-{len(list(WORK.iterdir()))}")) tree.mkdir(parents=True) for name in ("src", "tests"): for source in (ROOT / name).rglob("*"): if source.is_file(): target = tree / source.relative_to(ROOT) target.parent.mkdir(parents=True, exist_ok=True) target.write_bytes(source.read_bytes()) # written anew: fresh timestamps for name in ("Cargo.toml", "Cargo.lock", "README.md"): # README.md: the doctest (tree / name).write_bytes((ROOT / name).read_bytes()) if fault: _, file, text, replacement = fault path = tree / file source = path.read_text() if source.count(text) != 1: raise SystemExit(f"fault text occurs {source.count(text)} times in {file}: {text!r}") path.write_text(source.replace(text, replacement)) return tree def judge(tree: Path, slot: int) -> dict[str, bool] | str: target = WORK / f"target-{slot}" build = run(["cargo", "build", "--release", "-q", "-j", "4", "--manifest-path", str(tree / "Cargo.toml"), "--target-dir", str(target)]) if build.returncode: return "does not build: " + build.stderr.strip()[-300:] binary = target / "release" paths = {k: os.environ[k] for k in ("SST_CORPUS", "REFCACHE", "REFERENCE")} caught: dict[str, bool] = {} tables = run(["python3", str(ROOT / "scripts" / "gen_tables.py"), "--check", "--target", str(tree / "src" / "tables.rs")]) tests = run(["cargo", "test", "--release", "-q", "-j", "4", "--manifest-path", str(tree / "Cargo.toml"), "--target-dir", str(target)]) caught["r0"] = bool(tables.returncode or tests.returncode) report = WORK / f"sst-{slot}.json" run([str(binary / "arm7-sst"), paths["SST_CORPUS"], "--overrides", f"{paths['REFERENCE']}/tests/sst_overrides.json", "--jobs", "2", "--json", str(report)]) try: caught["r1"] = json.loads(report.read_text()) != json.loads((Path(paths["REFCACHE"]) / "sst-gate.json").read_text()) except (OSError, ValueError): caught["r1"] = True caught["r2"] = run([str(binary / "arm7-sst"), paths["SST_CORPUS"], "--lockstep", f"{paths['REFCACHE']}/sst", "--jobs", "2"]).returncode != 0 traces = WORK / f"traces-{slot}" caught["r3"] = run(["python3", str(ROOT / "scripts" / "rom_cli.py"), "--reference-cache", f"{paths['REFCACHE']}/roms", "--rust", str(binary / "arm7tdmi"), "--traces", str(traces)]).returncode != 0 scenarios = ROOT / "external" / "scenarios" for rung, pattern in (("r4", "rom-*.json"), ("r5", "[fm][uas]*-*.json")): # fuzz, mask, msrt caught[rung] = run(["python3", str(ROOT / "scripts" / "lockstep.py"), *map(str, sorted(scenarios.glob(pattern))), "--reference-cache", f"{paths['REFCACHE']}/traces", "--rust", str(binary / "arm7-trace"), "--traces", str(traces), "--jobs", "2", "--quiet"]).returncode != 0 caught["r6"] = run([str(binary / "arm7-multiply"), f"{paths['REFCACHE']}/multiply"]).returncode != 0 return caught def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--only", help="only the faults whose name contains this") parser.add_argument("--jobs", type=int, default=3) parser.add_argument("--json", type=Path, default=WORK / "result.json") args = parser.parse_args() for key in ("SST_CORPUS", "REFCACHE", "REFERENCE", "REFERENCE_PYTHON", "TEST_ROMS"): if key not in os.environ: raise SystemExit("source scripts/env.sh first (rung7.sh does)") WORK.mkdir(parents=True, exist_ok=True) faults = [f for f in FAULTS if not args.only or args.only in f[0]] for fault in faults: # every text must be there before anything is built source = (ROOT / fault[1]).read_text() if source.count(fault[2]) != 1: raise SystemExit(f"{fault[0]}: the text occurs {source.count(fault[2])} times in {fault[1]}") control = judge(faulted_tree(0, None), 0) if not isinstance(control, dict) or any(control.values()): print(f"control run is not clean: {control}") return 1 print("control: every judge passes", flush=True) slots = list(range(args.jobs)) def one(task: tuple[int, tuple]): index, fault = task slot = slots[index % len(slots)] return fault[0], judge(faulted_tree(slot, fault), slot) results: dict[str, dict[str, bool] | str] = {} caught_count = 0 # Each slot works through its own share in order, so no two faults share a tree at once. shares = [[(i, f) for i, f in enumerate(faults) if i % len(slots) == s] for s in slots] with ThreadPoolExecutor(len(slots)) as pool: for share in pool.map(lambda tasks: [one(t) for t in tasks], shares): for name, verdict in share: results[name] = verdict for fault in faults: verdict = results[fault[0]] if isinstance(verdict, str): print(f"NOT RUN {fault[0]}: {verdict}") continue by = [r for r in RUNGS if verdict[r]] caught_count += bool(by) print(f"{'caught' if by else 'MISSED':7} {fault[0]}: {' '.join(by) or '-'}") counts = {r: sum(1 for v in results.values() if isinstance(v, dict) and v[r]) for r in RUNGS} print(f"\n{caught_count} of {len(faults)} faults caught; by rung: " + ", ".join(f"{r} {n}" for r, n in counts.items())) args.json.write_text(json.dumps(results, indent=1) + "\n") return 0 if caught_count == len(faults) else 1 if __name__ == "__main__": sys.exit(main())