// SPDX-License-Identifier: MIT //! SingleStepTests ARM7TDMI against the core: rung 1 (the reference's own gate, transcribed) //! and rung 2 (every case in lockstep with the reference). //! //! The gate is a transcription of the reference's `tests/sst_runner.py` and //! `scripts/sst_gate.py`: each case loads a state with two prefetched opcodes, runs one //! instruction and compares the final state and the bus transactions with the corpus, after the //! override file (`tests/sst_overrides.json` in the reference: C1 mapped by `gba_access`, C10 //! LOCK on SWP's read ignored, C6's tested CP14 encodings compared to the hardware test's //! behaviour, C2, the other C6 encodings and C7 excluded and counted, never passed). The corpus //! was generated from a NanoBoyAdvance fork, so it is **emulator-derived: a detector, not a //! judge** (the reference's user decision 2). //! //! The lockstep mode hashes everything a case does on this core: every bus callback in order //! (kind, width, address, value, access bits; internal cycles with their address and whether //! they are coprocessor cycles), the cycles `step()` returned and the final 40 state words as //! the core leaves them (no mapping), and compares the hash with the reference's //! (`scripts/sst_reference.py`, run on the pinned reference core), case by case, for all //! 2,250,000 cases, the excluded ones included. //! //! ```text //! arm7-sst CORPUS_DIR --overrides FILE [--files NAME...] [--limit N] [--json OUT] [--jobs N] //! arm7-sst CORPUS_DIR --lockstep CACHE_DIR [--files NAME...] [--jobs N] //! arm7-sst CORPUS_DIR --dump NAME INDEX # one case's record, for a divergence //! ``` use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; use arm7tdmi::modes::{bank_of, condition_passes, BANK_FIQ, BANK_INVALID, BANK_USER}; use arm7tdmi::trace::crc32; use arm7tdmi::{gba_access, Bus, CPUState, ARM7TDMI, CODE, LOCK, SEQ}; const MAGIC: u32 = 0xD33D_BAE0; const NAMES: [&str; 40] = [ "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "fiq_r8", "fiq_r9", "fiq_r10", "fiq_r11", "fiq_r12", "fiq_r13", "fiq_r14", "svc_r13", "svc_r14", "abt_r13", "abt_r14", "irq_r13", "irq_r14", "und_r13", "und_r14", "cpsr", "spsr_fiq", "spsr_svc", "spsr_abt", "spsr_irq", "spsr_und", "pipe0", "pipe1", "access", ]; #[derive(Clone)] struct Case { initial: [u32; 40], final_: [u32; 40], transactions: Vec<[u32; 5]>, // kind, bytes, address, data, access opcode: u32, } fn i32_at(buf: &[u8], at: usize) -> i32 { i32::from_le_bytes(buf[at..at + 4].try_into().unwrap()) } fn u32_at(buf: &[u8], at: usize) -> u32 { u32::from_le_bytes(buf[at..at + 4].try_into().unwrap()) } /// Decode a `.json.bin` file (the format of the corpus's `transcode_json.py`). fn load(path: &Path, limit: Option) -> Vec { let buf = std::fs::read(path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); let (magic, count) = (u32_at(&buf, 0), u32_at(&buf, 4) as usize); assert_eq!( magic, MAGIC, "{}: not a SingleStepTests ARM7TDMI file", path.display() ); let count = limit.map_or(count, |l| l.min(count)); let mut cases = Vec::with_capacity(count); let mut ptr = 8; for _ in 0..count { let full = i32_at(&buf, ptr) as usize; let mut p = ptr + 4; let mut states = [[0u32; 40]; 2]; for state in states.iter_mut() { for (k, word) in state.iter_mut().enumerate() { *word = u32_at(&buf, p + 8 + 4 * k); } p += i32_at(&buf, p) as usize; } let (size, n) = (i32_at(&buf, p) as usize, i32_at(&buf, p + 8) as usize); let transactions = (0..n) .map(|k| { let at = p + 12 + 24 * k; [ u32_at(&buf, at), u32_at(&buf, at + 4), u32_at(&buf, at + 8), u32_at(&buf, at + 12), u32_at(&buf, at + 20), ] }) .collect(); p += size; let opcode = u32_at(&buf, p + 8); cases.push(Case { initial: states[0], final_: states[1], transactions, opcode, }); ptr += full; } cases } /// One callback as the bench logs it: a read or write (kind 0 code, 1 data, 2 write) or an /// internal cycle (kind 3; `access` holds whether it was a coprocessor cycle). #[derive(Clone, Copy, Debug)] struct Entry { kind: u32, size: u32, address: u32, data: u32, access: u32, } /// A host that answers reads from the case's transactions and records every callback. #[derive(Default)] struct BenchBus { transactions: Vec<[u32; 5]>, used: Vec, log: Vec, } impl Bus for BenchBus { fn read(&mut self, address: u32, width: u32, access: u32) -> u32 { let kind = if access & CODE != 0 { 0 } else { 1 }; let mut data = if kind == 0 { address } else { 0 }; for (index, t) in self.transactions.iter().enumerate() { if !self.used[index] && t[0] == kind && t[2] == address { self.used[index] = true; data = t[3]; break; } } if width < 32 { data &= (1 << width) - 1; } self.log.push(Entry { kind, size: width / 8, address, data, access, }); data } fn write(&mut self, address: u32, width: u32, value: u32, access: u32) { self.log.push(Entry { kind: 2, size: width / 8, address, data: value, access, }); } fn idle(&mut self, address: u32, coprocessor_cycle: bool) { self.log.push(Entry { kind: 3, size: 0, address, data: 0, access: coprocessor_cycle as u32, }); } } struct Bench { cpu: ARM7TDMI, cycles: u32, } impl Bench { fn new() -> Self { Bench { cpu: ARM7TDMI::new(BenchBus::default()), cycles: 0, } } fn run(&mut self, case: &Case) { let bus = &mut self.cpu.bus; bus.transactions.clone_from(&case.transactions); bus.used.clear(); bus.used.resize(case.transactions.len(), false); bus.log.clear(); self.cpu.restore_state(&CPUState::from_sst(&case.initial)); self.cycles = self.cpu.step(); } /// The lockstep record: every callback, the cycles, the final words (scripts/sst_reference.py /// packs the same bytes). fn record(&self) -> Vec { let mut bytes = Vec::with_capacity(self.cpu.bus.log.len() * 14 + 164); for e in &self.cpu.bus.log { bytes.push(e.kind as u8); bytes.push(e.size as u8); bytes.extend_from_slice(&e.address.to_le_bytes()); bytes.extend_from_slice(&e.data.to_le_bytes()); bytes.extend_from_slice(&e.access.to_le_bytes()); } bytes.extend_from_slice(&self.cycles.to_le_bytes()); for word in self.cpu.capture_state().to_sst() { bytes.extend_from_slice(&word.to_le_bytes()); } bytes } } /// The core's reads and writes with C1's mapping applied and LOCK dropped from reads /// (C10); and whether the last callback was an I cycle. fn bus_as_gba(log: &[Entry]) -> (Vec, bool) { let mut out = Vec::new(); let mut after_idle = false; for entry in log { if entry.kind == 3 { after_idle = true; continue; } let mut access = gba_access(entry.access, after_idle); if entry.kind != 2 { access &= !LOCK; } out.push(Entry { access, ..*entry }); after_idle = false; } (out, after_idle) } fn describe(transactions: &[[u32; 5]]) -> String { transactions .iter() .map(|&[k, s, addr, d, a]| { let kind = ["C", "R", "W"][k as usize]; let seq = if a & SEQ != 0 { "S" } else { "N" }; let data = if k == 2 { format!("={d:x}") } else { String::new() }; format!("{kind}{seq}{}@{addr:08x}{data}", s * 8) }) .collect::>() .join(" ") } /// Whether the case's instruction runs (Thumb always; ARM when its condition passes). fn executed(case: &Case) -> bool { let cpsr = case.initial[31]; cpsr & 0x20 != 0 || condition_passes(case.opcode >> 28, cpsr) } /// C2: an ARM single, halfword or block transfer with Rn = R15 and write-back. fn writes_back_r15(name: &str, case: &Case) -> bool { let op = case.opcode; if !name.starts_with("arm_") || (op >> 16) & 0xF != 15 || !executed(case) { return false; } if name == "arm_ldm_stm" { return op & (1 << 21) != 0; } if name.starts_with("arm_ldr_str") || name.starts_with("arm_ldrh_strh") || name.starts_with("arm_ldrsb_ldrsh") { return op & (1 << 21) != 0 || op & (1 << 24) == 0; } false } #[derive(PartialEq)] enum Cp14 { Tested, Other, } /// C6: 'tested' for the encodings alyosha-tas's Coprocessor_14 runs on hardware, 'other' /// for any other executed CP14 MRC/MCR, None otherwise. fn cp14_case(name: &str, case: &Case) -> Option { let op = case.opcode; if name != "arm_mcr_mrc" || (op >> 8) & 0xF != 14 || !executed(case) { return None; } let (opc1, crn, crm, opc2) = ((op >> 21) & 7, (op >> 16) & 0xF, op & 0xF, (op >> 5) & 7); let (load, rd) = (op & (1 << 20) != 0, (op >> 12) & 0xF); if opc1 == 0 && crm == 0 && opc2 == 0 { if load && (crn == 0 || crn == 1) { return Some(Cp14::Tested); // MRC p14,0,Rd,c0,c0,0 / c1,c0,0 (Rd = R15 sets the flags) } if !load && crn == 1 && rd == 1 { return Some(Cp14::Tested); // MCR p14,0,R1,c1,c0,0 } } Some(Cp14::Other) } /// Set Rd as the current mode sees it, in the corpus layout. fn with_register(words: &mut [u32; 40], rd: usize, value: u32) { let bank = bank_of(words[31]); if rd < 8 || rd == 15 || bank == BANK_USER || bank == BANK_INVALID { words[rd] = value; } else if bank == BANK_FIQ { words[16 + rd - 8] = value; } else if rd < 13 { words[rd] = value; } else { let offset = [0, 0, 23, 25, 27, 29][bank]; words[offset + rd - 13] = value; } } /// What alyosha-tas's Coprocessor_14 shows a GBA doing (U17): no trap; the prefetch only /// on the bus; MRC puts the opcode that prefetch read into Rd (or its top four bits into /// N Z C V for R15); MCR changes nothing. The next fetch: MRC ends with an I cycle, so the /// GBA times it N (C1); MCR's is N (table 6-20). fn cp14_expected(case: &Case) -> ([u32; 40], Vec<[u32; 5]>) { let mut words = case.initial; let fetch = case.transactions[0]; words[37] = case.initial[38]; words[38] = fetch[3]; words[15] = case.initial[15].wrapping_add(4); let op = case.opcode; if op & (1 << 20) != 0 { let rd = ((op >> 12) & 0xF) as usize; if rd == 15 { words[31] = (words[31] & 0x0FFF_FFFF) | (fetch[3] & 0xF000_0000); } else { with_register(&mut words, rd, fetch[3]); } } words[39] = CODE; (words, vec![fetch]) } /// Run one case; return its disagreements (empty when it passes). fn check(bench: &mut Bench, name: &str, case: &Case) -> Vec { bench.run(case); let mut problems = Vec::new(); let log = &bench.cpu.bus.log; if bench.cycles as usize != log.len() { problems.push(format!( "step() returned {} but made {} callbacks", bench.cycles, log.len() )); } let (ours, last_idle) = bus_as_gba(log); let mut words = bench.cpu.capture_state().to_sst(); words[39] = gba_access(words[39], last_idle); let (want_words, want_bus) = if cp14_case(name, case) == Some(Cp14::Tested) { cp14_expected(case) } else { (case.final_, case.transactions.clone()) }; for index in 0..40 { if words[index] != want_words[index] { problems.push(format!( "{} {:08x} != {:08x}", NAMES[index], words[index], want_words[index] )); } } let same = ours.len() == want_bus.len() && ours.iter().zip(want_bus.iter()).all(|(a, b)| { a.kind == b[0] && a.size == b[1] && a.address == b[2] && (a.kind != 2 || a.data == b[3]) && a.access & 0xB == b[4] & 0xB }); if !same { let ours: Vec<[u32; 5]> = ours .iter() .map(|e| [e.kind, e.size, e.address, e.data, e.access]) .collect(); problems.push(format!( "bus\n got {}\n want {}", describe(&ours), describe(&want_bus) )); } problems } #[derive(Default)] struct FileResult { name: String, cases: usize, passed: usize, failed: usize, excluded: BTreeMap, overridden: BTreeMap, mapped: usize, // cases where C1 or C10 changed an access or the final next-fetch type fields: BTreeMap, examples: Vec, } fn run_file( path: &Path, limit: Option, examples: usize, excluded_files: &BTreeMap, ) -> FileResult { let name = file_name(path); let mut result = FileResult { name: name.clone(), ..FileResult::default() }; let cases = load(path, limit); result.cases = cases.len(); if let Some(id) = excluded_files.get(&name) { result.excluded.insert(id.clone(), cases.len()); return result; } let mut bench = Bench::new(); for (number, case) in cases.iter().enumerate() { if writes_back_r15(&name, case) { *result.excluded.entry("C2".into()).or_default() += 1; continue; } let cp14 = cp14_case(&name, case); if cp14 == Some(Cp14::Other) { *result.excluded.entry("C6".into()).or_default() += 1; continue; } if cp14 == Some(Cp14::Tested) { *result.overridden.entry("C6".into()).or_default() += 1; } let problems = check(&mut bench, &name, case); let raw: Vec<&Entry> = bench.cpu.bus.log.iter().filter(|e| e.kind != 3).collect(); let (mapped, last_idle) = bus_as_gba(&bench.cpu.bus.log); let changed = raw .iter() .zip(mapped.iter()) .any(|(a, b)| a.access != b.access); if changed || (last_idle && bench.cpu.next_fetch_seq) { result.mapped += 1; } if problems.is_empty() { result.passed += 1; } else { result.failed += 1; for p in &problems { let field = p.split_whitespace().next().unwrap_or("").to_string(); *result.fields.entry(field).or_default() += 1; } if result.examples.len() < examples { result.examples.push(format!( "{name} case {number} opcode {:08x} cpsr {:08x}: {}", case.opcode, case.initial[31], problems.join("; ") )); } } } result } fn file_name(path: &Path) -> String { path.file_name() .unwrap() .to_string_lossy() .trim_end_matches(".json.bin") .to_string() } fn corpus_files(corpus: &Path, only: &[String]) -> Vec { if !only.is_empty() { return only .iter() .map(|n| corpus.join(format!("{n}.json.bin"))) .collect(); } let mut files: Vec = std::fs::read_dir(corpus) .unwrap_or_else(|e| panic!("{}: {e}", corpus.display())) .filter_map(|e| e.ok().map(|e| e.path())) .filter(|p| p.to_string_lossy().ends_with(".json.bin")) .collect(); files.sort(); files } /// Run `work` over `items` on `jobs` threads, returning the results in order. fn parallel(items: &[T], jobs: usize, work: impl Fn(&T) -> R + Sync) -> Vec { let next = AtomicUsize::new(0); let results: Mutex>> = Mutex::new((0..items.len()).map(|_| None).collect()); std::thread::scope(|scope| { for _ in 0..jobs.max(1) { scope.spawn(|| loop { let index = next.fetch_add(1, Ordering::SeqCst); if index >= items.len() { break; } let result = work(&items[index]); results.lock().unwrap()[index] = Some(result); }); } }); results .into_inner() .unwrap() .into_iter() .map(|r| r.unwrap()) .collect() } fn excluded_files(overrides: &Path) -> BTreeMap { let text = std::fs::read_to_string(overrides) .unwrap_or_else(|e| panic!("{}: {e}", overrides.display())); let entries: serde_json::Value = serde_json::from_str(&text).expect("the override file is JSON"); let mut out = BTreeMap::new(); for e in entries.as_array().expect("a list of overrides") { if e["action"] == "exclude-file" { out.insert( e["file"].as_str().unwrap().to_string(), e["id"].as_str().unwrap().to_string(), ); } } out } fn gate( files: &[PathBuf], overrides: &Path, limit: Option, examples: usize, jobs: usize, json: Option, ) -> i32 { let excluded_files = excluded_files(overrides); let start = std::time::Instant::now(); let results = parallel(files, jobs, |path| { run_file(path, limit, examples, &excluded_files) }); let (mut cases, mut passed, mut failed) = (0, 0, 0); let mut excluded: BTreeMap = BTreeMap::new(); let mut overridden: BTreeMap = BTreeMap::new(); let mut report = serde_json::Map::new(); for result in &results { cases += result.cases; passed += result.passed; failed += result.failed; for (k, v) in &result.excluded { *excluded.entry(k.clone()).or_default() += v; } for (k, v) in &result.overridden { *overridden.entry(k.clone()).or_default() += v; } let ex = result .excluded .iter() .map(|(k, v)| format!("{k}={v}")) .collect::>() .join(","); println!( "{:32} {:6}/{:<6} failed={:<6} excluded[{ex}]", result.name, result.passed, result.cases, result.failed ); for line in &result.examples { println!(" {line}"); } report.insert( result.name.clone(), serde_json::json!({ "cases": result.cases, "passed": result.passed, "failed": result.failed, "excluded": result.excluded, "overridden": result.overridden, "mapped": result.mapped, "fields": result.fields, }), ); } let total_excluded: usize = excluded.values().sum(); let gated = cases - total_excluded; println!( "\nall: {} of {} gated cases pass, {} fail; excluded {:?} ({}); overridden {:?}; {:.1} s wall", arm7tdmi::harness::thousands(passed as u64), arm7tdmi::harness::thousands(gated as u64), arm7tdmi::harness::thousands(failed as u64), excluded, arm7tdmi::harness::thousands(total_excluded as u64), overridden, start.elapsed().as_secs_f64() ); if let Some(path) = json { let text = serde_json::to_string_pretty(&serde_json::Value::Object(report)).unwrap(); std::fs::write(path, text + "\n").expect("cannot write the JSON report"); } if failed == 0 { 0 } else { 1 } } fn lockstep(files: &[PathBuf], cache: &Path, jobs: usize) -> i32 { let start = std::time::Instant::now(); let results = parallel(files, jobs, |path| { let name = file_name(path); let reference = match std::fs::read(cache.join(format!("{name}.crc"))) { Ok(bytes) => bytes, Err(e) => return (name, 0, 0, vec![format!("no reference hashes: {e}")]), }; let cases = load(path, None); let mut bench = Bench::new(); let mut differ = Vec::new(); let mut identical = 0; if reference.len() != 4 * cases.len() { differ.push(format!( "the reference hashed {} cases, the corpus holds {}", reference.len() / 4, cases.len() )); } for (index, case) in cases.iter().enumerate() { bench.run(case); let ours = crc32(0, &bench.record()); let want = if 4 * index + 4 <= reference.len() { u32_at(&reference, 4 * index) } else { !ours }; if ours == want { identical += 1; } else if differ.len() < 5 { differ.push(format!("case {index} opcode {:08x}", case.opcode)); } } (name, cases.len(), identical, differ) }); let (mut total, mut same, mut bad_files) = (0, 0, 0); for (name, cases, identical, differ) in &results { total += cases; same += identical; if !differ.is_empty() || identical != cases { bad_files += 1; println!( "{name:32} {identical}/{cases} identical: {}", differ.join("; ") ); } } println!( "lockstep: {} of {} cases identical to the reference (every bus cycle, cycles, state), {} files differ; {:.1} s wall", arm7tdmi::harness::thousands(same as u64), arm7tdmi::harness::thousands(total as u64), bad_files, start.elapsed().as_secs_f64() ); if bad_files == 0 && same == total { 0 } else { 1 } } fn dump(corpus: &Path, name: &str, index: usize) { let cases = load(&corpus.join(format!("{name}.json.bin")), Some(index + 1)); let case = &cases[index]; let mut bench = Bench::new(); bench.run(case); println!("opcode {:08x} cycles {}", case.opcode, bench.cycles); for e in &bench.cpu.bus.log { println!( " {} {} {:08x} {:08x} {}", e.kind, e.size, e.address, e.data, e.access ); } let words = bench.cpu.capture_state().to_sst(); for (k, w) in words.iter().enumerate() { println!(" {} {:08x}", NAMES[k], w); } } fn main() { let mut args = std::env::args().skip(1); let corpus = PathBuf::from(args.next().expect("usage: arm7-sst CORPUS_DIR ...")); let (mut only, mut limit, mut examples, mut jobs) = (Vec::new(), None, 2, 4); let (mut json, mut cache, mut overrides, mut dump_case) = (None, None, None, None); while let Some(arg) = args.next() { match arg.as_str() { "--files" => { for name in args.by_ref() { if name.starts_with("--") { panic!("put --files last"); } only.push(name); } } "--limit" => limit = args.next().and_then(|v| v.parse().ok()), "--examples" => examples = args.next().and_then(|v| v.parse().ok()).unwrap_or(2), "--jobs" => jobs = args.next().and_then(|v| v.parse().ok()).unwrap_or(4), "--json" => json = args.next().map(PathBuf::from), "--lockstep" => cache = args.next().map(PathBuf::from), "--overrides" => overrides = args.next().map(PathBuf::from), "--dump" => { let name = args.next().unwrap(); let index: usize = args.next().unwrap().parse().unwrap(); dump_case = Some((name, index)); } other => panic!("unknown argument {other}"), } } if let Some((name, index)) = dump_case { dump(&corpus, &name, index); return; } let files = corpus_files(&corpus, &only); let status = match cache { Some(cache) => lockstep(&files, &cache, jobs), None => gate( &files, &overrides.expect("--overrides FILE (the reference's tests/sst_overrides.json)"), limit, examples, jobs, json, ), }; std::process::exit(status); }