aboutsummaryrefslogtreecommitdiff
path: root/differential-tests/tests/differential-v7-thumb.rs
blob: 86804a1ecd32c4df31f6d9d5d3ce7697c0fe3990 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
//! this is a distinct set of tests from the `yaxpeax-arm` root tests because i don't want extra
//! (optional!) dependencies in the disassembler's dependency tree.

// use capstone::prelude::*;
use yaxpeax_arch::{Arch, Decoder};

use std::fmt::Write;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::num::ParseIntError;

#[derive(Debug, PartialEq, Eq)]
enum MemOffset {
    Imm(i64),
    Shift(String),
    Reg(String),
}

#[derive(Debug)]
enum ParsedOperand {
    Register { size: char, num: u8, neg: bool },
    Memory(String),
    MemoryWithOffset { base: String, offset: MemOffset, writeback: bool },
    SIMDRegister { size: char, num: u8 },
//    SIMDRegisterElements { num: u8, elems: u8, elem_size: char },
//    SIMDRegisterElement { num: u8, elem_size: char, elem: u8 },
    SIMDElementLane { elem: String, lane_selector: u8 },
    Immediate(i64),
    PCRel(i64),
    Float(f64),
    Other(String),
    RegisterFamily(String),
}

impl PartialEq for ParsedOperand {
    fn eq(&self, other: &Self) -> bool {
        use ParsedOperand::*;

        match (self, other) {
            (Register { size: size_l, num: num_l, neg: neg_l }, Register { size: size_r, num: num_r, neg: neg_r }) => {
                size_l == size_r && num_l == num_r && neg_l == neg_r
            },
            (Memory(l), Memory(r)) => {
                if l == "r10" && r == "sl" {
                    true
                } else {
                    l == r
                }
            },
            (
                MemoryWithOffset { base: base_l, offset: offset_l, writeback: writeback_l },
                MemoryWithOffset { base: base_r, offset: offset_r, writeback: writeback_r },
            ) => {
                base_l == base_r &&
                offset_l == offset_r &&
                writeback_l == writeback_r
            },
            // smooth over yax printing `[rN]` rather than `[rN, #0]` like capstone.
            (Memory(l), MemoryWithOffset { base, offset: MemOffset::Imm(0), writeback: false }) => {
                l == base
            },
            // and make equality reflexive.
            (MemoryWithOffset { base, offset: MemOffset::Imm(0), writeback: false }, Memory(r)) => {
                base == r
            },
            (Immediate(l), Immediate(r)) => {
                l == r
            },
            (PCRel(l), PCRel(r)) => {
                l == r
            },
            // TODO: don't actually know if this is thumb, 32-bit thumb, arm, .. so try a few
            // things.
            (Immediate(l), PCRel(r)) => { *l == 2 + r || *l == 4 + r },
            (PCRel(l), Immediate(r)) => { 2 + l == *r || 4 + l == *r },

            (Float(l), Float(r)) => {
                l.to_ne_bytes() == r.to_ne_bytes()
            },
            (RegisterFamily(l), RegisterFamily(r)) => {
                l == r
            },
            (SIMDRegister { size: size_l, num: num_l }, SIMDRegister { size: size_r, num: num_r }) => {
                size_l == size_r && num_l == num_r
            },
            (SIMDElementLane { elem: elem_l, lane_selector: lane_l }, SIMDElementLane { elem: elem_r, lane_selector: lane_r }) => {
                elem_l == elem_r && lane_l == lane_r
            }
            (Other(l), Other(r)) => {
                if let (Some(left), Some(right)) = (l.strip_suffix(" r10"), r.strip_suffix(" sl")) {
                    // probably something like `lsl r10` vs `lsl sl`. so strip the registers off
                    // the end and compare the rest. notionally the registers should be parsed
                    // but..
                    left == right
                }
                // yax prints `asr #0` as just `asr`. is this actually a no-op?
                else if (l == "asr" && r == "asr #0") || (l == "asr #0" && r == "asr") {
                    true
                } else if (l == "lsr" && r == "lsr #0") || (l == "lsr #0" && r == "lsr") {
                    true
                } else if (l == "ror" && r == "ror #0") || (l == "ror #0" && r == "ror") {
                    true
                } else {
                    l == r
                }
            }
            (_, _) => {
                false
            }
        }
    }
}

