// SPDX-License-Identifier: MIT //! Rung 1: sh2-python's generated corpus (validation/rung1), run natively on this crate. //! //! sh2-corpus CASES.txt.gz EXPECTED.txt.gz [--lockstep OUT] [--step N] //! //! The transcription of the reference's ``validation/rung1/corpus.py`` ``run_core`` and //! ``gate.py check``: every case on the same memory map as the referees (two xorshift //! regions, the case's words, landings), up to 16 steps until it lands, the result line //! in the corpus's format, which must equal ``expected.txt.gz``'s (agreed by MAME and //! jgenesis, or ruled from the manuals: overrides.json). With ``--lockstep`` it also //! writes, per case, a CRC-32 of every bus callback (kind, address, width, clock, //! value), which scripts/corpus_trace.py writes for the reference: rung 1's lockstep. use std::collections::BTreeMap; use std::fs::File; use std::io::{BufRead, BufReader, Write}; use flate2::read::GzDecoder; use sh2::bus::{Bus, BusContext, FETCH}; use sh2::{Options, Sh7604}; const CODE_BASE: u32 = 0x0600F000; const CODE_SIZE: usize = 0x2400; const DATA_BASE: u32 = 0x06020000; const DATA_SIZE: usize = 0x1000; const DATA_SEED_XOR: u32 = 0x9E3779B9; fn xorshift_fill(size: usize, seed: u32) -> Vec { let mut x = if seed == 0 { 0x12345678 } else { seed }; let mut out = vec![0u8; size]; for i in (0..size).step_by(4) { x ^= x << 13; x ^= x >> 17; x ^= x << 5; out[i..i + 4].copy_from_slice(&x.to_be_bytes()); } out } fn crc32(crc: u32, bytes: &[u8]) -> u32 { let mut c = !crc; for &b in bytes { c ^= b as u32; for _ in 0..8 { c = if c & 1 != 0 { 0xEDB88320 ^ (c >> 1) } else { c >> 1 }; } } !c } struct Case { id: u64, seed: u32, values: Vec, // pc sr gbr vbr mach macl pr r0..r15 words: Vec<(u32, u32)>, landings: Vec, } fn parse_case(line: &str) -> Case { let fields: Vec<&str> = line.split_whitespace().collect(); assert_eq!(fields[0], "C"); let w = fields.iter().position(|f| *f == "W").unwrap(); let l = fields.iter().position(|f| *f == "L").unwrap(); let values: Vec = fields[3..26].iter().map(|t| u32::from_str_radix(t, 16).unwrap()).collect(); let mut words = Vec::new(); for part in fields[w + 1..l].join(",").split(',') { if !part.is_empty() { let (a, v) = part.split_once(':').unwrap(); words.push((u32::from_str_radix(a, 16).unwrap(), u32::from_str_radix(v, 16).unwrap())); } } let landings = fields[l + 1..] .join(",") .split(',') .filter(|t| !t.is_empty()) .map(|t| u32::from_str_radix(t, 16).unwrap()) .collect(); Case { id: fields[1].parse().unwrap(), seed: u32::from_str_radix(fields[2], 16).unwrap(), values, words, landings } } /// ``run_core``'s memory: the two regions, what fell outside them, the bus CRC. struct Board { regions: [(u32, Vec); 2], outside: Vec, crc: u32, } impl Board { fn locate(&mut self, address: u32, width: u32, fetch: bool) -> Option<(usize, usize)> { let address = address & 0x1FFFFFFF; for (i, (base, buf)) in self.regions.iter().enumerate() { if *base <= address && address as u64 + (width >> 3) as u64 <= *base as u64 + buf.len() as u64 { return Some((i, (address - base) as usize)); } } if !fetch { self.outside.push(address); } None } fn note(&mut self, text: String) { self.crc = crc32(self.crc, text.as_bytes()); } } impl Bus for Board { fn read(&mut self, address: u32, width: u32, kind: u32, cx: &mut BusContext) -> u32 { // The core's pipeline fetches ahead of execution and fetches what a taken branch // discards (PM 7.7.5, U11): a fetch past the regions is not an access the case // makes; it reads 0. let value = match self.locate(address, width, kind & FETCH != 0) { None => 0, Some((r, offset)) => { let buf = &self.regions[r].1; let mut v = 0u32; for i in 0..(width >> 3) as usize { v = (v << 8) | buf[offset + i] as u32; } v } }; self.note(format!("r {address:x} {width} {kind} {} {value:x}\n", cx.clock)); value } fn write(&mut self, address: u32, width: u32, value: u32, kind: u32, cx: &mut BusContext) { self.note(format!("w {address:x} {width} {kind} {} {value:x}\n", cx.clock)); if let Some((r, offset)) = self.locate(address, width, false) { let buf = &mut self.regions[r].1; let count = (width >> 3) as usize; for i in 0..count { buf[offset + i] = (value >> (8 * (count - 1 - i))) as u8; } } } } /// ``run_core``: the case's result line and its bus CRC. fn run_core(case: &Case) -> (String, u32) { let mut code = xorshift_fill(CODE_SIZE, case.seed); let mut data = xorshift_fill(DATA_SIZE, case.seed ^ DATA_SEED_XOR); for (address, word) in &case.words { for (base, buf) in [(CODE_BASE, &mut code), (DATA_BASE, &mut data)] { if base <= *address && (*address as usize) < base as usize + buf.len() { let o = (*address - base) as usize; buf[o..o + 2].copy_from_slice(&(*word as u16).to_be_bytes()); } } } let images = [code.clone(), data.clone()]; let board = Board { regions: [(CODE_BASE, code), (DATA_BASE, data)], outside: Vec::new(), crc: 0 }; let mut chip = Sh7604::new(board, Options::default()); let v = &case.values; chip.r.copy_from_slice(&v[7..23]); chip.sr = v[1]; chip.gbr = v[2]; chip.vbr = v[3]; chip.mach = v[4]; chip.macl = v[5]; chip.pr = v[6]; chip.pc = v[0]; let mut status = "timeout"; for _ in 0..16 { chip.step(); if chip.delay_target < 0 && case.landings.contains(&chip.pc) { status = "ok"; break; } } if !chip.bus.outside.is_empty() { status = "outside"; } let mut regs = vec![chip.pc, chip.sr, chip.gbr, chip.vbr, chip.mach, chip.macl, chip.pr]; regs.extend_from_slice(&chip.r); let values: Vec = regs.iter().map(|x| format!("{x:X}")).collect(); let mut memory = BTreeMap::new(); for ((base, buf), image) in chip.bus.regions.iter().zip(images.iter()) { for (i, (a, b)) in buf.iter().zip(image.iter()).enumerate() { if a != b { memory.insert(base + i as u32, *a); } } } let diffs: Vec = memory.iter().map(|(a, b)| format!("{a:X}:{b:X}")).collect(); (format!("R {} {} {} M {}", case.id, status, values.join(" "), diffs.join(",")), chip.bus.crc) } fn lines(path: &str) -> Vec { BufReader::new(GzDecoder::new(File::open(path).unwrap())).lines().map(|l| l.unwrap()).collect() } fn main() { let args: Vec = std::env::args().collect(); let mut lockstep: Option = None; let mut step = 1; let mut i = 3; while i < args.len() { match args[i].as_str() { "--lockstep" => { lockstep = Some(File::create(&args[i + 1]).unwrap()); i += 2; } "--step" => { step = args[i + 1].parse().unwrap(); i += 2; } other => panic!("unknown argument {other}"), } } let cases: Vec = lines(&args[1]).iter().filter(|l| l.starts_with("C ")).step_by(step).map(|l| parse_case(l)).collect(); let mut expected = BTreeMap::new(); for line in lines(&args[2]) { let mut parts = line.splitn(3, ' '); let id: u64 = parts.next().unwrap().parse().unwrap(); let kind = parts.next().unwrap().to_string(); expected.insert(id, (kind, parts.next().unwrap().to_string())); } let mut counts: BTreeMap = BTreeMap::new(); let mut failures = Vec::new(); for case in &cases { let (kind, result) = &expected[&case.id]; let (got, crc) = run_core(case); if let Some(file) = lockstep.as_mut() { writeln!(file, "{} {crc:08x} {got}", case.id).unwrap(); } if &got == result { *counts.entry(kind.clone()).or_insert(0) += 1; } else { failures.push(format!("case {} ({kind}): expected {result}\n got {got}", case.id)); } } let total: u64 = counts.values().sum(); for (kind, count) in &counts { println!("{count:6} {kind}"); } for failure in failures.iter().take(10) { println!("{failure}"); } println!("rung 1 corpus: {total} of {} cases match expected.txt.gz ({} fail)", cases.len(), failures.len()); std::process::exit(if failures.is_empty() { 0 } else { 1 }); }