// SPDX-License-Identifier: MIT //! Rung 4: the capture lockstep, the reference's rung 4 and 4b //! (`tests/capture_replay.py` and `scripts/run_capture.py`, transcribed). //! //! capture CAPTURES_DIR STARTS_JSON FOOT_RAW [MACHINE [CAPTURE]] [--max-instructions N] [--jobs N] //! //! At most `--jobs` replays run at once (default 4, the most allowed). //! //! The captures are David Banks's: one 16-bit sample per CPU cycle, holding //! the data bus, RnW, SYNC, RDY and RST of a BBC Master (a GTE/CMD G65SC12) //! or a BBC B fitted with a Rockwell R65C02. **Tier 1**: what the chip did. //! There is no address bus. `CAPTURES_DIR` holds them unpacked as //! `MACHINE_CAPTURE.bin` (the reference's `reference/build`); `STARTS_JSON` //! is `scripts/capture_starts.py`'s (where the reference's `decoder_start` //! says each mid-run capture's lockstep begins); `FOOT_RAW` is George Foot's //! data-only capture, unpacked. //! //! The replay steps the core and answers each bus callback from the next //! sample: //! //! - a read returns the captured data byte, so the core follows the real //! chip's data whatever the machine around it did; //! - per cycle it compares: read or write against RnW; `sync` against SYNC; a //! written byte against the data bus. Any difference is a **mismatch** and //! ends the replay there (the two are no longer in step); //! - it keeps a memory model (what each address was last seen to hold, //! following the machine's paging: [`Paging`]) and compares every read's //! captured byte with it. A read whose byte differs from the model is a //! **model difference**, counted by opcode and cycle number: a dummy read //! from the wrong address shows up as its slot differing in most //! executions, which is how the capture decides addresses it does not //! record (U4). Memory-mapped I/O (`$FC00-$FEFF`) is not modelled. //! //! Interrupt entries are injected where the capture shows one: the next three //! cycles after two reads are writes, and it is not a `BRK`. The request is //! an IRQ if the core's poll would take one there, else an NMI. If the core //! would take neither the replay reports that as a mismatch. Samples with RDY //! low are dropped: the machine is holding the processor and the cycle //! repeats. //! //! The starting state: a reset capture starts at the reset sequence; when the //! first push of P differs from the core's only in flags unknown at reset, //! the replay is restarted with those flags as the chip had them //! (`adopted`). The other captures start where the reference's decoder start //! says, with its registers. //! //! Differences forced by Rust: the reference raises `Mismatch` inside a bus //! callback and catches it around `step()`, leaving the CPU mid-instruction; //! here the callback panics with a [`Mismatch`] payload and the replay catches //! it with `catch_unwind` around `step()`, which leaves the CPU in the same //! place (a panic hook keeps those quiet). A callback reads `cpu.pc` and //! `cpu.opcode` from [`Signals`]. The memory model's "unknown" is -1 in an //! `i16`. The output is the reference's `format_report`, line for line. use std::collections::HashMap; use std::panic::{self, AssertUnwindSafe}; use std::path::{Path, PathBuf}; use std::time::Instant; use serde::Deserialize; use w65c02::dispatch::opcodes_for; use w65c02::trace::{next_boundary, BoundaryKind}; use w65c02::{Bus, Cmos65c02, Frame, Row, Signals, G65SC02, R65C02, W65C02S}; // Sample bits (the decoder's default assignments). const RNW: u16 = 0x0100; const SYNC: u16 = 0x0200; const RDY: u16 = 0x0400; const RST: u16 = 0x4000; const IO_FIRST: u16 = 0xFC00; // FRED, JIM and SHEILA: memory-mapped I/O on both machines const IO_END: u16 = 0xFF00; const ROMSEL: u16 = 0xFE30; // the paged-ROM latch const ACCCON: u16 = 0xFE34; // the Master's access control latch const BANKS: usize = 20; const FLAGS_UNKNOWN_AT_RESET: u8 = 0xC3; // N V Z C // Where a model byte came from. const READ: u8 = 0; const WRITTEN: u8 = 1; const ROM: u8 = 2; // a write here was seen not to stay: the address is ROM or empty /// The captures of each machine, and its row. const MACHINES: [(&str, Row, [&str; 4]); 2] = [ ( "beebr65c02", R65C02, ["reset", "dormann_d65c11", "clark_bcd_full", "dormann_d6502"], ), ( "master", G65SC02, ["reset", "dormann_d65c10", "clark_bcd_full", "dormann_d6502"], ), ]; /// Foot's capture is replayed on the two rows with bit instructions. const FOOT_ROWS: [Row; 2] = [W65C02S, R65C02]; /// The capture's first nine bytes end with a reset vector (`$00 $FE`), and the /// bytes after them are the code at `$FE00`: the replay starts there. const FOOT_START: usize = 9; /// The board's device registers, left out of the memory model. const FOOT_IO_FIRST: u16 = 0xFF40; const FOOT_IO_END: u16 = 0xFF70; /// Which memory an address means: the machine's paging, so the model follows it. /// /// A bank is a separate 64 KB of model. BBC B (Advanced User Guide, "Paged /// ROMs"): `$8000-$BFFF` is the sideways ROM the low four bits of ROMSEL /// select (the latch is write-only at `$FE30-$FE3F`). BBC Master (Master /// Reference Manual part 1, "Memory"): the same, and ROMSEL bit 7 maps 4 KB of /// RAM at `$8000-$8FFF`; ACCCON bit 3 (Y) maps 8 KB of RAM over the MOS at /// `$C000-$DFFF`; `$3000-$7FFF` is shadow memory when ACCCON bit 2 (X) is set, /// or when bit 1 (E) is set and the code running is the VDU driver at /// `$C000-$DFFF`. These are the machines', not the processor's. struct Paging { master: bool, romsel: u8, acccon: u8, } impl Paging { fn written(&mut self, address: u16, value: u8) { if self.master { if address == ROMSEL { self.romsel = value; } else if address == ACCCON { self.acccon = value; } } else if (ROMSEL..ROMSEL + 0x10).contains(&address) { self.romsel = value; } } /// The bank `address` is in when code at `pc` accesses it (0: not paged). fn bank(&self, address: u16, pc: u16) -> usize { if address < 0x8000 { if self.master && address >= 0x3000 { let acccon = self.acccon; if acccon & 0x04 != 0 || (acccon & 0x02 != 0 && (0xC000..0xE000).contains(&pc)) { return 18; // shadow } } return 0; } if address < 0xC000 { if self.master && self.romsel & 0x80 != 0 && address < 0x9000 { return 17; } return 1 + (self.romsel & 0x0F) as usize; } if address < 0xE000 && self.master && self.acccon & 0x08 != 0 { return 19; } 0 } } /// The core and the capture are no longer in step (the panic payload). struct Mismatch(String); /// A bus-cycle slot: the sequence ("irq", "nmi", "reset") or the opcode, and the cycle from 1. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] enum Slot { Opcode(u8), Sequence(&'static str), } type Key = (Slot, usize); /// A finished replay: (passed, its report, seconds, cycles). type Outcome = (bool, String, f64, u64); /// What one replay found (the reference's `Report`). #[derive(Default)] struct Report { machine: String, capture: String, instructions: u64, cycles: usize, interrupts: Vec<(&'static str, u64)>, // in the order first seen, as a Python Counter model_differences: HashMap, model_examples: HashMap, model_agreed: HashMap, reads: HashMap, writes_not_kept: u64, adopted: Option<(u8, u8)>, start: String, mismatch: Option, ended: String, } impl Report { fn ok(&self) -> bool { self.mismatch.is_none() && self.model_differences.is_empty() } fn count_interrupt(&mut self, kind: &'static str) { match self.interrupts.iter_mut().find(|(k, _)| *k == kind) { Some((_, n)) => *n += 1, None => self.interrupts.push((kind, 1)), } } } /// The memory model shared by both replays. struct Model { memory: Vec, source: Vec, } impl Model { fn new(size: usize) -> Self { Model { memory: vec![-1; size], source: vec![READ; size], } } /// Compare a read's captured byte with the model, as both replays do. fn read(&mut self, report: &mut Report, key: Key, index: usize, address: u16, data: u8) { let known = self.memory[index]; if known == data as i16 { *report.model_agreed.entry(key).or_default() += 1; self.source[index] = READ; } else { if known >= 0 { if self.source[index] == WRITTEN && address >= 0x8000 { // The byte the core wrote here did not stay: ROM, or nothing // there. Later writes to it are ignored. self.source[index] = ROM; report.writes_not_kept += 1; } else { *report.model_differences.entry(key).or_default() += 1; let instructions = report.instructions; report.model_examples.entry(key).or_insert_with(|| { format!( "instruction {instructions}, ${address:04X}: model ${known:02X}, bus ${data:02X}" ) }); } } self.memory[index] = data as i16; } } fn write(&mut self, index: usize, value: u8) { if self.source[index] != ROM { self.memory[index] = value as i16; self.source[index] = WRITTEN; } } } /// The host of one replay of a BBC capture. struct Replay<'a> { samples: &'a [u16], position: usize, step_start: usize, slot: Option<&'static str>, paging: Paging, model: Model, report: Report, } fn mismatch(text: String) -> ! { panic::panic_any(Mismatch(text)) } impl Bus for Replay<'_> { fn read(&mut self, address: u16, _: &mut Frame, signals: Signals) -> u8 { let sample = self.samples[self.position]; self.position += 1; if sample & RNW == 0 { mismatch(format!( "the core reads ${address:04X}; the chip wrote ${:02X}", sample & 0xFF )); } if (sample & SYNC != 0) != signals.sync { mismatch(format!( "SYNC is {}; the core's sync is {}", (sample & SYNC != 0) as u8, if signals.sync { "True" } else { "False" } )); } let data = (sample & 0xFF) as u8; let cycle = self.position - self.step_start; // The slot: the sequence, or the opcode (in its fetch cycle, the byte being fetched). let key = ( match self.slot { Some(kind) => Slot::Sequence(kind), None if cycle == 1 => Slot::Opcode(data), None => Slot::Opcode(signals.opcode), }, cycle, ); *self.report.reads.entry(key).or_default() += 1; if (IO_FIRST..IO_END).contains(&address) { return data; } if self.slot == Some("reset") && (3..=5).contains(&cycle) { return data; // S is unknown at reset: these three reads are at an unknown address } let index = (self.paging.bank(address, signals.pc) << 16) | address as usize; self.model.read(&mut self.report, key, index, address, data); data } fn write(&mut self, address: u16, value: u8, _: &mut Frame, signals: Signals) { let sample = self.samples[self.position]; self.position += 1; if sample & RNW != 0 { mismatch(format!( "the core writes ${address:04X}; the chip read ${:02X}", sample & 0xFF )); } if sample & SYNC != 0 { mismatch("SYNC is 1 in a write cycle".into()); } if (sample & 0xFF) as u8 != value { mismatch(format!( "the core writes ${value:02X} to ${address:04X}; the chip wrote ${:02X}", sample & 0xFF )); } if (IO_FIRST..IO_END).contains(&address) { self.paging.written(address, value); return; } let index = (self.paging.bank(address, signals.pc) << 16) | address as usize; self.model.write(index, value); } } /// Whether the sequence starting at `position` is an interrupt entry. /// /// Cycles 3, 4 and 5 are writes only in an interrupt entry and in `BRK` (and /// in a G65SC12's reset); `BRK` fetches `$00` and pushes P with B set. fn interrupt_ahead(samples: &[u16], position: usize) -> bool { if samples[position + 2] & RNW != 0 || samples[position + 3] & RNW != 0 || samples[position + 4] & RNW != 0 { return false; } !(samples[position] & 0xFF == 0x00 && samples[position + 4] & 0x10 != 0) } fn load_samples(path: &Path) -> Vec { let data = std::fs::read(path).unwrap_or_else(|e| { panic!( "{}: {e} (unpacked by the reference's scripts/run_capture.py or build_tools.py)", path.display() ) }); data.chunks_exact(2) .map(|pair| u16::from_le_bytes([pair[0], pair[1]])) .collect() } #[derive(Deserialize, Clone)] struct Start { start: usize, registers: HashMap, } /// Replay one capture through the machine's row and report. fn replay( machine: &str, capture: &str, row: Row, captures: &Path, starts: &HashMap, max_instructions: Option, ) -> Report { let raw = load_samples(&captures.join(format!("{machine}_{capture}.bin"))); let mut registers: HashMap = HashMap::new(); let at_reset = raw[0] & RST == 0; let (start, origin) = if at_reset { let mut start = 0; while raw[start] & RST == 0 { start += 1; } while raw[start] & SYNC == 0 { // the reset sequence is counted from its SYNC cycle start += 1; } (start, format!("the reset sequence at sample {start}")) } else { let found = starts .get(&format!("{machine}/{capture}")) .unwrap_or_else(|| { panic!("no start for {machine}/{capture}: run scripts/capture_starts.py") }); registers = found.registers.clone(); if raw[found.start] & SYNC == 0 { panic!( "sample {} is not an opcode fetch: the decoder's numbering?", found.start ); } ( found.start, format!("sample {}, registers from the capture decoder", found.start), ) }; // Drop the cycles the machine held the processor in (RDY low). let samples: Vec = raw[start..] .iter() .copied() .filter(|sample| sample & RDY != 0) .collect(); drop(raw); let mut adopted: Option<(u8, u8)> = None; loop { let (mut report, flags) = replay_once( machine, capture, row, &samples, ®isters, at_reset, adopted, max_instructions, ); report.start = origin.clone(); match flags { None => return report, Some((wrong, bits)) => { let (mask, known) = adopted.unwrap_or((0, 0)); adopted = Some((mask | wrong, known | bits)); } } } } #[allow(clippy::too_many_arguments)] fn replay_once( machine: &str, capture: &str, row: Row, samples: &[u16], registers: &HashMap, at_reset: bool, adopted: Option<(u8, u8)>, max_instructions: Option, ) -> (Report, Option<(u8, u8)>) { let report = Report { machine: machine.into(), capture: capture.into(), adopted, ..Report::default() }; let host = Replay { samples, position: 0, step_start: 0, slot: None, paging: Paging { master: machine == "master", romsel: 0, acccon: 0, }, model: Model::new(BANKS << 16), report, }; let mut cpu = Cmos65c02::new(row, host); for (name, value) in registers { match name.as_str() { "a" => cpu.a = *value as u8, "x" => cpu.x = *value as u8, "y" => cpu.y = *value as u8, "s" => cpu.s = *value as u8, "p" => cpu.p = *value as u8, "pc" => cpu.pc = *value, other => panic!("unknown register {other}"), } } if at_reset { cpu.frame.request_reset(); if samples[2] & RNW == 0 { // The part writes PCH, PCL and P at reset: what they were before is // unknown, so the capture's own bytes are taken (only the direction // of these three cycles is judged). cpu.pc = ((samples[2] & 0xFF) << 8) | (samples[3] & 0xFF); cpu.p = ((samples[4] & 0xEF) as u8) | 0x20; } } let (mask, bits) = adopted.unwrap_or((0, 0)); let mnemonics: Vec<&str> = opcodes_for(&row).iter().map(|entry| entry.2).collect(); let limit = samples.len() - 16; // an instruction is at most 8 cycles: stay clear of the end let mut flags_fix = None; let outcome: Result<(), String> = (|| { while cpu.bus.position < limit { if let Some(max) = max_instructions { if cpu.bus.report.instructions >= max { cpu.bus.report.ended = "instruction limit".into(); return Ok(()); } } cpu.bus.step_start = cpu.bus.position; let slot = if cpu.frame.reset_pending { Some("reset") } else if interrupt_ahead(cpu.bus.samples, cpu.bus.position) { cpu.frame.request_maskable_interrupt(); let mut kind = next_boundary(&cpu.capture_state()); if kind != BoundaryKind::Irq { cpu.frame.clear_maskable_interrupt(); cpu.frame.request_non_maskable_interrupt(); kind = next_boundary(&cpu.capture_state()); if kind != BoundaryKind::Nmi { // The slot stays the last step's, as the reference's does here. return Err(format!( "the capture shows an interrupt entry here; the core's poll takes \ none at this boundary (after opcode ${:02X})", cpu.opcode )); } } Some(kind.as_str()) } else { None }; cpu.bus.slot = slot; let cycles = match panic::catch_unwind(AssertUnwindSafe(|| cpu.step())) { Ok(cycles) => cycles as usize, Err(payload) => match payload.downcast::() { Ok(found) => return Err(found.0), Err(other) => panic::resume_unwind(other), }, }; let made = cpu.bus.position - cpu.bus.step_start; if cycles != made { return Err(format!("step() returned {cycles} for {made} callbacks")); } match slot { None => cpu.bus.report.instructions += 1, Some(kind) => { cpu.bus.report.count_interrupt(kind); if kind == "irq" { cpu.frame.clear_maskable_interrupt(); } else if kind == "reset" && mask != 0 { // The flags the chip held at reset, learnt on an earlier pass. cpu.p = (cpu.p & !mask) | bits; } } } } cpu.bus.report.ended = "end of capture".into(); Ok(()) })(); if let Err(text) = outcome { let host = &cpu.bus; let (position, step_start) = (host.position, host.step_start); let name = match host.slot { Some(kind) => kind.to_string(), None => format!("${:02X} {}", cpu.opcode, mnemonics[cpu.opcode as usize]), }; let context: Vec = host.samples [step_start.saturating_sub(8)..(step_start + 10).min(host.samples.len())] .iter() .map(|sample| { format!( "{:02X}{}{}", sample & 0xFF, if sample & RNW != 0 { "" } else { "w" }, if sample & SYNC != 0 { "S" } else { "" } ) }) .collect(); let message = format!( "instruction {}, cycle {} of {name} (PC ${:04X}): {text}; samples around: {}", host.report.instructions, position - step_start, cpu.pc, context.join(" ") ); // A push of P whose only differences are flags unknown at reset and not // yet learnt: restart with them. let pushes_p = (host.slot.is_none() && cpu.opcode == 0x08 && position - step_start == 3) || (matches!(host.slot, Some("irq") | Some("nmi")) && position - step_start == 5); if at_reset && pushes_p && host.samples[position - 1] & RNW == 0 { let pushed = (host.samples[position - 1] & 0xFF) as u8; let wrong = (pushed ^ cpu.p) & 0xCF; // bits 4 and 5 are not flags if wrong != 0 && wrong & !FLAGS_UNKNOWN_AT_RESET == 0 && wrong & mask == 0 { flags_fix = Some((wrong, pushed & wrong)); } } cpu.bus.report.mismatch = Some(message); cpu.bus.report.ended = "mismatch".into(); } let mut report = std::mem::take(&mut cpu.bus.report); report.cycles = cpu.bus.position; (report, flags_fix) } /// The host of Foot's data-only replay. struct FootReplay<'a> { data: &'a [u8], position: usize, step_start: usize, model: Model, report: Report, } impl Bus for FootReplay<'_> { fn read(&mut self, address: u16, _: &mut Frame, signals: Signals) -> u8 { let value = self.data[self.position]; self.position += 1; let cycle = self.position - self.step_start; let key = ( Slot::Opcode(if cycle == 1 { value } else { signals.opcode }), cycle, ); *self.report.reads.entry(key).or_default() += 1; if (FOOT_IO_FIRST..FOOT_IO_END).contains(&address) { return value; } self.model .read(&mut self.report, key, address as usize, address, value); value } fn write(&mut self, address: u16, value: u8, _: &mut Frame, _: Signals) { let captured = self.data[self.position]; self.position += 1; if captured != value { mismatch(format!( "the core writes ${value:02X} to ${address:04X}; the bus held ${captured:02X}" )); } self.model.write(address as usize, value); } } /// Replay Foot's capture (6502Decoder issue #10) through `row`: rung 4b. /// /// One byte per cycle: the data bus of a 65C02 with bit instructions running /// Dormann's 65C02 test on Foot's own board. There is no RnW and no SYNC, so /// only a written byte against the bus, and every read's byte against the /// memory model, can be compared. There are no interrupts in the capture. fn replay_data_only(row: Row, data: &[u8], max_instructions: Option) -> Report { let report = Report { machine: "foot".into(), capture: format!("dormann on {}", row.name), start: format!("byte {FOOT_START}, the code at the reset vector"), ..Report::default() }; let host = FootReplay { data, position: FOOT_START, step_start: FOOT_START, model: Model::new(0x10000), report, }; let mut cpu = Cmos65c02::new(row, host); cpu.pc = ((data[FOOT_START - 1] as u16) << 8) | data[FOOT_START - 2] as u16; let limit = data.len() - 16; let outcome: Result<(), String> = (|| { while cpu.bus.position < limit { if let Some(max) = max_instructions { if cpu.bus.report.instructions >= max { cpu.bus.report.ended = "instruction limit".into(); return Ok(()); } } cpu.bus.step_start = cpu.bus.position; let before = cpu.pc; match panic::catch_unwind(AssertUnwindSafe(|| cpu.step())) { Ok(_) => {} Err(payload) => match payload.downcast::() { Ok(found) => return Err(found.0), Err(other) => panic::resume_unwind(other), }, } cpu.bus.report.instructions += 1; if cpu.pc == before { cpu.bus.report.ended = format!("the program's trap at ${before:04X}"); return Ok(()); } } cpu.bus.report.ended = "end of capture".into(); Ok(()) })(); if let Err(text) = outcome { let host = &cpu.bus; let step_start = host.step_start; let context: Vec = host.data [step_start.saturating_sub(8)..(step_start + 10).min(host.data.len())] .iter() .map(|byte| format!("{byte:02X}")) .collect(); let message = format!( "instruction {}, cycle {} of opcode ${:02X} (PC ${:04X}): {text}; bytes around: {}", host.report.instructions, host.position - step_start, cpu.opcode, cpu.pc, context.join(" ") ); cpu.bus.report.mismatch = Some(message); cpu.bus.report.ended = "mismatch".into(); } let mut report = std::mem::take(&mut cpu.bus.report); report.cycles = cpu.bus.position - FOOT_START; report } /// 1234567 -> "1,234,567", as Python's `{:,}`. fn commas(value: u64) -> String { let text = value.to_string(); let mut out = String::new(); for (index, digit) in text.chars().enumerate() { if index > 0 && (text.len() - index) % 3 == 0 { out.push(','); } out.push(digit); } out } /// The reference's `format_report`, line for line. fn format_report(report: &Report, slots: usize) -> String { let interrupts: Vec = report .interrupts .iter() .map(|(kind, count)| format!("'{kind}': {count}")) .collect(); let mut lines = vec![ format!( "{}/{}: {} instructions, {} cycles, interrupts {{{}}}; ended: {}", report.machine, report.capture, commas(report.instructions), commas(report.cycles as u64), interrupts.join(", "), report.ended ), format!(" started at {}", report.start), ]; if let Some((mask, bits)) = report.adopted { lines.push(format!( " adopted: flags unknown at reset, mask ${mask:02X} = ${bits:02X} (from the chip's first push of P)" )); } if let Some(text) = &report.mismatch { lines.push(format!(" MISMATCH {text}")); } lines.push(format!( " reads that agreed with a known model byte: {}; that differed: {}; ROM addresses written to: {}", commas(report.model_agreed.values().sum()), commas(report.model_differences.values().sum()), commas(report.writes_not_kept) )); let mut differences: Vec<(&Key, &u64)> = report.model_differences.iter().collect(); differences.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0))); for (key, count) in differences.into_iter().take(slots) { let name = match key.0 { Slot::Sequence(kind) => kind.to_string(), Slot::Opcode(opcode) => format!("${opcode:02X}"), }; lines.push(format!( " model difference: {name} cycle {}: {} (agreed {}); first: {}", key.1, commas(*count), commas(report.model_agreed.get(key).copied().unwrap_or(0)), report.model_examples[key] )); } lines.join("\n") } fn main() { // A Mismatch payload is the replay's signal, caught around step(): keep it quiet. let default_hook = panic::take_hook(); panic::set_hook(Box::new(move |info| { if info.payload().downcast_ref::().is_none() { default_hook(info); } })); let mut args = std::env::args().skip(1); let mut positional: Vec = Vec::new(); let mut max_instructions = None; let mut jobs: usize = 4; while let Some(arg) = args.next() { if arg == "--max-instructions" { max_instructions = Some(args.next().expect("N").parse().expect("a number")); } else if arg == "--jobs" { jobs = args.next().expect("N").parse().expect("a number"); } else { positional.push(arg); } } if positional.len() < 3 { eprintln!("usage: capture CAPTURES_DIR STARTS_JSON FOOT_RAW [MACHINE [CAPTURE]] [--max-instructions N] [--jobs N]"); std::process::exit(2); } let captures = PathBuf::from(&positional[0]); let starts: HashMap = serde_json::from_str( &std::fs::read_to_string(&positional[1]) .expect("the starts file (scripts/capture_starts.py)"), ) .expect("parse the starts file"); let foot_path = PathBuf::from(&positional[2]); let only_machine = positional.get(3).cloned(); let only_capture = positional.get(4).cloned(); // Tasks in the reference's order: machines sorted (beebr65c02, foot, master). let mut tasks: Vec<(String, String)> = Vec::new(); for machine in ["beebr65c02", "foot", "master"] { if only_machine.as_deref().is_some_and(|m| m != machine) { continue; } let names: Vec = if machine == "foot" { FOOT_ROWS .iter() .map(|row| row.name.to_lowercase()) .collect() } else { MACHINES .iter() .find(|(name, _, _)| *name == machine) .unwrap() .2 .iter() .map(|c| c.to_string()) .collect() }; for capture in names { if only_capture.as_deref().is_some_and(|c| c != capture) { continue; } tasks.push((machine.to_string(), capture)); } } let foot = if tasks.iter().any(|(m, _)| m == "foot") { std::fs::read(&foot_path).unwrap_or_else(|e| panic!("{}: {e}", foot_path.display())) } else { Vec::new() }; // At most four replays at once (the machine is shared), printed in order. let results: Vec>> = tasks.iter().map(|_| std::sync::Mutex::new(None)).collect(); let next = std::sync::atomic::AtomicUsize::new(0); std::thread::scope(|scope| { for _ in 0..jobs.clamp(1, 4).min(tasks.len()) { scope.spawn(|| loop { let index = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); if index >= tasks.len() { break; } let (machine, capture) = &tasks[index]; let started = Instant::now(); let report = if machine == "foot" { let row = FOOT_ROWS .into_iter() .find(|row| row.name.to_lowercase() == *capture) .unwrap(); replay_data_only(row, &foot, max_instructions) } else { let row = MACHINES.iter().find(|(m, _, _)| m == machine).unwrap().1; replay(machine, capture, row, &captures, &starts, max_instructions) }; let seconds = started.elapsed().as_secs_f64(); *results[index].lock().unwrap() = Some(( report.ok(), format_report(&report, 40), seconds, report.cycles as u64, )); }); } }); let mut passed = true; for result in results { let (ok, text, seconds, cycles) = result.into_inner().unwrap().unwrap(); println!("{text}"); eprintln!( " {seconds:.1} s: {:.1} million cycles a second", cycles as f64 / seconds / 1e6 ); passed &= ok; } std::process::exit(if passed { 0 } else { 1 }); }