huc6280/
trace.rs

1//! Boundary traces in the reference's version 1 JSON Lines schema
2//! (`trace.py` and the parts of `debug.py` a trace needs; 6502-python
3//! `docs/trace-schema.md`).
4//!
5//! One JSON object per boundary: `kind` one of [`BoundaryKind`]'s values,
6//! `before` and `after` every field of [`CpuState`], `instruction.address`
7//! the 16-bit logical PC and `instruction.data` the instruction's bytes (no
8//! mnemonic: the reference disassembles the bytes itself), and `accesses`
9//! `[kind, address, value]` with kinds `"r"`, `"w"`, `"d"` (a dummy read,
10//! value 0) and `"i"` (an internal cycle, recorded at address 0, value 0)
11//! and 21-bit physical addresses, one per cycle. The reference's reader,
12//! `read_trace`, and `first_trace_divergence` compare a trace written here
13//! with one its `HuC6280Session` wrote. Only writing is transcribed;
14//! comparing is the reference's job.
15
16use serde_json::{json, Map, Value};
17
18use crate::core::I;
19use crate::dispatch::OPCODES;
20use crate::state::CpuState;
21
22pub const TRACE_SCHEMA_VERSION: u32 = 1;
23
24/// Kind of work performed by one `HuC6280::step()` call.
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum BoundaryKind {
27    Instruction,
28    Reset,
29    Nmi,
30    Irq1,
31    Irq2,
32    Tiq,
33}
34
35impl BoundaryKind {
36    pub const fn as_str(self) -> &'static str {
37        match self {
38            BoundaryKind::Instruction => "instruction",
39            BoundaryKind::Reset => "reset",
40            BoundaryKind::Nmi => "nmi",
41            BoundaryKind::Irq1 => "irq1",
42            BoundaryKind::Irq2 => "irq2",
43            BoundaryKind::Tiq => "tiq",
44        }
45    }
46}
47
48/// What the next `step()` will do, decided as the reference's
49/// `debug.next_boundary` decides it from a state.
50pub fn next_boundary(state: &CpuState) -> BoundaryKind {
51    if state.reset_pending {
52        return BoundaryKind::Reset;
53    }
54    if state.skipped_poll {
55        return BoundaryKind::Instruction;
56    }
57    let nmi = state
58        .polled_non_maskable_interrupt
59        .unwrap_or(state.non_maskable_interrupt_pending);
60    if nmi {
61        return BoundaryKind::Nmi;
62    }
63    let irq = state
64        .polled_maskable_interrupt
65        .unwrap_or(state.maskable_interrupt_pending);
66    let masked = state.polled_i.unwrap_or(state.p & I != 0);
67    if irq && !masked {
68        // The vector is chosen from the lines the poll saw, in priority order
69        // (HW HB-13). The switches are not state: this is the defaults'
70        // decision (irq_poll_cycle SecondToLast, vanished_interrupt Mesen2:
71        // the timer must still be asserted, and with no source left an
72        // instruction runs; C18, issue 0005).
73        let enabled = !state.irq_disable & 7;
74        let live = ((state.tiq as u8) << 2 | (state.irq1 as u8) << 1 | state.irq2 as u8) & enabled;
75        let polled = match state.polled_irq_lines {
76            None => live,
77            Some(lines) => lines & enabled,
78        };
79        if polled & live & 4 != 0 {
80            return BoundaryKind::Tiq;
81        }
82        if polled & 2 != 0 {
83            return BoundaryKind::Irq1;
84        }
85        if polled & 1 != 0 {
86            return BoundaryKind::Irq2;
87        }
88    }
89    BoundaryKind::Instruction
90}
91
92/// How many bytes the instruction with this opcode occupies (the
93/// reference's `FORM_BYTES` by its form).
94pub fn instruction_length(opcode: u8) -> usize {
95    OPCODES[opcode as usize].3.bytes()
96}
97
98/// One cycle as the trace records it.
99#[derive(Clone, Copy, Debug, PartialEq, Eq)]
100pub enum Access {
101    Read(u32, u8),
102    Write(u32, u8),
103    /// A dummy read at this address.
104    Dummy(u32),
105    /// An internal cycle.
106    Idle,
107}
108
109/// One processor boundary.
110#[derive(Clone, Debug)]
111pub struct StepRecord {
112    pub sequence: u64,
113    pub kind: BoundaryKind,
114    pub cycles: u32,
115    /// The instruction's logical address and bytes, for an instruction boundary.
116    pub instruction: Option<(u16, Vec<u8>)>,
117    pub before: CpuState,
118    pub after: CpuState,
119    pub accesses: Option<Vec<Access>>,
120}
121
122fn state_value(state: &CpuState) -> Value {
123    json!({
124        "a": state.a,
125        "x": state.x,
126        "y": state.y,
127        "s": state.s,
128        "pc": state.pc,
129        "p": state.p,
130        "mpr": state.mpr,
131        "high_speed": state.high_speed,
132        "mpr_latch": state.mpr_latch,
133        "irq1": state.irq1,
134        "irq2": state.irq2,
135        "tiq": state.tiq,
136        "irq_disable": state.irq_disable,
137        "halted": state.halted,
138        "reset_pending": state.reset_pending,
139        "maskable_interrupt_pending": state.maskable_interrupt_pending,
140        "non_maskable_interrupt_pending": state.non_maskable_interrupt_pending,
141        "polled_i": state.polled_i,
142        "polled_maskable_interrupt": state.polled_maskable_interrupt,
143        "polled_non_maskable_interrupt": state.polled_non_maskable_interrupt,
144        "skipped_poll": state.skipped_poll,
145        "polled_irq_lines": state.polled_irq_lines,
146    })
147}
148
149impl StepRecord {
150    /// The versioned JSON representation.
151    pub fn to_value(&self) -> Value {
152        let mut record = Map::new();
153        record.insert("version".into(), json!(TRACE_SCHEMA_VERSION));
154        record.insert("sequence".into(), json!(self.sequence));
155        record.insert("kind".into(), json!(self.kind.as_str()));
156        record.insert("cycles".into(), json!(self.cycles));
157        let instruction = match &self.instruction {
158            None => Value::Null,
159            Some((address, data)) => {
160                let hex: String = data.iter().map(|b| format!("{b:02x}")).collect();
161                json!({"address": address, "data": hex})
162            }
163        };
164        record.insert("instruction".into(), instruction);
165        record.insert("before".into(), state_value(&self.before));
166        record.insert("after".into(), state_value(&self.after));
167        if let Some(accesses) = &self.accesses {
168            let list: Vec<Value> = accesses
169                .iter()
170                .map(|access| match *access {
171                    Access::Read(address, value) => json!(["r", address, value]),
172                    Access::Write(address, value) => json!(["w", address, value]),
173                    Access::Dummy(address) => json!(["d", address, 0]),
174                    Access::Idle => json!(["i", 0, 0]),
175                })
176                .collect();
177            record.insert("accesses".into(), Value::Array(list));
178        }
179        Value::Object(record)
180    }
181
182    /// One JSON Lines line, without the newline.
183    pub fn to_line(&self) -> String {
184        self.to_value().to_string()
185    }
186}