// SPDX-License-Identifier: MIT //! The test ROMs natively in the harness: the reference's rungs 2 and 3. //! //! roms CPUTEST_DIR KROM_DIR //! //! Rung 2 is the reference's `tests/test_cputest.py`: gilyon's cputest-full //! and cputest-basic run in the harness until they spin (or print "Failed"), //! and the verdict and test number they printed are read back from VRAM. Rung //! 3 is its `tests/test_krom.py`: each of krom's 23 CPU tests runs in the //! harness with every VRAM low-byte write logged (`TextLog`), CPUMSC reset //! once after its STP, and every `PrintText(Pass, $DEST, 4)` in the ROM's //! source must have printed "PASS" at `$DEST` as often as the source has it, //! with no "FAIL" at a Fail destination. //! //! One line per ROM, in the form `scripts/reference_roms.py` prints from the //! reference's harness; rung 2/3 compares the two outputs and checks each //! line's verdict. Exit status 1 if any ROM fails its test. use std::collections::BTreeMap; use std::path::Path; use w65c816::harness::{Harness, Hooks, Machine, Plain}; const LAST_TEST: [(&str, u32); 2] = [("cputest-full.sfc", 0x0649), ("cputest-basic.sfc", 0x0452)]; const CPUTEST_MAX_CYCLES: u64 = 20_000_000; // full needs about 4.9 million const KROM_MAX_CYCLES: u64 = 10_000_000; // the longest, LDR, needs about 1.5 million const GROUPS: [&str; 23] = [ "ADC", "AND", "ASL", "BIT", "BRA", "CMP", "DEC", "EOR", "INC", "JMP", "LDR", "LSR", "MOV", "MSC", "ORA", "PHL", "PSR", "RET", "ROL", "ROR", "SBC", "STR", "TRN", ]; /// The ROM's own verdict and test number, as it printed them. fn verdict(machine: &Machine) -> (String, Option) { let lines = machine.screen(0, 4); let word = lines[1].get(17..).unwrap_or("").trim().to_string(); // re.fullmatch(r" Test number: ([0-9A-F]{4})", lines[3]) let number = lines[3] .strip_prefix(" Test number: ") .filter(|hex| { hex.len() == 4 && hex .bytes() .all(|b| b.is_ascii_digit() || (b'A'..=b'F').contains(&b)) }) .map(|hex| u32::from_str_radix(hex, 16).unwrap()); (word, number) } fn cputest(folder: &Path) -> bool { let mut ok = true; for (name, last) in LAST_TEST { let rom = std::fs::read(folder.join(name)).unwrap_or_else(|e| panic!("{name}: {e}")); let mut harness = Harness::new(&rom); let mut failed = |h: &mut Harness| verdict(&h.cpu.bus).0 == "Failed"; let result = harness.run(CPUTEST_MAX_CYCLES, Some(&mut failed)); let (word, number) = verdict(&harness.cpu.bus); let number_text = number.map_or("none".to_string(), |n| format!("{n:04X}")); let pass = result.reason == "spin" && word == "Success" && number == Some(last); println!( "{name}: {} after {} cycles at {:06X}; printed '{word}', test {number_text}: {}", result.reason, result.cycles, result.pc, if pass { "pass" } else { "FAIL" } ); ok &= pass; } ok } /// The harness, noting every VRAM low-byte write with its word address (`TextLog`). #[derive(Default)] struct TextLog { writes: Vec<(u32, u8)>, } impl Hooks for TextLog { fn io_write(machine: &mut Machine, offset: u32, value: u8) { if offset == 0x2118 { let address = machine.vram_address; machine.hooks.writes.push((address, value)); } machine.base_io_write(offset, value); } } impl TextLog { /// How many times `word` was written at consecutive VRAM words, by its /// first word's byte address (as the sources write `$DEST`). fn printed(&self, word: &[u8]) -> BTreeMap { let mut found = BTreeMap::new(); let size = word.len(); if self.writes.len() < size { return found; } for index in 0..=self.writes.len() - size { let run = &self.writes[index..index + size]; if run.iter().map(|&(_, v)| v).eq(word.iter().copied()) && run .iter() .enumerate() .all(|(k, &(a, _))| a == run[0].0 + k as u32) { *found.entry(run[0].0 << 1 & 0xFFFF).or_insert(0) += 1; } } found } fn failing(&self) -> bool { let n = self.writes.len(); n >= 4 && self.writes[n - 4..].iter().map(|&(_, v)| v).eq(*b"FAIL") } } /// The `PrintText(Pass|Fail, $XXXX, 4)` calls of a source (the reference's regular expression). fn expected(source: &str) -> (BTreeMap, Vec) { let mut passes = BTreeMap::new(); let mut fails = Vec::new(); for (start, _) in source.match_indices("PrintText(") { let rest = &source[start + "PrintText(".len()..]; for (kind, is_pass) in [("Pass, $", true), ("Fail, $", false)] { if let Some(tail) = rest.strip_prefix(kind) { let hex = tail.get(..4).unwrap_or(""); if hex.len() == 4 && hex .bytes() .all(|b| b.is_ascii_digit() || (b'A'..=b'F').contains(&b)) && tail[4..].starts_with(", 4)") { let destination = u32::from_str_radix(hex, 16).unwrap(); if is_pass { *passes.entry(destination).or_insert(0) += 1; } else if !fails.contains(&destination) { fails.push(destination); } } } } } (passes, fails) } fn krom(folder: &Path) -> bool { let mut ok = true; for group in GROUPS { let base = folder.join(group); let source = std::fs::read(base.join(format!("CPU{group}.asm"))).expect("krom source"); let (passes, fails) = expected(&String::from_utf8_lossy(&source)); let rom = std::fs::read(base.join(format!("CPU{group}.sfc"))).expect("krom ROM"); let mut harness = Harness::with_hooks(&rom, None, 30_000, TextLog::default()); let mut failing = |h: &mut Harness| h.cpu.bus.hooks.failing(); let mut result = harness.run(KROM_MAX_CYCLES, Some(&mut failing)); if result.reason == "stopped" && group == "MSC" { harness.cpu.frame.request_reset(); result = harness.run(KROM_MAX_CYCLES, Some(&mut failing)); } let log = &harness.cpu.bus.hooks; let failed = log.printed(b"FAIL"); let failed_at = fails.iter().filter(|at| failed.contains_key(at)).count(); let printed = log.printed(b"PASS"); let rows: u32 = passes.values().sum(); let matched = passes .iter() .filter(|(at, n)| printed.get(at) == Some(n)) .count(); let pass = failed_at == 0 && result.reason == "spin" && matched == passes.len() && rows > 0; println!( "CPU{group}: {} after {} cycles at {:06X}; {} PASS rows expected, {matched} of {} destinations as expected, FAIL at {failed_at}: {}", result.reason, result.cycles, result.pc, rows, passes.len(), if pass { "pass" } else { "FAIL" } ); ok &= pass; } ok } fn main() { let args: Vec = std::env::args().skip(1).collect(); if args.len() != 2 { eprintln!("usage: roms CPUTEST_DIR KROM_DIR"); std::process::exit(2); } let ok = cputest(Path::new(&args[0])) & krom(Path::new(&args[1])); std::process::exit(if ok { 0 } else { 1 }); }