#[test]
fn test_operand_parsing() {
    assert_eq!(ParsedOperand::parse("r3", 64), (ParsedOperand::Register { size: 'r', num: 3, neg: false }, 2));
    assert_eq!(ParsedOperand::parse("r11", 64), (ParsedOperand::Register { size: 'r', num: 11, neg: false }, 3));
    assert_eq!(ParsedOperand::parse("-r11", 64), (ParsedOperand::Register { size: 'r', num: 11, neg: true }, 4));
    assert_eq!(ParsedOperand::parse("sl", 32), (ParsedOperand::Register { size: 'r', num: 10, neg: false }, 2));
    assert_eq!(ParsedOperand::parse("-sl", 32), (ParsedOperand::Register { size: 'r', num: 10, neg: true }, 3));
}

#[test]
fn test_instruction_parsing() {
    /*
    let inst = ParsedDisassembly::parse("msub w17, w8, w15, w0");
    assert_eq!(inst, ParsedDisassembly {
        opcode: "msub".to_string(),
        operands: [
            Some(ParsedOperand::Register { size: 'w', num: 17 }),
            Some(ParsedOperand::Register { size: 'w', num: 8 }),
            Some(ParsedOperand::Register { size: 'w', num: 15 }),
            Some(ParsedOperand::Register { size: 'w', num: 0 }),
            None,
            None,
        ]
    });

    let inst = ParsedDisassembly::parse("stlurb w0, [x0, #0x1]");
    assert_eq!(inst, ParsedDisassembly {
        opcode: "stlurb".to_string(),
        operands: [
            Some(ParsedOperand::Register { size: 'w', num: 0 }),
            Some(ParsedOperand::MemoryWithOffset { base: "x0".to_string(), offset: Some(1), writeback: false }),
            None,
            None,
            None,
            None,
        ]
    });
    let inst2 = ParsedDisassembly::parse("stlurb w0, [x0, #1]");
    assert_eq!(inst, inst2);

    let inst = ParsedDisassembly::parse("mov wsp, #0x80000001");
    assert_eq!(inst.opcode, "mov");
    assert_eq!(inst.operands[0], Some(ParsedOperand::Register { size: 'w', num: 33 }));
    assert_eq!(inst.operands[1], Some(ParsedOperand::Immediate(-0x7fffffff)));
    */
}

