trace/
trace.rs

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