sst/
sst.rs

1// SPDX-License-Identifier: MIT
2//! Rung 2: the SingleStepTests huc6280 corpus (Mesen-generated; emulator
3//! tier), every case run and judged as the reference's `tests/single_step.py`
4//! judges it, mask for mask.
5//!
6//!     sst CORPUS_DIR [--limit N] [--formula mesen|mednafen] [--jobs N]
7//!         [--verdicts DIR] [--opcode XX]
8//!
9//! `CORPUS_DIR` holds `XX.json.bin` (the corpus's `v1/`). The binary layout
10//! is the one the reference's `scripts/sst_reader.py` reads: little-endian,
11//! `u32 count`, then per test `i32 size, 50-byte name, u32 opcode, initial
12//! state, final state, u32 num_cycles, u32 recorded, recorded x u32`; a state
13//! is `i32 size, A X Y S P, u16 PC, 8 MPR bytes, i32 n, n x (u32 address, u8
14//! value)`; a cycle word is `RD | WR << 1 | dummy << 2 | address << 3 (21
15//! bits) | data << 24`.
16//!
17//! The readings, each counted as a mask (the reference's module docstring
18//! gives the reasons): `st_write` (C1: the corpus records ST0-ST2's write
19//! cycle as an internal one), `truncated` (a block transfer of which the
20//! corpus kept 500 cycles and 500 RAM pairs), `block_unknown` (a transfer
21//! that read an address the case does not list: A, X, Y are not compared and
22//! what a tainted byte feeds is not), `block_self_overlap` (a transfer over
23//! its own bytes or stack cells), `block_final_unexplained`, `tma_latch`
24//! (TMA #$00 returns a register the corpus does not initialise), `tsb_z`
25//! (C12) and `decimal_formula` (C13: a decimal ADC or SBC that differs under
26//! the core's default formula and passes under Mesen's).
27//!
28//! `--verdicts DIR` writes one line per case, `index verdict masks`, into
29//! `DIR/XX.txt`: what `scripts/reference_sst.py` writes for the reference,
30//! so the two cores are compared case for case (`scripts/compare_sst.py`).
31
32use std::collections::BTreeMap;
33use std::path::{Path, PathBuf};
34use std::sync::atomic::{AtomicUsize, Ordering};
35use std::sync::Mutex;
36
37use huc6280::{Bus, DecimalFormula, HuC6280, Pins};
38
39const ST_OPCODES: [u32; 3] = [0x03, 0x13, 0x23];
40const TSB_TRB: [u32; 4] = [0x04, 0x0C, 0x14, 0x1C];
41const BLOCK_OPCODES: [u32; 5] = [0x73, 0xC3, 0xD3, 0xE3, 0xF3];
42const TMA: u32 = 0x43;
43const DECIMAL_ARITHMETIC: [u32; 18] = [
44    0x61, 0x65, 0x69, 0x6D, 0x71, 0x72, 0x75, 0x79, 0x7D, 0xE1, 0xE5, 0xE9, 0xED, 0xF1, 0xF2, 0xF5,
45    0xF9, 0xFD,
46];
47
48struct State {
49    a: u8,
50    x: u8,
51    y: u8,
52    s: u8,
53    p: u8,
54    pc: u16,
55    mpr: [u8; 8],
56    ram: Vec<(u32, u8)>,
57}
58
59struct Case {
60    name: String,
61    opcode: u32,
62    initial: State,
63    end: State,
64    num_cycles: u32,
65    /// (address, data, RD | WR << 1 | dummy << 2)
66    cycles: Vec<(u32, u8, u8)>,
67}
68
69fn u32_at(buf: &[u8], at: usize) -> u32 {
70    u32::from_le_bytes(buf[at..at + 4].try_into().unwrap())
71}
72
73fn state(buf: &[u8], mut ptr: usize) -> (usize, State) {
74    let size = u32_at(buf, ptr) as usize;
75    ptr += 4;
76    let (a, x, y, s, p) = (
77        buf[ptr],
78        buf[ptr + 1],
79        buf[ptr + 2],
80        buf[ptr + 3],
81        buf[ptr + 4],
82    );
83    let pc = u16::from_le_bytes([buf[ptr + 5], buf[ptr + 6]]);
84    ptr += 7;
85    let mpr: [u8; 8] = buf[ptr..ptr + 8].try_into().unwrap();
86    ptr += 8;
87    let count = u32_at(buf, ptr) as usize;
88    ptr += 4;
89    let mut ram = Vec::with_capacity(count);
90    for _ in 0..count {
91        ram.push((u32_at(buf, ptr), buf[ptr + 4]));
92        ptr += 5;
93    }
94    (
95        size,
96        State {
97            a,
98            x,
99            y,
100            s,
101            p,
102            pc,
103            mpr,
104            ram,
105        },
106    )
107}
108
109/// Every test in one `XX.json.bin` file.
110fn load_cases(path: &Path, limit: Option<usize>) -> Vec<Case> {
111    let buf = std::fs::read(path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
112    let count = u32_at(&buf, 0) as usize;
113    let mut ptr = 4;
114    let mut cases = Vec::new();
115    for _ in 0..count.min(limit.unwrap_or(usize::MAX)) {
116        let size = u32_at(&buf, ptr) as usize;
117        let mut at = ptr + 4;
118        let name = String::from_utf8_lossy(&buf[at..at + 50])
119            .trim_matches(|c| c == '\0' || c == ' ')
120            .to_string();
121        at += 50;
122        let opcode = u32_at(&buf, at);
123        at += 4;
124        let (used, initial) = state(&buf, at);
125        at += used;
126        let (used, end) = state(&buf, at);
127        at += used;
128        let num_cycles = u32_at(&buf, at);
129        let recorded = u32_at(&buf, at + 4) as usize;
130        at += 8;
131        let mut cycles = Vec::with_capacity(recorded);
132        for n in 0..recorded {
133            let word = u32_at(&buf, at + 4 * n);
134            let pins = (word & 7) as u8;
135            let transfer = pins & 3 != 0;
136            cycles.push((
137                if transfer { (word >> 3) & 0x1FFFFF } else { 0 },
138                if transfer { (word >> 24) as u8 } else { 0 },
139                pins,
140            ));
141        }
142        cases.push(Case {
143            name,
144            opcode,
145            initial,
146            end,
147            num_cycles,
148            cycles,
149        });
150        ptr += size;
151    }
152    cases
153}
154
155const SIZE: usize = 0x200000;
156
157/// The case's sparse RAM over the flat 2 MB, and the bookkeeping the
158/// reference keeps in dicts and sets.
159#[derive(Default)]
160struct Ram {
161    memory: Vec<u8>,
162    /// The address is a key of the reference's `memory` dict.
163    listed: Vec<bool>,
164    /// Block transfers read far more than the 500 RAM pairs the generator
165    /// kept: a read of an address the case does not list returns 0 and
166    /// taints the byte written next, and anything that depends on a tainted
167    /// byte is not compared.
168    tainted: Vec<bool>,
169    touched: Vec<u32>,
170    seen: Vec<(u8, u32, u8)>,
171    unlisted: Option<u32>,
172    pending_taint: bool,
173    own_cells: Vec<u32>,
174    overlapped: bool,
175}
176
177impl Ram {
178    fn new() -> Self {
179        Ram {
180            memory: vec![0; SIZE],
181            listed: vec![false; SIZE],
182            tainted: vec![false; SIZE],
183            touched: Vec::new(),
184            seen: Vec::new(),
185            unlisted: None,
186            pending_taint: false,
187            own_cells: Vec::new(),
188            overlapped: false,
189        }
190    }
191
192    fn clear(&mut self) {
193        for &address in &self.touched {
194            let address = address as usize;
195            self.memory[address] = 0;
196            self.listed[address] = false;
197            self.tainted[address] = false;
198        }
199        self.touched.clear();
200        self.seen.clear();
201        self.unlisted = None;
202        self.pending_taint = false;
203        self.own_cells.clear();
204        self.overlapped = false;
205    }
206
207    fn set(&mut self, address: u32, value: u8) {
208        self.memory[address as usize] = value;
209        self.listed[address as usize] = true;
210        self.touched.push(address);
211    }
212}
213
214impl Bus for Ram {
215    fn read(&mut self, address: u32, _: &mut Pins) -> u8 {
216        let index = address as usize;
217        if self.tainted[index] || !self.listed[index] {
218            self.unlisted.get_or_insert(address);
219            self.pending_taint = true;
220        }
221        let value = self.memory[index];
222        self.seen.push((b'r', address, value));
223        value
224    }
225
226    fn write(&mut self, address: u32, value: u8, _: &mut Pins) {
227        self.set(address, value);
228        // The transfer's own writes start after its three pushes (seen[3..6]).
229        let own = self.own_cells.contains(&address) && self.seen.len() >= 6;
230        if self.pending_taint || own {
231            self.tainted[address as usize] = true;
232            self.pending_taint = false;
233            if own {
234                self.overlapped = true;
235            }
236        } else {
237            self.tainted[address as usize] = false;
238        }
239        self.seen.push((b'w', address, value));
240    }
241
242    fn idle(&mut self, address: Option<u32>, _: &mut Pins) {
243        self.seen.push(match address {
244            None => (b'i', 0, 0),
245            Some(address) => (b'd', address, 0),
246        });
247    }
248}
249
250type Masks = BTreeMap<&'static str, u32>;
251
252/// A difference, and whether it is one of the final-state ones (A, X, Y or a
253/// RAM cell) that `block_final_unexplained` covers.
254struct Problem {
255    final_state: bool,
256    text: String,
257}
258
259fn physical(mpr: &[u8; 8], logical: u16) -> u32 {
260    ((mpr[(logical >> 13) as usize] as u32) << 13) | (logical & 0x1FFF) as u32
261}
262
263/// TMA #$00 returns the hidden latch: the operand byte is the case's second code byte.
264fn tma_latch(case: &Case) -> bool {
265    let initial = &case.initial;
266    let operand = physical(&initial.mpr, initial.pc.wrapping_add(1));
267    // The reference builds a dict from the pairs: the last pair for an address wins.
268    initial
269        .ram
270        .iter()
271        .rev()
272        .find(|(address, _)| *address == operand)
273        .map_or(0, |(_, value)| *value)
274        == 0
275}
276
277/// The physical cells of a block transfer's own opcode and operand bytes and
278/// the three stack bytes it pushes.
279fn own_cells(initial: &State) -> Vec<u32> {
280    let mut cells: Vec<u32> = (0..7)
281        .map(|offset| physical(&initial.mpr, initial.pc.wrapping_add(offset)))
282        .collect();
283    cells.extend(
284        (0..3).map(|offset| physical(&initial.mpr, 0x2100 | initial.s.wrapping_sub(offset) as u16)),
285    );
286    cells
287}
288
289fn run_once(
290    case: &Case,
291    cpu: &mut HuC6280<Ram>,
292    formula: Option<DecimalFormula>,
293) -> (Vec<Problem>, Masks) {
294    let opcode = case.opcode;
295    let initial = &case.initial;
296    let block = BLOCK_OPCODES.contains(&opcode);
297    cpu.bus.clear();
298    for &(address, value) in &initial.ram {
299        cpu.bus.set(address, value);
300    }
301    if block {
302        cpu.bus.own_cells = own_cells(initial);
303    }
304    // A new CPU for every case, as the reference makes one; the buffers are kept.
305    let bus = std::mem::take(&mut cpu.bus);
306    *cpu = HuC6280::new(bus);
307    cpu.block_reads_hardware_page_as_zero = false; // no hardware page in the corpus
308    if let Some(formula) = formula {
309        cpu.decimal_formula = formula;
310    }
311    cpu.a = initial.a;
312    cpu.x = initial.x;
313    cpu.y = initial.y;
314    cpu.s = initial.s;
315    cpu.p = initial.p;
316    cpu.pc = initial.pc;
317    cpu.mpr = initial.mpr;
318    cpu.step();
319
320    let mut masks = Masks::new();
321    let mut problems: Vec<Problem> = Vec::new();
322    let mut problem =
323        |final_state: bool, text: String| problems.push(Problem { final_state, text });
324    let end = &case.end;
325    if cpu.bus.overlapped {
326        *masks.entry("block_self_overlap").or_default() += 1;
327    }
328    let block_unknown = block && cpu.bus.unlisted.is_some();
329    if block_unknown {
330        *masks.entry("block_unknown").or_default() += 1;
331    }
332    let latch = opcode == TMA && tma_latch(case);
333    for (name, got, want) in [
334        ("a", cpu.a as u16, end.a as u16),
335        ("x", cpu.x as u16, end.x as u16),
336        ("y", cpu.y as u16, end.y as u16),
337        ("s", cpu.s as u16, end.s as u16),
338        ("p", cpu.p as u16, end.p as u16),
339        ("pc", cpu.pc, end.pc),
340    ] {
341        let axy = matches!(name, "a" | "x" | "y");
342        if block_unknown && axy {
343            continue;
344        }
345        if name == "p" && TSB_TRB.contains(&opcode) && got ^ want == 0x02 {
346            *masks.entry("tsb_z").or_default() += 1;
347            continue;
348        }
349        if got != want && !(latch && name == "a") {
350            problem(axy, format!("{name}: got ${got:X}, want ${want:X}"));
351        }
352    }
353    if latch {
354        *masks.entry("tma_latch").or_default() += 1;
355    }
356    if cpu.mpr != end.mpr {
357        problem(false, format!("mpr: got {:?}, want {:?}", cpu.mpr, end.mpr));
358    }
359    for &(address, value) in &end.ram {
360        if cpu.bus.tainted[address as usize] {
361            continue;
362        }
363        let got = cpu.bus.memory[address as usize];
364        if got != value
365            && !(ST_OPCODES.contains(&opcode) && (0x1FE000..=0x1FE003).contains(&address))
366        {
367            problem(
368                true,
369                format!("ram ${address:06X}: got ${got:02X}, want ${value:02X}"),
370            );
371        }
372    }
373    let expected = &case.cycles;
374    let seen = &cpu.bus.seen;
375    let truncated = case.num_cycles as usize != expected.len();
376    if truncated {
377        *masks.entry("truncated").or_default() += 1;
378    }
379    if seen.len() != case.num_cycles as usize {
380        problem(
381            false,
382            format!("cycles: got {}, want {}", seen.len(), case.num_cycles),
383        );
384    }
385    if let (Some(address), false) = (cpu.bus.unlisted, block) {
386        problem(
387            false,
388            format!("read of an address the case does not list: ${address:06X}"),
389        );
390    }
391    for (index, (&(address, value, pins), &(got_kind, got_address, got_value))) in
392        expected.iter().zip(seen.iter()).enumerate()
393    {
394        let want_kind = match pins {
395            0b001 => b'r',
396            0b010 => b'w',
397            0b101 => b'd',
398            0b000 => b'i',
399            other => panic!("{}: a cycle with pins {other:03b}", case.name),
400        };
401        if ST_OPCODES.contains(&opcode) && index == 3 {
402            *masks.entry("st_write").or_default() += 1;
403            continue;
404        }
405        if got_kind != want_kind {
406            problem(
407                false,
408                format!(
409                    "cycle {index}: {}, want {}",
410                    got_kind as char, want_kind as char
411                ),
412            );
413            break;
414        }
415        if want_kind != b'i' && got_address != address {
416            problem(
417                false,
418                format!("cycle {index}: address ${got_address:06X}, want ${address:06X}"),
419            );
420        }
421        if (want_kind == b'r' || want_kind == b'w') && got_value != value {
422            problem(
423                false,
424                format!("cycle {index}: value ${got_value:02X}, want ${value:02X}"),
425            );
426        }
427    }
428    // Nothing but the final state of a truncated transfer disagrees (a, x, y
429    // or listed RAM), and that state depends on the 99% of the transfer the
430    // corpus did not record. Counted, not hidden.
431    if truncated && block && !problems.is_empty() && problems.iter().all(|p| p.final_state) {
432        *masks.entry("block_final_unexplained").or_default() += 1;
433        problems.clear();
434    }
435    (problems, masks)
436}
437
438/// Run one case; return the differences (empty: it passes) and the masks it used.
439fn run_case(
440    case: &Case,
441    cpu: &mut HuC6280<Ram>,
442    formula: Option<DecimalFormula>,
443) -> (Vec<Problem>, Masks) {
444    let (problems, mut masks) = run_once(case, cpu, formula);
445    if !problems.is_empty() && formula.is_none() {
446        // C13: the corpus is Mesen's. A case Mesen's formula fixes, and only
447        // that, is counted.
448        let decimal = DECIMAL_ARITHMETIC.contains(&case.opcode) && case.initial.p & 0x08 != 0;
449        if decimal
450            && run_once(case, cpu, Some(DecimalFormula::Mesen))
451                .0
452                .is_empty()
453        {
454            *masks.entry("decimal_formula").or_default() += 1;
455            return (Vec::new(), masks);
456        }
457    }
458    (problems, masks)
459}
460
461struct Totals {
462    passed: usize,
463    failed: usize,
464    masks: Masks,
465}
466
467fn main() {
468    let mut corpus: Option<PathBuf> = None;
469    let mut limit: Option<usize> = None;
470    let mut formula: Option<DecimalFormula> = None;
471    let mut jobs = 8usize;
472    let mut verdicts: Option<PathBuf> = None;
473    let mut only: Option<usize> = None;
474    let mut args = std::env::args().skip(1);
475    while let Some(arg) = args.next() {
476        match arg.as_str() {
477            "--limit" => limit = Some(args.next().expect("--limit N").parse().expect("N")),
478            "--jobs" => jobs = args.next().expect("--jobs N").parse().expect("N"),
479            "--verdicts" => verdicts = Some(args.next().expect("--verdicts DIR").into()),
480            "--opcode" => {
481                only =
482                    Some(usize::from_str_radix(&args.next().expect("--opcode XX"), 16).expect("XX"))
483            }
484            "--formula" => {
485                formula = Some(match args.next().expect("--formula NAME").as_str() {
486                    "mesen" => DecimalFormula::Mesen,
487                    "mednafen" => DecimalFormula::Mednafen,
488                    other => panic!("unknown formula {other}"),
489                })
490            }
491            _ => corpus = Some(arg.into()),
492        }
493    }
494    let corpus = corpus
495        .expect("usage: sst CORPUS_DIR [--limit N] [--formula NAME] [--jobs N] [--verdicts DIR]");
496    if let Some(directory) = &verdicts {
497        std::fs::create_dir_all(directory).expect("verdicts directory");
498    }
499    let opcodes: Vec<usize> = match only {
500        Some(opcode) => vec![opcode],
501        None => (0..256).collect(),
502    };
503    let next = AtomicUsize::new(0);
504    let totals = Mutex::new(Totals {
505        passed: 0,
506        failed: 0,
507        masks: Masks::new(),
508    });
509    std::thread::scope(|scope| {
510        for _ in 0..jobs.max(1) {
511            scope.spawn(|| {
512                let mut cpu = HuC6280::new(Ram::new());
513                loop {
514                    let index = next.fetch_add(1, Ordering::Relaxed);
515                    let Some(&opcode) = opcodes.get(index) else {
516                        break;
517                    };
518                    let cases = load_cases(&corpus.join(format!("{opcode:02x}.json.bin")), limit);
519                    let (mut passed, mut failed) = (0, 0);
520                    let mut masks = Masks::new();
521                    let mut lines = String::new();
522                    let mut first: Option<String> = None;
523                    for (number, case) in cases.iter().enumerate() {
524                        let (problems, used) = run_case(case, &mut cpu, formula);
525                        for (name, count) in &used {
526                            *masks.entry(name).or_default() += count;
527                        }
528                        if problems.is_empty() {
529                            passed += 1;
530                        } else {
531                            failed += 1;
532                            if first.is_none() {
533                                let texts: Vec<&str> =
534                                    problems.iter().take(3).map(|p| p.text.as_str()).collect();
535                                first = Some(format!("{}: {}", case.name, texts.join("; ")));
536                            }
537                        }
538                        if verdicts.is_some() {
539                            let used: Vec<String> = used
540                                .iter()
541                                .map(|(name, count)| format!("{name}={count}"))
542                                .collect();
543                            let used = if used.is_empty() {
544                                "-".to_string()
545                            } else {
546                                used.join(",")
547                            };
548                            let verdict = if problems.is_empty() { 'P' } else { 'F' };
549                            lines.push_str(&format!("{number} {verdict} {used}\n"));
550                        }
551                    }
552                    if let Some(directory) = &verdicts {
553                        std::fs::write(directory.join(format!("{opcode:02x}.txt")), lines)
554                            .expect("write verdicts");
555                    }
556                    if let Some(first) = first {
557                        println!("{opcode:02X}: {failed} failing; {first}");
558                    }
559                    let mut totals = totals.lock().unwrap();
560                    totals.passed += passed;
561                    totals.failed += failed;
562                    for (name, count) in masks {
563                        *totals.masks.entry(name).or_default() += count;
564                    }
565                }
566            });
567        }
568    });
569    let totals = totals.into_inner().unwrap();
570    let masks: Vec<String> = totals
571        .masks
572        .iter()
573        .map(|(name, count)| format!("{name} {count}"))
574        .collect();
575    println!(
576        "cases {}, passed {}, failed {}; masks: {}",
577        totals.passed + totals.failed,
578        totals.passed,
579        totals.failed,
580        masks.join(", ")
581    );
582    std::process::exit(if totals.failed != 0 { 1 } else { 0 });
583}