impl ParsedOperand {
    fn parse(s: &str, width: u8) -> (Self, usize) {
        let parse_hex_or_dec = |mut s: &str| {
            let mut negate = false;
            if s.as_bytes()[0] == b'-' {
                negate = true;
                s = &s[1..];
            }

            let v = if !s.starts_with("0x") {
                i64::from_str_radix(s, 10).map_err(|e| { panic!("failed to parse {}", s); }).expect("can parse string")
            } else {
                u64::from_str_radix(&s[2..], 16).expect("can parse string") as i64
            };
            if negate {
                -v
            } else {
                v
            }
        };

        let parse_imm = |mut s: &str| {
            if s.starts_with("#") {
                parse_hex_or_dec(&s[1..])
            } else {
                parse_hex_or_dec(s)
            }
        };

        fn parse_reg(s: &str) -> Option<&str> {
            if s.starts_with("r") {
                Some(s)
            } else if s == "fp" ||
                      s == "ip" ||
                      s == "sb" ||
                      s == "pc" ||
                      s == "lr" ||
                      s == "sl" ||
                      s == "sp" {
                Some(s)
            } else {
                None
            }
        };

        fn parse_shift(s: &str) -> Option<&str> {
            if s.starts_with("lsl") ||
               s.starts_with("lsr") ||
               s.starts_with("asr") ||
               s.starts_with("ror") {
                Some(s)
            } else {
                None
            }
        }

        if s.as_bytes()[0] == b'#' {
            let end = s.find(',').unwrap_or(s.len());
            let mut imm_str = &s[1..end];
            // TODO: improve the following hack, useful to parse `[reg], -1!`
            if imm_str.ends_with('!') {
                imm_str = &s[1..end - 1];
            }
            if imm_str.contains('.') {
                use std::str::FromStr;
                (ParsedOperand::Float(f64::from_str(imm_str).expect("can parse string")), end)
            } else {
                let imm = parse_hex_or_dec(imm_str);
                let imm = if width == 32 {
                    imm as i32 as i64
                } else {
                    imm
                };
                (ParsedOperand::Immediate(imm), end)
            }
        } else if s.as_bytes()[0] == b'$' {
            let end = s.find(',').unwrap_or(s.len());
            let imm_str = &s[1..end];
            let imm_str = if imm_str.starts_with("+") {
                &imm_str[1..]
            } else {
                imm_str
            };
            let imm = parse_hex_or_dec(imm_str);
            (ParsedOperand::PCRel(imm), end)
        } else if s.as_bytes()[0] == b'[' {
            let brace_end = s.find(']').map(|x| x + 1).unwrap_or(s.len());
            let mut end = brace_end;
            let mut writeback = false;
            if s.as_bytes().get(end) == Some(&b'!') {
                end += 1;
                writeback = true;
            }

            let addr = &s[1..brace_end - 1];

            let offset = addr.rfind(',').map(|comma| {
                addr[comma + 1..].trim()
            }).map(|mut offset_str| {
                if let Some(reg) = parse_reg(offset_str) {
                    MemOffset::Reg(reg.to_string())
                } else if let Some(shift) = parse_shift(offset_str) {
                    MemOffset::Shift(shift.to_string())
                } else {
                    MemOffset::Imm(parse_imm(offset_str))
                }
            });

            let base_end = addr.rfind(',').unwrap_or(addr.len());
            let base = addr[..base_end].trim();

            if let Some(offset) = offset {
                (ParsedOperand::MemoryWithOffset {
                    base: base.to_string(),
                    offset: offset,
                    writeback,
                }, end)
            } else if writeback {
                (ParsedOperand::MemoryWithOffset {
                    base: base.to_string(),
                    offset: MemOffset::Imm(0),
                    writeback,
                }, end)
            } else {
                (ParsedOperand::Memory(base.to_string()), end)
            }
        } else if s.as_bytes()[0] == b'{' {
            let brace_end = s.find('}');
            if let Some(brace_end) = brace_end {
                if s.as_bytes().get(brace_end + 1) == Some(&b'[') {
                    if let Some(end) = s.find(']') {
                        let group = &s[0..brace_end];
                        let lane = &s[brace_end + 2..end];
                        let lane = parse_hex_or_dec(lane);

                        return (ParsedOperand::SIMDElementLane {
                            elem: group.to_string(),
                            lane_selector: lane as u8,
                        }, end);
                    }
                }

                let end = s[brace_end..].find(',').unwrap_or(s.len() - brace_end) + brace_end;
                (ParsedOperand::RegisterFamily(s[0..end].to_string()), end)
            } else {
                let end = s.find(',').unwrap_or(s.len());
                (ParsedOperand::Other(s[0..end].to_string()), end)
            }
        } else {
            let mut start = 0;
            let end = s.find(',').unwrap_or(s.len());
            let mut substr = &s[..end];
            let mut neg = false;
            if substr.as_bytes()[0] == b'-' {
                start += 1;
                neg = true;
                substr = &substr[1..];
            }
            if substr == "sl" {
                return (ParsedOperand::Register { size: 'r', num: 10, neg }, end);
            }
            match s.as_bytes()[start] as char {
                sz @ 'r' => {
                    if &s[start + 1..end] == "zr" {
                        return (ParsedOperand::Register { size: sz, num: 32, neg }, end);
                    }
                    if &s[start + 1..end] == "sp" {
                        return (ParsedOperand::Register { size: sz, num: 33, neg }, end);
                    }
                    let num: Result<u8, ParseIntError> = s[start + 1..end].parse();
                    match num {
                        Ok(num) => {
                            (ParsedOperand::Register { size: sz, num, neg }, end)
                        }
                        Err(_) => {
                            (ParsedOperand::Other(s[start..end].to_string()), end)
                        }
                    }
                }
                sz @ 'b' | sz @ 'h' | sz @ 's' | sz @ 'd' | sz @ 'q' => {
                    let num: Result<u8, ParseIntError> = s[start + 1..end].parse();
                    match num {
                        Ok(num) => {
                            (ParsedOperand::SIMDRegister { size: sz, num }, end)
                        }
                        Err(_) => {
                            (ParsedOperand::Other(s[start..end].to_string()), end)
                        }
                    }
                }
                'v' => {
                    match substr.find('[') {
                        Some(lane_selector_start) => {
                            let lane_selector_end = substr.find(']').unwrap();
                            let elem = substr[..lane_selector_start].to_string();
                            let lane_selector = parse_hex_or_dec(&substr[lane_selector_start + 1..lane_selector_end]) as u8;
                            (ParsedOperand::SIMDElementLane { elem, lane_selector }, end)
                        }
                        None => {
                            // some kind of simd element that does not include a trailing `[]`.
                            // treat it as an opaque string for now.
                            (ParsedOperand::Other(substr.to_string()), end)
                        }
                    }
                }
                _ => {
                    (ParsedOperand::Other(s[start..end].to_string()), end)
                }
            }
        }
    }
}

