#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Rung 6: can the gate fail? One-line faults seeded into the transcription, each caught. python3 scripts/seeded_faults.py [--jobs 4] [--only N,N,...] Each fault is one textual change to a file of src/, the kind of slip a transcription makes (an off-by-one, a swapped case, a dropped line, a wrong constant). It is applied to a copy of the crate under the git-ignored external/faults// with fresh timestamps (methodology: a copy with old timestamps can let cargo reuse a stale build), built there, and judged by the rungs in order of cost: cargo test, rung 0 (tables), rung 1 (corpus, natively and in lockstep), rung 3 (pipeline), rung 4 (DN, 32xspd, the write buffer), rung 5 (fuzz), rung 2's prefix lockstep (MAME code). The first rung that fails catches it. The unbroken copy (fault 0) is judged first and must pass all of them. The reference's traces must be in the cache already (scripts/ladder.sh fills it). Exit status 1 if the unbroken copy fails or any fault goes uncaught. """ from __future__ import annotations import argparse import os import queue import shutil import subprocess import sys import threading from pathlib import Path ROOT = Path(__file__).resolve().parents[1] WORK = ROOT / "external" / "faults" # (what is broken, file, text to find, replacement); the text must occur exactly once. FAULTS: tuple[tuple[str, str, str, str], ...] = ( # -- the scheduler (pipeline.rs) -- ("an 'if' needs the previous longword's line", "pipeline.rs", "let request = if address & 2 != 0 && line == self.p_fetch_line {", "let request = if address & 2 != 0 {"), ("a fetch slot lasts its cycles with no minimum", "pipeline.rs", "length = ma + if fetched > 1 { fetched } else { 1 };", "length = ma + fetched;"), ("a load-use split is never made", "pipeline.rs", "self.p_lu[ring(ex)] = 1; // PM 7.5", "self.p_lu[ring(ex)] = 0; // PM 7.5"), ("a load-use split lasts the MA alone", "pipeline.rs", "length = ma + 1;\n split = true;", "length = ma;\n split = true;"), ("the multiplier's mm starts at the MA's start", "pipeline.rs", "self.p_mm_end = t0 + length + self.p_mm;", "self.p_mm_end = t0 + self.p_mm;"), ("a multiplier MA does not wait for mm", "pipeline.rs", "if self.p_mm_end - t0 > length {", "if false && self.p_mm_end - t0 > length {"), ("a taken BT/BF discards one fetch, not two", "pipeline.rs", "self.place(ex + 1);\n self.place(ex + 2);\n self.p_next_ex = ex + 3;", "self.place(ex + 1);\n self.p_next_ex = ex + 2;"), ("a delayed branch's slot is not stalled", "pipeline.rs", "self.place(ex + p.stall);\n self.p_next_ex = ex + 1 + p.stall;\n } else if kind == KIND_COND_DELAYED", "self.place(ex);\n self.p_next_ex = ex + 1;\n } else if kind == KIND_COND_DELAYED"), ("a taken BT/S makes no discarded fetch", "pipeline.rs", "self.place(ex); // PM figure 7.80", "// PM figure 7.80"), ("TRAPA overruns one fetch fewer", "pipeline.rs", "self.place(ex); // PM figures 7.93, 7.97", "// PM figures 7.93, 7.97"), ("SLEEP's next stall is table 7.2's 3", "pipeline.rs", "let stall = if pclass.name == \"sleep\" { 2 } else { pclass.next_id_stall };", "let stall = if pclass.name == \"sleep\" { 3 } else { pclass.next_id_stall };"), ("MAC.W's multiplier runs three states", "pipeline.rs", "\"IF ID EX MA MA mm mm\", 3, 1, 2,", "\"IF ID EX MA MA mm mm\", 3, 1, 3,"), ("MAC.L's first MA waits for the multiplier", "pipeline.rs", " \"mac_l\" => 1,", " \"mac_l\" => 0,"), ("RTE's slot stalls one slot", "pipeline.rs", "c(\"rte\", \"RTE\", \"IF ID EX MA MA\", 4, 3, 0,", "c(\"rte\", \"RTE\", \"IF ID EX MA MA\", 4, 1, 0,"), ("the saved pipeline forgets the write buffer", "pipeline.rs", " self.wb_end = values[13];\n", " self.wb_end = 0;\n"), # -- the core (core.rs) -- ("a buffered write releases the CPU two states later", "core.rs", "self.clock = taken + 1;", "self.clock = taken + 2;"), ("a read does not wait for a buffered write", "core.rs", " pub(crate) fn bus_read(&mut self, address: u32, width: u32, kind: u32) -> u32 {\n if self.clock < self.wb_end {", " pub(crate) fn bus_read(&mut self, address: u32, width: u32, kind: u32) -> u32 {\n if false && self.clock < self.wb_end {"), ("a line fills in address order", "core.rs", "for step in [4, 8, 12, 0] {", "for step in [0, 4, 8, 12] {"), ("a fill's first cycle is not marked", "core.rs", "let mut flag = FIRST;", "let mut flag = 0;"), ("IRL at the mask level is accepted", "core.rs", "self.irl > mask || self.onchip_level > mask", "self.irl >= mask || self.onchip_level > mask"), ("IRL n takes vector 64 + n", "core.rs", "self.exception(IRL_VECTOR_BASE + (level >> 1), pc, level as i64, INTERRUPT, -1);", "self.exception(IRL_VECTOR_BASE + level, pc, level as i64, INTERRUPT, -1);"), ("an on-chip source wins a tie with IRL", "core.rs", "if irl >= self.onchip_level {", "if irl > self.onchip_level {"), ("LDC and friends do not block an interrupt (outside a slot)", "core.rs", " self.retire(o.plan, pc as i64 + 2);\n self.no_interrupt = o.blocks;", " self.retire(o.plan, pc as i64 + 2);\n self.no_interrupt = false;"), # -fast: o.blocks, the Op record (67652c5) ("a fetch from on-chip space executes", "core.rs", "if pc & 1 != 0 || pc >= 0xFFFFFE00 {", "if pc & 1 != 0 {"), ("the exception pushes PC before SR", "core.rs", " self.write32(self.r[15], sr);\n self.r[15] = self.r[15].wrapping_sub(4);\n self.write32(self.r[15], saved_pc);", " self.write32(self.r[15], saved_pc);\n self.r[15] = self.r[15].wrapping_sub(4);\n self.write32(self.r[15], sr);"), ("the illegal instruction saves the next address", "core.rs", "let saved = self.pc.wrapping_sub(2);", "let saved = self.pc;"), ("a slot-illegal saves the slot's address", "core.rs", "self.exception(VECTOR_SLOT_ILLEGAL, target as u32, -1, ILLEGAL, -1);", "self.exception(VECTOR_SLOT_ILLEGAL, pc, -1, ILLEGAL, -1);"), ("a refresh cycle is a state longer", "core.rs", "let end = start + length + self.wait;\n self.bsc.refresh_end(end);", "let end = start + length + 1 + self.wait;\n self.bsc.refresh_end(end);"), ("a short SDRAM read drops the burst's unused cycles", "core.rs", "let unused = self.bsc.burst[area] - calls.len() as i64;", "let unused = 0;"), ("a longword read of the 8-bit on-chip half is allowed", "core.rs", "if (width == 8 && address >= 0xFFFFFF00) || (width == 32 && address < 0xFFFFFF00) {\n self.address_error = true; // HM table 4.6", "if width == 8 && address >= 0xFFFFFF00 {\n self.address_error = true; // HM table 4.6"), ("a cache-area write with the cache on is marked THROUGH", "core.rs", "let kind = if !self.cache.enabled { THROUGH } else { DATA };", "let kind = THROUGH;"), ("ID stops data replacement", "core.rs", "if self.cache.ccr & (if kind & FETCH != 0 { CCR_ID } else { CCR_OD }) != 0 {", "if self.cache.ccr & CCR_ID != 0 {"), ("a DMA write does not wait for the CPU's buffered write", "core.rs", " if self.clock < self.wb_end {\n self.clock = self.wb_end;\n }\n self.write_cycles(address, width, value, kind);\n self.wb_end = self.clock;", " self.write_cycles(address, width, value, kind);\n self.wb_end = self.clock;"), ("a sleeping CPU idles a whole event's states", "core.rs", "let idle = (self.next_event - self.clock).max(1).min(16);", "let idle = (self.next_event - self.clock).max(1);"), # -- the instructions -- ("ADDC carries at 2^32 - 1", "arith.rs", "self.set_t(total > 0xFFFF_FFFF);", "self.set_t(total >= 0xFFFF_FFFF);"), ("SUBV's range is one short", "arith.rs", " let difference = s32(self.r[n]) - s32(self.r[((op >> 4) & 15) as usize]);\n self.r[n] = difference as u32;\n self.set_t(!(-0x8000_0000..=0x7FFF_FFFF).contains(&difference));", " let difference = s32(self.r[n]) - s32(self.r[((op >> 4) & 15) as usize]);\n self.r[n] = difference as u32;\n self.set_t(!(-0x7FFF_FFFF..=0x7FFF_FFFF).contains(&difference));"), ("DIV1's case Q=1 M=0 flips the other way", "arith.rs", " } else if old_q == 1 && mm == 0 {\n if q == 0 {\n carry\n } else {\n !carry\n }", " } else if old_q == 1 && mm == 0 {\n if q == 0 {\n !carry\n } else {\n carry\n }"), ("DIV1 Rn,Rn divides by the unshifted value", "arith.rs", "let rm = if same { rn } else { rm };", "let rm = if same { rm } else { rm };"), ("CMP/STR misses the top byte", "arith.rs", "self.set_t(x & 0xFF000000 == 0 || x & 0x00FF0000 == 0", "self.set_t(x & 0x00FF0000 == 0"), ("MOV.L @Rm+,Rm increments too", "transfer.rs", " let value = self.read32(self.r[m]);\n if n != m {\n self.r[m] = self.r[m].wrapping_add(4);", " let value = self.read32(self.r[m]);\n if true {\n self.r[m] = self.r[m].wrapping_add(4);"), ("MOVA does not clear the PC's low bits", "transfer.rs", "self.r[0] = (self.pc.wrapping_add(2) & !3).wrapping_add((op & 0xFF) << 2);", "self.r[0] = self.pc.wrapping_add(2).wrapping_add((op & 0xFF) << 2);"), ("MOV.W @(disp,PC) scales by 4", "transfer.rs", "let address = self.pc.wrapping_add(2).wrapping_add((op & 0xFF) << 1);", "let address = self.pc.wrapping_add(2).wrapping_add((op & 0xFF) << 2);"), ("BSRF writes PR before reading Rm", "branch.rs", " let target = pc.wrapping_add(self.r[((op >> 8) & 15) as usize]); // Rm read before PR is written\n self.pr = pc;", " self.pr = pc;\n let target = pc.wrapping_add(self.r[((op >> 8) & 15) as usize]); // Rm read before PR is written"), ("BT/S's displacement is not doubled", "branch.rs", " let d = (op & 0xFF) as u8 as i8 as i32;\n (d << 1) as u32", " let d = (op & 0xFF) as u8 as i8 as i32;\n d as u32"), ("MAC.W with S saturates at the top minus one", "multiply.rs", " if total > 0x7FFFFFFF {\n total = 0x7FFFFFFF;", " if total > 0x7FFFFFFE {\n total = 0x7FFFFFFE;"), ("MAC.L with S does not sign-extend MAC's 48 bits", "multiply.rs", " low48 -= 1 << 48;", " low48 -= 0;"), ("MAC.W reads @Rm first", "multiply.rs", " let tn = s16(self.read16(self.r[n]));\n self.r[n] = self.r[n].wrapping_add(2);\n let tm = s16(self.read16(self.r[m]));\n self.r[m] = self.r[m].wrapping_add(2);", " let tm = s16(self.read16(self.r[m]));\n self.r[m] = self.r[m].wrapping_add(2);\n let tn = s16(self.read16(self.r[n]));\n self.r[n] = self.r[n].wrapping_add(2);"), ("SR keeps a reserved bit", "system.rs", "pub const SR_MASK: u32 = 0x3F3;", "pub const SR_MASK: u32 = 0x3F7;"), ("RTE pops SR before PC", "system.rs", " let target = self.read32(self.r[15]);\n self.r[15] = self.r[15].wrapping_add(4);\n let sr = self.read32(self.r[15]);", " let sr = self.read32(self.r[15]);\n self.r[15] = self.r[15].wrapping_add(4);\n let target = self.read32(self.r[15]);"), ("TAS.B sets bit 6", "logic.rs", "self.bus_write(address, 8, value | 0x80, THROUGH);", "self.bus_write(address, 8, value | 0x40, THROUGH);"), ("TAS.B reads through the cache's MA without its own", "logic.rs", " value = self.bus_read(address, 8, THROUGH);\n if self.p_ma_left != 0 {\n self.ma_next();\n }", " value = self.bus_read(address, 8, THROUGH);"), # -- the cache -- ("way 1's LRU update sets the wrong bit", "cache.rs", "pub const LRU_SET: [u32; 4] = [0x00, 0x20, 0x14, 0x0B];", "pub const LRU_SET: [u32; 4] = [0x00, 0x10, 0x14, 0x0B];"), ("two-way mode replaces way 1", "cache.rs", "return if lru & 1 != 0 { 2 } else { 3 };", "return if lru & 1 != 0 { 1 } else { 3 };"), ("a CCR purge keeps the LRU", "cache.rs", " self.valid = [0; 256];\n self.lru = [0; 64];", " self.valid = [0; 256];"), ("the associative purge never invalidates", "cache.rs", " self.valid[base + way] = 0;", " self.valid[base + way] = 1;"), ("a CCR write does not wait behind a buffered write", "cache.rs", "if self.wb_end > self.clock {\n self.ccr_at = self.wb_end;", "if false && self.wb_end > self.clock {\n self.ccr_at = self.wb_end;"), # -- the BSC -- ("BCR2's 01 is a 16-bit port", "bsc.rs", "pub const PORT_WIDTHS: [u32; 4] = [32, 8, 16, 32];", "pub const PORT_WIDTHS: [u32; 4] = [32, 16, 16, 32];"), ("the long waits start at 4", "bsc.rs", "pub const LONG_WAITS: [i64; 4] = [3, 4, 5, 6];", "pub const LONG_WAITS: [i64; 4] = [4, 4, 5, 6];"), ("a BSC write needs no key", "bsc.rs", "if width == 32 && value & 0xFFFF0000 == KEY {", "if width == 32 {"), ("a bank-active read of the open row costs a Tr", "bsc.rs", " if self.rows[area][bank] == row {\n if cas == 1 {", " if self.rows[area][bank] == row && false {\n if cas == 1 {"), ("an SDRAM write in an open row costs two states", "bsc.rs", " states = 1; // Tc (figure 7.23)", " states = 2; // Tc (figure 7.23)"), ("the refresh timer counts one tick late", "bsc.rs", " if ticks < need {\n self.bsc.count = (self.bsc.count + ticks) & 0xFF;", " if ticks <= need {\n self.bsc.count = (self.bsc.count + ticks) & 0xFF;"), ("BCR1.MASTER reads 0 in slave mode", "bsc.rs", "value = (value & 0x7FFF) | if self.bsc.slave { 0x8000 } else { 0 };", "value &= 0x7FFF;"), # -- the INTC, DMAC, DIVU, FRT, WDT, SCI, UBC, power -- ("IPRA's WDT nibble is the low one", "intc.rs", "\"wdt\" => self.get(0xFFFFFEE3) >> 4,", "\"wdt\" => self.get(0xFFFFFEE3) & 15,"), ("the last source at a level wins", "intc.rs", " if level > best_level {", " if level >= best_level {"), ("a VCR keeps its top bit", "intc.rs", " (0xFFFFFE62, 0x7F),\n (0xFFFFFE63, 0x7F),", " (0xFFFFFE62, 0xFF),\n (0xFFFFFE63, 0x7F),"), ("TE clears without being read", "dmac.rs", "if merged & 2 == 0 && te_read[channel.number as usize] != 0 {", "if merged & 2 == 0 {"), ("a 16-byte unit steps SAR by SM", "dmac.rs", "if unit == 16 || sm == 1 {", "if sm == 1 {"), ("a burst stops after one transfer", "dmac.rs", "if self.dmac.channels[number].chcr & 2 != 0 || burst == 0 || self.dmac.dmaor & 4 != 0 {", "if true {"), ("TCR counts 16-byte units by one", "dmac.rs", "let step = if unit == 16 { 4 } else { 1 };", "let step = 1;"), # -- the reference's R1 and R2 fixes (sh2-python 8824075) -- ("a burst runs on after a DMA address error", "dmac.rs", "|| burst == 0 || self.dmac.dmaor & 4 != 0 {", "|| burst == 0 {"), ("a DMA address error does not set AE", "dmac.rs", " self.dmac.dmaor |= 4; // AE", " self.dmac.dmaor |= 0; // AE"), ("a faulting DMA write is still made", "dmac.rs", " if !write_fault {\n self.dma_write(dst, width, value, kind);", " if true {\n self.dma_write(dst, width, value, kind);"), ("a 16-byte unit checks only word alignment", "dmac.rs", "let width = if unit == 16 { 32 } else { unit * 8 };", "let width = if unit == 16 { 16 } else { unit * 8 };"), ("a byte DMA at H'FFFFFF00- is no address error", "core.rs", "return (width == 8 && address >= 0xFFFFFF00) || (width == 32 && address < 0xFFFFFF00);", "return width == 32 && address < 0xFFFFFF00;"), ("a DMA address error does not end SLEEP", "core.rs", " self.dma_address_error = false;\n self.sleeping = false;", " self.dma_address_error = false;"), ("a DMA address error takes vector 9", "core.rs", "pub const VECTOR_DMA_ADDRESS_ERROR: u32 = 10; // HM table 4.3", "pub const VECTOR_DMA_ADDRESS_ERROR: u32 = 9; // HM table 4.3"), ("a pending DMA address error is not in the state", "cpu.rs", " dma_address_error: self.dma_address_error,\n internal,", " dma_address_error: false,\n internal,"), ("the cache's LRU is not in the state", "cache.rs", " for (i, v) in values[4608..4672].iter().enumerate() {\n self.lru[i] = *v as u32;\n }", ""), ("the cache's tags load one entry off", "cache.rs", " for (i, v) in values[4096..4352].iter().enumerate() {\n self.tags[i] = *v as u32;", " for (i, v) in values[4097..4353].iter().enumerate() {\n self.tags[i] = *v as u32;"), ("an SDRAM bank's ready and precharge swap in the state", "bsc.rs", " self.bsc.ready[area] = [row[2], row[3]];\n self.bsc.pre_ok[area] = [row[4], row[5]];", " self.bsc.ready[area] = [row[4], row[5]];\n self.bsc.pre_ok[area] = [row[2], row[3]];"), ("the refresh's end is not in the state", "bsc.rs", " self.refresh_end = values[25];\n", ""), ("RTCSR.CMF as last read is not in the state", "bsc.rs", " self.bsc.cmf_read = values[24] != 0;\n", ""), ("the FRT's catch-up clock is not in the state", "frt.rs", " self.clock = values[0];\n self.flags_read = values[1] as u32;", " self.flags_read = values[1] as u32;"), ("the WDT's catch-up clock is not in the state", "wdt.rs", " pub fn load_internal(&mut self, values: &[i64]) {\n self.clock = values[0];", " pub fn load_internal(&mut self, values: &[i64]) {\n let _ = values;"), ("SSR as last read is not in the state", "sci.rs", " self.ssr_read = values[0] as u32;", " let _ = values;"), ("CHCR.TE as last read is not in the state", "dmac.rs", " self.te_read = [values[0] as u32, values[1] as u32];", " let _ = values;"), ("the NMI edge detector is not in the state", "cpu.rs", " self.nmi_seen = values[0] as u32;", " let _ = values;"), ("a division takes 38 states", "divu.rs", "pub const DIVIDE_STATES: i64 = 39;", "pub const DIVIDE_STATES: i64 = 38;"), ("an overflow saturates the other way", "divu.rs", "self.divu.dvdntl = if (dividend < 0) != (divisor < 0) { 0x8000_0000 } else { 0x7FFF_FFFF };", "self.divu.dvdntl = if (dividend < 0) == (divisor < 0) { 0x8000_0000 } else { 0x7FFF_FFFF };"), ("the early state runs two steps", "divu.rs", "let (dvdnth, partial_low) = early_state(high, low, self.divu.dvsr, 3);", "let (dvdnth, partial_low) = early_state(high, low, self.divu.dvsr, 2);"), ("an access during a division does not wait", "divu.rs", " if remaining > 0 {\n self.stall(remaining);", " if remaining > 0 && false {\n self.stall(remaining);"), ("CCLRA does not clear FRC", "frt.rs", " if self.frt.ftcsr & CCLRA != 0 {\n nxt = 0;", " if self.frt.ftcsr & CCLRA != 0 {\n nxt = (frc + 1) & 0xFFFF;"), ("FTOA takes OLVLB", "frt.rs", "self.frt_set_ftoa((self.frt.tocr >> 1) & 1, when);", "self.frt_set_ftoa(self.frt.tocr & 1, when);"), ("reading FRC's high byte does not latch the low", "frt.rs", " frt.temp = (word & 0xFF) as u32;\n return (word >> 8) as u32;", " return (word >> 8) as u32;"), ("φ/32 counts at φ/16", "frt.rs", "pub const DIVIDERS: [i64; 4] = [8, 32, 128, 0];", "pub const DIVIDERS: [i64; 4] = [8, 16, 128, 0];"), ("the WDT's WTCSR key is H'5A", "wdt.rs", " if key == 0xA5 {\n // OVF can only be cleared", " if key == 0x5A {\n // OVF can only be cleared"), ("φ/64 counts at φ/32 in the WDT", "wdt.rs", "pub const DIVIDERS: [i64; 8] = [2, 64, 128,", "pub const DIVIDERS: [i64; 8] = [2, 32, 128,"), ("a transmitted byte leaves TDRE clear", "sci.rs", " self.sci.ssr |= TDRE | TEND;", " self.sci.ssr |= TEND;"), ("an overrun overwrites RDR", "sci.rs", " if self.sci.ssr & RDRF != 0 {\n self.sci.ssr |= ORER;\n } else {", " if false {\n self.sci.ssr |= ORER;\n } else {"), ("the UBC answers unmapped bytes", "ubc.rs", " Some(i) if self.present[i] => self.bytes[i],", " Some(i) => self.bytes[i],"), ("SBYCR keeps its reserved bit", "power.rs", "self.sbycr = value & 0xDF;", "self.sbycr = value & 0xFF;"), # -- the composition (cpu.rs, module.rs) -- ("the FRT's map stops at H'FFFFFE18", "cpu.rs", "claim(0xFFFFFE10, 0xFFFFFE19, ModuleId::Frt);", "claim(0xFFFFFE10, 0xFFFFFE18, ModuleId::Frt);"), ("the INTC resets before the cache", "cpu.rs", " for id in MODULES {\n self.module_reset(id);\n }", " for id in MODULES.iter().rev() {\n self.module_reset(*id);\n }"), ("PR is not a use of RTS", "cpu.rs", "const IMPLICIT_PR: [&str; 4] = [\"RTS\", \"BSR\", \"BSRF\", \"JSR\"];", "const IMPLICIT_PR: [&str; 3] = [\"BSR\", \"BSRF\", \"JSR\"];"), ("STS is not interrupt-blocking", "cpu.rs", "pub const INTERRUPT_DISABLING: [&str; 8] = [\"LDC\", \"LDC.L\", \"STC\", \"STC.L\", \"LDS\", \"LDS.L\", \"STS\", \"STS.L\"];", "pub const INTERRUPT_DISABLING: [&str; 7] = [\"LDC\", \"LDC.L\", \"STC\", \"STC.L\", \"LDS\", \"LDS.L\", \"STS.L\"];"), ("a byte split writes low byte first", "module.rs", "write8(address.wrapping_add(offset), (((value as u64) >> (8 * (count - 1 - offset))) & 0xFF) as u32);", "write8(address.wrapping_add(offset), (((value as u64) >> (8 * offset)) & 0xFF) as u32);"), ("a restored state keeps the old SR bits", "cpu.rs", " self.sr = state.sr & SR_MASK;\n self.gbr = state.gbr;", " self.gbr = state.gbr;"), # Replacements for two equivalent mutants found by the first run (40: MOV.L @Rm+,Rm's # increment is overwritten by the load; 43: PR is not a general register), kept above # as recorded and not counted. ("MOV.B @Rm+ steps Rm by 2", "transfer.rs", "self.r[m] = self.r[m].wrapping_add(1);", "self.r[m] = self.r[m].wrapping_add(2);"), ("JSR saves the slot's address", "branch.rs", "self.pr = self.pc.wrapping_add(2);", "self.pr = self.pc;"), ("the disassembler prints GBR byte displacements in four digits", "disasm.rs", "let shown = if scale == 1 { format!(\"${value:02X}\") } else { format!(\"${value:04X}\") };", "let shown = format!(\"${value:04X}\");"), # -- the fork's own code (67652c5): the packed Op record (cpu.rs), step's reads of it # (core.rs), the plans' fixed MA arrays (pipeline.rs). Rung 0 dumps the six tables the # record is built from, not the record, so these must be caught by behaviour. ("the record's plan is the opcode's with bit 8 flipped", "cpu.rs", " plan: t.plan[opcode],", " plan: t.plan[opcode ^ 0x100],"), ("the record's handler is the opcode's with bit 0 flipped", "cpu.rs", " handler: t.handler[opcode],", " handler: t.handler[opcode ^ 1],"), ("the record drops the load's destination", "cpu.rs", " load_dest: t.load_dest[opcode],", " load_dest: 0,"), ("the record drops the load-use registers", "cpu.rs", " uses: t.uses[opcode],", " uses: 0,"), ("the record's load destination and uses swap", "cpu.rs", " load_dest: t.load_dest[opcode],\n uses: t.uses[opcode],", " load_dest: t.uses[opcode],\n uses: t.load_dest[opcode],"), ("the record is never slot-illegal", "cpu.rs", " slot_illegal: t.slot_illegal[opcode] != 0,", " slot_illegal: false,"), ("the record never blocks an interrupt", "cpu.rs", " blocks: t.blocks[opcode] != 0,", " blocks: false,"), ("LDC and friends in a delay slot do not block an interrupt", "core.rs", " self.retire(o.plan, target);\n self.no_interrupt = o.blocks;", " self.retire(o.plan, target);\n self.no_interrupt = false;"), ("the plans' MA array is one entry late (the first MA in EX)", "pipeline.rs", " ma[..mas.len()].copy_from_slice(&mas);", " ma[1..mas.len() + 1].copy_from_slice(&mas);"), ("a three-MA sequence opens only two", "pipeline.rs", " self.p_ma_left = p.n_mas;", " self.p_ma_left = p.n_mas.min(2);"), ("every MA opens at the first MA's slot", "pipeline.rs", "let slot = self.p_ex + self.p_plan.unwrap().ma[i];", "let slot = self.p_ex + self.p_plan.unwrap().ma[0];"), ("a plan with no MA retires one slot past EX", "pipeline.rs", "let last = if n_mas == 0 { 0 } else { mas[n_mas - 1] };", "let last = if n_mas == 0 { 1 } else { mas[n_mas - 1] };"), ("a plan's last MA is taken as its first", "pipeline.rs", "let last = if n_mas == 0 { 0 } else { mas[n_mas - 1] };", "let last = if n_mas == 0 { 0 } else { mas[0] };"), # Replacement for the equivalent mutant just above (retire has opened every MA, so its # final advance to the last MA is a no-op whenever the plan has one). ("a plan's retire advances one slot past its last MA", "pipeline.rs", "let last = if n_mas == 0 { 0 } else { mas[n_mas - 1] };", "let last = if n_mas == 0 { 0 } else { mas[n_mas - 1] + 1 };"), ) # fmt: skip # Faults whose change no program can observe (methodology: noted, not counted). EQUIVALENT = { "MOV.L @Rm+,Rm increments too": "the load writes Rm after the increment: R[n] = value overwrites it", "BSRF writes PR before reading Rm": "PR is not one of R0-R15, so reading Rm after writing PR reads the same value", "the UBC answers unmapped bytes": "an unmapped byte is never written (write8 checks the map), so it reads 0 either way", "the INTC resets before the cache": "by analysis: what the resets compute between them (INTC.update, the BSC's " "reschedule) reset() recomputes after them (onchip_level = 0, _reschedule); not proven", "a plan's last MA is taken as its first": "-fast: retire opens every remaining MA first (while p_ma_left != 0), " "each ma_next advancing the cursor to its slot in increasing order, and advance() does nothing for a target at " "or before the cursor; so with any MA, advance(p_ex + last) is a no-op for every last up to the final MA's slot " "(Plan.last matters only for plans with no MA)", } RUNGS = ("cargo test", "rung 0", "rung 1", "rung 3", "rung 4", "rung 5", "rung 2 prefix") def apply(worker: Path, fault: tuple | None) -> None: """A fresh copy of the crate in ``worker``, with ``fault`` applied.""" src = worker / "src" if src.exists(): aside = WORK / "aside" / f"{os.getpid()}-{worker.name}-{len(list((WORK / 'aside').glob('*'))) if (WORK / 'aside').exists() else 0}" aside.parent.mkdir(parents=True, exist_ok=True) shutil.move(str(src), str(aside)) # the previous copy is set aside, never deleted shutil.copytree(ROOT / "src", src) for part in ("tests",): if (worker / part).exists(): shutil.move(str(worker / part), str(WORK / "aside" / f"{os.getpid()}-{worker.name}-{part}-{id(fault)}")) shutil.copytree(ROOT / part, worker / part) for name in ("Cargo.toml", "Cargo.lock"): shutil.copy2(ROOT / name, worker / name) if fault: _, file, find, replacement = fault path = src / file text = path.read_text() if text.count(find) != 1: raise SystemExit(f"fault {fault[0]!r}: its text occurs {text.count(find)} times in {file}") path.write_text(text.replace(find, replacement)) for path in list(src.rglob("*")) + list((worker / "tests").rglob("*")) + [worker / "Cargo.toml"]: if path.is_file(): os.utime(path) def run(cmd: list, env: dict) -> bool: """Whether ``cmd`` passes; one that runs away (an hour) fails, so it catches.""" try: result = subprocess.run(cmd, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=3600) except subprocess.TimeoutExpired: return False return result.returncode == 0 def judge(worker: Path, label: str) -> str | None: """The first rung that fails on ``worker``'s build, or None.""" env = {**os.environ, "CARGO_TARGET_DIR": str(worker / "target")} stable = Path.home() / ".rustup/toolchains/stable-x86_64-unknown-linux-gnu/bin" if (stable / "cargo").exists(): env["PATH"] = f"{stable}:{env['PATH']}" manifest = ["--manifest-path", str(worker / "Cargo.toml")] if not run(["nice", "-n", "19", "cargo", "build", "--release", "-q", "-j", "2", *manifest], env): return "build" if not run(["nice", "-n", "19", "cargo", "test", "--release", "-q", "-j", "2", *manifest], env): return "cargo test" release = worker / "target" / "release" out = worker / "out" out.mkdir(exist_ok=True) env.update(BIN=str(release / "sh2-trace"), OUT=str(out), LABEL=label) scripts = ROOT / "scripts" if not run([str(scripts / "rung0.sh")], env): return "rung 0" if not run([str(scripts / "rung1.sh")], {**env, "BIN": str(release)}): return "rung 1" for rung in ("rung 3", "rung 4", "rung 5"): if not run([str(scripts / f"rung{rung[-1]}.sh")], env): return rung if not run([str(scripts / "rung2.sh")], {**env, "BIN": str(release), "FULL": "0", "PREFIX": "300000"}): return "rung 2 prefix" return None def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--jobs", type=int, default=4) parser.add_argument("--only", help="fault numbers, e.g. 1,5,9 (1-based; 0 is the unbroken copy)") args = parser.parse_args() numbers = [int(n) for n in args.only.split(",")] if args.only else list(range(1, len(FAULTS) + 1)) WORK.mkdir(parents=True, exist_ok=True) base = WORK / "w0" apply(base, None) verdict = judge(base, "faults-w0") print(f" 0 unbroken copy: {'passes every rung' if verdict is None else 'FAILS ' + verdict}", flush=True) if verdict is not None: return 1 jobs: queue.Queue = queue.Queue() for n in numbers: jobs.put(n) results: dict[int, str | None] = {} lock = threading.Lock() def worker(index: int) -> None: place = WORK / f"w{index}" if not place.exists() and base.exists(): shutil.copytree(base / "target", place / "target", symlinks=True) # a warm build directory while True: try: n = jobs.get_nowait() except queue.Empty: return fault = FAULTS[n - 1] apply(place, fault) caught = judge(place, f"faults-w{index}") with lock: results[n] = caught print(f"{n:3} {fault[0]}: {'caught by ' + caught if caught else 'MISSED'}", flush=True) threads = [threading.Thread(target=worker, args=(i + 1,)) for i in range(args.jobs)] for t in threads: t.start() for t in threads: t.join() for n in list(results): if FAULTS[n - 1][0] in EQUIVALENT and not results[n]: print(f"{n:3} {FAULTS[n - 1][0]}: equivalent ({EQUIVALENT[FAULTS[n - 1][0]]}), not counted") del results[n] caught = sum(1 for v in results.values() if v) by_rung: dict[str, int] = {} for v in results.values(): if v: by_rung[v] = by_rung.get(v, 0) + 1 print(f"rung 6: {caught} of {len(results)} seeded faults caught; first catches: " + ", ".join(f"{k} {by_rung[k]}" for k in (*RUNGS, "build") if k in by_rung)) # fmt: skip missed = [n for n, v in results.items() if not v] if missed: print("missed: " + ", ".join(f"{n} ({FAULTS[n - 1][0]})" for n in sorted(missed))) return 0 if caught == len(results) else 1 if __name__ == "__main__": sys.exit(main())