// SPDX-License-Identifier: MIT //! SingleStepTests/680x0 as a detector, every disagreement classified (rung 6). //! //! A transcription of m68000-python's `tests/harness_680x0.py` (the //! byte-addressed host and what each case compares) and //! `scripts/classify_680x0.py` (the rules sorting each disagreement into a //! named cause, each explained by a higher-tier source in the reference's //! `docs/validation.md`, "Rung 5"). The corpus is Tom Harte's, generated by //! his CLK emulator (tier T3, no license file, never committed): a //! disagreement is a question, never a verdict. //! //! The rung is z80-rust's FUSE rung in this family's shape: the output is the //! reference classifier's table, and `scripts/rung6.sh` requires it to be //! identical to the reference's own, so every case agrees or disagrees here //! for exactly the reason it does there. An unclassified case is printed in //! full and fails the run. //! //! Usage: `m68k-680x0 `. use std::collections::HashMap; use std::io::Read; use std::path::PathBuf; use std::process::ExitCode; use m68000_rust::{Bus, BusError, CpuState, Cycle, M68000}; use serde_json::Value; const REGISTERS: [&str; 19] = [ "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "usp", "ssp", "sr", "pc", ]; const FRAME: [&str; 7] = [ "pc_low", "sr", "pc_high", "ir", "address_low", "information", "address_high", ]; /// One access in the 680x0 corpus's shape: kind, address, width, value, FC. #[derive(Clone, Debug, PartialEq, Eq)] struct Entry { kind: String, address: u32, word: bool, value: u32, fc: u32, } struct State { registers: [u32; 19], prefetch: [u32; 2], ram: Vec<(u32, u8)>, } struct Case { name: String, initial: State, final_state: State, cycles: u32, transactions: Vec, } fn number(value: &Value) -> u32 { value.as_u64().expect("a number") as u32 } fn state(record: &Value) -> State { let mut registers = [0; 19]; for (index, name) in REGISTERS.iter().enumerate() { registers[index] = number(&record[name]); } // The corpus's pc is the instruction's own address; the m68000 corpus's, // which the harness loads, is the prefetch address (+4). registers[18] = registers[18].wrapping_add(4); let prefetch = [ number(&record["prefetch"][0]), number(&record["prefetch"][1]), ]; let ram = record["ram"] .as_array() .unwrap() .iter() .map(|pair| (number(&pair[0]), number(&pair[1]) as u8)) .collect(); State { registers, prefetch, ram, } } fn read_file(path: &PathBuf) -> Vec { let mut text = String::new(); flate2::read::GzDecoder::new(std::fs::File::open(path).expect("readable corpus file")) .read_to_string(&mut text) .expect("gzip JSON"); let records: Value = serde_json::from_str(&text).expect("JSON"); records .as_array() .unwrap() .iter() .map(|record| { let transactions = record .get("transactions") .and_then(Value::as_array) .map(|list| { list.iter() .filter(|entry| entry[0] != "n") .map(|entry| { let word = entry[4] == ".w"; let data = number(&entry[5]); Entry { kind: entry[0].as_str().unwrap().to_string(), address: number(&entry[3]), word, // A byte's value is the byte (the reference rebuilds the // bus half and shifts it back; the result is data & 0xFF). value: if word { data } else { data & 0xFF }, fc: number(&entry[2]), } }) .collect() }) .unwrap_or_default(); Case { name: record["name"].as_str().unwrap().to_string(), initial: state(&record["initial"]), final_state: state(&record["final"]), cycles: number(&record["length"]), transactions, } }) .collect() } /// Byte-addressed sparse RAM logging accesses in the 680x0 corpus's shape. struct ByteHost { memory: HashMap, log: Vec, } impl ByteHost { fn byte(&self, address: u32) -> u8 { *self.memory.get(&address).unwrap_or(&0) } fn note(&mut self, kind: &str, address: u32, word: bool, value: u32, cycle: Cycle) { self.log.push(Entry { kind: kind.to_string(), address, word, value, fc: u32::from(cycle.fc), }); } } impl Bus for ByteHost { fn read_word(&mut self, address: u32, cycle: Cycle) -> Result { // The reference adds 1 without masking: a word at $FFFFFE reads $1000000. let value = u16::from_be_bytes([self.byte(address), self.byte(address + 1)]); self.note("r", address, true, u32::from(value), cycle); Ok(value) } fn read_byte(&mut self, address: u32, cycle: Cycle) -> Result { let value = self.byte(address); self.note("r", address, false, u32::from(value), cycle); Ok(value) } fn write_word(&mut self, address: u32, value: u16, cycle: Cycle) -> Result<(), BusError> { let [high, low] = value.to_be_bytes(); self.memory.insert(address, high); self.memory.insert(address + 1, low); self.note("w", address, true, u32::from(value), cycle); Ok(()) } fn write_byte(&mut self, address: u32, value: u8, cycle: Cycle) -> Result<(), BusError> { self.memory.insert(address, value); self.note("w", address, false, u32::from(value), cycle); Ok(()) } // tas_write defaults to write_byte, as the reference's harness passes it. } /// The reference's `run_case_680x0`: (differing field names, our log). fn run_case(case: &Case) -> (Vec, Vec) { let host = ByteHost { memory: case.initial.ram.iter().copied().collect(), log: Vec::new(), }; let r = &case.initial.registers; let mut cpu = M68000::new(host); cpu.restore_state(&CpuState { d: r[0..8].try_into().unwrap(), a: r[8..15].try_into().unwrap(), usp: r[15], ssp: r[16], sr: r[17] as u16, pc: r[18].wrapping_sub(4), ir: case.initial.prefetch[0] as u16, irc: case.initial.prefetch[1] as u16, ..CpuState::default() }); let cycles = cpu.step(); let after = cpu.capture_state(); let mut actual = [0u32; 19]; actual[0..8].copy_from_slice(&after.d); actual[8..15].copy_from_slice(&after.a); actual[15] = after.usp; actual[16] = after.ssp; actual[17] = u32::from(after.sr); actual[18] = after.pc.wrapping_add(4); let mut fields = Vec::new(); for (index, name) in REGISTERS.iter().enumerate() { if actual[index] != case.final_state.registers[index] { fields.push(name.to_string()); } } if [u32::from(after.ir), u32::from(after.irc)] != case.final_state.prefetch { fields.push("prefetch".into()); } if case .final_state .ram .iter() .any(|&(address, value)| cpu.bus.byte(address) != value) { fields.push("ram".into()); } if cycles != case.cycles { fields.push("cycles".into()); } if cpu.bus.log != case.transactions { fields.push("transactions".into()); } let log = std::mem::take(&mut cpu.bus.log); (fields, log) } /// Python's `list[start:end]` for possibly negative bounds. fn py_slice(list: &[T], start: Option, end: Option) -> Vec { let length = list.len() as isize; let clamp = |index: isize| -> usize { let index = if index < 0 { index + length } else { index }; index.clamp(0, length) as usize }; let (start, end) = (clamp(start.unwrap_or(0)), clamp(end.unwrap_or(length))); if start >= end { return Vec::new(); } list[start..end].to_vec() } /// Index of the vector-3 fetch in an access log, or None. fn address_error(log: &[Entry]) -> Option { log.iter() .position(|e| e.kind == "r" && e.address == 0x0C) .map(|i| i as isize) } /// The reference's `causes`: every named cause of one disagreement. fn causes( stem: &str, name: &str, fields: &[String], ours: &[Entry], theirs: &[Entry], ) -> Vec { let has = |field: &str| fields.iter().any(|f| f == field); let mut found: Vec = Vec::new(); match (address_error(ours), address_error(theirs)) { (Some(ours_ae), Some(theirs_ae)) => { if has("cycles") { found.push("address error: +8 clocks (aborted cycle counted)".into()); } let frame_ours = py_slice(ours, Some(ours_ae - 7), Some(ours_ae)); let frame_theirs = py_slice(theirs, Some(theirs_ae - 7), Some(theirs_ae)); // zip(..., strict=True): the reference raises if the lengths differ. assert!( frame_ours.len() == FRAME.len() && frame_theirs.len() == FRAME.len(), "{stem} {name}: a frame slice is not seven entries" ); let slots: Vec<&str> = FRAME .iter() .zip(frame_ours.iter().zip(&frame_theirs)) .filter(|(_, (a, b))| a != b) .map(|(slot, _)| *slot) .collect(); let pc_slot = slots.contains(&"pc_low") || slots.contains(&"pc_high"); if pc_slot { let target = theirs .iter() .any(|e| e.kind == "r" && (e.fc == 2 || e.fc == 6) && e.address & 1 != 0); found.push(format!( "address error: stacked PC{}", if target { " (odd jump target)" } else { "" } )); } if slots.contains(&"information") && !pc_slot { found.push("address error: FC of a PC-relative access".into()); } if slots.contains(&"ir") { found.push("address error: IR word".into()); } if py_slice(ours, None, Some(ours_ae - 7)) != py_slice(theirs, None, Some(theirs_ae - 7)) { found.push("address error: accesses before the fault".into()); } let registers = fields.iter().any(|f| { (f.starts_with('a') || f.starts_with('d')) && f.len() > 1 && f[1..].chars().all(|c| c.is_ascii_digit()) }); if registers { found.push("address error: register moved or not".into()); } if has("sr") { found.push("address error: halfway flags of a long".into()); } if found.is_empty() { found.push("address error: other".into()); } return found; } (None, None) => {} _ => return vec!["address error on one side only".into()], } let only = |set: &[&str]| fields.len() == set.len() && set.iter().all(|f| has(f)); if stem == "ASL.b" && (name.ends_with(" 1583") || name.ends_with(" 1761")) { return vec!["corpus issue #4 (ASL.b 1583, 1761)".into()]; } if stem.starts_with("ASR") && only(&["sr"]) { return vec!["ASR by a register count: X and C".into()]; } if stem == "TAS" { return vec!["TAS logged as one read-modify-write access".into()]; } if stem == "RTE" || stem == "RTR" { return vec!["RTE/RTR: order of the stack reads".into()]; } if stem == "LINK" { return vec!["LINK A7: value pushed".into()]; } if stem == "CHK" { if has("transactions") { found.push("CHK trap: queue refill before the frame".into()); } if has("sr") { found.push("CHK: undefined flags".into()); } if has("cycles") && !has("transactions") { found.push("CHK: clocks".into()); } return found; } if stem == "DIVU" || stem == "DIVS" { if has("sr") { found.push(format!("{stem}: flags")); } if has("cycles") { found.push(format!("{stem}: clocks")); } if has("transactions") { found.push("PC-relative operand: function code".into()); } return found; } if only(&["cycles"]) && (stem == "ADD.l" || stem == "SUB.l") { return vec!["ADDQ/SUBQ.L to An: clocks".into()]; } if only(&["transactions"]) { let pairs: Vec<(&Entry, &Entry)> = ours.iter().zip(theirs).filter(|(a, b)| a != b).collect(); let same_first_four = |a: &Entry, b: &Entry| { a.kind == b.kind && a.address == b.address && a.word == b.word && a.value == b.value }; if ours.len() == theirs.len() && pairs.iter().all(|(a, b)| same_first_four(a, b)) { return vec!["PC-relative operand: function code".into()]; } } vec!["UNCLASSIFIED".into()] } /// Python's `f"{n:,}"`. fn grouped(n: u64) -> String { let digits = n.to_string(); let mut out = String::new(); for (index, digit) in digits.chars().enumerate() { if index > 0 && (digits.len() - index) % 3 == 0 { out.push(','); } out.push(digit); } out } fn main() -> ExitCode { let Some(directory) = std::env::args().nth(1) else { eprintln!("usage: m68k-680x0 "); return ExitCode::from(2); }; let mut paths: Vec = std::fs::read_dir(&directory) .expect("readable directory") .map(|entry| entry.unwrap().path()) .filter(|path| path.to_string_lossy().ends_with(".json.gz")) .collect(); paths.sort(); // The reference's collections.Counter: counts in first-seen order. let mut order: Vec = Vec::new(); let mut counts: HashMap = HashMap::new(); let mut files: HashMap> = HashMap::new(); let (mut total, mut agreed, mut unclassified) = (0u64, 0u64, 0u64); for path in &paths { let stem = path .file_name() .unwrap() .to_string_lossy() .trim_end_matches(".json.gz") .to_string(); for case in read_file(path) { total += 1; let (fields, ours) = run_case(&case); if fields.is_empty() { agreed += 1; continue; } for cause in causes(&stem, &case.name, &fields, &ours, &case.transactions) { if !counts.contains_key(&cause) { order.push(cause.clone()); } *counts.entry(cause.clone()).or_insert(0) += 1; let stems = files.entry(cause.clone()).or_default(); if !stems.contains(&stem) { stems.push(stem.clone()); } if cause == "UNCLASSIFIED" { unclassified += 1; println!( "{stem}\n {}\n {fields:?}\n {ours:?}\n {:?}", case.name, case.transactions ); } } } eprintln!("{stem:16} done"); } println!( "{} of {} cases agree; causes of the rest (a case may have several):", grouped(agreed), grouped(total) ); // most_common(): by count, descending; ties keep first-seen order (a stable sort). let mut table: Vec<(String, u64)> = order.iter().map(|c| (c.clone(), counts[c])).collect(); table.sort_by_key(|entry| std::cmp::Reverse(entry.1)); for (cause, count) in table { let mut shown = files[&cause].clone(); shown.sort(); let more = if shown.len() > 6 { format!(" and {} more", shown.len() - 6) } else { String::new() }; let head = shown.iter().take(6).cloned().collect::>().join(", "); println!("{:>9} {cause} [{head}{more}]", grouped(count)); } if unclassified == 0 { ExitCode::SUCCESS } else { ExitCode::FAILURE } }