replay/
replay.rs

1//! Rung 5: replay MAME 0.285's trace of a real game through the core, as the
2//! reference's `tests/mame_replay.py` does, and print the same report.
3//!
4//!     replay TRACE_DIR [--limit N]
5//!
6//! `TRACE_DIR` holds `cart.pce` and `error.log` (one line per instruction
7//! before it runs, `PC A X Y S P totalcycles`, then `M MPR0 ... MPR7`, then
8//! the hardware-page reads that instruction made, `[luaengine] R address
9//! value`). The core runs in the reference's minimal harness (`harness.py`,
10//! the part a replay uses: a HuCard, work RAM, a stubbed hardware page,
11//! master-clock accounting) from the same reset and is answered from the log,
12//! so it sees what MAME's board gave MAME's CPU. MAME is a detector here, not
13//! a judge: the rung passes when this binary prints what
14//! `scripts/reference_replay.py` prints for the reference core, the report
15//! and a digest of the core after every step.
16
17use std::collections::VecDeque;
18use std::io::{BufRead, BufReader};
19use std::path::Path;
20
21use huc6280::trace::{next_boundary, BoundaryKind};
22use huc6280::{Bus, CpuState, HuC6280, Pins};
23
24const HARDWARE_PAGE: u32 = 0x1FE000; // physical; offsets $0000-$1FFF within it
25const VDC_VCE_MASK: u32 = 0x1FF800; // (address & mask) == $1FE000: VDC and VCE
26const B_FLAG: u8 = 0x10;
27const VECTORS: [(&str, u16); 4] = [
28    ("irq2", 0xFFF6),
29    ("irq1", 0xFFF8),
30    ("tiq", 0xFFFA),
31    ("nmi", 0xFFFC),
32];
33const BLOCK_OPCODES: [u8; 5] = [0x73, 0xC3, 0xD3, 0xE3, 0xF3];
34const REGISTERS: [&str; 6] = ["pc", "a", "x", "y", "s", "p"];
35
36/// One instruction of MAME's trace: the registers before it, the 7.16 MHz
37/// cycle count before it, and the hardware-page reads it made.
38struct Line {
39    registers: [u32; 14], // pc a x y s p, then MPR0-7
40    cycles: i64,
41    reads: Vec<(u32, u8)>,
42}
43
44fn hex(field: &[u8]) -> Option<u32> {
45    let text = std::str::from_utf8(field).ok()?;
46    u32::from_str_radix(text, 16).ok()
47}
48
49/// MAME's trace lines with their reads, lazily, from an `error.log`.
50struct Log<R: BufRead> {
51    input: R,
52    raw: Vec<u8>,
53    registers: Option<[u32; 14]>,
54    cycles: i64,
55    reads: Vec<(u32, u8)>,
56    head: Option<([u32; 6], i64)>,
57    done: bool,
58}
59
60impl<R: BufRead> Log<R> {
61    fn new(input: R) -> Self {
62        Log {
63            input,
64            raw: Vec::new(),
65            registers: None,
66            cycles: 0,
67            reads: Vec::new(),
68            head: None,
69            done: false,
70        }
71    }
72}
73
74impl<R: BufRead> Iterator for Log<R> {
75    type Item = Line;
76
77    fn next(&mut self) -> Option<Line> {
78        if self.done {
79            return None;
80        }
81        loop {
82            self.raw.clear();
83            if self
84                .input
85                .read_until(b'\n', &mut self.raw)
86                .expect("read the log")
87                == 0
88            {
89                self.done = true;
90                let registers = self.registers.take()?;
91                return Some(Line {
92                    registers,
93                    cycles: self.cycles,
94                    reads: std::mem::take(&mut self.reads),
95                });
96            }
97            let fields: Vec<&[u8]> = self
98                .raw
99                .split(|byte| byte.is_ascii_whitespace())
100                .filter(|field| !field.is_empty())
101                .collect();
102            if fields.len() == 4 && fields[0] == b"[luaengine]" && fields[1] == b"R" {
103                let address = hex(fields[2]).expect("a read's address");
104                let value = hex(fields[3]).expect("a read's value");
105                self.reads.push((address, value as u8));
106            } else if fields.len() == 9 && fields[0] == b"M" && self.head.is_some() {
107                let mut mpr = [0u32; 8];
108                let mut valid = true;
109                for (slot, field) in mpr.iter_mut().zip(&fields[1..]) {
110                    match hex(field) {
111                        Some(value) => *slot = value,
112                        None => valid = false,
113                    }
114                }
115                if !valid {
116                    continue;
117                }
118                let (head, head_cycles) = self.head.take().unwrap();
119                let mut registers = [0u32; 14];
120                registers[..6].copy_from_slice(&head);
121                registers[6..].copy_from_slice(&mpr);
122                let finished = self.registers.replace(registers).map(|registers| Line {
123                    registers,
124                    cycles: self.cycles,
125                    reads: std::mem::take(&mut self.reads),
126                });
127                self.cycles = head_cycles;
128                self.reads.clear();
129                if finished.is_some() {
130                    return finished;
131                }
132            } else if fields.len() == 7 && !self.raw.starts_with(b"[") {
133                let mut head = [0u32; 6];
134                let mut valid = true;
135                for (slot, field) in head.iter_mut().zip(&fields[..6]) {
136                    match hex(field) {
137                        Some(value) => *slot = value,
138                        None => valid = false,
139                    }
140                }
141                let cycles = std::str::from_utf8(fields[6])
142                    .ok()
143                    .and_then(|text| text.parse::<i64>().ok());
144                self.head = match (valid, cycles) {
145                    (true, Some(cycles)) => Some((head, cycles)),
146                    _ => None,
147                };
148            }
149        }
150    }
151}
152
153/// Where in the ROM (in 8 KB banks) each sixteenth of the 128 ROM pages
154/// starts: Mesen2's mirroring as the reference states it (emulator tier).
155fn bank_offsets(banks: usize) -> [usize; 8] {
156    match banks {
157        0x30 => [0, 0x10, 0, 0x10, 0x20, 0x20, 0x20, 0x20],
158        0x40 => [0, 0x10, 0x20, 0x30, 0x20, 0x30, 0x20, 0x30],
159        0x60 => [0, 0x10, 0x20, 0x30, 0x40, 0x50, 0x40, 0x50],
160        _ => [0, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70],
161    }
162}
163
164/// The reference's minimal harness with MAME's board behind its
165/// hardware-page reads (`Harness` and `Replay`).
166struct Board {
167    rom: Vec<u8>,
168    ram: Vec<u8>,
169    rom_banks: Vec<usize>,
170    open_bus: u8,
171    master_clocks: u64,
172    reads: VecDeque<(u32, u8)>,
173    /// A hardware-page read nothing logged, this step.
174    guessed: Option<u32>,
175}
176
177impl Board {
178    fn new(rom: Vec<u8>) -> Self {
179        let banks = rom.len() / 0x2000;
180        let offsets = bank_offsets(banks);
181        let rom_banks = if banks != 0 {
182            (0..0x80)
183                .map(|page| (offsets[page >> 4] + (page & 0x0F)) % banks)
184                .collect()
185        } else {
186            Vec::new()
187        };
188        Board {
189            rom,
190            ram: vec![0; 0x2000],
191            rom_banks,
192            open_bus: 0xFF,
193            master_clocks: 0,
194            reads: VecDeque::new(),
195            guessed: None,
196        }
197    }
198
199    fn tick(&mut self, address: Option<u32>, pins: &Pins) {
200        // 12 master clocks a CPU cycle at 1.79 MHz, 3 at 7.16 MHz.
201        let mut per_cycle = if pins.high_speed { 3 } else { 12 };
202        // The VDC/VCE stretch: one extra cycle on any access there (U18), the board's job.
203        if matches!(address, Some(address) if address & VDC_VCE_MASK == HARDWARE_PAGE) {
204            per_cycle *= 2;
205        }
206        self.master_clocks += per_cycle;
207    }
208
209    /// The byte at a physical address as the bus would give it;
210    /// `side_effects = false` (a debugger's view) answers the hardware page
211    /// with $FF.
212    fn peek(&mut self, address: u32, side_effects: bool) -> u8 {
213        let page = address >> 13;
214        if page < 0x80 {
215            if self.rom_banks.is_empty() {
216                return 0xFF;
217            }
218            let bank = self.rom_banks[page as usize];
219            return self.rom[(bank << 13) | (address & 0x1FFF) as usize];
220        }
221        if (0xF8..=0xFB).contains(&page) {
222            return self.ram[address as usize & 0x1FFF];
223        }
224        if (page == 0xF7 || page == 0xFF) && side_effects {
225            return self.answer(address);
226        }
227        0xFF
228    }
229
230    fn answer(&mut self, address: u32) -> u8 {
231        let offset = address & 0x1FFF;
232        if matches!(self.reads.front(), Some(&(first, _)) if first == address) {
233            return self.reads.pop_front().unwrap().1;
234        }
235        if let Some(position) = self.reads.iter().position(|&(logged, _)| logged == address) {
236            // MAME logged other reads first (a block transfer's, say): skip them.
237            self.reads.drain(..position);
238            return self.reads.pop_front().unwrap().1;
239        }
240        self.guessed = Some(address);
241        if address >= HARDWARE_PAGE {
242            self.default_io_read(offset)
243        } else {
244            0xFF
245        }
246    }
247
248    fn default_io_read(&self, offset: u32) -> u8 {
249        if (0x1000..0x1400).contains(&offset) {
250            return 0xBF; // port K: no button pressed, bit 6 set
251        }
252        if offset < 0x0800 {
253            return 0; // VDC, VCE: nothing there
254        }
255        self.open_bus // PSG, timer, interrupt registers: the I/O buffer (U13), roughly
256    }
257}
258
259impl Bus for Board {
260    fn read(&mut self, address: u32, pins: &mut Pins) -> u8 {
261        self.tick(Some(address), pins);
262        let value = self.peek(address, true);
263        self.open_bus = value;
264        value
265    }
266
267    fn write(&mut self, address: u32, value: u8, pins: &mut Pins) {
268        self.tick(Some(address), pins);
269        self.open_bus = value;
270        if (0xF8..=0xFB).contains(&(address >> 13)) {
271            self.ram[address as usize & 0x1FFF] = value;
272        }
273    }
274
275    fn idle(&mut self, address: Option<u32>, pins: &mut Pins) {
276        self.tick(address, pins);
277    }
278}
279
280/// A counter that remembers the order its keys arrived in, as Python's does.
281struct Counter<K: PartialEq + Clone>(Vec<(K, u64)>);
282
283impl<K: PartialEq + Clone> Counter<K> {
284    fn new() -> Self {
285        Counter(Vec::new())
286    }
287
288    fn add(&mut self, key: K, count: u64) {
289        match self.0.iter_mut().find(|(k, _)| *k == key) {
290            Some(entry) => entry.1 += count,
291            None => self.0.push((key, count)),
292        }
293    }
294
295    /// The `n` most common, ties in arrival order (`Counter.most_common`).
296    fn most_common(&self, n: usize) -> Vec<(K, u64)> {
297        let mut items = self.0.clone();
298        items.sort_by_key(|item| std::cmp::Reverse(item.1)); // stable: ties keep arrival order
299        items.truncate(n);
300        items
301    }
302}
303
304struct Divergence {
305    index: u64,
306    address: u32,
307    opcode: u8,
308    differences: Vec<(String, u32, u32)>, // register: (core, MAME)
309}
310
311struct Report {
312    instructions: u64,
313    interrupts: Counter<&'static str>,
314    forced: Counter<&'static str>,
315    forced_after: Counter<(&'static str, u8)>,
316    adopted: u64,
317    block_registers: u64,
318    adopted_addresses: Counter<u32>,
319    unread: u64,
320    unread_addresses: Counter<u32>,
321    divergences: Vec<Divergence>,
322    cycles_equal: u64,
323    cycles_skipped: u64,
324    cycle_differences: Counter<(u8, i64)>,
325    entry_differences: Counter<i64>,
326}
327
328/// An integer with thousands separators (Python's `{:,}`).
329fn commas(value: u64) -> String {
330    let digits = value.to_string();
331    let mut out = String::new();
332    for (index, digit) in digits.chars().enumerate() {
333        if index != 0 && (digits.len() - index) % 3 == 0 {
334            out.push(',');
335        }
336        out.push(digit);
337    }
338    out
339}
340
341fn or_else(text: String, fallback: &str) -> String {
342    if text.is_empty() {
343        fallback.to_string()
344    } else {
345        text
346    }
347}
348
349fn named(counter: &Counter<&'static str>) -> String {
350    let mut items = counter.0.clone();
351    items.sort();
352    let parts: Vec<String> = items
353        .iter()
354        .map(|(k, v)| format!("{k} {}", commas(*v)))
355        .collect();
356    or_else(parts.join(", "), "none")
357}
358
359impl Report {
360    fn summary(&self) -> String {
361        let unexplained: u64 = self.cycle_differences.0.iter().map(|(_, n)| n).sum();
362        let compared = self.cycles_equal + unexplained;
363        let mut entries = self.entry_differences.0.clone();
364        entries.sort();
365        let entries: Vec<String> = entries
366            .iter()
367            .map(|(d, n)| format!("{d:+} x{}", commas(*n)))
368            .collect();
369        let mut lines = vec![
370            format!(
371                "instructions {}; interrupts taken {}; taken a boundary earlier than the core's poll would: {}",
372                commas(self.instructions),
373                named(&self.interrupts),
374                named(&self.forced)
375            ),
376            format!(
377                "register divergences {}; block transfers' A, X, Y adopted {}; adopted MAME's registers after {} unlogged reads; {} logged reads not made",
378                commas(self.divergences.len() as u64),
379                commas(self.block_registers),
380                commas(self.adopted),
381                commas(self.unread)
382            ),
383            format!(
384                "cycles equal {} of {}, differ {} ({} steps with an interrupt entry compared apart: {})",
385                commas(self.cycles_equal),
386                commas(compared),
387                commas(unexplained),
388                commas(self.cycles_skipped),
389                or_else(entries.join(", "), "-")
390            ),
391        ];
392        let mut by_opcode: Counter<u8> = Counter::new();
393        for ((opcode, _), count) in &self.cycle_differences.0 {
394            by_opcode.add(*opcode, *count);
395        }
396        for (opcode, count) in by_opcode.most_common(25) {
397            let mut deltas: Vec<(i64, u64)> = self
398                .cycle_differences
399                .0
400                .iter()
401                .filter(|((o, _), _)| *o == opcode)
402                .map(|((_, d), n)| (*d, *n))
403                .collect();
404            deltas.sort();
405            let text: Vec<String> = deltas
406                .iter()
407                .map(|(d, n)| format!("{d:+} x{}", commas(*n)))
408                .collect();
409            lines.push(format!(
410                "  opcode {opcode:02X}: {} differ (MAME - core: {})",
411                commas(count),
412                text.join(", ")
413            ));
414        }
415        for (label, counter) in [
416            ("logged reads not made", &self.unread_addresses),
417            ("unlogged reads", &self.adopted_addresses),
418        ] {
419            if !counter.0.is_empty() {
420                let common: Vec<String> = counter
421                    .most_common(8)
422                    .iter()
423                    .map(|(a, n)| format!("{a:06X} x{}", commas(*n)))
424                    .collect();
425                lines.push(format!("  {label}: {}", common.join(", ")));
426            }
427        }
428        if !self.forced_after.0.is_empty() {
429            let common: Vec<String> = self
430                .forced_after
431                .most_common(8)
432                .iter()
433                .map(|((n, o), c)| format!("{n} after {o:02X} x{}", commas(*c)))
434                .collect();
435            lines.push(format!("  taken early: {}", common.join(", ")));
436        }
437        for divergence in self.divergences.iter().take(20) {
438            let diffs: Vec<String> = divergence
439                .differences
440                .iter()
441                .map(|(name, core, mame)| format!("{name} core {core:X} MAME {mame:X}"))
442                .collect();
443            lines.push(format!(
444                "  line {} at {:04X} (opcode {:02X}): {}",
445                commas(divergence.index),
446                divergence.address,
447                divergence.opcode,
448                diffs.join(", ")
449            ));
450        }
451        lines.join("\n")
452    }
453}
454
455/// The core and the digest of it after every step the replay makes.
456struct Replay {
457    cpu: HuC6280<Board>,
458    digest: u64,
459    steps: u64,
460}
461
462impl Replay {
463    fn step(&mut self) -> u32 {
464        let cycles = self.cpu.step();
465        let cpu = &self.cpu;
466        let mut values = [0u64; 17];
467        values[..7].copy_from_slice(&[
468            cycles as u64,
469            cpu.pc as u64,
470            cpu.a as u64,
471            cpu.x as u64,
472            cpu.y as u64,
473            cpu.s as u64,
474            cpu.p as u64,
475        ]);
476        for (slot, register) in values[7..15].iter_mut().zip(cpu.mpr) {
477            *slot = register as u64;
478        }
479        values[15] = cpu.high_speed() as u64;
480        values[16] = cpu.bus.master_clocks & 0xFFFFFFFF;
481        for value in values {
482            self.digest = (self.digest ^ value).wrapping_mul(0x100000001B3);
483        }
484        self.steps += 1;
485        cycles
486    }
487
488    fn registers(&self) -> [u32; 14] {
489        let cpu = &self.cpu;
490        let mut registers = [0u32; 14];
491        registers[..6].copy_from_slice(&[
492            cpu.pc as u32,
493            cpu.a as u32,
494            cpu.x as u32,
495            cpu.y as u32,
496            cpu.s as u32,
497            (cpu.p & !B_FLAG) as u32,
498        ]);
499        for (slot, register) in registers[6..].iter_mut().zip(cpu.mpr) {
500            *slot = register as u32;
501        }
502        registers
503    }
504
505    fn peek_logical(&mut self, logical: u16) -> u8 {
506        let physical = self.cpu.physical(logical);
507        self.cpu.bus.peek(physical, false)
508    }
509
510    /// If MAME's next line is an interrupt handler's first instruction, step the entry.
511    fn take_interrupt(
512        &mut self,
513        line: &Line,
514        report: &mut Report,
515        previous: u8,
516    ) -> Option<&'static str> {
517        if line.registers[4] != self.cpu.s.wrapping_sub(3) as u32 {
518            return None;
519        }
520        let mut found = None;
521        for (name, vector) in VECTORS {
522            let target = self.peek_logical(vector) as u32
523                | ((self.peek_logical(vector.wrapping_add(1)) as u32) << 8);
524            if target == line.registers[0] {
525                found = Some(name);
526                break;
527            }
528        }
529        let name = found?;
530        if self.cpu.pc as u32 == line.registers[0] {
531            // Already at the handler: no entry to make, and no line left
532            // asserted (issue 0005).
533            return None;
534        }
535        if name == "nmi" {
536            self.cpu.request_non_maskable_interrupt();
537        } else {
538            self.cpu
539                .set_irq_lines(name == "irq1", name == "irq2", name == "tiq");
540        }
541        let state = self.cpu.capture_state();
542        if next_boundary(&state) == BoundaryKind::Instruction {
543            // The core's poll would wait an instruction (CLI, SEI or PLP
544            // before it, or an entry): MAME took the interrupt now, so make
545            // the poll see the current I and lines and count it.
546            self.cpu.pins.frame.polled_i = None;
547            self.cpu.pins.frame.polled = None;
548            // The reference also clears _polled_lines; Pins keeps it private,
549            // so it goes through a state with the poll agreeing (the frame's
550            // fields restored as they now stand, polled_irq_lines None).
551            let cleared = CpuState {
552                polled_irq_lines: None,
553                ..self.cpu.capture_state()
554            };
555            if state.polled_irq_lines.is_some() {
556                self.cpu.restore_state(&cleared).expect("a captured state");
557            }
558            report.forced.add(name, 1);
559            report.forced_after.add((name, previous), 1);
560        }
561        self.step();
562        if name != "nmi" {
563            self.cpu.set_irq_lines(false, false, false);
564        }
565        Some(name)
566    }
567}
568
569fn replay(
570    rom: Vec<u8>,
571    log: &Path,
572    limit: Option<u64>,
573    max_divergences: usize,
574) -> (Report, Replay) {
575    let mut report = Report {
576        instructions: 0,
577        interrupts: Counter::new(),
578        forced: Counter::new(),
579        forced_after: Counter::new(),
580        adopted: 0,
581        block_registers: 0,
582        adopted_addresses: Counter::new(),
583        unread: 0,
584        unread_addresses: Counter::new(),
585        divergences: Vec::new(),
586        cycles_equal: 0,
587        cycles_skipped: 0,
588        cycle_differences: Counter::new(),
589        entry_differences: Counter::new(),
590    };
591    let mut cpu = HuC6280::new(Board::new(rom));
592    cpu.request_reset();
593    let mut harness = Replay {
594        cpu,
595        digest: 0xCBF29CE484222325,
596        steps: 0,
597    };
598    harness.step(); // the reset sequence
599    let file = std::fs::File::open(log).unwrap_or_else(|e| panic!("{}: {e}", log.display()));
600    let mut iterator = Log::new(BufReader::with_capacity(1 << 20, file));
601    let mut line = iterator.next();
602    let mut index = 0u64;
603    // The previous instruction's cycles are settled once we know whether an
604    // interrupt entry followed it (MAME's delta to the next line holds the
605    // entry): (opcode, MAME's cycles, the core's).
606    let mut pending: Option<(u8, i64, i64)> = None;
607    while let Some(current) = line.take() {
608        if matches!(limit, Some(limit) if index >= limit) {
609            break;
610        }
611        let following = iterator.next();
612        let mut entered = None;
613        let mut entry_clocks = 0;
614        let mut want = current.registers;
615        want[5] &= !(B_FLAG as u32);
616        if harness.registers()[..6] != want[..6] {
617            let mark = harness.cpu.bus.master_clocks;
618            entered = harness.take_interrupt(&current, &mut report, pending.map_or(0, |p| p.0));
619            entry_clocks = harness.cpu.bus.master_clocks - mark;
620            if let Some(name) = entered {
621                report.interrupts.add(name, 1);
622            }
623        }
624        if let Some((last_opcode, mame, core)) = pending.take() {
625            if entered.is_some() {
626                report.cycles_skipped += 1;
627                report
628                    .entry_differences
629                    .add(mame - core - (entry_clocks / 3) as i64, 1);
630            } else if mame == core {
631                report.cycles_equal += 1;
632            } else {
633                report.cycle_differences.add((last_opcode, mame - core), 1);
634            }
635        }
636        let mine = harness.registers();
637        if mine != want {
638            let names = REGISTERS
639                .iter()
640                .map(|name| name.to_string())
641                .chain((0..8).map(|n| format!("mpr{n}")));
642            let differences = names
643                .zip(mine.iter().zip(want.iter()))
644                .filter(|(_, (a, b))| a != b)
645                .map(|(name, (a, b))| (name, *a, *b))
646                .collect();
647            let opcode = harness.peek_logical(want[0] as u16);
648            report.divergences.push(Divergence {
649                index,
650                address: want[0],
651                opcode,
652                differences,
653            });
654            if report.divergences.len() >= max_divergences {
655                break;
656            }
657            // Take MAME's registers so one divergence does not spread.
658            let cpu = &mut harness.cpu;
659            cpu.pc = want[0] as u16;
660            cpu.a = want[1] as u8;
661            cpu.x = want[2] as u8;
662            cpu.y = want[3] as u8;
663            cpu.s = want[4] as u8;
664            cpu.p = want[5] as u8;
665            for (register, value) in cpu.mpr.iter_mut().zip(&want[6..]) {
666                *register = *value as u8;
667            }
668        }
669        harness.cpu.bus.reads = current.reads.iter().copied().collect();
670        harness.cpu.bus.guessed = None;
671        let opcode = harness.peek_logical(harness.cpu.pc);
672        let start = harness.cpu.bus.master_clocks;
673        harness.step();
674        report.instructions += 1;
675        report.unread += harness.cpu.bus.reads.len() as u64;
676        for &(address, _) in &harness.cpu.bus.reads {
677            report.unread_addresses.add(address, 1);
678        }
679        if let Some(next) = &following {
680            let cpu = &mut harness.cpu;
681            if BLOCK_OPCODES.contains(&opcode) {
682                // C14: MAME's block transfers keep A, X and Y in the CPU and
683                // never push them; the core (like Mesen and Mednafen) pushes
684                // and pops them (HW HB-6), so a transfer over the stack gives
685                // them back overwritten. MAME's are adopted.
686                report.block_registers += 1;
687                cpu.a = next.registers[1] as u8;
688                cpu.x = next.registers[2] as u8;
689                cpu.y = next.registers[3] as u8;
690            }
691            if let Some(guessed) = cpu.bus.guessed {
692                report.adopted += 1;
693                report.adopted_addresses.add(guessed, 1);
694                cpu.a = next.registers[1] as u8;
695                cpu.x = next.registers[2] as u8;
696                cpu.y = next.registers[3] as u8;
697                cpu.s = next.registers[4] as u8;
698                cpu.pc = next.registers[0] as u16;
699                cpu.p = next.registers[5] as u8 & !B_FLAG;
700            }
701            pending = Some((
702                opcode,
703                next.cycles - current.cycles,
704                ((cpu.bus.master_clocks - start) / 3) as i64,
705            ));
706        }
707        line = following;
708        index += 1;
709    }
710    (report, harness)
711}
712
713fn main() {
714    let mut directory: Option<String> = None;
715    let mut limit: Option<u64> = None;
716    let mut args = std::env::args().skip(1);
717    while let Some(arg) = args.next() {
718        if arg == "--limit" {
719            limit = Some(args.next().expect("--limit N").parse().expect("N"));
720        } else {
721            directory = Some(arg);
722        }
723    }
724    let directory = directory.expect("usage: replay TRACE_DIR [--limit N]");
725    let directory = Path::new(&directory);
726    let rom = std::fs::read(directory.join("cart.pce")).expect("cart.pce");
727    let began = std::time::Instant::now();
728    let (report, harness) = replay(rom, &directory.join("error.log"), limit, 50);
729    println!("{}", report.summary());
730    println!(
731        "digest {:016x} over {} steps",
732        harness.digest,
733        commas(harness.steps)
734    );
735    eprintln!("{:.3} s", began.elapsed().as_secs_f64());
736}