trace/
trace.rs

1// SPDX-License-Identifier: MIT
2//! Run a scenario and write its boundary trace (rungs 1 and 4).
3//!
4//!     trace SCENARIO.json [--out TRACE.jsonl]
5//!
6//! The scenario format (`conformance/README.md`) is read the same way by
7//! `scripts/reference_trace.py`, which runs it on huc6280-python; the two
8//! traces are compared with the reference's `first_trace_divergence`.
9
10use std::collections::HashMap;
11use std::io::{BufWriter, Write};
12
13use huc6280::trace::{instruction_length, next_boundary, Access, BoundaryKind, StepRecord};
14use huc6280::{Bus, DecimalFormula, HuC6280, IrqPollCycle, Pins, TmaMultiple, VanishedInterrupt};
15use serde::Deserialize;
16
17#[derive(Deserialize)]
18struct Block {
19    address: u32,
20    hex: String,
21}
22
23#[derive(Deserialize, Default, Clone)]
24struct Registers {
25    a: Option<u8>,
26    x: Option<u8>,
27    y: Option<u8>,
28    s: Option<u8>,
29    pc: Option<u16>,
30    p: Option<u8>,
31    mpr: Option<[u8; 8]>,
32}
33
34#[derive(Deserialize, Default)]
35#[serde(deny_unknown_fields)]
36struct Switches {
37    decimal_formula: Option<String>,
38    sbc_honours_t: Option<bool>,
39    irq_poll_cycle: Option<String>,
40    vanished_interrupt: Option<String>,
41    tma_multiple: Option<String>,
42    tsb_z_from_test: Option<bool>,
43    zero_page_pointer_wraps: Option<bool>,
44    block_reads_hardware_page_as_zero: Option<bool>,
45    nop_63_cycles: Option<u32>,
46    interrupt_entry_cycles: Option<u32>,
47}
48
49#[derive(Deserialize, Clone)]
50struct Event {
51    #[serde(default)]
52    step: Option<u64>,
53    #[serde(default)]
54    access: Option<u64>,
55    action: String,
56    #[serde(default)]
57    value: u8,
58    /// For the action `set`: the registers the host loads at that boundary.
59    #[serde(default)]
60    registers: Option<Registers>,
61}
62
63#[derive(Deserialize)]
64struct Scenario {
65    /// Seeded noise over the whole 2 MB, under the blocks.
66    #[serde(default)]
67    fill: Option<u64>,
68    /// The host answers three hardware-page addresses as a board would.
69    #[serde(default)]
70    board: bool,
71    memory: Vec<Block>,
72    #[serde(default)]
73    registers: Registers,
74    #[serde(default)]
75    switches: Switches,
76    #[serde(default)]
77    reset: bool,
78    steps: u64,
79    #[serde(default)]
80    events: Vec<Event>,
81    #[serde(default = "default_true")]
82    accesses: bool,
83}
84
85fn default_true() -> bool {
86    true
87}
88
89/// A host action a bus callback can make: it reaches the CPU through its pins.
90fn act(pins: &mut Pins, event: &Event) {
91    let value = &event.value;
92    match event.action.as_str() {
93        // The three lines in the $1402 layout: bit 0 IRQ2, bit 1 IRQ1, bit 2 TIQ.
94        "lines" => pins.set_irq_lines(value & 2 != 0, value & 1 != 0, value & 4 != 0),
95        "disable" => pins.set_irq_disable(*value),
96        "nmi" => pins.frame.request_non_maskable_interrupt(),
97        "nmi_clear" => pins.frame.clear_non_maskable_interrupt(),
98        "reset" => pins.frame.request_reset(),
99        other => panic!("unknown action {other}"),
100    }
101}
102
103/// 2 MB of flat RAM, the scenario's in-cycle actions and the access log.
104struct Host {
105    memory: Vec<u8>,
106    count: u64,
107    log: Option<Vec<Access>>,
108    during: HashMap<u64, Vec<Event>>,
109    board: bool,
110}
111
112/// The sliver of a PC Engine the interrupt workout uses (`"board": true`).
113const IRQ_DISABLE: u32 = 0x1FF402;
114const TIMER_ACKNOWLEDGE: u32 = 0x1FF403;
115const VDC_STATUS: u32 = 0x1FE000;
116
117impl Host {
118    fn tick(&mut self, pins: &mut Pins) {
119        let index = self.count;
120        self.count += 1;
121        if let Some(actions) = self.during.get(&index) {
122            for action in actions {
123                act(pins, action);
124            }
125        }
126    }
127}
128
129impl Bus for Host {
130    fn read(&mut self, address: u32, pins: &mut Pins) -> u8 {
131        self.tick(pins);
132        if self.board && address == VDC_STATUS {
133            let (_, irq2, tiq) = pins.irq_lines();
134            pins.set_irq_lines(false, irq2, tiq);
135        }
136        let value = self.memory[address as usize];
137        if let Some(log) = &mut self.log {
138            log.push(Access::Read(address, value));
139        }
140        value
141    }
142
143    fn write(&mut self, address: u32, value: u8, pins: &mut Pins) {
144        if let Some(log) = &mut self.log {
145            log.push(Access::Write(address, value));
146        }
147        self.tick(pins);
148        if self.board && address == IRQ_DISABLE {
149            pins.set_irq_disable(value);
150        } else if self.board && address == TIMER_ACKNOWLEDGE {
151            let (irq1, irq2, _) = pins.irq_lines();
152            pins.set_irq_lines(irq1, irq2, false);
153        }
154        self.memory[address as usize] = value;
155    }
156
157    fn idle(&mut self, address: Option<u32>, pins: &mut Pins) {
158        if let Some(log) = &mut self.log {
159            log.push(match address {
160                Some(address) => Access::Dummy(address),
161                None => Access::Idle,
162            });
163        }
164        self.tick(pins);
165    }
166}
167
168fn set_switches(cpu: &mut HuC6280<Host>, switches: &Switches) {
169    if let Some(name) = &switches.decimal_formula {
170        cpu.decimal_formula = match name.as_str() {
171            "mednafen" => DecimalFormula::Mednafen,
172            "mesen" => DecimalFormula::Mesen,
173            other => panic!("unknown decimal_formula {other}"),
174        };
175    }
176    if let Some(name) = &switches.irq_poll_cycle {
177        cpu.irq_poll_cycle = match name.as_str() {
178            "second_to_last" => IrqPollCycle::SecondToLast,
179            "last" => IrqPollCycle::Last,
180            other => panic!("unknown irq_poll_cycle {other}"),
181        };
182    }
183    if let Some(name) = &switches.vanished_interrupt {
184        cpu.vanished_interrupt = match name.as_str() {
185            "mesen2" => VanishedInterrupt::Mesen2,
186            "drop" => VanishedInterrupt::Drop,
187            other => panic!("unknown vanished_interrupt {other}"),
188        };
189    }
190    if let Some(name) = &switches.tma_multiple {
191        cpu.tma_multiple = match name.as_str() {
192            "or" => TmaMultiple::Or,
193            "highest" => TmaMultiple::Highest,
194            "lowest" => TmaMultiple::Lowest,
195            other => panic!("unknown tma_multiple {other}"),
196        };
197    }
198    if let Some(value) = switches.sbc_honours_t {
199        cpu.sbc_honours_t = value;
200    }
201    if let Some(value) = switches.tsb_z_from_test {
202        cpu.tsb_z_from_test = value;
203    }
204    if let Some(value) = switches.zero_page_pointer_wraps {
205        cpu.zero_page_pointer_wraps = value;
206    }
207    if let Some(value) = switches.block_reads_hardware_page_as_zero {
208        cpu.block_reads_hardware_page_as_zero = value;
209    }
210    if let Some(value) = switches.nop_63_cycles {
211        cpu.nop_63_cycles = value;
212    }
213    if let Some(value) = switches.interrupt_entry_cycles {
214        cpu.interrupt_entry_cycles = value;
215    }
216}
217
218fn main() {
219    let mut args = std::env::args().skip(1);
220    let path = args
221        .next()
222        .expect("usage: trace SCENARIO.json [--out TRACE.jsonl]");
223    let mut out: Box<dyn Write> = Box::new(std::io::stdout().lock());
224    while let Some(arg) = args.next() {
225        if arg == "--out" {
226            let file = std::fs::File::create(args.next().expect("--out PATH")).expect("create");
227            out = Box::new(file);
228        }
229    }
230    let mut out = BufWriter::new(out);
231    let parsed: serde_json::Value =
232        serde_json::from_str(&std::fs::read_to_string(&path).expect("read")).expect("parse");
233    // A file holds one scenario or a list of them, run one after another.
234    let scenarios: Vec<Scenario> = if parsed.is_array() {
235        serde_json::from_value(parsed).expect("scenarios")
236    } else {
237        vec![serde_json::from_value(parsed).expect("scenario")]
238    };
239    for scenario in &scenarios {
240        run(scenario, &mut out);
241    }
242}
243
244fn set_registers(cpu: &mut HuC6280<Host>, r: &Registers) {
245    cpu.a = r.a.unwrap_or(cpu.a);
246    cpu.x = r.x.unwrap_or(cpu.x);
247    cpu.y = r.y.unwrap_or(cpu.y);
248    cpu.s = r.s.unwrap_or(cpu.s);
249    cpu.pc = r.pc.unwrap_or(cpu.pc);
250    cpu.p = r.p.unwrap_or(cpu.p);
251    cpu.mpr = r.mpr.unwrap_or(cpu.mpr);
252}
253
254fn run(scenario: &Scenario, out: &mut impl Write) {
255    let mut memory = vec![0u8; 0x200000];
256    if let Some(seed) = scenario.fill {
257        // The same generator as scripts/reference_trace.py's.
258        let mut state = seed;
259        for byte in memory.iter_mut() {
260            state = state
261                .wrapping_mul(6364136223846793005)
262                .wrapping_add(1442695040888963407);
263            *byte = (state >> 56) as u8;
264        }
265    }
266    for block in &scenario.memory {
267        let hex = &block.hex;
268        for (offset, i) in (0..hex.len()).step_by(2).enumerate() {
269            let byte = u8::from_str_radix(&hex[i..i + 2], 16).expect("hex");
270            memory[(block.address as usize + offset) & 0x1FFFFF] = byte;
271        }
272    }
273    let mut during: HashMap<u64, Vec<Event>> = HashMap::new();
274    let mut between: HashMap<u64, Vec<Event>> = HashMap::new();
275    for event in &scenario.events {
276        match (event.step, event.access) {
277            (Some(step), None) => between.entry(step).or_default().push(event.clone()),
278            (None, Some(access)) => during.entry(access).or_default().push(event.clone()),
279            _ => panic!("an event has step or access"),
280        }
281    }
282    let host = Host {
283        memory,
284        count: 0,
285        log: scenario.accesses.then(Vec::new),
286        during,
287        board: scenario.board,
288    };
289    let mut cpu = HuC6280::new(host);
290    set_registers(&mut cpu, &scenario.registers);
291    set_switches(&mut cpu, &scenario.switches);
292    if scenario.reset {
293        cpu.request_reset();
294    }
295
296    for sequence in 0..scenario.steps {
297        if let Some(actions) = between.get(&sequence) {
298            for event in actions {
299                match event.action.as_str() {
300                    "restore" => {
301                        // Capture and restore at this boundary, as the reference's script does.
302                        let state = cpu.capture_state();
303                        cpu.restore_state(&state).expect("restore");
304                    }
305                    "set" => set_registers(&mut cpu, event.registers.as_ref().expect("registers")),
306                    _ => act(&mut cpu.pins, event),
307                }
308            }
309        }
310        let before = cpu.capture_state();
311        let kind = next_boundary(&before);
312        let instruction = if kind == BoundaryKind::Instruction {
313            let pc = before.pc;
314            let peek = |logical: u16| cpu.bus.memory[cpu.physical(logical) as usize];
315            let length = instruction_length(peek(pc));
316            let data = (0..length)
317                .map(|n| peek(pc.wrapping_add(n as u16)))
318                .collect();
319            Some((pc, data))
320        } else {
321            None
322        };
323        if let Some(log) = &mut cpu.bus.log {
324            log.clear();
325        }
326        let cycles = cpu.step();
327        let after = cpu.capture_state();
328        let record = StepRecord {
329            sequence,
330            kind,
331            cycles,
332            instruction,
333            before,
334            after,
335            accesses: cpu.bus.log.clone(),
336        };
337        writeln!(out, "{}", record.to_line()).expect("write");
338    }
339}