replay/
replay.rs

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