// SPDX-License-Identifier: MIT //! Run a lockstep scenario and write its slice trace (this crate's half of rungs 4 and 5; the //! reference's half is scripts/reference_trace.py, which writes the same lines). //! //! ```text //! arm7-trace SCENARIO.json [--out TRACE] [--detail FROM TO] //! ``` //! //! A scenario (scripts/make_scenarios.py) is a test ROM in the minimal harness //! (`"kind": "rom"`) or random memory with a random starting state and the IRQ and FIQ lines //! changed between instructions (`"kind": "fuzz"`). Each line covers `slice` instructions: //! //! ```text //! STEPS CYCLES BUS_CRC STATE_CRC W0 ... W39 //! ``` //! //! `STEPS` and `CYCLES` are counted from the start; `BUS_CRC` is the CRC-32 of every bus //! callback in the slice, each packed as `, detail: bool, lines: Vec, } impl Log { fn record(&mut self, kind: u8, size: u8, address: u32, value: u32, access: u32) { self.bus.push(kind); self.bus.push(size); self.bus.extend_from_slice(&address.to_le_bytes()); self.bus.extend_from_slice(&value.to_le_bytes()); self.bus.extend_from_slice(&access.to_le_bytes()); if self.detail { self.lines.push(format!( " {kind} {size} {address:08x} {value:08x} {access}" )); } } } /// Flat memory of a power-of-two size, mirrored through the whole address space; like the /// harness it ignores the low address bits a width does not use. struct FuzzBus { memory: Vec, mask: u32, log: Rc>, } impl Bus for FuzzBus { fn read(&mut self, address: u32, width: u32, access: u32) -> u32 { let offset = ((address & !(width / 8 - 1)) & self.mask) as usize; let mut value = 0u32; for byte in (0..(width / 8) as usize).rev() { value = value << 8 | self.memory[offset + byte] as u32; } let kind = if access & CODE != 0 { 0 } else { 1 }; self.log .borrow_mut() .record(kind, (width / 8) as u8, address, value, access); value } fn write(&mut self, address: u32, width: u32, value: u32, access: u32) { let offset = ((address & !(width / 8 - 1)) & self.mask) as usize; for byte in 0..(width / 8) as usize { self.memory[offset + byte] = (value >> (8 * byte)) as u8; } self.log .borrow_mut() .record(2, (width / 8) as u8, address, value, access); } fn idle(&mut self, address: u32, coprocessor_cycle: bool) { self.log .borrow_mut() .record(3, 0, address, 0, coprocessor_cycle as u32); } } fn state_bytes(cpu: &ARM7TDMI, cycles: u32, out: &mut Vec) -> [u32; 40] { out.extend_from_slice(&cycles.to_le_bytes()); let words = cpu.capture_state().to_sst(); for word in words { out.extend_from_slice(&word.to_le_bytes()); } out.push(cpu.irq_masked as u8); out.push(cpu.fiq_masked as u8); out.push(cpu.glitch_next as u8); words } fn words_hex(words: &[u32; 40]) -> String { words .iter() .map(|w| format!("{w:08x}")) .collect::>() .join(" ") } fn u32s(value: &serde_json::Value) -> Vec { value .as_array() .expect("a list") .iter() .map(|v| v.as_u64().expect("a number") as u32) .collect() } fn expand(path: &str) -> PathBuf { let roms = std::env::var("TEST_ROMS").unwrap_or_default(); PathBuf::from(path.replace("$TEST_ROMS", &roms)) } struct Writer { out: Box, detail: Option<(u64, u64)>, } impl Writer { fn in_detail(&self, step: u64) -> bool { matches!(self.detail, Some((from, to)) if step >= from && step < to) } } /// The stepping loop both kinds share: one line per slice (or detail lines). struct Slicer { slice: u64, steps: u64, cycles: u64, states: Vec, in_slice: u64, } impl Slicer { fn after_step( &mut self, cpu: &ARM7TDMI, cycles: u32, log: &Rc>, w: &mut Writer, ) { self.steps += 1; self.cycles += cycles as u64; self.in_slice += 1; let words = state_bytes(cpu, cycles, &mut self.states); if w.detail.is_some() { let mut log = log.borrow_mut(); if w.in_detail(self.steps - 1) { for line in log.lines.drain(..) { writeln!(w.out, "{line}").unwrap(); } writeln!( w.out, "step {} cycles {} {}", self.steps, cycles, words_hex(&words) ) .unwrap(); } log.lines.clear(); log.detail = w.in_detail(self.steps); } if self.in_slice == self.slice { self.flush(&words, log, w); } } fn flush(&mut self, words: &[u32; 40], log: &Rc>, w: &mut Writer) { let bus = crc32(0, &log.borrow().bus); let state = crc32(0, &self.states); if w.detail.is_none() { writeln!( w.out, "{} {} {bus:08x} {state:08x} {}", self.steps, self.cycles, words_hex(words) ) .unwrap(); } log.borrow_mut().bus.clear(); self.states.clear(); self.in_slice = 0; } } fn run_rom(scenario: &serde_json::Value, w: &mut Writer) { let rom = std::fs::read(expand(scenario["rom"].as_str().unwrap())).expect("the ROM"); let slice = scenario["slice"].as_u64().unwrap_or(1); let max_steps = scenario["max_steps"].as_u64().unwrap_or(1_000_000); let log = Rc::new(RefCell::new(Log { detail: w.in_detail(0), ..Log::default() })); let sink = Rc::clone(&log); let observer: Observer = Box::new(move |kind, address, width, access, value| { let code = match kind { "read" if access & CODE != 0 => 0, "read" => 1, "write" => 2, _ => 3, }; sink.borrow_mut() .record(code, (width / 8) as u8, address, value, access); }); let mut harness = Harness::new(&rom, Some(observer)); { let bus = crc32(0, &log.borrow().bus); log.borrow_mut().bus.clear(); log.borrow_mut().lines.clear(); writeln!( w.out, "start {} {bus:08x} {}", harness.cycles(), words_hex(&harness.cpu.capture_state().to_sst()) ) .unwrap(); } let mut slicer = Slicer { slice, steps: 0, cycles: 0, states: Vec::new(), in_slice: 0, }; let end; loop { if harness.at_branch_to_self() { end = format!( "end branch-to-self r12={} cycles={}", harness.cpu.r[12], harness.cycles() ); break; } if slicer.steps >= max_steps { end = format!("end max-steps cycles={}", harness.cycles()); break; } let cycles = match harness.step() { Ok(cycles) => cycles, Err(error) => { end = format!( "end bios r12={} cycles={} {}", error.r12, harness.cycles(), error.message ); break; } }; slicer.after_step(&harness.cpu, cycles, &log, w); } if slicer.in_slice != 0 { let words = harness.cpu.capture_state().to_sst(); slicer.flush(&words, &log, w); } writeln!(w.out, "{end}").unwrap(); } fn run_fuzz(scenario: &serde_json::Value, base: &Path, w: &mut Writer) { let memory = std::fs::read(base.join(scenario["memory"].as_str().unwrap())).expect("the memory image"); let mask = scenario["mask"].as_u64().unwrap() as u32; let slice = scenario["slice"].as_u64().unwrap_or(16); let steps = scenario["steps"].as_u64().unwrap(); let log = Rc::new(RefCell::new(Log { detail: w.in_detail(0), ..Log::default() })); let mut cpu = ARM7TDMI::new(FuzzBus { memory, mask, log: Rc::clone(&log), }); let s = &scenario["state"]; let mut state = CPUState::default(); state.registers.copy_from_slice(&u32s(&s["registers"])); for (bank, values) in s["banks"].as_array().unwrap().iter().enumerate() { state.banks[bank].copy_from_slice(&u32s(values)); } state.cpsr = s["cpsr"].as_u64().unwrap() as u32; state.spsr.copy_from_slice(&u32s(&s["spsr"])); state.pipeline.copy_from_slice(&u32s(&s["pipeline"])); state.next_fetch_seq = s["next_fetch_seq"].as_bool().unwrap(); cpu.restore_state(&state); let lines: Vec> = scenario["lines"] .as_array() .unwrap() .iter() .map(u32s) .collect(); let mut next_line = 0; let mut slicer = Slicer { slice, steps: 0, cycles: 0, states: Vec::new(), in_slice: 0, }; while slicer.steps < steps { while next_line < lines.len() && lines[next_line][0] as u64 == slicer.steps { cpu.irq = lines[next_line][1] != 0; cpu.fiq = lines[next_line][2] != 0; next_line += 1; } // A Thumb step with an ARM word in the pipeline (MSR set T) indexes past the Thumb // table, in the reference (IndexError) as here (a panic): reported upstream // (docs/status.md "Reported to the reference"); both sides must stop here alike. let stepped = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| cpu.step())); let Ok(cycles) = stepped else { writeln!( w.out, "end crash steps={} cycles={}", slicer.steps, slicer.cycles ) .unwrap(); return; }; slicer.after_step(&cpu, cycles, &log, w); } if slicer.in_slice != 0 { let words = cpu.capture_state().to_sst(); slicer.flush(&words, &log, w); } writeln!(w.out, "end steps={} cycles={}", slicer.steps, slicer.cycles).unwrap(); } fn main() { let mut args = std::env::args().skip(1); let path = PathBuf::from( args.next() .expect("usage: arm7-trace SCENARIO.json [--out TRACE] [--detail FROM TO]"), ); let mut out: Option = None; let mut detail = None; while let Some(arg) = args.next() { match arg.as_str() { "--out" => out = args.next().map(PathBuf::from), "--detail" => { let from = args.next().unwrap().parse().unwrap(); let to = args.next().unwrap().parse().unwrap(); detail = Some((from, to)); } other => panic!("unknown argument {other}"), } } std::panic::set_hook(Box::new(|_| {})); // a crash is a trace line, not a message let scenario: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&path).expect("the scenario")).expect("JSON"); let stream: Box = match out { Some(p) => Box::new(BufWriter::new( File::create(p).expect("cannot create the trace"), )), None => Box::new(BufWriter::new(std::io::stdout())), }; let mut w = Writer { out: stream, detail, }; match scenario["kind"].as_str() { Some("rom") => run_rom(&scenario, &mut w), Some("fuzz") => run_fuzz(&scenario, path.parent().unwrap(), &mut w), other => panic!("unknown scenario kind {other:?}"), } w.out.flush().unwrap(); }