// SPDX-License-Identifier: MIT //! Run a scenario and write its boundary trace (the lockstep rungs). //! //! trace SCENARIO.json [--out TRACE.jsonl] //! trace --tables (the opcode table, as JSON, for check_tables.py) //! //! The scenario format (`conformance/README.md`) is read the same way by //! `scripts/reference_trace.py`, which runs it on 65816-python through its own //! `W65C816Session`; the two traces are compared byte for byte, and on a //! difference with the reference's `first_trace_divergence`. use std::collections::HashMap; use std::io::{BufWriter, Write}; use std::path::{Path, PathBuf}; use serde::Deserialize; use serde_json::json; use w65c816::dispatch::{operand_size, OPCODES}; use w65c816::harness::{load_rom, Harness, Hooks, Machine}; use w65c816::trace::{next_boundary, Access, BoundaryKind, StepRecord}; use w65c816::{request_abort, Bus, Frame, Signals, W65C816}; #[derive(Deserialize)] struct Block { address: u32, #[serde(default)] hex: Option, #[serde(default)] file: Option, #[serde(default)] length: Option, } /// Bytes from the scenario's generator (`fill_random` in make_scenarios.py /// and reference_trace.py): a 32-bit xorshift, one byte per step. #[derive(Deserialize)] struct Fill { seed: u32, address: u32, length: usize, } #[derive(Deserialize, Default)] struct Registers { a: Option, x: Option, y: Option, s: Option, d: Option, dbr: Option, pbr: Option, pc: Option, p: Option, e: Option, } #[derive(Deserialize, Clone)] struct Event { #[serde(default)] step: Option, #[serde(default)] access: Option, action: String, } #[derive(Deserialize, Clone)] struct Stall { access: u64, halted: u32, #[serde(default)] during: Vec, } #[derive(Deserialize, Clone)] struct HaltedEvent { cycle: u32, action: String, } #[derive(Deserialize)] struct Scenario { #[serde(default)] memory: Vec, #[serde(default)] fill: Vec, /// A cartridge to run in the harness instead of flat memory. #[serde(default)] rom: Option, #[serde(default)] registers: Registers, #[serde(default)] reset: bool, steps: u64, #[serde(default)] events: Vec, #[serde(default)] stalls: Vec, #[serde(default = "default_true")] accesses: bool, /// With `rom`: stop where the harness's `run` stops (STP, or a jump to self). #[serde(default)] until_spin: bool, /// With `until_spin`: resets to request at an STP before stopping. #[serde(default)] reset_on_stop: u32, } fn default_true() -> bool { true } fn fill_random(memory: &mut [u8], fill: &Fill) { let mut state = fill.seed | 1; for offset in 0..fill.length { state ^= state << 13; state ^= state >> 17; state ^= state << 5; memory[(fill.address as usize + offset) & 0xFFFFFF] = (state >> 24) as u8; } } fn act(frame: &mut Frame, action: &str) { match action { "irq" => frame.request_maskable_interrupt(), "irq_clear" => frame.clear_maskable_interrupt(), "nmi" => frame.request_non_maskable_interrupt(), "nmi_clear" => frame.clear_non_maskable_interrupt(), "abort" => request_abort(frame), "reset" => frame.request_reset(), other => panic!("unknown action {other}"), } } /// The scenario's in-cycle requests and RDY stalls, and the access log. #[derive(Default)] struct Events { count: u64, log: Option>, during: HashMap>, stalls: HashMap, } impl Events { /// The in-cycle requests and the stall of access `index`, before it completes. fn cycle(&mut self, frame: &mut Frame) { let index = self.count; self.count += 1; if let Some(actions) = self.during.get(&index) { for action in actions { act(frame, action); } } if let Some(stall) = self.stalls.get(&index) { frame.note_stall(); for cycle in 1..=stall.halted { for event in stall.during.iter().filter(|e| e.cycle == cycle) { act(frame, &event.action); } frame.note_stall(); } } } fn note(&mut self, direction: char, kind: u8, address: u32, value: u8) { if let Some(log) = &mut self.log { log.push(Access { direction, kind, address, value, }); } } } struct Flat { memory: Vec, events: Events, } impl Bus for Flat { fn read(&mut self, address: u32, frame: &mut Frame, signals: Signals) -> u8 { self.events.cycle(frame); let value = self.memory[address as usize]; self.events.note('r', signals.kind, address, value); value } fn write(&mut self, address: u32, value: u8, frame: &mut Frame, signals: Signals) { self.events.cycle(frame); self.events.note('w', signals.kind, address, value); self.memory[address as usize] = value; } fn idle(&mut self, address: u32, frame: &mut Frame, signals: Signals) { self.events.cycle(frame); self.events.note('i', signals.kind, address, 0); } } /// The harness with the session's tracking wrapped around its bus. struct Tracked { log: Vec, } impl Hooks for Tracked { fn read_byte( machine: &mut Machine, address: u32, frame: &mut Frame, signals: Signals, ) -> u8 { let value = machine.base_read_byte(address, frame); machine.hooks.log.push(Access { direction: 'r', kind: signals.kind, address, value, }); value } fn write_byte( machine: &mut Machine, address: u32, value: u8, frame: &mut Frame, signals: Signals, ) { machine.hooks.log.push(Access { direction: 'w', kind: signals.kind, address, value, }); machine.base_write_byte(address, value, frame); } fn idle(machine: &mut Machine, address: u32, frame: &mut Frame, signals: Signals) { machine.hooks.log.push(Access { direction: 'i', kind: signals.kind, address, value: 0, }); Self::tick(machine, frame); } } fn instruction_bytes(peek: &mut dyn FnMut(u32) -> u8, address: u32, m: bool, x: bool) -> Vec { let bank = address & 0xFF0000; let opcode = peek(address); let size = operand_size(opcode, m, x); let mut data = vec![opcode]; for n in 1..=size as u32 { data.push(peek(bank | (address + n) & 0xFFFF)); } data } fn set_registers(cpu: &mut W65C816, registers: &Registers) { // In the reference's attribute order: a x y s d dbr pbr pc p e. if let Some(v) = registers.a { cpu.a = v; } if let Some(v) = registers.x { cpu.x = v; } if let Some(v) = registers.y { cpu.y = v; } if let Some(v) = registers.s { cpu.s = v; } if let Some(v) = registers.d { cpu.d = v; } if let Some(v) = registers.dbr { cpu.dbr = v; } if let Some(v) = registers.pbr { cpu.pbr = v; } if let Some(v) = registers.pc { cpu.pc = v; } if let Some(v) = registers.p { cpu.p = v; } if let Some(v) = registers.e { cpu.e = v; } } fn record( sequence: u64, kind: BoundaryKind, cycles: u32, instruction: Option<(u32, Vec)>, before: w65c816::CpuState, after: w65c816::CpuState, accesses: Option>, ) -> String { let record = StepRecord { sequence, kind, cycles, instruction, before, after, accesses, }; serde_json::to_string(&record.to_value()).unwrap() } fn run_flat(scenario: &Scenario, base: &Path, out: &mut dyn Write) { let mut memory = vec![0u8; 1 << 24]; for fill in &scenario.fill { fill_random(&mut memory, fill); } for block in &scenario.memory { let mut data = match (&block.hex, &block.file) { (Some(hex), _) => (0..hex.len()) .step_by(2) .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap()) .collect::>(), (None, Some(file)) => { let path = Path::new(file); let path = if path.is_absolute() { path.to_path_buf() } else { base.join(path) }; std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())) } (None, None) => panic!("a memory block needs hex or file"), }; if let Some(length) = block.length { data.truncate(length); } for (offset, byte) in data.into_iter().enumerate() { memory[(block.address as usize + offset) & 0xFFFFFF] = byte; } } let mut events = Events::default(); let mut between: HashMap> = HashMap::new(); for event in &scenario.events { match (event.step, event.access) { (Some(step), _) => between.entry(step).or_default().push(event.action.clone()), (None, Some(access)) => events .during .entry(access) .or_default() .push(event.action.clone()), (None, None) => panic!("an event needs step or access"), } } for stall in &scenario.stalls { events.stalls.insert(stall.access, stall.clone()); } events.log = scenario.accesses.then(Vec::new); let mut cpu = W65C816::new(Flat { memory, events }); set_registers(&mut cpu, &scenario.registers); if scenario.reset { cpu.frame.request_reset(); } for sequence in 0..scenario.steps { if let Some(actions) = between.get(&sequence) { for action in actions { act(&mut cpu.frame, action); } } let before = cpu.capture_state(); let kind = next_boundary(&before); let instruction = (kind == BoundaryKind::Instruction).then(|| { let memory = &cpu.bus.memory; let data = instruction_bytes( &mut |a| memory[a as usize], before.address(), before.p & 0x20 != 0, before.p & 0x10 != 0, ); (before.address(), data) }); if let Some(log) = &mut cpu.bus.events.log { log.clear(); } let cycles = cpu.step(); let after = cpu.capture_state(); let accesses = cpu.bus.events.log.clone(); writeln!( out, "{}", record(sequence, kind, cycles, instruction, before, after, accesses) ) .unwrap(); } } fn run_rom(scenario: &Scenario, rom: &Path, out: &mut dyn Write) { let rom = load_rom(rom).unwrap_or_else(|e| panic!("{}: {e}", rom.display())); let mut harness = Harness::with_hooks(&rom, None, 30_000, Tracked { log: Vec::new() }); let cpu = &mut harness.cpu; set_registers(cpu, &scenario.registers); let mut resets = scenario.reset_on_stop; for sequence in 0..scenario.steps { let before = cpu.capture_state(); let kind = next_boundary(&before); let instruction = (kind == BoundaryKind::Instruction).then(|| { let machine = &mut cpu.bus; let data = instruction_bytes( &mut |a| machine.inspect(a), before.address(), before.p & 0x20 != 0, before.p & 0x10 != 0, ); (before.address(), data) }); cpu.bus.hooks.log.clear(); let cycles = cpu.step(); let after = cpu.capture_state(); let accesses = scenario.accesses.then(|| cpu.bus.hooks.log.clone()); writeln!( out, "{}", record(sequence, kind, cycles, instruction, before, after, accesses) ) .unwrap(); if scenario.until_spin { // The harness's run's stop conditions, in its order; rung 3 // resets CPUMSC once after its STP. if cpu.stopped { if resets > 0 { resets -= 1; cpu.frame.request_reset(); continue; } break; } let address = before.address(); if after.address() == address && w65c816::harness::SPIN_OPCODES.contains(&cpu.bus.peek(address)) { break; } } } } fn main() { let args: Vec = std::env::args().skip(1).collect(); if args.first().map(String::as_str) == Some("--tables") { let table: Vec<_> = OPCODES .iter() .map(|(op, mode)| json!([op.name(), mode.map(|m| m.name())])) .collect(); println!("{}", serde_json::to_string(&table).unwrap()); return; } let mut scenario_path = None; let mut out_path: Option = None; let mut index = 0; while index < args.len() { if args[index] == "--out" { index += 1; out_path = Some(PathBuf::from(&args[index])); } else { scenario_path = Some(PathBuf::from(&args[index])); } index += 1; } let scenario_path = scenario_path.expect("usage: trace SCENARIO.json [--out TRACE.jsonl]"); let text = std::fs::read_to_string(&scenario_path).expect("scenario"); let scenario: Scenario = serde_json::from_str(&text).expect("scenario JSON"); let base = scenario_path.parent().unwrap_or(Path::new(".")); let mut out: Box = match out_path { Some(path) => Box::new(BufWriter::new(std::fs::File::create(path).expect("--out"))), None => Box::new(BufWriter::new(std::io::stdout())), }; match &scenario.rom { Some(rom) => { let rom = Path::new(rom); let rom = if rom.is_absolute() { rom.to_path_buf() } else { base.join(rom) }; run_rom(&scenario, &rom, &mut out); } None => run_flat(&scenario, base, &mut out), } out.flush().unwrap(); }