sgx_trace/
sgx-trace.rs

1//! The lockstep gate's Rust side: run a card on the SuperGrafx and write one line a frame, the
2//! same lines `scripts/sgx_trace.py` writes for the reference.
3//!
4//!     sgx-trace IMAGE --frames N [--mode sgx|compat|base] [--vpc NAME=VALUE]... [--compat-at N]
5//!               [options of pcengine_rust::trace::Setup] [--detail FRAME] --out FILE
6//!
7//! With `--detail FRAME` only the bus cycles of the frame whose line would start with FRAME are
8//! written, one a line (`r ADDRESS VALUE MCLK`, `w ...`, `i MCLK`).
9
10use std::io::Write;
11
12use pcengine_rust::trace::{detail_lines, frame_line};
13use supergrafx_rust::trace::SgxSetup;
14
15fn run() -> Result<(), String> {
16    let args: Vec<String> = std::env::args().skip(1).collect();
17    let setup = SgxSetup::parse(&args)?;
18    if let Some(unknown) = setup.rest.first() {
19        return Err(format!("unknown argument {unknown}"));
20    }
21    let mut system = setup.build()?;
22    system.board_mut().bus_log = Some(Vec::new());
23    let mut out: Box<dyn Write> = match &setup.base.out {
24        Some(path) => Box::new(std::io::BufWriter::new(
25            std::fs::File::create(path).map_err(|error| format!("{path}: {error}"))?,
26        )),
27        None => Box::new(std::io::stdout().lock()),
28    };
29    let io = |error: std::io::Error| error.to_string();
30    for _ in 0..setup.base.frames {
31        setup.before_frame(&mut system);
32        let wanted = setup.base.detail.map(|frame| frame == system.frame() + 1);
33        if wanted == Some(true) {
34            system.board_mut().bus_detail = Some(Vec::new());
35        }
36        system.run_frame();
37        let line = frame_line(&mut system);
38        match wanted {
39            None => writeln!(out, "{line}").map_err(io)?,
40            Some(true) => {
41                for cycle in detail_lines(&mut system) {
42                    writeln!(out, "{cycle}").map_err(io)?;
43                }
44                break;
45            }
46            Some(false) => {}
47        }
48    }
49    out.flush().map_err(io)
50}
51
52fn main() {
53    if let Err(error) = run() {
54        eprintln!("sgx-trace: {error}");
55        std::process::exit(1);
56    }
57}