// SPDX-License-Identifier: MIT AND BSD-3-Clause // `burst` is MAME 0.285's bus_5A22_cycle_burst (src/devices/cpu/g65816/g65816.cpp, BSD-3-Clause, Karl Stenerud), as the reference transcribed it: notice in NOTICE.md. //! Rung 4: replay MAME 0.285's trace of a real game through the core (the //! reference's `tests/mame_replay.py`, transcribed). //! //! mame_replay GAME_DIR [--limit N] //! //! `scripts/mame_trace.py GAME --io` (the reference's) leaves an `error.log` //! holding one line per instruction, before it runs (`PC PB A X Y S D DB P E //! totalcycles`), and after each line the I/O and cartridge-RAM reads that //! instruction made (`R address value`; the reference's docs/mame-oracle.md). //! [`Replay`] runs the core in the minimal harness from the same reset and //! answers those reads from the log in order, so the core sees what MAME's //! board gave MAME's CPU. After every instruction it compares the registers //! with MAME's next line, and the instruction's length in master clocks with //! MAME's `totalcycles` delta. The output is the game's name and the report's //! `summary()`, the text `scripts/reference_mame.py` prints from the reference, //! so the two can be compared line for line. //! //! MAME is emulator-derived (the reference's validation.md): a difference is a //! lead, never a verdict. What the replay knows about MAME and adjusts for, //! each counted, is the reference's module docstring: interrupts come from //! MAME's board (the harness's frame NMI is off); MAME's NMI entry leaves I //! clear (`nmi_i`); reads MAME's watchpoints did not log are answered by the //! harness and the core then takes MAME's registers (`adopted`); power-on WRAM //! is MAME's $55; MVN/MVP's A is read as 16 bits; reset's undefined registers //! are taken from MAME's first line. //! //! Differences forced by Rust: `Replay` subclasses `Harness` in Python; here //! it is the [`Hooks`] of a [`Machine`]. `Counter`s are [`Counter`], a map that //! keeps first-insertion order so that `most_common` breaks ties as Python's //! does. `take` sets the frame's `polled_i` and `polled` (the Python //! `cpu._polled_i`, `cpu._polled`) directly, as the reference does. use std::collections::{HashMap, VecDeque}; use std::hash::Hash; use std::io::{BufRead, BufReader}; use std::path::Path; use w65c816::harness::{Harness, Hooks, Machine}; use w65c816::{Frame, Signals}; const I_FLAG: u8 = 0x04; const REGISTERS: [&str; 10] = ["pc", "pbr", "a", "x", "y", "s", "d", "dbr", "p", "e"]; /// A `collections.Counter`: counts by key, in first-insertion order. #[derive(Clone, Debug)] struct Counter { order: Vec<(K, i64)>, index: HashMap, } impl Default for Counter { fn default() -> Self { Counter { order: Vec::new(), index: HashMap::new(), } } } impl Counter { fn add(&mut self, key: K, count: i64) { match self.index.get(&key) { Some(&i) => self.order[i].1 += count, None => { self.index.insert(key.clone(), self.order.len()); self.order.push((key, count)); } } } fn get(&self, key: &K) -> i64 { self.index.get(key).map_or(0, |&i| self.order[i].1) } fn total(&self) -> i64 { self.order.iter().map(|(_, n)| n).sum() } fn is_empty(&self) -> bool { self.order.is_empty() } /// `most_common(n)`: by count, largest first, ties in insertion order. fn most_common(&self, n: usize) -> Vec<(K, i64)> { let mut items = self.order.clone(); items.sort_by_key(|item| std::cmp::Reverse(item.1)); // stable items.truncate(n); items } } /// One instruction of MAME's trace: the registers before it (in REGISTERS /// order), the master clock count before it, and the logged reads it made. #[derive(Clone, Debug)] struct Line { registers: [u64; 10], clocks: i64, reads: Vec<(u32, u8)>, } impl Line { fn address(&self) -> u32 { (self.registers[1] << 16 | self.registers[0]) as u32 } } /// Python's `bytes.split()`: runs of ASCII whitespace separate fields. fn split(raw: &[u8]) -> Vec<&[u8]> { raw.split(|b| matches!(b, b' ' | b'\t' | b'\n' | b'\r' | 0x0B | 0x0C)) .filter(|field| !field.is_empty()) .collect() } fn hex(field: &[u8]) -> Option { u64::from_str_radix(std::str::from_utf8(field).ok()?, 16).ok() } /// MAME's trace lines with their reads, lazily, from an `error.log`. struct ReadLog { lines: std::io::Split>, registers: Option<[u64; 10]>, clocks: i64, reads: Vec<(u32, u8)>, done: bool, } impl ReadLog { fn open(path: &Path) -> Self { let file = std::fs::File::open(path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); ReadLog { lines: BufReader::with_capacity(1 << 20, file).split(b'\n'), registers: None, clocks: 0, reads: Vec::new(), done: false, } } } impl Iterator for ReadLog { type Item = Line; fn next(&mut self) -> Option { if self.done { return None; } for raw in self.lines.by_ref() { let raw = raw.expect("error.log"); let fields = split(&raw); if fields.len() == 3 && fields[0] == b"R" { if let (Some(address), Some(value)) = (hex(fields[1]), hex(fields[2])) { self.reads.push((address as u32, value as u8)); continue; } // int() would raise here; the reference does not catch it. panic!("unreadable read line {:?}", String::from_utf8_lossy(&raw)); } if fields.len() != 11 || raw.starts_with(b"[") { continue; } let mut values = [0u64; 10]; let mut ok = true; for (slot, field) in values.iter_mut().zip(&fields[..10]) { match hex(field) { Some(value) => *slot = value, None => ok = false, } } let total = std::str::from_utf8(fields[10]) .ok() .and_then(|t| t.parse::().ok()); let Some(total) = total.filter(|_| ok) else { continue; }; // MAME's "pc" is PB:PC, 24 bits; the core's is 16. MAME's MVN // and MVP count A below zero without a mask (REGISTER_A--, // g65816op.ipp), which shows as $FFFFFFFF until the next // instruction that rebuilds A: registers are 16 bits. values[0] &= 0xFFFF; values[2] &= 0xFFFF; values[3] &= 0xFFFF; values[4] &= 0xFFFF; let previous = self.registers.replace(values); let line = previous.map(|registers| Line { registers, clocks: self.clocks, reads: std::mem::take(&mut self.reads), }); self.clocks = total; self.reads.clear(); if line.is_some() { return line; } } self.done = true; self.registers.take().map(|registers| Line { registers, clocks: self.clocks, reads: std::mem::take(&mut self.reads), }) } } /// MAME 0.285's `bus_5A22_cycle_burst`: the clocks a read or write adds to /// the 6 every cycle costs, by region. /// /// Transcribed (by the reference) from MAME 0.285 /// `src/devices/cpu/g65816/g65816.cpp` (license: BSD-3-Clause; /// copyright-holders: Karl Stenerud). fn burst(address: u32, fast_rom: bool) -> i64 { let address = address as i64; if address & 0x408000 != 0 { return if address & 0x800000 != 0 && fast_rom { 0 } else { 2 }; } if (address + 0x6000) & 0x4000 != 0 { return 2; } if (address - 0x4000) & 0x7E00 != 0 { return 0; } 6 } const DEFAULT_BANKS: [u32; 2] = [0x00, 0x80]; /// The banks whose I/O reads mame_trace.py had MAME log (its trace.lua). fn watched_banks(trace_lua: &Path) -> Vec { let Ok(text) = std::fs::read_to_string(trace_lua) else { return DEFAULT_BANKS.to_vec(); }; // re.findall(r"wpset ([0-9A-F]*)2000,6000,", text) let mut found = Vec::new(); for (start, _) in text.match_indices("wpset ") { let rest = &text[start + 6..]; let run = rest .bytes() .take_while(|b| b.is_ascii_digit() || (b'A'..=b'F').contains(b)) .count(); if run >= 4 && rest[..run].ends_with("2000") && rest[run..].starts_with(",6000,") { let bank = &rest[..run - 4]; found.push(if bank.is_empty() { 0 } else { u32::from_str_radix(bank, 16).unwrap() }); } } found.sort(); found.dedup(); if found.is_empty() { DEFAULT_BANKS.to_vec() } else { found } } /// Whether MAME's watchpoints log reads of `address` (mame_trace.py). fn logged(address: u32, banks: &[u32]) -> bool { let (bank, offset) = (address >> 16, address & 0xFFFF); if banks.contains(&bank) { return (0x2000..0x8000).contains(&offset); } if (0x20..0x40).contains(&bank) { return (0x6000..0x8000).contains(&offset); } (0x70..=0x7D).contains(&bank) && offset < 0x8000 } /// Reads the harness cannot answer as MAME's board would: I/O and cartridge /// RAM (LoROM's banks $70-$7D, HiROM's $6000-$7FFF). fn unmodelled(address: u32) -> bool { let (bank, offset) = (address >> 16, address & 0xFFFF); if bank & 0x7F < 0x40 { return (0x2000..0x8000).contains(&offset); } (0x70..=0x7D).contains(&bank) && offset < 0x8000 } // MAME's cycle counts, where they are not the datasheet's (g65816op.ipp, // g65816.cpp; the core follows DS Table 5-7, rung 0). Indexed addressing adds // one cycle only when the index carries out of the page (EA_AX, EA_AY, // EA_DIY), whatever the index width; the datasheet adds one for a carry *or* // 16-bit index registers on reads, and always (one, not two) on writes and // read-modify-writes. MAME's a,x and a,y store and RMW constants (CLK_W_AX = // 3) already include that cycle, so a carry makes two; its (d),y store // constant does not (CLK_W_DIY = CLK_DIY), so without a carry it is one short. // Each rule was found by a replay and read in MAME's source after (the // reference's account). fn indexed_read(opcode: u8) -> Option<&'static str> { match opcode { 0x1D | 0x3D | 0x5D | 0x7D | 0xBD | 0xBC | 0xDD | 0xFD | 0x3C => Some("x"), 0x19 | 0x39 | 0x59 | 0x79 | 0xB9 | 0xBE | 0xD9 | 0xF9 => Some("y"), 0x11 | 0x31 | 0x51 | 0x71 | 0xB1 | 0xD1 | 0xF1 => Some("dy"), _ => None, } } fn indexed_write(opcode: u8) -> Option<&'static str> { match opcode { 0x9D | 0x9E | 0x1E | 0x3E | 0x5E | 0x7E | 0xDE | 0xFE => Some("x"), 0x99 => Some("y"), 0x91 => Some("dy"), _ => None, } } const XBA: u8 = 0xEB; // CLK_OP + CLK_IMPLIED: 2 cycles with M = 1 (3 with M = 0); DS 3 const RTI: u8 = 0x40; // CLK(7) emulation, CLK(8) native; DS 6 and 7 const JMP_AXI: u8 = 0x7C; // CLK_OP + CLK_AXI: 5 cycles; DS 6 /// How many CPU cycles more than the datasheet MAME 0.285 charges for the /// instruction about to run from `registers` (negative: fewer). fn mame_extra_cycles(machine: &mut Machine, registers: &[u64; 10]) -> i64 { let (pc, pbr, x, y, d, p) = ( registers[0] as u32, registers[1] as u32, registers[3] as u32, registers[4] as u32, registers[6] as u32, registers[8] as u32, ); let opcode = machine.peek(pbr << 16 | pc); if opcode == XBA { return if p & 0x20 != 0 { -1 } else { 0 }; } if opcode == RTI { return 1; } if opcode == JMP_AXI { return -1; } let Some(mode) = indexed_read(opcode).or_else(|| indexed_write(opcode)) else { return 0; }; let operand = pbr << 16 | (pc + 1) & 0xFFFF; let base = if mode == "dy" { let pointer = (d + machine.peek(operand) as u32) & 0xFFFF; machine.peek(pointer) as u32 | (machine.peek((pointer + 1) & 0xFFFF) as u32) << 8 } else { machine.peek(operand) as u32 | (machine.peek(operand + 1) as u32) << 8 }; let index = if mode == "x" { x } else { y }; let crossed = (base ^ (base + index)) & 0xFF00 != 0; if indexed_write(opcode).is_some() { return crossed as i64 - (mode == "dy") as i64; } if p & 0x10 == 0 && !crossed { -1 } else { 0 } } struct Divergence { index: u64, // MAME line number (0 = the first instruction) address: u32, // 24-bit address of the instruction that was stepped opcode: u8, differences: Vec<(&'static str, u64, u64)>, // register, core, MAME } #[derive(Default)] struct Report { instructions: u64, nmi: u64, irq: u64, nmi_i: u64, forced: Counter<&'static str>, adopted: u64, adopted_addresses: Counter, unread: i64, unread_addresses: Counter, divergences: Vec, clocks_equal: u64, clocks_mame_rule: u64, clocks_skipped: u64, clock_differences: Counter<(u8, i64)>, } /// Python's `{:,}`. fn commas(value: i64) -> String { let digits = value.unsigned_abs().to_string(); let mut text = String::new(); for (i, c) in digits.chars().enumerate() { if i > 0 && (digits.len() - i) % 3 == 0 { text.push(','); } text.push(c); } if value < 0 { format!("-{text}") } else { text } } impl Report { fn unexplained(&self) -> i64 { self.clock_differences.total() } fn summary(&self) -> String { let compared = self.clocks_equal as i64 + self.clocks_mame_rule as i64 + self.clock_differences.total(); let mut lines = vec![ format!( "instructions {}; NMI {}, IRQ {} (I flag set to MAME's after {} NMIs); taken a boundary earlier than the core's poll would: NMI {}, IRQ {}", commas(self.instructions as i64), commas(self.nmi as i64), commas(self.irq as i64), commas(self.nmi_i as i64), commas(self.forced.get(&"nmi")), commas(self.forced.get(&"irq")), ), format!( "register divergences {}; adopted MAME's registers after {} unlogged reads; {} logged reads not made", commas(self.divergences.len() as i64), commas(self.adopted as i64), commas(self.unread), ), format!( "clocks equal {} of {}, MAME's cycle rules {}, unexplained {} ({} steps with DMA, WAI or an interrupt entry skipped)", commas(self.clocks_equal as i64), commas(compared), commas(self.clocks_mame_rule as i64), commas(self.unexplained()), commas(self.clocks_skipped as i64), ), ]; let mut by_opcode: Counter = Counter::default(); for ((opcode, _), count) in &self.clock_differences.order { by_opcode.add(*opcode, *count); } for (opcode, count) in by_opcode.most_common(20) { let mut deltas: Vec<(i64, i64)> = self .clock_differences .order .iter() .filter(|((o, _), _)| *o == opcode) .map(|((_, d), n)| (*d, *n)) .collect(); deltas.sort(); let text: Vec = deltas .iter() .map(|(d, n)| format!("{d:+} x{}", commas(*n))) .collect(); lines.push(format!( " opcode {opcode:02X}: {} differ (MAME - core: {})", commas(count), text.join(", ") )); } if !self.unread_addresses.is_empty() { let common: Vec = self .unread_addresses .most_common(8) .iter() .map(|(a, n)| format!("{a:06X} x{}", commas(*n))) .collect(); lines.push(format!(" logged reads not made: {}", common.join(", "))); } if !self.adopted_addresses.is_empty() { let common: Vec = self .adopted_addresses .most_common(8) .iter() .map(|(a, n)| format!("{a:06X} x{}", commas(*n))) .collect(); lines.push(format!(" unlogged reads: {}", common.join(", "))); } for divergence in self.divergences.iter().take(20) { let diffs: Vec = divergence .differences .iter() .map(|(name, core, mame)| format!("{name} core {core:X} MAME {mame:X}")) .collect(); lines.push(format!( " line {} at {:06X} (opcode {:02X}): {}", commas(divergence.index as i64), divergence.address, divergence.opcode, diffs.join(", ") )); } lines.join("\n") } } /// The minimal harness with MAME's board behind its unmodelled reads (`Replay`). struct Replay { banks: Vec, clocks: i64, fast_rom: bool, reads: VecDeque<(u32, u8)>, guessed: Option, // an unlogged unmodelled read this step dma_started: bool, unread_addresses: Counter, in_dma: bool, } impl Hooks for Replay { // The harness's frame and its NMI are MAME's to decide here. fn tick(machine: &mut Machine, _frame: &mut Frame) { machine.cycles += 1; } fn read_byte( machine: &mut Machine, address: u32, frame: &mut Frame, _signals: Signals, ) -> u8 { Self::tick(machine, frame); machine.hooks.clocks += 6 + burst(address, machine.hooks.fast_rom); let mut value = machine.peek(address); // the harness's side effects ($2180, ...) if unmodelled(address) { let replay = &mut machine.hooks; let reads = &mut replay.reads; if reads.front().is_some_and(|r| r.0 == address) { value = reads.pop_front().unwrap().1; } else if logged(address, &replay.banks) && !reads.is_empty() && reads.iter().any(|&(a, _)| a == address) { // MAME logged other reads first (a DMA's B-bus reads): skip them. while reads[0].0 != address { let skipped = reads.pop_front().unwrap().0; replay.unread_addresses.add(skipped, 1); } value = reads.pop_front().unwrap().1; } else { replay.guessed = Some(address); } } machine.open_bus = value; value } fn write_byte( machine: &mut Machine, address: u32, value: u8, frame: &mut Frame, _signals: Signals, ) { Self::tick(machine, frame); machine.hooks.clocks += 6 + burst(address, machine.hooks.fast_rom); machine.open_bus = value; machine.poke(address, value); } fn idle(machine: &mut Machine, _address: u32, frame: &mut Frame, _signals: Signals) { Self::tick(machine, frame); machine.hooks.clocks += 6; } fn dma(machine: &mut Machine, channel: usize) { machine.hooks.in_dma = true; machine.base_dma(channel); machine.hooks.in_dma = false; } /// A DMA's B-bus read (MAME logs it at $00:21xx): MAME's value. fn io_read(machine: &mut Machine, offset: u32) -> u8 { let mut value = machine.base_io_read(offset); let replay = &mut machine.hooks; if replay.in_dma && replay.reads.front().is_some_and(|r| r.0 == offset) { value = replay.reads.pop_front().unwrap().1; } value } fn io_write(machine: &mut Machine, offset: u32, value: u8) { if offset == 0x420D { machine.hooks.fast_rom = value & 1 != 0; } else if offset == 0x420B && value != 0 { machine.hooks.dma_started = true; } machine.base_io_write(offset, value); } } type ReplayHarness = Harness; fn registers(harness: &ReplayHarness) -> [u64; 10] { let cpu = &harness.cpu; [ cpu.pc as u64, cpu.pbr as u64, cpu.a as u64, cpu.x as u64, cpu.y as u64, cpu.s as u64, cpu.d as u64, cpu.dbr as u64, cpu.p as u64, cpu.e as u64, ] } fn adopt(harness: &mut ReplayHarness, registers: &[u64; 10]) { let cpu = &mut harness.cpu; cpu.pc = registers[0] as u16; cpu.pbr = registers[1] as u8; cpu.a = registers[2] as u16; cpu.x = registers[3] as u16; cpu.y = registers[4] as u16; cpu.s = registers[5] as u16; cpu.d = registers[6] as u16; cpu.dbr = registers[7] as u8; cpu.p = registers[8] as u8; cpu.e = registers[9] as u8; } /// The 16-bit handler address of "nmi" or "irq" for the core's mode. fn vector_target(harness: &mut ReplayHarness, kind: &str) -> u64 { let vector = match (kind, harness.cpu.e != 0) { ("nmi", false) => 0xFFEA, ("irq", false) => 0xFFEE, ("nmi", true) => 0xFFFA, _ => 0xFFFE, }; let machine = &mut harness.cpu.bus; machine.peek(vector) as u64 | (machine.peek(vector + 1) as u64) << 8 } /// Which interrupt MAME took before `line`, if the core is not there. fn interrupt_before(harness: &mut ReplayHarness, line: &Line) -> Option<&'static str> { let cpu = &harness.cpu; if line.address() == ((cpu.pbr as u32) << 16 | cpu.pc as u32) && !cpu.waiting { return None; } let pushed: u16 = if cpu.e != 0 { 3 } else { 4 }; if line.registers[1] != 0 || line.registers[5] != cpu.s.wrapping_sub(pushed) as u64 { return None; } ["nmi", "irq"] .into_iter() .find(|&kind| line.registers[0] == vector_target(harness, kind)) } /// Request `kind` and step the core into it, at this boundary as MAME did; /// true if the core's own poll would have waited one more instruction (after /// CLI, PLP or REP cleared I, or right after an entry), which this overrides. fn take(harness: &mut ReplayHarness, kind: &str) -> bool { let cpu = &mut harness.cpu; if kind == "nmi" { cpu.frame.request_non_maskable_interrupt(); } else { cpu.frame.request_maskable_interrupt(); } if cpu.waiting { cpu.step(); // the IO cycle that ends WAI } // The frame's poll memory: the I flag or the requests as the last // instruction's poll saw them. let forced = cpu.frame.polled_i.is_some() || cpu.frame.polled.is_some(); cpu.frame.polled_i = None; cpu.frame.polled = None; cpu.step(); if kind == "irq" { cpu.frame.clear_maskable_interrupt(); } forced } /// Run the core against MAME's trace `log` of `rom`; at a register divergence, /// record it and take MAME's registers (`max_divergences` at most). fn replay(rom: &[u8], log: &Path, limit: Option, max_divergences: usize) -> Report { let hooks = Replay { banks: watched_banks(&log.parent().unwrap().join("trace.lua")), clocks: 0, fast_rom: false, reads: VecDeque::new(), guessed: None, dma_started: false, unread_addresses: Counter::default(), in_dma: false, }; let mut harness = Harness::with_hooks(rom, None, 30_000, hooks); // MAME's power-on WRAM ("0x55 isn't exactly right but it's close", // snes_m.cpp snes_init_ram); the real chip powers up with a pattern of // its own, which the harness's zeros are no closer to. harness.cpu.bus.wram.fill(0x55); let mut report = Report::default(); let mut lines = ReadLog::open(log); let first = lines.next().expect("an empty trace"); harness.cpu.step(); // reset let address = (harness.cpu.pbr as u32) << 16 | harness.cpu.pc as u32; if first.address() != address { panic!("reset to {address:06X}, MAME {:06X}", first.address()); } adopt(&mut harness, &first.registers); let mut line = first; for (index, following) in lines.enumerate() { let index = index as u64; if limit.is_some_and(|limit| index >= limit) { break; } let opcode = harness.cpu.bus.peek(line.address()); harness.cpu.bus.hooks.reads = line.reads.iter().copied().collect(); harness.cpu.bus.hooks.guessed = None; harness.cpu.bus.hooks.dma_started = false; let extra = mame_extra_cycles(&mut harness.cpu.bus, &line.registers); let start = harness.cpu.bus.hooks.clocks; harness.cpu.step(); report.instructions += 1; let mut whole = harness.cpu.bus.hooks.dma_started || harness.cpu.waiting; let kind = interrupt_before(&mut harness, &following); match kind { None if harness.cpu.waiting => { // WAI ended by an IRQ with I set: MAME runs on after it (U11). harness.cpu.frame.request_maskable_interrupt(); harness.cpu.step(); harness.cpu.frame.clear_maskable_interrupt(); } None => {} Some(kind) => { if take(&mut harness, kind) { report.forced.add(kind, 1); } whole = true; if kind == "nmi" { report.nmi += 1; let mame_i = following.registers[8] as u8 & I_FLAG; if (harness.cpu.p & I_FLAG != 0) != (mame_i != 0) { harness.cpu.p = harness.cpu.p & !I_FLAG | mame_i; report.nmi_i += 1; } } else { report.irq += 1; } } } let replay = &mut harness.cpu.bus.hooks; let left: Vec = replay.reads.iter().map(|&(a, _)| a).collect(); for address in left { replay.unread_addresses.add(address, 1); } if let Some(guessed) = replay.guessed { report.adopted += 1; report.adopted_addresses.add(guessed, 1); adopt(&mut harness, &following.registers); } else { let got = registers(&harness); if got != following.registers { let differences = REGISTERS .iter() .zip(got.iter().zip(following.registers.iter())) .filter(|(_, (core, mame))| core != mame) .map(|(name, (core, mame))| (*name, *core, *mame)) .collect(); report.divergences.push(Divergence { index, address: line.address(), opcode, differences, }); adopt(&mut harness, &following.registers); if report.divergences.len() >= max_divergences { break; } } } let delta = following.clocks - line.clocks; let clocks = harness.cpu.bus.hooks.clocks - start; if whole { report.clocks_skipped += 1; } else if clocks == delta && extra == 0 { report.clocks_equal += 1; } else if clocks + 6 * extra == delta { report.clocks_mame_rule += 1; } else { report.clock_differences.add((opcode, delta - clocks), 1); } line = following; } report.unread_addresses = harness.cpu.bus.hooks.unread_addresses.clone(); report.unread = report.unread_addresses.total(); report } fn main() { let args: Vec = std::env::args().skip(1).collect(); let mut folder = None; let mut limit = None; let mut index = 0; while index < args.len() { if args[index] == "--limit" { index += 1; limit = Some(args[index].parse().expect("--limit N")); } else { folder = Some(std::path::PathBuf::from(&args[index])); } index += 1; } let folder = folder.expect("usage: mame_replay GAME_DIR [--limit N]"); let rom = std::fs::read(folder.join("cart.sfc")).expect("cart.sfc"); let report = replay(&rom, &folder.join("error.log"), limit, 50); println!("{}", folder.file_name().unwrap().to_string_lossy()); println!("{}", report.summary()); let failed = !report.divergences.is_empty() || report.unexplained() != 0 || report.instructions == 0; std::process::exit(if failed { 1 } else { 0 }); }