huc6280/
trace.rs

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