// SPDX-License-Identifier: MIT //! Replay a MAME 0.285 trace of real SPC700 code on the core (`replay.py`; the //! reference's validation.md rung 4). //! //! MAME is an emulator-derived detector (the reference's docs/mame-oracle.md). //! A real sound driver reads I/O registers whose values come from a board the //! core does not have, so the replay is board-free: every read of $F0-$FF is //! answered from MAME's own log (the reference's `scripts/mame_trace.py --io`), //! in order, and every write there is compared with the log. RAM and the IPL ROM //! are the replay's own; the core starts from the registers of MAME's first //! line, at the IPL ROM's entry. //! //! After each instruction the replay compares `PC A X Y SP PSW` with MAME's next //! line, and the cycles with the difference of MAME's `totalcycles` divided by //! 2. MAME's core is instruction-level: its stores do not read their //! destination (U1), and it makes no dummy read of PC (C2), so a dummy read here //! that MAME did not log is answered from RAM, not a divergence. The other way //! round, MAME's `SUBOP_ADC` macro evaluates its second argument twice, so its //! memory-destination ADC logs two reads of the destination where anomie and //! SingleStepTests have one: the repeat, same address, same value, is dropped //! and counted (C10). The first divergence is a lead, not a verdict. //! //! Differences forced by Rust: `Divergence.describe()` lists the last //! instructions disassembled; the disassembler is Python-side tooling, so the //! history here is the registers and the instruction's bytes, and the rung //! compares the summary line (counts and the first problem), not that text. //! A logged I/O entry is formatted as Python's tuple repr in a problem's text. use std::collections::{BTreeSet, VecDeque}; use std::io::BufRead; use crate::core::{Bus, Signals, Spc700}; use crate::harness::IPL_BASE; use crate::opcodes::OPCODES; use crate::state::CpuState; pub const START_PC: u16 = 0xFFC0; pub const REGISTER_NAMES: [&str; 6] = ["pc", "a", "x", "y", "sp", "psw"]; /// One MAME instruction line (state before the instruction) and the I/O it then made. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Line { pub pc: u64, pub opcode: u64, pub a: u64, pub x: u64, pub y: u64, pub sp: u64, pub psw: u64, pub cycles: i64, // MAME totalcycles: two per SPC700 cycle pub io: Vec<(char, u64, u64)>, // ('R' or 'W', address, data) } /// An I/O entry as Python prints the tuple, or `None`. fn repr(entry: Option<&(char, u64, u64)>) -> String { match entry { None => "None".into(), Some((kind, address, data)) => format!("('{kind}', {address}, {data})"), } } /// Python's `str.split()` on ASCII whitespace. fn split(text: &str) -> Vec<&str> { text.split(|c: char| { matches!( c, ' ' | '\t' | '\n' | '\r' | '\x0b' | '\x0c' | '\x1c'..='\x1f' | '\u{85}' | '\u{a0}' ) }) .filter(|f| !f.is_empty()) .collect() } /// Yield MAME instruction lines from the first at `start_pc`, each with the I/O /// after it. MAME's own messages are skipped. pub fn parse_trace(reader: impl BufRead, start_pc: u16) -> impl Iterator { let mut current: Option = None; let mut started = false; let mut lines = reader.split(b'\n'); let mut done = false; std::iter::from_fn(move || { if done { return None; } for raw in lines.by_ref() { let raw = raw.expect("a trace line"); // latin-1: every byte is the character of that code point. let text: String = raw.iter().map(|&b| b as char).collect(); let fields = split(&text); if fields.len() == 4 && (fields[0] == "R" || fields[0] == "W") { if started { if let Some(line) = current.as_mut() { if let (Ok(address), Ok(data)) = ( u64::from_str_radix(fields[1], 16), u64::from_str_radix(fields[2], 16), ) { line.io .push((fields[0].chars().next().unwrap(), address, data)); } } } continue; } if fields.len() != 8 { continue; } let mut values = [0u64; 7]; let mut ok = true; for (slot, field) in values.iter_mut().zip(&fields[..7]) { match u64::from_str_radix(field, 16) { Ok(v) => *slot = v, Err(_) => ok = false, } } let Some(cycles) = fields[7].parse::().ok().filter(|_| ok) else { continue; }; if !started { if values[0] != start_pc as u64 { continue; } started = true; } let next = Line { pc: values[0], opcode: values[1], a: values[2], x: values[3], y: values[4], sp: values[5], psw: values[6], cycles, io: Vec::new(), }; if let Some(previous) = current.replace(next) { return Some(previous); } } done = true; current.take() }) } /// RAM, the IPL ROM overlay, and I/O answered from and compared with the MAME log. pub struct ReplayHost { pub ram: Vec, pub ipl: [u8; 64], pub ipl_mapped: bool, pub io: VecDeque<(char, u64, u64)>, pub problems: Vec, pub unlogged_dummy_reads: u64, pub repeated_reads: u64, } impl Bus for ReplayHost { fn read(&mut self, address: u16, signals: Signals) -> u8 { if (0xF0..=0xFF).contains(&address) { let head = self.io.front().copied(); if let Some(head) = head { if head.0 == 'R' && head.1 == address as u64 { self.io.pop_front(); if self.io.front() == Some(&head) && OPCODES[signals.opcode as usize].mnemonic == "ADC" { self.io.pop_front(); self.repeated_reads += 1; } return head.2 as u8; } } if signals.dummy { self.unlogged_dummy_reads += 1; // U1, C2: MAME makes no such read return self.ram[address as usize]; } self.problems.push(format!( "core read ${address:04X}, MAME logged {}", repr(head.as_ref()) )); return 0; } if address >= IPL_BASE && self.ipl_mapped { return self.ipl[(address - IPL_BASE) as usize]; } self.ram[address as usize] } fn write(&mut self, address: u16, value: u8, _signals: Signals) { self.ram[address as usize] = value; // B4 if (0xF0..=0xFF).contains(&address) { let head = self.io.pop_front(); if head != Some(('W', address as u64, value as u64)) { self.problems.push(format!( "core wrote ${address:04X}=${value:02X}, MAME logged {}", repr(head.as_ref()) )); } if address == 0xF1 { self.ipl_mapped = value & 0x80 != 0; } } } } impl ReplayHost { pub fn peek(&self, address: u16) -> u8 { if address >= IPL_BASE && self.ipl_mapped { return self.ipl[(address - IPL_BASE) as usize]; } self.ram[address as usize] } } /// The first place the core and MAME disagree. #[derive(Clone, Debug)] pub struct Divergence { pub position: u64, // index of the MAME line the replay was executing when it diverged pub line: Line, pub problems: Vec, pub history: Vec, // the last few states, for context } #[derive(Clone, Debug)] pub struct ReplayResult { pub compared: u64, // MAME instruction lines compared without a difference pub divergence: Option, pub io_reads: u64, // I/O reads answered from the log pub io_writes: u64, // I/O writes compared with the log pub unlogged_dummy_reads: u64, // U1 and C2 reads of $F0-$FF that MAME's core does not make pub repeated_reads: u64, // MAME's second read of an ADC destination, dropped pub opcodes: BTreeSet, // distinct opcodes executed } impl ReplayResult { pub fn ok(&self) -> bool { self.divergence.is_none() } } /// Python's `{value:g}` for a half-integer or integer. fn general(value: f64) -> String { if value.fract() == 0.0 { format!("{}", value as i64) } else { format!("{value}") } } /// Run the core against MAME's lines; stop at the first divergence or the end or limit. pub fn replay( lines: impl Iterator, ipl: [u8; 64], limit: Option, ) -> Result { let host = ReplayHost { ram: vec![0; 0x10000], ipl, ipl_mapped: true, io: VecDeque::new(), problems: Vec::new(), unlogged_dummy_reads: 0, repeated_reads: 0, }; let mut cpu = Spc700::new(host); let mut iterator = lines; let Some(mut current) = iterator.next() else { return Err("the trace has no line at the IPL ROM's entry".into()); }; cpu.restore_state(&CpuState { a: current.a as u8, x: current.x as u8, y: current.y as u8, sp: current.sp as u8, pc: current.pc as u16, psw: current.psw as u8, stopped: false, }); let mut history: VecDeque = VecDeque::with_capacity(8); let (mut compared, mut reads, mut writes) = (0u64, 0u64, 0u64); let mut opcodes = BTreeSet::new(); for (position, following) in iterator.enumerate() { if limit.is_some_and(|limit| compared >= limit) { break; } let before = cpu.capture_state(); if history.len() == 8 { history.pop_front(); } history.push_back(before); cpu.bus.io = current.io.iter().copied().collect(); cpu.bus.problems.clear(); reads += current.io.iter().filter(|e| e.0 == 'R').count() as u64; writes += current.io.iter().filter(|e| e.0 == 'W').count() as u64; let used = cpu.step(); opcodes.insert(cpu.opcode); let state = cpu.capture_state(); let mut problems = cpu.bus.problems.clone(); if !cpu.bus.io.is_empty() { problems.push(format!( "MAME logged {} more I/O cycle(s), first {}", cpu.bus.io.len(), repr(cpu.bus.io.front()) )); } let got = [ state.pc as u64, state.a as u64, state.x as u64, state.y as u64, state.sp as u64, state.psw as u64, ]; let want = [ following.pc, following.a, following.x, following.y, following.sp, following.psw, ]; for ((name, got), want) in REGISTER_NAMES.iter().zip(got).zip(want) { if got != want { problems.push(format!("{} = {got:X}, MAME {want:X}", name.to_uppercase())); } } let difference = following.cycles - current.cycles; let (delta, remainder) = (difference.div_euclid(2), difference.rem_euclid(2)); if remainder != 0 || delta != used as i64 { problems.push(format!( "{used} cycles, MAME {}", general(difference as f64 / 2.0) )); } if !problems.is_empty() { let divergence = Divergence { position: position as u64, line: current, problems, history: history.iter().copied().collect(), }; return Ok(ReplayResult { compared, divergence: Some(divergence), io_reads: reads, io_writes: writes, unlogged_dummy_reads: cpu.bus.unlogged_dummy_reads, repeated_reads: cpu.bus.repeated_reads, opcodes, }); } compared += 1; current = following; } Ok(ReplayResult { compared, divergence: None, io_reads: reads, io_writes: writes, unlogged_dummy_reads: cpu.bus.unlogged_dummy_reads, repeated_reads: cpu.bus.repeated_reads, opcodes, }) }