#[derive(Debug, PartialEq)]
struct ParsedDisassembly {
    opcode: String,
    // arm instructions do not have six operands, but due to parse ambiguity and the rather hackjob
    // parser here, pretend they might.
    operands: [Option<ParsedOperand>; 6]
}

impl ParsedDisassembly {
    fn parse(s: &str) -> Self {
        let mut operands = [None, None, None, None, None, None];
        if let Some((opcode, mut operands_text)) = s.split_once(' ') {
            let opcode = opcode.to_string();

            let mut i = 0;
            let mut width = 64;

            while operands_text.len() > 0 {
                if operands_text.as_bytes()[0] == b',' {
                    operands_text = &operands_text[1..];
                }
                operands_text = operands_text.trim();
                let (parsed, amount) = ParsedOperand::parse(&operands_text, width);
                operands[i] = Some(parsed);
                if let Some(ParsedOperand::Register { size: 'w', .. }) = &operands[i] {
                    width = 32;
                }
                operands_text = &operands_text[amount..];
                i += 1;
            }

            ParsedDisassembly {
                opcode,
                operands,
            }
        } else {
            ParsedDisassembly {
                opcode: s.to_string(),
                operands,
            }
        }
    }

    fn operand_count(&self) -> u8 {
        let mut i = 0;

        for op in self.operands.iter() {
            if op.is_none() {
                break;
            }
            i += 1;
        }

        i
    }
}

