sst/
sst.rs

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