// SPDX-License-Identifier: MIT //! SingleStepTests 65816 through this core (the reference's rung 1). //! //! sst CORPUS_DIR [--limit N] [--jobs N] //! sst CORPUS_DIR --dump OUT [--limit N] [--jobs N] //! //! The judge is the reference's `tests/single_step.py` and //! `scripts/run_single_step.py`, transcribed: the same readings (SH = $01 in //! emulation mode, XH = YH = 0 with X = 1; the C1, C2 and C9 masks; C4's cases //! excluded and counted; WAI and STP one step), the same per-file failure lines //! and the same total line, so the output can be compared with the //! reference's counts (`conformance/expected/sst.txt`). //! //! `--dump` is the lockstep half (`scripts/sst_lockstep.py`): every case of the //! first `--limit` of each file, C4's included, run with nothing masked, one //! line per case with the final registers, the memory the case touched and //! every cycle (address, value, pins), in the format //! `scripts/reference_sst.py` writes from the reference core. use std::collections::HashMap; use std::io::Write; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; use serde::Deserialize; use w65c816::{Bus, Frame, Signals, W65C816}; #[derive(Deserialize, Clone)] struct State { pc: u16, s: u16, p: u8, a: u16, x: u16, y: u16, dbr: u8, d: u16, pbr: u8, e: u8, ram: Vec<(u32, u8)>, } #[derive(Deserialize)] struct Case { name: String, initial: State, #[serde(rename = "final")] end: State, cycles: Vec<(Option, Option, String)>, } const C1_OPCODES: [u8; 2] = [0x7C, 0xFC]; const C4_OPCODES: [u8; 8] = [0x01, 0x21, 0x41, 0x61, 0x81, 0xA1, 0xC1, 0xE1]; const RTI_P_PULL: usize = 3; // RTI's cycle that pulls P: opcode, IO, IO, P (DS Table 5-7 row 22g) /// (vda, vpa, vpb, write, mlb, e, m, x), as the reference's `kinds()`. type Kinds = [bool; 8]; fn initial_state(state: &State) -> State { let mut state = state.clone(); if state.e != 0 { state.s = 0x0100 | (state.s & 0xFF); state.p |= 0x30; } if state.p & 0x10 != 0 { state.x &= 0xFF; state.y &= 0xFF; } state } /// C4: the corpus reads (d,x)'s high byte from the next page; the core does not. fn excluded(opcode: u8, case: &Case) -> bool { if !C4_OPCODES.contains(&opcode) { return false; } let state = initial_state(&case.initial); if state.e == 0 || state.d & 0xFF == 0 { return false; } let ram: HashMap = case.initial.ram.iter().copied().collect(); let operand = *ram .get(&((state.pbr as u32) << 16 | (state.pc as u32 + 1) & 0xFFFF)) .unwrap_or(&0) as u32; (state.d as u32 + operand + state.x as u32) & 0xFF == 0xFF } struct Host { memory: HashMap, seen: Vec<(u32, Option, Kinds)>, } fn kinds(signals: Signals, write: bool) -> Kinds { [ signals.vda(), signals.vpa(), signals.vpb(), write, signals.mlb(), signals.e, signals.m, signals.x_flag, ] } impl Bus for Host { fn read(&mut self, address: u32, _: &mut Frame, signals: Signals) -> u8 { let value = *self.memory.get(&address).unwrap_or(&0); self.seen .push((address, Some(value), kinds(signals, false))); value } fn write(&mut self, address: u32, value: u8, _: &mut Frame, signals: Signals) { self.memory.insert(address, value); self.seen.push((address, Some(value), kinds(signals, true))); } fn idle(&mut self, address: u32, _: &mut Frame, signals: Signals) { self.seen.push((address, None, kinds(signals, false))); } } /// Run one case as the reference's `run_case` runs it; return the CPU. fn execute(case: &Case) -> (W65C816, u8, usize) { let state = initial_state(&case.initial); let memory: HashMap = case.initial.ram.iter().copied().collect(); let mut cpu = W65C816::new(Host { memory, seen: Vec::new(), }); cpu.pc = state.pc; cpu.s = state.s; cpu.p = state.p; cpu.a = state.a; cpu.x = state.x; cpu.y = state.y; cpu.dbr = state.dbr; cpu.d = state.d; cpu.pbr = state.pbr; cpu.e = state.e; let opcode = *cpu .bus .memory .get(&((state.pbr as u32) << 16 | state.pc as u32)) .unwrap_or(&0); let expected = case.cycles.iter().filter(|row| row.0.is_some()).count(); while cpu.bus.seen.len() < expected { let before = cpu.bus.seen.len(); cpu.step(); if cpu.bus.seen.len() == before || opcode == 0xCB || opcode == 0xDB { break; // WAI, STP: one step } } (cpu, opcode, expected) } /// Run one case; return a description of each difference (empty: it passes). fn run_case(case: &Case) -> Vec { let (cpu, opcode, _) = execute(case); let mut problems = Vec::new(); let end = &case.end; let pairs: [(&str, u32, u32); 10] = [ ("pc", cpu.pc as u32, end.pc as u32), ("s", cpu.s as u32, end.s as u32), ("p", cpu.p as u32, end.p as u32), ("a", cpu.a as u32, end.a as u32), ("x", cpu.x as u32, end.x as u32), ("y", cpu.y as u32, end.y as u32), ("dbr", cpu.dbr as u32, end.dbr as u32), ("d", cpu.d as u32, end.d as u32), ("pbr", cpu.pbr as u32, end.pbr as u32), ("e", cpu.e as u32, end.e as u32), ]; for (name, got, want) in pairs { if got != want { problems.push(format!("{name}: got ${got:X}, want ${want:X}")); } } for &(address, value) in &end.ram { let got = *cpu.bus.memory.get(&address).unwrap_or(&0); if got != value { problems.push(format!( "ram ${address:06X}: got ${got:02X}, want ${value:02X}" )); } } let expected: Vec<&(Option, Option, String)> = case.cycles.iter().filter(|row| row.0.is_some()).collect(); let seen = &cpu.bus.seen; if seen.len() != expected.len() { problems.push(format!( "cycles: got {}, want {}", seen.len(), expected.len() )); } for (index, (row, &(got_address, got_value, got_kinds))) in expected.iter().zip(seen).enumerate() { let (address, value, flags) = (row.0.unwrap(), row.1, row.2.as_bytes()); let want_kinds: Kinds = [ flags[0] == b'd', flags[1] == b'p', flags[2] == b'v', flags[3] == b'w', flags[7] == b'l', flags[4] == b'e', flags[5] == b'm', flags[6] == b'x', ]; let (mut want, mut got): (Vec, Vec) = (want_kinds.to_vec(), got_kinds.to_vec()); if C1_OPCODES.contains(&opcode) && index + 2 >= expected.len() { want = want[2..].to_vec(); got = got[2..].to_vec(); } if opcode == 0x42 && index == 1 { // C2; the E/M/X pins still count want = [&got[..5], &want[5..]].concat(); } if opcode == 0x40 && index > RTI_P_PULL { want.truncate(5); // C9 got.truncate(5); } if got_address != address { problems.push(format!( "cycle {index}: address ${got_address:06X}, want ${address:06X}" )); } if let (Some(value), Some(got_value)) = (value, got_value) { if got_value != value { problems.push(format!( "cycle {index}: value ${got_value:02X}, want ${value:02X}" )); } } if got != want { problems.push(format!( "cycle {index}: kinds {got:?}, want {want:?} ({})", row.2 )); } } problems } /// The lockstep line of one case: nothing masked, nothing excluded. fn dump_case(case: &Case) -> String { let (cpu, _, _) = execute(case); let mut line = format!( "{} {:x} {:x} {:x} {:x} {:x} {:x} {:x} {:x} {:x} {:x} {}", case.name.replace(' ', "_"), cpu.pc, cpu.s, cpu.p, cpu.a, cpu.x, cpu.y, cpu.dbr, cpu.d, cpu.pbr, cpu.e, cpu.bus.seen.len() ); let mut memory: Vec<(&u32, &u8)> = cpu.bus.memory.iter().collect(); memory.sort(); line.push_str(" |"); for (address, value) in memory { line.push_str(&format!(" {address:x}={value:x}")); } line.push_str(" |"); for &(address, value, kinds) in &cpu.bus.seen { let value = match value { Some(value) => format!("{value:x}"), None => "-".into(), }; let pins: String = kinds .iter() .zip("dpvwlemx".chars()) .map(|(&on, letter)| if on { letter } else { '-' }) .collect(); line.push_str(&format!(" {address:x}:{value}:{pins}")); } line } fn load(path: &Path) -> Vec { let text = std::fs::read(path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); serde_json::from_slice(&text).unwrap_or_else(|e| panic!("{}: {e}", path.display())) } struct FileResult { name: String, passed: u64, failed: u64, skipped: u64, first: Vec, } fn run_file(path: &Path, limit: Option) -> FileResult { let name = path.file_stem().unwrap().to_string_lossy().to_string(); let opcode = u8::from_str_radix(&name[..2], 16).unwrap(); let cases = load(path); let cases = &cases[..limit.unwrap_or(cases.len()).min(cases.len())]; let (mut passed, mut failed, mut skipped) = (0, 0, 0); let mut first = Vec::new(); for case in cases { if excluded(opcode, case) { skipped += 1; continue; } let problems = run_case(case); if problems.is_empty() { passed += 1; } else { failed += 1; if first.is_empty() { first.push(case.name.clone()); first.extend(problems.into_iter().take(3)); } } } FileResult { name, passed, failed, skipped, first, } } fn main() { let args: Vec = std::env::args().skip(1).collect(); let mut corpus = None; let mut limit = None; let mut jobs = 4usize; let mut dump: Option = None; let mut index = 0; while index < args.len() { match args[index].as_str() { "--limit" => { index += 1; limit = Some(args[index].parse().expect("--limit N")); } "--jobs" => { index += 1; jobs = args[index].parse().expect("--jobs N"); } "--dump" => { index += 1; dump = Some(PathBuf::from(&args[index])); } other => corpus = Some(PathBuf::from(other)), } index += 1; } let corpus = corpus.expect("usage: sst CORPUS_DIR [--limit N] [--jobs N] [--dump OUT]"); let mut files: Vec = std::fs::read_dir(&corpus) .expect("corpus directory") .map(|entry| entry.unwrap().path()) .filter(|path| path.extension().is_some_and(|e| e == "json")) .collect(); files.sort(); let next = AtomicUsize::new(0); if let Some(out) = dump { let lines: Mutex)>> = Mutex::new(Vec::new()); std::thread::scope(|scope| { for _ in 0..jobs.max(1) { scope.spawn(|| loop { let i = next.fetch_add(1, Ordering::SeqCst); if i >= files.len() { break; } let cases = load(&files[i]); let cases = &cases[..limit.unwrap_or(cases.len()).min(cases.len())]; let text: Vec = cases.iter().map(dump_case).collect(); lines.lock().unwrap().push((i, text)); }); } }); let mut lines = lines.into_inner().unwrap(); lines.sort_by_key(|(i, _)| *i); let mut file = std::io::BufWriter::new(std::fs::File::create(&out).expect("--dump file")); for (_, text) in lines { for line in text { writeln!(file, "{line}").unwrap(); } } return; } let results: Mutex> = Mutex::new(Vec::new()); std::thread::scope(|scope| { for _ in 0..jobs.max(1) { scope.spawn(|| loop { let i = next.fetch_add(1, Ordering::SeqCst); if i >= files.len() { break; } let result = run_file(&files[i], limit); if result.failed != 0 { println!( "{}: {} failing; {:?}", result.name, result.failed, result.first ); } results.lock().unwrap().push(result); }); } }); let results = results.into_inner().unwrap(); let passed: u64 = results.iter().map(|r| r.passed).sum(); let failed: u64 = results.iter().map(|r| r.failed).sum(); let skipped: u64 = results.iter().map(|r| r.skipped).sum(); println!( "files {}, passed {passed}, failed {failed}, excluded (C4) {skipped}", files.len() ); std::process::exit(if failed != 0 { 1 } else { 0 }); }