// SPDX-License-Identifier: MIT //! Rung 2: SingleStepTests 65x02, the three CMOS sets each on its row, every //! case read and judged as the reference's `tests/single_step.py` and //! `scripts/run_single_step.py` do (transcribed here). //! //! sst CORPUS_DIR [--set NAME ...] [--limit N] [--jobs N] //! //! `CORPUS_DIR` holds `wdc65c02/v1/*.json`, `rockwell65c02/v1/*.json` and //! `synertek65c02/v1/*.json` (the reference's `reference/src/65x02`). The //! corpus is **emulator-generated** (the reference's docs/validation.md): a //! volume detector, never a judge. A case passes when the core's registers, //! RAM, cycle count (`step()`'s return and the number of callbacks) and every //! cycle's address, value and direction equal the corpus's. //! //! How the corpus is read: //! //! - **B** (bit 4 of P) has no flip-flop; the core never stores it. The //! corpus keeps a B bit in its `p`. It is dropped going in and not compared //! coming out. Bit 5 is compared. //! //! Where a higher tier contradicts the corpus the core follows the higher //! tier, and the cases are **counted by name**, each class an entry of the //! reference's docs/undocumented-behavior.md. A case is counted only if it //! fails the full comparison and passes its classes' reduced comparison, //! which is everything the contradiction does not touch. Two kinds of class: //! //! *The instruction itself differs.* //! //! - `C1`: `$5C` is 8 cycles (CAP on both parts, DS, GDS, VDS, NDS), 4 in the //! corpus. Reduced: registers, RAM and the first three cycles. //! - `C2`: `x7` and `xF` on the part without bit instructions are one-byte, //! one-cycle NOPs (CAP on the G65SC12; GDS, VDS, NDS); the `synertek65c02` //! set has two- and three-byte NOPs. Reduced: A X Y S P and RAM unchanged, //! the opcode fetch. //! - `C3`: `$CB` and `$DB` without `WAI`/`STP` are one-byte, one-cycle NOPs //! (GDS, VDS, NDS, CL); the Rockwell and Synertek sets have 1 byte 2 cycles //! and 2 bytes 4 cycles. Reduced: as C2. //! //! *Only the address of a dummy read differs* (the captures of two real parts //! decide the address, rung 4; the corpus has another). Reduced: registers, //! RAM, the cycle count, every cycle's direction, and the address and value //! of every cycle but the named dummy cycle(s): `C10` (`$DC`/`$FC` cycle 4), //! `C13` (the decimal cycle of `ADC`/`SBC`, the last), `C14` (indexed stores //! and `INC`/`DEC abs,X` without a page crossing, cycle 4), `C15` (`(zp),Y`, //! cycle 5), `C16` (a branch taken across a page, cycle 4), `C17` (`JMP //! (abs)` cycles 4 to 6, `JMP (abs,X)` cycle 4), `C18` (`zp,X`, `zp,Y`, //! `(zp,X)`, cycle 3). //! //! Differences forced by Rust: the reference's memory is a dict seeded from //! the case; here a 64 KB array, zeroed again after each case at every //! address the case named or touched, which reads the same. Its multiprocess //! pool is threads here. use std::collections::BTreeMap; use std::io::{BufRead, BufReader}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; use serde::Deserialize; use w65c02::dispatch::{Form, Mode, OPCODES}; use w65c02::{Bus, Cmos65c02, Frame, Row, Signals, G65SC02, R65C02, W65C02S}; /// corpus set -> the row it is run on (the reference's docs/validation.md, rung 1). const SETS: [(&str, Row); 3] = [ ("wdc65c02", W65C02S), ("rockwell65c02", R65C02), ("synertek65c02", G65SC02), ]; const B: u8 = 0x10; const D: u8 = 0x08; #[derive(Deserialize)] struct Snapshot { pc: u16, s: u8, a: u8, x: u8, y: u8, p: u8, ram: Vec<(u16, u8)>, } #[derive(Deserialize)] struct Case { name: String, initial: Snapshot, #[serde(rename = "final")] end: Snapshot, cycles: Vec<(u16, u8, String)>, } /// (address, value, is a write) type Cycle = (u16, u8, bool); struct Ram { memory: Vec, seen: Vec, } impl Bus for Ram { fn read(&mut self, address: u16, _: &mut Frame, _: Signals) -> u8 { let value = self.memory[address as usize]; self.seen.push((address, value, false)); value } fn write(&mut self, address: u16, value: u8, _: &mut Frame, _: Signals) { self.memory[address as usize] = value; self.seen.push((address, value, true)); } } /// (opcode, cycle index from 0) -> the class that says the corpus's dummy address is wrong. fn dummy_classes() -> BTreeMap<(u8, usize), &'static str> { let mut classes = BTreeMap::new(); for (opcode, (_handler, mode, _mnemonic, form, _cycles)) in OPCODES.iter().enumerate() { let opcode = opcode as u8; if matches!(form, Form::Zpx | Form::Zpy | Form::Idx) { classes.insert((opcode, 2), "C18"); } if *form == Form::Idy { classes.insert((opcode, 4), "C15"); } if matches!(mode, Mode::EaAbxFixed | Mode::EaAbyFixed | Mode::EaIdyFixed) && matches!(form, Form::Abx | Form::Aby) { classes.insert((opcode, 3), "C14"); } if *form == Form::Rel { classes.insert((opcode, 3), "C16"); } } for index in [3, 4, 5] { classes.insert((0x6C, index), "C17"); } classes.insert((0x7C, 3), "C17"); classes.insert((0xDC, 3), "C10"); classes.insert((0xFC, 3), "C10"); classes } fn is_adc_sbc(opcode: u8) -> bool { matches!(OPCODES[opcode as usize].2, "ADC" | "SBC") } fn is_bit_opcode(opcode: u8) -> bool { matches!(opcode & 0x0F, 0x07 | 0x0F) } /// Run one case on the set's row. Returns (problems, classes): no problems /// and no classes is a pass; no problems and classes is a case counted under /// those names; problems are a failure. fn run_case( case: &Case, set_name: &str, cpu: &mut Cmos65c02, classes_of: &BTreeMap<(u8, usize), &'static str>, ) -> (Vec, Vec<&'static str>) { let initial = &case.initial; let end = &case.end; for &(address, value) in &initial.ram { cpu.bus.memory[address as usize] = value; } cpu.bus.seen.clear(); cpu.frame = Frame::default(); cpu.waiting = false; cpu.stopped = false; cpu.sync = false; cpu.fetch = false; cpu.opcode = 0; cpu.pc = initial.pc; cpu.s = initial.s; cpu.a = initial.a; cpu.x = initial.x; cpu.y = initial.y; cpu.p = initial.p & !B; let returned = cpu.step() as usize; let opcode = u8::from_str_radix(case.name.split(' ').next().unwrap(), 16).unwrap(); let expected: Vec = case .cycles .iter() .map(|(address, value, kind)| (*address, *value, kind == "write")) .collect(); let seen = std::mem::take(&mut cpu.bus.seen); let mut registers = Vec::new(); for (name, got, want) in [ ("pc", cpu.pc, end.pc), ("s", cpu.s as u16, end.s as u16), ("a", cpu.a as u16, end.a as u16), ("x", cpu.x as u16, end.x as u16), ("y", cpu.y as u16, end.y as u16), ] { if got != want { registers.push(format!("{name}: got ${got:X}, want ${want:X}")); } } if (cpu.p ^ end.p) & !B != 0 { registers.push(format!( "p: got ${:02X}, want ${:02X} (B not compared)", cpu.p, end.p )); } let mut ram = Vec::new(); for &(address, value) in &end.ram { let got = cpu.bus.memory[address as usize]; if got != value { ram.push(format!( "ram ${address:04X}: got ${got:02X}, want ${value:02X}" )); } } let mut count = Vec::new(); if returned != seen.len() { count.push(format!( "step() returned {returned} for {} callbacks", seen.len() )); } if seen.len() != expected.len() { count.push(format!( "cycles: got {}, want {}", seen.len(), expected.len() )); } let differing: Vec = seen .iter() .zip(expected.iter()) .enumerate() .filter(|(_, (a, b))| a != b) .map(|(index, _)| index) .collect(); // Leave memory clean for the next case: zero every byte this one named or touched. for &(address, _) in initial.ram.iter().chain(end.ram.iter()) { cpu.bus.memory[address as usize] = 0; } for &(address, _, _) in &seen { cpu.bus.memory[address as usize] = 0; } let mut problems: Vec = Vec::new(); problems.extend(registers.iter().cloned()); problems.extend(ram.iter().cloned()); problems.extend(count.iter().cloned()); problems.extend(differing.iter().map(|&index| { format!( "cycle {}: got {:?}, want {:?}", index + 1, seen[index], expected[index] ) })); if problems.is_empty() { return (vec![], vec![]); } // The classes where the instruction itself differs. if opcode == 0x5C { if registers.is_empty() && ram.is_empty() && seen.len() >= 3 && expected.len() >= 3 && seen[..3] == expected[..3] && returned == seen.len() && seen.len() == 8 { return (vec![], vec!["C1"]); } return (problems, vec![]); } let mut name = None; if set_name == "synertek65c02" && is_bit_opcode(opcode) { name = Some("C2"); } else if set_name != "wdc65c02" && (opcode == 0xCB || opcode == 0xDB) { name = Some("C3"); } if let Some(name) = name { let unchanged = cpu.s == initial.s && cpu.a == initial.a && cpu.x == initial.x && cpu.y == initial.y && (cpu.p ^ initial.p) & !B == 0 && ram.is_empty(); if unchanged && seen.len() == expected.len().min(1) && seen[..] == expected[..seen.len()] && cpu.pc == initial.pc.wrapping_add(1) { return (vec![], vec![name]); } return (problems, vec![]); } // The classes where only a dummy read's address differs. if !registers.is_empty() || !ram.is_empty() || !count.is_empty() { return (problems, vec![]); } let mut classes = Vec::new(); for &index in &differing { let mut name = classes_of.get(&(opcode, index)).copied(); if name.is_none() && is_adc_sbc(opcode) && initial.p & D != 0 && index == seen.len() - 1 { name = Some("C13"); } match name { Some(name) if !seen[index].2 && !expected[index].2 => { if !classes.contains(&name) { classes.push(name); } } _ => return (problems, vec![]), } } classes.sort(); (vec![], classes) } #[derive(Default)] struct Totals { cases: usize, passed: usize, failed: usize, counted: usize, by_name: BTreeMap<&'static str, usize>, first: Vec, } fn run_file(path: &Path, set_name: &str, row: Row, limit: Option) -> Totals { let classes_of = dummy_classes(); let mut totals = Totals::default(); let file = std::fs::File::open(path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); let mut cpu = Cmos65c02::new( row, Ram { memory: vec![0; 0x10000], seen: Vec::with_capacity(16), }, ); let mut remaining = limit; for line in BufReader::new(file).lines() { let line = line.expect("read"); // The array's brackets and separators; a case starts with "{" and ends with "}". let line = line .trim() .trim_start_matches('[') .trim_end_matches([',', ']']); if !line.starts_with('{') { continue; } let case: Case = serde_json::from_str(line).unwrap_or_else(|e| panic!("{}: {e}", path.display())); let (problems, names) = run_case(&case, set_name, &mut cpu, &classes_of); totals.cases += 1; if !problems.is_empty() { totals.failed += 1; if totals.first.is_empty() { totals.first.push(case.name.clone()); totals.first.extend(problems.into_iter().take(4)); } } else if !names.is_empty() { totals.counted += 1; for name in names { *totals.by_name.entry(name).or_default() += 1; } } else { totals.passed += 1; } if let Some(left) = remaining.as_mut() { *left -= 1; if *left == 0 { break; } } } totals } /// 1234567 -> "1,234,567", as Python's `{:,}`. fn commas(value: usize) -> String { let text = value.to_string(); let mut out = String::new(); for (index, digit) in text.chars().enumerate() { if index > 0 && (text.len() - index) % 3 == 0 { out.push(','); } out.push(digit); } out } fn main() { let mut args = std::env::args().skip(1); let mut corpus: Option = None; let mut wanted = Vec::new(); let mut limit = None; let mut jobs = 4usize; while let Some(arg) = args.next() { match arg.as_str() { "--limit" => limit = Some(args.next().expect("--limit N").parse().expect("a number")), "--jobs" => jobs = args.next().expect("--jobs N").parse().expect("a number"), "--set" => wanted.push(args.next().expect("--set NAME")), _ if corpus.is_none() => corpus = Some(PathBuf::from(arg)), other => panic!("unexpected argument {other}"), } } let corpus = corpus.expect("usage: sst CORPUS_DIR [--set NAME ...] [--limit N] [--jobs N]"); let mut failed = 0; for (set_name, row) in SETS { if !wanted.is_empty() && !wanted.iter().any(|w| w == set_name) { continue; } if !corpus.join(set_name).join("v1").join("a9.json").is_file() { eprintln!( "{}: no {set_name} corpus (the reference's scripts/fetch_references.py)", corpus.display() ); std::process::exit(2); } let files: Vec = (0..256) .map(|opcode| { corpus .join(set_name) .join("v1") .join(format!("{opcode:02x}.json")) }) .collect(); let next = AtomicUsize::new(0); let totals = Mutex::new(Totals::default()); std::thread::scope(|scope| { for _ in 0..jobs.clamp(1, 4) { scope.spawn(|| loop { let index = next.fetch_add(1, Ordering::Relaxed); if index >= files.len() { break; } let one = run_file(&files[index], set_name, row, limit); if one.failed > 0 { println!( "{set_name} {index:02X}: {} failing; {:?}", one.failed, one.first ); } let mut total = totals.lock().unwrap(); total.cases += one.cases; total.passed += one.passed; total.failed += one.failed; total.counted += one.counted; for (name, count) in one.by_name { *total.by_name.entry(name).or_default() += count; } }); } }); let total = totals.into_inner().unwrap(); failed += total.failed; let mut named: Vec<(&str, usize)> = total.by_name.into_iter().collect(); named.sort_by_key(|(name, _)| name[1..].parse::().unwrap()); let counted = if named.is_empty() { "none".to_string() } else { named .iter() .map(|(name, count)| format!("{name} {}", commas(*count))) .collect::>() .join(", ") }; println!( "{set_name} on {}: {} cases, {} pass in full, {} counted under a named contradiction, \ {} fail; by name (a case can be in two): {counted}", row.name, commas(total.cases), commas(total.passed), commas(total.counted), commas(total.failed), ); } std::process::exit(if failed == 0 { 0 } else { 1 }); }