// SPDX-License-Identifier: MIT //! Rung 2: replay a MAME 0.285 trace of a 32X SH-2 on this crate, register-exact. //! //! sh2-replay LOG [--cache] [--seed FILE@ADDRESS] [--limit N] [--slices N --out FILE] //! //! The transcription of sh2-python's ``validation/rung2/replay.py`` (its docstring has the //! method: the replay host answers every read with MAME's value, injects MAME's //! interrupts, substitutes MAME's time-dependent on-chip values and DMA writes, holds //! the cache off unless ``--cache``, and stops at the first difference the docs do not //! attribute to MAME). It prints the same report. With ``--slices N`` it also writes one //! line per N replayed instructions: a CRC-32 of every bus callback (kind, address, //! width, clock, value) with the clock and PC, which scripts/replay_trace.py writes for //! the reference: the lockstep of rung 2. //! //! MAME's traces are machine-local (the reference's scripts/mame_trace.py makes them from //! the user's own cartridges): nothing of them is committed here. use std::collections::{BTreeMap, HashMap}; use std::fs::File; use std::io::{BufRead, BufReader, Write}; use std::time::Instant; use sh2::bus::{Bus, BusContext}; use sh2::disasm::disassemble_word; use sh2::{Options, Sh7604}; const MEMORY: usize = 0x08000000; // MAME's SH-2 masks external addresses to A26-A0 const CCR: u32 = 0xFFFFFE92; const REGS: [&str; 23] = [ "pc", "sr", "pr", "gbr", "vbr", "mach", "macl", "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", ]; /// On-chip registers whose value depends on when it is read (C5): MAME's value is used. fn time_dependent(address: u32) -> Option<&'static str> { match address { 0xFFFFFE10..=0xFFFFFE19 => Some("FRT"), 0xFFFFFE80..=0xFFFFFE83 => Some("WDT"), 0xFFFFFE04 => Some("SCI.SSR"), 0xFFFFFF80..=0xFFFFFFB3 => Some("DMAC"), 0xFFFFFE71 | 0xFFFFFE72 => Some("DMAC"), 0xFFFFFFF0..=0xFFFFFFF3 => Some("BSC.RTCSR"), 0xFFFFFFF4..=0xFFFFFFF7 => Some("BSC.RTCNT"), _ => None, } } fn crc32(crc: u32, bytes: &[u8]) -> u32 { static TABLE: std::sync::OnceLock<[u32; 256]> = std::sync::OnceLock::new(); let table = TABLE.get_or_init(|| { let mut table = [0u32; 256]; for (i, entry) in table.iter_mut().enumerate() { let mut c = i as u32; for _ in 0..8 { c = if c & 1 != 0 { 0xEDB88320 ^ (c >> 1) } else { c >> 1 }; } *entry = c; } table }); let mut c = !crc; for &b in bytes { c = table[((c ^ b as u32) & 0xFF) as usize] ^ (c >> 8); } !c } /// One instruction of the log: the registers before it and the accesses after. struct Group { regs: Option<[u32; 23]>, line: u64, accesses: Vec<(u8, u32, u32, u32)>, // (tag R/W/r/w for IR/IW, address, bits, value) } /// The log's instruction groups, streamed (a log is gigabytes). struct LogReader { lines: std::io::Split>, number: u64, group: Option, done: bool, } impl LogReader { fn new(path: &str) -> LogReader { let file = File::open(path).unwrap_or_else(|e| panic!("{path}: {e}")); LogReader { lines: BufReader::with_capacity(1 << 20, file).split(b'\n'), number: 0, group: Some(Group { regs: None, line: 0, accesses: Vec::new() }), done: false, } } } impl Iterator for LogReader { type Item = Group; fn next(&mut self) -> Option { if self.done { return None; } loop { let raw = match self.lines.next() { Some(Ok(raw)) => raw, _ => { // the end (a log still being written ends mid-line: split drops it) self.done = true; return self.group.take(); } }; self.number += 1; let text = std::str::from_utf8(&raw).unwrap_or(""); let (tag, rest) = text.split_once(' ').unwrap_or((text, "")); match tag { "S" => { let values: Vec<&str> = rest.split_whitespace().collect(); let mut regs = [0u32; 23]; for (i, v) in values[..23].iter().enumerate() { regs[i] = u32::from_str_radix(v, 16).unwrap(); } let previous = self.group.replace(Group { regs: Some(regs), line: self.number, accesses: Vec::new() }); return previous; } "R" | "W" | "IR" | "IW" => { let fields: Vec<&str> = rest.split_whitespace().collect(); let code = match tag { "R" => b'R', "W" => b'W', "IR" => b'r', _ => b'w', }; let parse = |s: &str| u32::from_str_radix(s, 16).unwrap(); if let Some(group) = self.group.as_mut() { group.accesses.push((code, parse(fields[0]), parse(fields[1]), parse(fields[2]))); } } _ => {} } } } } /// The replay host's bus. struct Host { memory: Vec, cache: bool, core_writes: HashMap, onchip_log: HashMap>, substituted: BTreeMap, mismatch: Option, ccr: u32, crc: u32, hashing: bool, slices: u64, calls: u64, out: Option, } impl Host { /// Fold one callback into the CRC; every ``slices`` callbacks, a slice line. fn hash(&mut self, text: String) { self.crc = crc32(self.crc, text.as_bytes()); self.calls += 1; if self.calls % self.slices == 0 { self.flush(); } } fn flush(&mut self) { if let Some(file) = self.out.as_mut() { writeln!(file, "slice {} {:08x}", self.calls, self.crc).unwrap(); } self.crc = 0; } fn store(&mut self, address: u32, bits: u32, value: u32) { let a = address as usize % MEMORY; let count = (bits >> 3) as usize; for i in 0..count { self.memory[a + i] = (value >> (8 * (count - 1 - i))) as u8; } } } impl Bus for Host { fn read(&mut self, address: u32, width: u32, kind: u32, cx: &mut BusContext) -> u32 { let a = address as usize % MEMORY; let mut value = 0u32; for i in 0..(width >> 3) as usize { value = (value << 8) | self.memory[a + i] as u32; } if self.hashing { self.hash(format!("r {address:x} {width} {kind} {} {value:x}\n", cx.clock)); } value } fn write(&mut self, address: u32, width: u32, value: u32, kind: u32, cx: &mut BusContext) { if self.hashing { self.hash(format!("w {address:x} {width} {kind} {} {value:x}\n", cx.clock)); } let a = address as usize % MEMORY; let count = (width >> 3) as usize; for i in 0..count { self.core_writes.insert(a + i, (value >> (8 * (count - 1 - i))) as u8); } } fn read_onchip_instead(&mut self, address: u32, _width: u32) -> Option { if address == CCR && !self.cache { return Some(self.ccr); } None } fn read_onchip_seen(&mut self, address: u32, width: u32, value: u32) -> u32 { if let Some(logged) = self.onchip_log.get_mut(&address) { if let Some(theirs) = logged.pop_front() { if let Some(name) = time_dependent(address) { if theirs != value { *self.substituted.entry(name.to_string()).or_insert(0) += 1; } return theirs; } if theirs != value { self.mismatch = Some(format!("on-chip read {address:08X}/{width}: core {value:X}, MAME {theirs:X}")); } } } value } fn write_onchip(&mut self, address: u32, _width: u32, value: u32) -> u32 { if address == CCR && !self.cache { self.ccr = value & !0x10; // CP reads 0 return value & !0x01; // the cache stays off: every read reaches the log's values } value } } struct Replay { chip: Sh7604, counts: BTreeMap, order: Vec, first: BTreeMap, } fn where_text(number: u64, line: u64, pc: u32, opcode: u32) -> String { format!("#{number} (log line {line}) {pc:08X} {}", disassemble_word(opcode, pc).text()) } impl Replay { fn load(&mut self, regs: &[u32; 23]) { let chip = &mut self.chip; chip.r.copy_from_slice(®s[7..23]); chip.sr = regs[1]; chip.gbr = regs[3]; chip.vbr = regs[4]; chip.mach = regs[5]; chip.macl = regs[6]; chip.pr = regs[2]; chip.pc = regs[0]; // the core refetches when the host moves the PC chip.delay_target = -1; } fn differs(&self, regs: &[u32; 23]) -> Vec { let chip = &self.chip; let mut mine = [0u32; 23]; mine[..7].copy_from_slice(&[chip.pc, chip.sr, chip.pr, chip.gbr, chip.vbr, chip.mach, chip.macl]); mine[7..].copy_from_slice(&chip.r); let mut out = Vec::new(); for (i, name) in REGS.iter().enumerate() { if mine[i] != regs[i] { out.push(format!("{name}: core {:08X} MAME {:08X}", mine[i], regs[i])); } } out } fn note(&mut self, kind: &str, text: String) { if !self.counts.contains_key(kind) { self.order.push(kind.to_string()); } *self.counts.entry(kind.to_string()).or_insert(0) += 1; self.first.entry(kind.to_string()).or_insert(text); } /// The docs' MAME attribution for a difference, or None (C4, C12). fn attribute(&self, problems: &[String]) -> Option<&'static str> { let divu_read = problems.iter().any(|p| p.contains("on-chip read FFFFFF")); if divu_read && self.chip.divu.dvcr & 1 != 0 { return Some("divu-overflow"); } None } } fn python_pairs(items: &[(usize, u8)]) -> String { let parts: Vec = items.iter().map(|(a, v)| format!("({a}, {v})")).collect(); format!("[{}]", parts.join(", ")) } fn python_list(items: &[usize]) -> String { let parts: Vec = items.iter().map(|a| a.to_string()).collect(); format!("[{}]", parts.join(", ")) } fn main() { let args: Vec = std::env::args().collect(); let log = args[1].clone(); let mut cache = false; let mut limit: Option = None; let mut seeds: Vec<(String, usize)> = Vec::new(); let mut slices: u64 = 0; let mut out_path: Option = None; let mut i = 2; while i < args.len() { match args[i].as_str() { "--cache" => { cache = true; i += 1; } "--limit" => { limit = Some(args[i + 1].parse().unwrap()); i += 2; } "--seed" => { let (file, at) = args[i + 1].rsplit_once('@').unwrap(); let at = if let Some(hex) = at.strip_prefix("0x") { usize::from_str_radix(hex, 16).unwrap() } else { at.parse().unwrap() }; seeds.push((file.to_string(), at)); i += 2; } "--slices" => { slices = args[i + 1].parse().unwrap(); i += 2; } "--out" => { out_path = Some(args[i + 1].clone()); i += 2; } other => panic!("unknown argument {other}"), } } let host = Host { memory: vec![0; MEMORY], cache, core_writes: HashMap::new(), onchip_log: HashMap::new(), substituted: BTreeMap::new(), mismatch: None, ccr: 0, crc: 0, hashing: slices != 0, slices, calls: 0, out: out_path.map(|p| File::create(p).unwrap()), }; let mut chip = Sh7604::new(host, Options { area0_width: 16, ..Options::default() }); chip.replay_interrupts = true; chip.dmac_run_disabled = true; // transfers come from MAME's log (the reference's docstring) for (file, at) in &seeds { let data = std::fs::read(file).unwrap(); chip.bus.memory[*at..*at + data.len()].copy_from_slice(&data); } let mut replay = Replay { chip, counts: BTreeMap::new(), order: Vec::new(), first: BTreeMap::new() }; let mut groups = LogReader::new(&log); let reset = groups.next().unwrap(); for (tag, address, bits, value) in &reset.accesses { if *tag == b'R' { replay.chip.bus.store(*address, *bits, *value); } } let mut current = groups.next().unwrap(); replay.load(current.regs.as_ref().unwrap()); let mut replayed: u64 = 0; let mut injected: u64 = 0; let started = Instant::now(); let mut stop: Option<(String, Vec)> = None; for following in groups { if let Some(limit) = limit { if replayed >= limit { break; } } let Some(expected) = following.regs else { break }; let mut onchip: HashMap> = HashMap::new(); let mut mame_writes: BTreeMap = BTreeMap::new(); let mut mame_order: Vec = Vec::new(); let mut tail: Vec<(u8, u32, u32, u32)> = Vec::new(); for access in ¤t.accesses { let (tag, address, bits, value) = *access; if tag == b'R' { replay.chip.bus.store(address, bits, value); tail.push(access.to_owned()); } else if tag == b'W' { let a = address as usize % MEMORY; let count = (bits >> 3) as usize; for i in 0..count { if !mame_writes.contains_key(&(a + i)) { mame_order.push(a + i); } mame_writes.insert(a + i, (value >> (8 * (count - 1 - i))) as u8); } tail.push(access.to_owned()); } else if tag == b'r' { onchip.entry(address).or_default().push_back(value); } } for (tag, address, bits, value) in &following.accesses { if *tag == b'R' { // the next instruction's fetch (the core fetches longwords) replay.chip.bus.store(*address, *bits, *value); break; } } replay.chip.bus.onchip_log = onchip; replay.chip.bus.core_writes.clear(); replay.chip.bus.mismatch = None; let pc = replay.chip.pc; let p = pc as usize % MEMORY; let opcode = ((replay.chip.bus.memory[p] as u32) << 8) | replay.chip.bus.memory[p + 1] as u32; let before_sleep = replay.chip.sleeping; // The core fetches two instructions ahead (PM 7.4) and fetches what taken branches // discard (U11); this memory is filled one instruction ahead, so the core reads // each opcode again when it runs it. Timing is not compared. replay.chip.drop_fetched(); replay.chip.step(); replayed += 1; let text = where_text(replayed, current.line, pc, opcode); let mut entry = false; if replay.chip.pc != expected[0] && tail.len() >= 3 { // Interrupt entry: two pushes then a vector read end the group. let t = &tail[tail.len() - 3..]; entry = (t[0].0, t[1].0, t[2].0) == (b'W', b'W', b'R') && (t[2].1 as i64 - expected[4] as i64).rem_euclid(4) == 0; if entry { let vector = ((t[2].1 as i64 - expected[4] as i64) & 0x1FFFFFFF) >> 2; let level = (expected[1] >> 4) & 15; // An IRL auto-vector is left for the core to compute (HM table 5.3). let v = if vector == 64 + (level >> 1) as i64 { -1 } else { vector }; replay.chip.inject_interrupt(level, v); if replay.chip.no_interrupt() || replay.chip.delay_target >= 0 { // HM 4.6: no interrupt here; MAME took one anyway. replay.note("mame-interrupt-after-ldc", text.clone()); replay.chip.set_no_interrupt(false); } replay.chip.drop_fetched(); replay.chip.step(); injected += 1; } } // MAME's SLEEP: it loops on the instruction (sh2.cpp SLEEP: pc -= 2). if (opcode == 0x001B || before_sleep) && expected[0] == pc && !entry { replay.note("mame-sleep", text.clone()); replay.chip.sleeping = false; replay.load(&expected); for (a, v) in &mame_writes { replay.chip.bus.memory[*a] = *v; } current = following; continue; } let mut problems = replay.differs(&expected); if let Some(mismatch) = replay.chip.bus.mismatch.clone() { problems.push(mismatch); } // Every byte the core wrote must be a byte MAME wrote, with MAME's value; bytes // only MAME wrote are its DMAC's (allowed while a channel is set up). let core_writes = &replay.chip.bus.core_writes; let mut wrong: Vec<(usize, u8)> = core_writes.iter().filter(|(a, v)| mame_writes.get(a) != Some(v)).map(|(a, v)| (*a, *v)).collect(); wrong.sort(); let mut unmatched: Vec = mame_order.iter().filter(|a| !core_writes.contains_key(a)).copied().collect(); if !wrong.is_empty() { problems.push(format!("core writes MAME did not make: {}", python_pairs(&wrong[..wrong.len().min(4)]))); } if !unmatched.is_empty() && !replay.chip.dmac.active { unmatched.sort(); problems.push(format!( "MAME writes the core did not make: {}", python_list(&unmatched[..unmatched.len().min(4)]) )); } else if !unmatched.is_empty() { *replay.counts.entry("dma-writes".to_string()).or_insert(0) += 1; if !replay.order.contains(&"dma-writes".to_string()) { replay.order.push("dma-writes".to_string()); } } if !problems.is_empty() { match replay.attribute(&problems) { None => { stop = Some((text.clone(), problems)); break; } Some(kind) => { let joined = problems[..problems.len().min(3)].join("; "); replay.note(kind, format!("{text}: {joined}")); replay.load(&expected); } } } for (a, v) in &mame_writes { replay.chip.bus.memory[*a] = *v; } current = following; } if replay.chip.bus.hashing { replay.chip.bus.flush(); } let elapsed = started.elapsed().as_secs_f64(); let attributed: Vec = replay.order.iter().map(|k| format!(" \"{k}\": {}", replay.counts[k])).collect(); let first: Vec = replay.order.iter().filter_map(|k| replay.first.get(k).map(|t| format!(" \"{k}\": \"{t}\""))).collect(); let substituted: Vec = replay.chip.bus.substituted.iter().map(|(k, v)| format!(" \"{k}\": {v}")).collect(); println!("{{"); println!(" \"log\": \"{log}\","); println!(" \"cache\": {cache},"); println!(" \"replayed\": {replayed},"); println!(" \"interrupts_injected\": {injected},"); println!(" \"seconds\": {elapsed:.1},"); println!(" \"instructions_per_second\": {},", (replayed as f64 / elapsed.max(1e-9)).round()); println!(" \"attributed\": {{\n{}\n }},", attributed.join(",\n")); println!(" \"first_attributed\": {{\n{}\n }},", first.join(",\n")); println!(" \"substituted_onchip_reads\": {{\n{}\n }},", substituted.join(",\n")); match &stop { None => println!(" \"stopped_at\": null"), Some((text, problems)) => { println!(" \"stopped_at\": {{\"instruction\": \"{text}\", \"differences\": {problems:?}}}") } } println!("}}"); std::process::exit(if stop.is_none() { 0 } else { 1 }); }