// SPDX-License-Identifier: MIT //! Run a scenario and write its boundary trace (the lockstep rung). //! //! trace SCENARIO.json [--out TRACE.jsonl] //! trace --tables (the handler and opcode tables, 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 spc700-python through its own //! `DebugSession`; 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 spc700::dispatch::HANDLERS; use spc700::harness::{Harness, Machine, Script, SELF_BRANCHES}; use spc700::opcodes::OPCODES; use spc700::trace::{instruction_bytes, next_boundary, Access, BoundaryKind, StepRecord}; use spc700::{Bus, CpuState, Signals, Spc700}; #[derive(Deserialize)] struct Block { address: u16, hex: String, } /// Bytes from a 32-bit xorshift, one byte per step (as 65816-rust's scenarios). #[derive(Deserialize)] struct Fill { seed: u32, } #[derive(Deserialize, Default)] struct Registers { a: Option, x: Option, y: Option, sp: Option, pc: Option, psw: Option, } #[derive(Deserialize, Clone)] struct Event { step: u64, action: String, /// For `jump`: the new PC and PSW (the core runs again). #[serde(default)] pc: u16, #[serde(default)] psw: u8, } #[derive(Deserialize)] struct Program { file: String, org: u16, /// Play spctest's S-CPU side for its first program (`run_spctest`'s setup). #[serde(default)] spctest: bool, } #[derive(Deserialize)] struct Scenario { #[serde(default)] memory: Vec, #[serde(default)] fill: Option, #[serde(default)] program: Option, #[serde(default)] registers: Registers, steps: u64, #[serde(default)] events: Vec, #[serde(default = "default_true")] accesses: bool, /// With `program`: stop where the harness's `run` stops. #[serde(default)] until_stop: bool, } fn default_true() -> bool { true } fn fill_random(memory: &mut [u8], seed: u32) { let mut state = seed | 1; for byte in memory.iter_mut() { state ^= state << 13; state ^= state >> 17; state ^= state << 5; *byte = (state >> 24) as u8; } } /// Flat 64 KiB memory, every cycle logged. struct Flat { memory: Vec, log: Vec, } impl Bus for Flat { fn read(&mut self, address: u16, signals: Signals) -> u8 { let value = self.memory[address as usize]; self.log.push(Access::Read(address, value, signals.dummy)); value } fn write(&mut self, address: u16, value: u8, _: Signals) { self.log.push(Access::Write(address, value)); self.memory[address as usize] = value; } fn idle(&mut self, _: Signals) { self.log.push(Access::Internal); } } /// The harness's machine with the session's tracking around it. struct Tracked { machine: Machine, log: Vec, } impl Bus for Tracked { fn read(&mut self, address: u16, signals: Signals) -> u8 { let value = self.machine.read(address, signals); self.log.push(Access::Read(address, value, signals.dummy)); value } fn write(&mut self, address: u16, value: u8, signals: Signals) { self.log.push(Access::Write(address, value)); self.machine.write(address, value, signals); } fn idle(&mut self, signals: Signals) { self.log.push(Access::Internal); self.machine.idle(signals); } } fn set_registers(cpu: &mut Spc700, registers: &Registers) { let mut state: CpuState = cpu.capture_state(); if let Some(v) = registers.a { state.a = v; } if let Some(v) = registers.x { state.x = v; } if let Some(v) = registers.y { state.y = v; } if let Some(v) = registers.sp { state.sp = v; } if let Some(v) = registers.pc { state.pc = v; } if let Some(v) = registers.psw { state.psw = v; } cpu.restore_state(&state); } #[allow(clippy::too_many_arguments)] fn line( sequence: u64, kind: BoundaryKind, cycles: u32, instruction: Option<(u16, Vec)>, before: CpuState, after: 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, out: &mut dyn Write) { let mut memory = vec![0u8; 0x10000]; if let Some(fill) = &scenario.fill { fill_random(&mut memory, fill.seed); } for block in &scenario.memory { let bytes = &block.hex; for (offset, i) in (0..bytes.len()).step_by(2).enumerate() { memory[(block.address as usize + offset) & 0xFFFF] = u8::from_str_radix(&bytes[i..i + 2], 16).unwrap(); } } let mut between: HashMap> = HashMap::new(); for event in &scenario.events { between.entry(event.step).or_default().push(event.clone()); } let mut cpu = Spc700::new(Flat { memory, log: Vec::new(), }); set_registers(&mut cpu, &scenario.registers); for sequence in 0..scenario.steps { for event in between.get(&sequence).into_iter().flatten() { match event.action.as_str() { "reset" => cpu.reset(), "jump" => { let state = CpuState { pc: event.pc, psw: event.psw, stopped: false, ..cpu.capture_state() }; cpu.restore_state(&state); } other => panic!("unknown action {other}"), } } let before = cpu.capture_state(); let kind = next_boundary(&before); let instruction = (kind == BoundaryKind::Instruction).then(|| { let memory = &cpu.bus.memory; ( before.pc, instruction_bytes(&mut |a| memory[a as usize], before.pc), ) }); cpu.bus.log.clear(); let cycles = cpu.step(); let after = cpu.capture_state(); let accesses = scenario.accesses.then(|| cpu.bus.log.clone()); writeln!( out, "{}", line(sequence, kind, cycles, instruction, before, after, accesses) ) .unwrap(); } } fn run_program(scenario: &Scenario, program: &Program, base: &Path, out: &mut dyn Write) { let path = Path::new(&program.file); let path = if path.is_absolute() { path.to_path_buf() } else { base.join(path) }; let data = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); let mut harness = Harness::new(None); harness.load_file(&data, program.org).expect("a program"); if program.spctest { let machine = harness.machine(); machine.ports_in[1] = 1; machine.ports_in[2] = 0xFF; // one less than test 0 machine.ports_in[3] = 0xFF; machine.script = Script::SpcTest { tests: Vec::new(), failing: Vec::new(), }; } set_registers(&mut harness.cpu, &scenario.registers); // Move the machine behind the tracking wrapper (the session wraps the bus). let Harness { cpu } = harness; let state = cpu.capture_state(); let (opcode, cycle) = (cpu.opcode, cpu.cycle); let mut cpu = Spc700::new(Tracked { machine: cpu.bus, log: Vec::new(), }); cpu.restore_state(&state); cpu.opcode = opcode; cpu.cycle = cycle; for sequence in 0..scenario.steps { if scenario.until_stop && (cpu.bus.machine.finished || cpu.stopped) { break; } let before = cpu.capture_state(); let kind = next_boundary(&before); let instruction = (kind == BoundaryKind::Instruction).then(|| { let machine = &cpu.bus.machine; ( before.pc, instruction_bytes(&mut |a| machine.peek(a), before.pc), ) }); cpu.bus.log.clear(); let cycles = cpu.step(); let after = cpu.capture_state(); let accesses = scenario.accesses.then(|| cpu.bus.log.clone()); writeln!( out, "{}", line(sequence, kind, cycles, instruction, before, after, accesses) ) .unwrap(); if scenario.until_stop && cpu.pc == before.pc && SELF_BRANCHES.contains(&cpu.opcode) { break; } } } fn main() { let args: Vec = std::env::args().skip(1).collect(); if args.first().map(String::as_str) == Some("--tables") { let handlers: Vec<_> = HANDLERS.iter().map(|op| json!(op.name())).collect(); let opcodes: Vec<_> = OPCODES .iter() .map(|o| json!([o.mnemonic, o.operands, o.length, o.cycles, o.flags])) .collect(); println!("{}", json!({"handlers": handlers, "opcodes": opcodes})); 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.program { Some(program) => run_program(&scenario, program, base, &mut out), None => run_flat(&scenario, &mut out), } out.flush().unwrap(); }