#[test]
fn capstone_differential_thumb() {
    struct Stats {
        mismatch: AtomicUsize,
        good: AtomicUsize,
        yax_reject: AtomicUsize,
        missed_incomplete: AtomicUsize,
    }

    let stats = Stats {
        mismatch: AtomicUsize::new(0),
        good: AtomicUsize::new(0),
        yax_reject: AtomicUsize::new(0),
        missed_incomplete: AtomicUsize::new(0),
    };

    fn test_range(start: u64, end: u64, stats: Arc<Stats>) {
        /*
        let mut local_mismatch = 0usize;
        let mut local_good = 0usize;
        let mut local_yax_reject = 0usize;
        let mut local_missed_incomplete = 0usize;
        */

        let mut csh: capstone_sys::csh = capstone_sys::csh::default();
        assert_eq!(
            unsafe { capstone_sys::cs_open(capstone_sys::cs_arch::CS_ARCH_ARM, capstone_sys::cs_mode(1<<4), &mut csh as *mut capstone_sys::csh) },
            0
        );
        unsafe {
            assert_eq!(capstone_sys::cs_option(
                csh, capstone_sys::cs_opt_type::CS_OPT_DETAIL, 0,
            ), 0);
        }
        let cs_insn: *mut capstone_sys::cs_insn = unsafe { libc::malloc(std::mem::size_of::<capstone_sys::cs_insn>()) as *mut capstone_sys::cs_insn };
        unsafe {
            // cs_insn is otherwise random garbage: set detail to NULL so
            // capstone doesn't think it's a real pointer to walk and
            // populate with operand data.
            (*cs_insn).detail = std::ptr::null_mut();
        };
        /*
        let cs = Capstone::new()
            .arm64()
            .mode(capstone::arch::arm64::ArchMode::Arm)
            .build()
            .expect("can create capstone");
            */

        let yax = <yaxpeax_arm::armv7::ARMv7 as Arch>::Decoder::default()
            .with_thumb_mode(true)
            .allow_nonconforming(true);

        let mut cs_text = String::new();
        let mut yax_text = String::new();

        for i in start..=end {
            let i = i as u32;
            let bytes = &i.to_le_bytes();
            if i % 0x01_00_00_00 == 0 {
//                eprintln!("case {:08x}", i);
            }

//            let res = cs.disasm_all(bytes, 0);
            let res = unsafe {
                capstone_sys::cs_disasm_iter(
                    csh,
                    &mut bytes.as_ptr() as *mut *const u8,
                    &mut bytes.len() as *mut usize,
                    &mut 0u64 as *mut u64,
                    cs_insn,
                )
            };
//            if let Ok(insts) = &res {
            if res {
//                let insts_slice = insts.as_ref();
//              if insts_slice.len() == 1 {
                {
                    cs_text.clear();
                    yax_text.clear();
                    // then yax should also succeed..
                    // and it should only be one instruction
//                    let cs_text = format!("{}", insts_slice[0]);
//                    let cs_text = &cs_text[5..];
                    unsafe {
                        use std::ffi::CStr;
                        write!(cs_text, "{} {}",
                            CStr::from_ptr((*cs_insn).mnemonic.as_ptr()).to_str().unwrap(),
                            CStr::from_ptr((*cs_insn).op_str.as_ptr()).to_str().unwrap(),
                        ).unwrap();
                    };

                    // TODO: temporary to get one diff run done
                    if cs_text.starts_with("mrseq") {
                        continue;
                    }

                    let yax_res = yax.decode(&mut yaxpeax_arch::U8Reader::new(bytes));
                    if let Ok(inst) = yax_res {
                        write!(yax_text, "{}", inst).unwrap();
                    } else if let Err(yaxpeax_arm::armv7::DecodeError::Incomplete) = yax_res {
                        // stats.missed_incomplete.fetch_add(1, Ordering::Relaxed);
                        continue;
                    } else {
                        let word = i;
                        if (word >> 16) & 0xf0ff == 0xf0bf &&
                            cs_text.starts_with("it") &&
                            yax_res == Err(yaxpeax_arm::armv7::DecodeError::Nonconforming) {
                            // capstone accepts IT/firstcond=1111, but the encoding is
                            // UNPREDICTABLE.
                            continue;
                        } else if cs_text.starts_with("udf") &&
                            yax_res == Err(yaxpeax_arm::armv7::DecodeError::Undefined) {
                            // TODO: yax decodes undefined instructions as "Undefined", but the
                            // manual reports them as udf #imm. yax needs to change.
                            continue;
                        } else if cs_text.starts_with("stlex" ) || cs_text.starts_with("ldrex") {
                            // TODO: yax is missing thumb-mode ldrexd/stlexd? it's not clear which
                            // ISA version these were added in, though they're in DDI0487 G.b ..
                            continue;
                        } else if cs_text.starts_with("usada8") || cs_text.starts_with("usad8") {
                            // TODO: not sure what's up with this. fix it!
                            continue;
                        } else if !cs_text.starts_with("stc") {
                            eprintln!("yax errored where capstone succeeded. cs text: '{}', bytes: {:x?}. meanwhile, yax: {:?}", cs_text, bytes, yax_res);
                            stats.missed_incomplete.fetch_add(1, Ordering::Relaxed);
                        };
                    }

                    fn acceptable_match(word: u32, yax_text: &str, cs_text: &str) -> bool {
                        if yax_text == cs_text {
                            return true;
                        }

                        // TODO: temp while getting one differential test go..
                        if yax_text.starts_with("mrseq") && cs_text.starts_with("mrseq") {
                            return true;
                        }

                        // TODO: more hax
                        if cs_text.starts_with("stc") {
                            return true;
                        }

                        let parsed_yax = ParsedDisassembly::parse(yax_text);
                        let parsed_cs = ParsedDisassembly::parse(cs_text);

                        if parsed_yax == parsed_cs {
                            return true;
                        }

                        if (parsed_yax.opcode == "add" &&
                            parsed_cs.opcode == "add") ||
                            (parsed_yax.opcode == "adds" &&
                             parsed_cs.opcode == "adds") {
                            // capstone prints the T2 encoding of `ADD (register, Thumb)` as if
                            // it is the T1 encoding with three registers.
                            if parsed_yax.operand_count() == 2 && parsed_cs.operand_count() == 3 {
                                if parsed_yax.operands[0] == parsed_cs.operands[0] &&
                                    parsed_yax.operands[1] == parsed_cs.operands[1] &&
                                    parsed_cs.operands[0] == parsed_cs.operands[2] {
                                    return true;
                                }
                            }

                            // capstone prints the T2 encoding of `ADD (SP plus immediate)` with
                            // two operands instead of the three from the manual.
                            if word & 0xff80 == 0xb000 &&
                                parsed_yax.opcode == "add" &&
                                parsed_cs.opcode == "add" &&
                                parsed_yax.operands[0] == parsed_cs.operands[0] &&
                                parsed_yax.operands[0] == parsed_yax.operands[1] &&
                                parsed_cs.operands[1] == parsed_yax.operands[2] {
                                return true;
                            }
                        }

                        if (parsed_yax.opcode == "sub" &&
                            parsed_cs.opcode == "sub") {
                            // capstone prints the T1 encoding of `SUB (SP minus immediate)` with
                            // two operands instead of the three from the manual.
                            if word & 0xff80 == 0xb080 &&
                                parsed_yax.opcode == "sub" &&
                                parsed_cs.opcode == "sub" &&
                                parsed_yax.operands[0] == parsed_cs.operands[0] &&
                                parsed_yax.operands[0] == parsed_yax.operands[1] &&
                                parsed_cs.operands[1] == parsed_yax.operands[2] {
                                return true;
                            }
                        }

                        if (parsed_yax.opcode == "cpsie" && parsed_cs.opcode == "cpsie") ||
                            (parsed_yax.opcode == "cpsid" && parsed_cs.opcode == "cpsid") {
                            // TODO: is cpsie <none> printed with the label or no?
                            if let Some(ParsedOperand::Other(name)) = parsed_cs.operands[0].as_ref() {
                                if name == "none" && parsed_yax.operands[0].is_none() {
                                    return true;
                                }
                            }
                        }

                        // TODO: yaxpeax-arm doesn't know about armv8-m yet, which gets `bxns` to
                        // replace `bx` in some encodings.
                        if parsed_yax.opcode == "bx" && parsed_cs.opcode == "bxns" {
                            if parsed_yax.operands == parsed_cs.operands {
                                return true;
                            }
                        }

                        // TODO: same for blx/blxns.
                        if parsed_yax.opcode == "blx" && parsed_cs.opcode == "blxns" {
                            if parsed_yax.operands == parsed_cs.operands {
                                return true;
                            }
                        }

                        // TODO: yax probably should simply write `stm` in this case like the
                        // manual implies and capstone does.
                        if parsed_yax.opcode == "stmia" && parsed_cs.opcode == "stm"
                            && parsed_yax.operands == parsed_cs.operands {
                                return true;
                        }

                        static BRANCHES: &'static [&'static str] = &[
                            "bgt", "bhi", "b", "ble", "bge", "blt", "bge",
                            "bhs", "blo", "beq", "bne", "bpl", "bmi", "bvc",
                            "bvs", "bls", "bfi", "b.w","blx.w",
                        ];
                        if BRANCHES.contains(&parsed_yax.opcode.as_str()) && parsed_yax.opcode == parsed_cs.opcode {
                            // TODO: the harness doesn't relativeizie branch targets?
                            return true;
                        }

                        if false {
                            eprintln!("yax: {} -> {:?}", yax_text, parsed_yax);
                            eprintln!("cs: {} -> {:?}", cs_text, parsed_cs);
                        }

                        false
                    }

//                    eprintln!("{}", yax_text);
                    if !acceptable_match(i, &yax_text, &cs_text) {
//                        eprintln!("disassembly mismatch: {} != {}. bytes: {:x?}", yax_text, cs_text, bytes);
//                        std::process::abort();
                        stats.mismatch.fetch_add(1, Ordering::Relaxed);
                    } else {
                        stats.good.fetch_add(1, Ordering::Relaxed);
                    }
//                } else {
                    // yax should also fail?
                }
            }
        }

        // add to stats only once because for some reason on aarch64 the increments here call into
        // a builtin to conditionally use the armv8.1 atomic instructions....???
        /*
        stats.mismatch.fetch_add(local_mismatch, Ordering::Release);
        stats.good.fetch_add(local_good, Ordering::Release);
        stats.yax_reject.fetch_add(local_yax_reject, Ordering::Release);
        stats.missed_incomplete.fetch_add(local_missed_incomplete, Ordering::Release);
        */
    }

    const NR_THREADS: u64 = 512;

    let range_size = (u32::MAX as u64 + 1) / NR_THREADS;

    let mut handles = Vec::new();

    let stats = Arc::new(stats);

    // test_range(0x00_00_00_00, 0xff_ff_ff_ff, Arc::clone(&stats));

    for i in 0..NR_THREADS {
        let stats = Arc::clone(&stats);
        let handle = std::thread::spawn(move || test_range(i * range_size, i * range_size + range_size, stats));
        handles.push(handle);
    }

    while let Some(handle) = handles.pop() {
        handle.join().unwrap();
    }

    eprintln!("match:      {}", stats.good.load(Ordering::SeqCst));
    eprintln!("mismatch:   {}", stats.mismatch.load(Ordering::SeqCst));
    eprintln!("bad reject: {}", stats.yax_reject.load(Ordering::SeqCst));
    eprintln!("incomplete: {}", stats.missed_incomplete.load(Ordering::SeqCst));
}