cverif 0.1.1

Verifies that compiled machine code faithfully matches its C source
Documentation
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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
//! Differential test of the symbolic Thumb executor (and of the reference interpreter in
//! `tests/support/armsim.rs`) against QEMU's models of real Cortex-M cores.
//!
//! `exec_diff.rs` checks the executor against `armsim`, but both were written from the same
//! reading of the architecture manual.  Here QEMU (`qemu-system-arm`, full-system emulation of
//! an MPS2 or micro:bit board) is the judge:
//!
//! - Batches of cases are generated: single instructions of every encoding space, short
//!   sequences, IT blocks, flag producer/consumer chains and loads/stores (aligned or not)
//!   through registers that point into a data window, each with a random register and flag
//!   state.
//! - A small bare-metal harness (`tests/qemu/harness.{c,S}`, built with arm-none-eabi-gcc)
//!   reads the cases through semihosting, runs each one in Thread mode and stores the
//!   registers, xPSR, fault status and every changed word of memory.  Every case ends in an
//!   exception: the code under test is followed by `bx lr`, LR points at a UDF (the return
//!   pad) and the code field around the case is filled with UDF, so taken branches end at a UDF
//!   too.  One QEMU run executes a whole batch.
//! - `armsim` pre-runs each case: cases that would access memory outside the window, leave the
//!   code field or loop are not sent to QEMU.
//! - The executor's terms are evaluated on the same initial state and compared with what QEMU
//!   did: end (return, trap at which address, or fault), r0-r14, NZCV, every memory word.
//!   `armsim` is compared too.  Instructions QEMU treats as UNDEFINED (or that fault) must not
//!   be given a meaning by the executor.
//!
//! The executor is given each board's core (`cverif::thumb::arch::Profile`): an instruction the
//! core does not have (Thumb-2 on ARMv6-M, the DSP extension on Cortex-M3, floating point
//! without a unit, double precision on a single-precision one) must be a trap at that
//! instruction for both.  The M4 and M33 harnesses enable the floating-point unit and load
//! s0-s31 from the data window, so floating-point instructions are compared there.  armsim is
//! not core-specific: its runs of such instructions are counted separately, as are the
//! alignment faults the executor cannot decide (it traps on LDM / STM / LDRD / STRD only at
//! constant misaligned addresses, and ARMv6-M faults on every misaligned access).  Everything
//! else that differs fails the test.
//!
//! QEMU bugs found on the way (see the triage notes at `qemu_ldrh_hint_bug`,
//! `qemu_m0_runs_thumb2` and `qemu_m3_runs_dsp`): the LDRH memory hints with Rt=15 are executed
//! as loads into the PC, CBZ / CBNZ / IT run on the Cortex-M0, and most DSP extends and
//! multiplies run on the Cortex-M3, which do not have them.
//!
//! The test skips itself when `qemu-system-arm` or `arm-none-eabi-gcc` is missing.
//! `CVERIF_QEMU_CASES=<n>` sets the number of cases per core (default 10000);
//! `CVERIF_QEMU_VERBOSE=1` prints every disagreement class with examples.

#![allow(clippy::needless_range_loop)]

#[path = "support/armsim.rs"]
mod armsim;

use armsim::{Bus, Cpu};
use cverif::image::{Image, Segment};
use cverif::sym::{Ctx, Limits, Mem, Stop, UNINIT_EPOCH};
use cverif::term::{Env, Node, T};
use cverif::thumb::arch::{Fpu, Need, Profile, need};
use cverif::thumb::exec::{Callee, Exit, Machine};
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

const QEMU: &str = "qemu-system-arm";
const GCC: &str = "arm-none-eabi-gcc";

// ---------------------------------------------------------------------------------------------
// targets and memory layout (see tests/qemu/harness.c)

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
enum Arch {
    V6M,
    V7M,
    V7EM,
    V8MMain,
}

struct Target {
    name: &'static str,
    machine: &'static str,
    /// Where the harness's code goes (flash or code RAM; the vector table is at its start).
    flash: u32,
    ram: u32,
    arch: Arch,
}

impl Target {
    /// What QEMU's model of the core has: the M4 and M33 boards have the DSP extension and a
    /// single-precision unit (FPv4 and FPv5).
    fn profile(&self) -> Profile {
        let p = Profile::from_cpu(self.name).unwrap();
        match self.arch {
            Arch::V7EM => p.with_fpu("fpv4-sp-d16").unwrap(),
            Arch::V8MMain => p.with_fpu("fpv5-sp-d16").unwrap(),
            _ => p,
        }
    }
}

const M0: Target = Target {
    name: "cortex-m0",
    machine: "microbit",
    flash: 0,
    ram: 0x2000_0000,
    arch: Arch::V6M,
};
const M3: Target = Target {
    name: "cortex-m3",
    machine: "mps2-an385",
    flash: 0,
    ram: 0x2000_0000,
    arch: Arch::V7M,
};
const M4: Target = Target {
    name: "cortex-m4",
    machine: "mps2-an386",
    flash: 0,
    ram: 0x2000_0000,
    arch: Arch::V7EM,
};
const M33: Target = Target {
    name: "cortex-m33",
    machine: "mps2-an505",
    flash: 0x1000_0000,
    ram: 0x3800_0000,
    arch: Arch::V8MMain,
};

const FIELD_LEN: u32 = 0x1000;
const WIN_LEN: u32 = 0x2000;
const CODE_MAX: usize = 64;
const MEM_MAX: usize = 64;
const OUT_WORDS: usize = 24;
const UDF_FILL: u16 = 0xdefe;
const MAGIC: u32 = 0x5145_4d55;

#[derive(Clone, Copy)]
struct Layout {
    field: u32,
    at: u32,
    retpad: u32,
    win: u32,
    sp0: u32,
    /// The core, as the executor is told it; with a floating-point unit, the harness enables
    /// it and loads s0-s31 from the first words of the window.
    profile: Profile,
}

impl Layout {
    fn of(t: &Target) -> Layout {
        Layout {
            field: t.ram,
            at: t.ram + 0x800,
            retpad: t.ram + FIELD_LEN - 2,
            win: t.ram + FIELD_LEN,
            sp0: t.ram + 0x2000,
            profile: t.profile(),
        }
    }

    fn has_fpu(&self) -> bool {
        matches!(self.profile.fpu, Fpu::Present { .. })
    }

    fn in_field(&self, a: u32) -> bool {
        a.wrapping_sub(self.field) < FIELD_LEN
    }

    fn in_win(&self, a: u32) -> bool {
        a.wrapping_sub(self.win) < WIN_LEN
    }

    /// Initial value of an observed word (must match `expected` in harness.c).
    fn word(&self, a: u32, seed: u32) -> u32 {
        if self.in_field(a) {
            return (UDF_FILL as u32) << 16 | UDF_FILL as u32;
        }
        if a == self.sp0 - 4 {
            return self.at | 1;
        }
        let mut x = a.wrapping_mul(0x9e37_79b1) ^ seed;
        x ^= x >> 15;
        x = x.wrapping_mul(0x85eb_ca77);
        x ^= x >> 13;
        x = x.wrapping_mul(0xc2b2_ae3d);
        x ^= x >> 16;
        x
    }

    fn byte(&self, a: u32, seed: u32) -> u8 {
        (self.word(a & !3, seed) >> (8 * (a & 3))) as u8
    }

    /// The code field with `code` and the `bx lr` after it.
    fn field_image(&self, code: &[u8]) -> Vec<u8> {
        let mut data = Vec::with_capacity(FIELD_LEN as usize);
        while data.len() < FIELD_LEN as usize {
            data.extend_from_slice(&UDF_FILL.to_le_bytes());
        }
        let o = (self.at - self.field) as usize;
        data[o..o + code.len()].copy_from_slice(code);
        data[o + code.len()..o + code.len() + 2].copy_from_slice(&0x4770u16.to_le_bytes());
        data
    }
}

// ---------------------------------------------------------------------------------------------
// random states and cases

struct Rng(u64);

impl Rng {
    fn next(&mut self) -> u64 {
        self.0 ^= self.0 << 13;
        self.0 ^= self.0 >> 7;
        self.0 ^= self.0 << 17;
        self.0
    }

    fn below(&mut self, n: u64) -> u64 {
        self.next() % n
    }

    fn chance(&mut self, num: u64, den: u64) -> bool {
        self.below(den) < num
    }

    fn value(&mut self, lay: &Layout) -> u32 {
        match self.below(16) {
            0 => 0,
            1 => 1,
            2 => 0xffff_ffff,
            3 => 0x8000_0000,
            4 => 0x7fff_ffff,
            5 => self.below(40) as u32,
            6 => (self.below(64) as u32).wrapping_neg(),
            7 => 1 << self.below(32),
            8 => self.below(256) as u32 * 4,
            9 => self.next() as u32 & 0xffff,
            10 => self.next() as u32,
            // addresses in the data window, mostly aligned
            11 | 12 => (lay.win + 0x400 + self.below(0x1800) as u32) & !3,
            13 => lay.win + 0x400 + self.below(0x1800) as u32,
            _ => lay.win + 0xc00 + (self.below(0x200) as u32) * 4,
        }
    }
}

#[derive(Clone, Debug)]
struct State {
    r: [u32; 15],
    flags: [bool; 4], // n z c v
}

fn random_state(rng: &mut Rng, lay: &Layout) -> State {
    let mut r = [0u32; 15];
    for x in r.iter_mut() {
        *x = rng.value(lay);
    }
    r[13] = lay.sp0;
    r[14] = lay.retpad | 1;
    let f = rng.next();
    State {
        r,
        flags: [f & 1 != 0, f & 2 != 0, f & 4 != 0, f & 8 != 0],
    }
}

fn is_wide(hw1: u16) -> bool {
    hw1 >> 11 >= 0b11101
}

fn halfwords(code: &[u8]) -> Vec<u16> {
    code.chunks(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect()
}

fn hex(code: &[u8]) -> String {
    halfwords(code)
        .iter()
        .map(|h| format!("{h:04x}"))
        .collect::<Vec<_>>()
        .join(" ")
}

/// Instructions the harness cannot run: semihosting calls, sleeps, changes of the execution
/// priority or of the stack in use, the Security-state branches, and the hint QEMU mistakes for
/// a load into the PC (which can jump into the harness).
fn forbidden(code: &[u8]) -> bool {
    if qemu_ldrh_hint_bug(code) {
        return true;
    }
    let h = halfwords(code);
    let mut i = 0;
    while i < h.len() {
        let w = h[i];
        if w == 0xbeab || w == 0xbf20 || w == 0xbf30 || w & 0xffe8 == 0xb660 || w & 0xff07 == 0x4704 {
            return true;
        }
        if is_wide(w) {
            let w2 = *h.get(i + 1).unwrap_or(&0);
            // MSR, and the WFE / WFI hints
            if w & 0xffe0 == 0xf380 && w2 & 0xd000 == 0x8000 {
                return true;
            }
            if w & 0xfff0 == 0xf3a0 && w2 & 0xd700 == 0x8000 && matches!(w2 & 0xff, 2 | 3) {
                return true;
            }
            i += 2;
        } else {
            i += 1;
        }
    }
    false
}

fn push16(v: &mut Vec<u8>, hws: &[u16]) {
    for hw in hws {
        v.extend(hw.to_le_bytes());
    }
}

/// A 32-bit branch (B.W, B<c>.W, BL) whose target is near enough to stay in the code field.
fn near_branch(rng: &mut Rng, hw1: u16, hw2: u16) -> (u16, u16) {
    let off = rng.below(0x600) as i32 - 0x300; // halfwords
    let s = (off < 0) as u16;
    if hw2 & 0x1000 == 0 && hw2 & 0x4000 == 0 {
        // B<c>.W: S:J2:J1:imm6:imm11
        let imm11 = off as u16 & 0x7ff;
        let imm6 = (off >> 11) as u16 & 0x3f;
        let (j1, j2) = (s, s);
        (
            hw1 & 0xfbc0 | s << 10 | imm6,
            hw2 & 0xd000 | j1 << 13 | j2 << 11 | imm11,
        )
    } else {
        // B.W / BL / BLX: S:I1:I2:imm10:imm11, I = !(J ^ S)
        let imm11 = off as u16 & 0x7ff;
        let imm10 = (off >> 11) as u16 & 0x3ff;
        let (i1, i2) = (s, s);
        let (j1, j2) = (!(i1 ^ s) & 1, !(i2 ^ s) & 1);
        (
            hw1 & 0xf800 | s << 10 | imm10,
            hw2 & 0xd000 | j1 << 13 | j2 << 11 | imm11,
        )
    }
}

fn rand32(rng: &mut Rng) -> Vec<u8> {
    let x = rng.next();
    let mut hw1 = 0xe800 | (x as u16 & 0x1fff);
    // Mostly the integer instruction space: coprocessor / FP space only now and then.
    if (hw1 & 0x0400 != 0 && hw1 >> 11 == 0b11101 || hw1 >> 10 == 0b111111) && !rng.chance(1, 8) {
        hw1 &= !0x0400;
    }
    let mut hw2 = (x >> 16) as u16;
    if hw1 >> 11 == 0b11110 && hw2 & 0x8000 != 0 && rng.chance(3, 4) {
        (hw1, hw2) = near_branch(rng, hw1, hw2);
    }
    let mut v = Vec::new();
    push16(&mut v, &[hw1, hw2]);
    v
}

/// The 32-bit instructions of ARMv6-M (BL, MRS, the barriers, UDF.W), with random bits.
fn v6m_32(rng: &mut Rng) -> Vec<u8> {
    let (hw1, hw2) = match rng.below(4) {
        0 => near_branch(rng, 0xf000, 0xd000),
        1 => (
            0xf3ef,
            0x8000 | (rng.below(16) as u16) << 8 | [0, 1, 2, 3, 5, 6, 7, 8, 9, 16, 20][rng.below(11) as usize],
        ),
        2 => (0xf3bf, 0x8f40 | (rng.below(3) as u16) << 4 | 0xf),
        _ => (0xf7f0 | rng.below(16) as u16, 0xa000 | rng.below(0x1000) as u16),
    };
    let mut v = Vec::new();
    push16(&mut v, &[hw1, hw2]);
    v
}

fn rand16(rng: &mut Rng, it_ok: bool) -> u16 {
    loop {
        let hw = rng.below(0xe800) as u16;
        if hw & 0xff00 == 0xbf00 && hw & 0xf != 0 && !it_ok {
            continue;
        }
        return hw;
    }
}

/// 16-bit loads and stores, LDM/STM, PUSH/POP, literal loads.
fn mem16(rng: &mut Rng) -> u16 {
    match rng.below(5) {
        0 | 1 => 0x5000 + rng.below(0x5000) as u16,
        2 => 0x4800 + rng.below(0x800) as u16,
        3 => 0xc000 + rng.below(0x1000) as u16,
        _ => [0xb400, 0xbc00][rng.below(2) as usize] | rng.below(0x200) as u16,
    }
}

/// 32-bit loads and stores: single, dual, multiple, exclusive, table branches.
fn mem32(rng: &mut Rng) -> Vec<u8> {
    let hw1 = if rng.chance(2, 3) {
        0xf800 | rng.below(0x200) as u16
    } else {
        0xe800 | rng.below(0x200) as u16
    };
    let mut hw2 = rng.next() as u16;
    if rng.chance(1, 2) {
        hw2 &= 0xff0f; // small offsets / shift amounts
    }
    let mut v = Vec::new();
    push16(&mut v, &[hw1, hw2]);
    v
}

/// Instructions compilers emit, one or two bits away (the list of `exec_diff.rs`).
const NEAR: &[(u16, u16)] = &[
    (0xf04f, 0x30ff),
    (0xf100, 0x0c01),
    (0xf1a0, 0x0210),
    (0xf5b0, 0x7f80),
    (0xf000, 0x0301),
    (0xf080, 0x0003),
    (0xf64c, 0x41cd),
    (0xf6cc, 0x41cc),
    (0xf2c0, 0x0100),
    (0xeb00, 0x0081),
    (0xeba0, 0x0043),
    (0xea4f, 0x1030),
    (0xea40, 0x2001),
    (0xea6f, 0x0000),
    (0xeb10, 0x0001),
    (0xeb41, 0x0103),
    (0xeb61, 0x0103),
    (0xebc0, 0x00c0),
    (0xebb0, 0x0f01),
    (0xea10, 0x0f01),
    (0xfa00, 0xf001),
    (0xfa20, 0xf001),
    (0xfa40, 0xf001),
    (0xfa60, 0xf001),
    (0xfa0f, 0xf080),
    (0xfa1f, 0xf080),
    (0xfa4f, 0xf080),
    (0xfa5f, 0xf080),
    (0xfa90, 0xf080),
    (0xfa90, 0xf0a0),
    (0xfab0, 0xf080),
    (0xfb00, 0xf001),
    (0xfb00, 0x2001),
    (0xfb00, 0x2011),
    (0xfb90, 0xf0f1),
    (0xfbb0, 0xf0f1),
    (0xfba0, 0x1201),
    (0xfb80, 0x0101),
    (0xfbe0, 0x1201),
    (0xfbc0, 0x0101),
    (0xfb10, 0xf001),
    (0xfb10, 0x2011),
    (0xf8d0, 0x0004),
    (0xf8c0, 0x1004),
    (0xf890, 0x0001),
    (0xf8b0, 0x0002),
    (0xf990, 0x0001),
    (0xf9b0, 0x0002),
    (0xf850, 0x0021),
    (0xf840, 0x1022),
    (0xf850, 0x1b04),
    (0xf840, 0x1d04),
    (0xf85d, 0x7b04),
    (0xf84d, 0x7d04),
    (0xf810, 0x1f01),
    (0xf800, 0x1c01),
    (0xf8df, 0x0010),
    (0xf85f, 0x0004),
    (0xe9d0, 0x0102),
    (0xe9c0, 0x0102),
    (0xe8f0, 0x0102),
    (0xe9e0, 0x0102),
    (0xe8bd, 0x41f0),
    (0xe92d, 0x41f0),
    (0xe890, 0x000e),
    (0xe8a0, 0x000e),
    (0xe8b0, 0x000e),
    (0xe930, 0x000e),
    (0xe8df, 0xf001),
    (0xe8df, 0xf011),
    (0xf360, 0x0107),
    (0xf36f, 0x0107),
    (0xf3c0, 0x1003),
    (0xf340, 0x1003),
    (0xf300, 0x0007),
    (0xf380, 0x0008),
    (0xf1c0, 0x0000),
    (0xf140, 0x0000),
    (0xf160, 0x0000),
    (0xf110, 0x0f01),
    (0xf090, 0x0f01),
    (0xf010, 0x0f01),
    (0xf060, 0x0001),
    (0xf020, 0x0001),
    (0xf44f, 0x7080),
    (0xf06f, 0x0001),
    (0xf20f, 0x0004),
    (0xf2af, 0x0004),
    (0xf200, 0x0001),
    (0xf2a0, 0x0001),
    (0xea5f, 0x0030),
    (0xea5f, 0x0050),
    (0xf3af, 0x8000),
    (0xf7f0, 0xa000),
    (0xfb20, 0x0001),
    (0xfb30, 0x0001),
    (0xfb40, 0x0001),
    (0xfac0, 0xf080),
    (0xfa80, 0xf000),
];

fn near_compiler(rng: &mut Rng) -> Vec<u8> {
    let (hw1, hw2) = NEAR[rng.below(NEAR.len() as u64) as usize];
    let word = (hw1 as u32) << 16 | hw2 as u32;
    let v = match rng.below(3) {
        0 => word ^ 1 << rng.below(32),
        1 => word ^ 1 << rng.below(32) ^ 1 << rng.below(32),
        _ => word ^ (rng.next() as u32 & 0x000f_7fff),
    };
    let (mut a, b) = ((v >> 16) as u16, v as u16);
    if !is_wide(a) {
        a = hw1;
    }
    let mut out = Vec::new();
    push16(&mut out, &[a, b]);
    out
}

/// IT block bodies (16-bit and 32-bit, flag-setting or not).
const BODY: &[&[u16]] = &[
    &[0x1840],
    &[0x1a40],
    &[0x3001],
    &[0x3801],
    &[0x2105],
    &[0x4048],
    &[0x4308],
    &[0x43c8],
    &[0x4088],
    &[0x4108],
    &[0x4148],
    &[0x4188],
    &[0x4248],
    &[0x4348],
    &[0x0048],
    &[0x1048],
    &[0x4288],
    &[0x42c8],
    &[0x2800],
    &[0x4608],
    &[0x6808],
    &[0x6008],
    &[0xb2c8],
    &[0xf04f, 0x0801],
    &[0xf110, 0x0001],
    &[0xeb10, 0x0041],
    &[0xfb00, 0xf001],
    &[0xf1b0, 0x0f05],
    &[0xea5f, 0x0040],
    &[0xf850, 0x1b04],
    &[0xbf00],
    &[0xdefe],
    &[0x4770],
    &[0xe7fe],
];

fn it_block(rng: &mut Rng) -> Vec<u8> {
    let cond = rng.below(15) as u16;
    let mask = 1 + rng.below(15) as u16;
    let len = 4 - mask.trailing_zeros() as usize;
    let mut code = Vec::new();
    push16(&mut code, &[0xbf00 | cond << 4 | mask]);
    for _ in 0..len {
        let b = BODY[rng.below(BODY.len() as u64) as usize];
        push16(&mut code, b);
    }
    code
}

const PRODUCERS: &[&[u16]] = &[
    &[0x1840],
    &[0x1a40],
    &[0x4288],
    &[0x42c8],
    &[0x4208],
    &[0x0048],
    &[0x0848],
    &[0x1048],
    &[0x4088],
    &[0x40c8],
    &[0x4108],
    &[0x41c8],
    &[0x4248],
    &[0x4348],
    &[0x2800],
    &[0x4148],
    &[0x4188],
    &[0xf110, 0x0f01],
    &[0xf1b0, 0x0f05],
    &[0xebb0, 0x0f41],
    &[0xea10, 0x7f01],
    &[0xea90, 0x0f31],
    &[0xea5f, 0x0031],
    &[0xea5f, 0x0071],
    &[0xfa10, 0xf001],
    &[0xfa30, 0xf001],
    &[0xfa50, 0xf001],
    &[0xfa70, 0xf001],
    &[0xf090, 0x4f00],
    &[0xf010, 0x0fff],
    &[0xf5b0, 0x3f80],
    &[0xeb50, 0x0001],
    &[0xeb70, 0x0001],
    &[0xf1d0, 0x0000],
    &[0xf150, 0x0000],
    &[0xf170, 0x0000],
    &[0xebd0, 0x0001],
];

const CONSUMERS: &[&[u16]] = &[
    &[0x4148],
    &[0x4188],
    &[0x41c8],
    &[0xeb41, 0x0002],
    &[0xeb61, 0x0002],
    &[0xea4f, 0x0030],
    &[0xea5f, 0x0030],
    &[0xf141, 0x0100],
    &[0xf161, 0x0100],
    &[0xd000],
    &[0xd100],
    &[0xd200],
    &[0xd300],
    &[0xd400],
    &[0xd500],
    &[0xd600],
    &[0xd700],
    &[0xd800],
    &[0xd900],
    &[0xda00],
    &[0xdb00],
    &[0xdc00],
    &[0xdd00],
    &[0xf000, 0x8000],
    &[0xf040, 0x8000],
    &[0xf280, 0x8000],
    &[0xf2c0, 0x8000],
    &[0xf300, 0x8000],
    &[0xf340, 0x8000],
    &[0xf200, 0x8000],
    &[0xf240, 0x8000],
];

fn flag_chain(rng: &mut Rng, thumb1: bool) -> Vec<u8> {
    loop {
        let p = PRODUCERS[rng.below(PRODUCERS.len() as u64) as usize];
        let c = CONSUMERS[rng.below(CONSUMERS.len() as u64) as usize];
        if thumb1 && (p.len() > 1 || c.len() > 1) {
            continue;
        }
        let mut code = Vec::new();
        push16(&mut code, p);
        push16(&mut code, c);
        push16(&mut code, &[0x3701]); // a taken branch skips `adds r7, #1`
        return code;
    }
}

/// A floating-point data-processing instruction (any encoding of the space), followed by moves
/// of its destination register to r0 (and r1), so that the result is observed, and now and then
/// by the VMRS that copies the comparison flags.
fn fp_op(rng: &mut Rng) -> Vec<u8> {
    let x = rng.next();
    let hw1 = 0xee00 | (x as u16 & 0xff);
    let hw2 = ((x >> 16) as u16 & 0xf1ef) | 0x0a00;
    let double = hw2 & 0x100 != 0;
    let (d, vd) = ((hw1 >> 6) & 1, hw2 >> 12);
    let s = if double { 2 * (d << 4 | vd) } else { vd << 1 | d };
    let mut v = Vec::new();
    push16(&mut v, &[hw1, hw2]);
    for (rt, sn) in [(0u16, s), (1, s + 1)].into_iter().take(1 + double as usize) {
        if sn < 32 {
            push16(&mut v, &[0xee10 | sn >> 1, rt << 12 | 0x0a10 | (sn & 1) << 7]);
        }
    }
    if rng.chance(1, 4) {
        push16(&mut v, &[0xeef1, 0xfa10]);
    }
    v
}

fn gen_code(rng: &mut Rng, arch: Arch) -> (Vec<u8>, &'static str) {
    loop {
        let (code, class) = if arch == Arch::V6M {
            match rng.below(20) {
                0..=6 => {
                    let it = rng.chance(1, 20);
                    (rand16(rng, it).to_le_bytes().to_vec(), "16-bit")
                }
                7..=10 => (mem16(rng).to_le_bytes().to_vec(), "16-bit memory"),
                11..=13 => (flag_chain(rng, true), "flag chain"),
                14 | 15 => {
                    let mut v = Vec::new();
                    for _ in 0..2 + rng.below(2) {
                        push16(&mut v, &[rand16(rng, false)]);
                    }
                    (v, "16-bit sequence")
                }
                16..=18 => (v6m_32(rng), "ARMv6-M 32-bit"),
                _ => (rand32(rng), "32-bit"),
            }
        } else {
            match rng.below(20) {
                0..=3 => (rand16(rng, false).to_le_bytes().to_vec(), "16-bit"),
                4..=8 => (rand32(rng), "32-bit"),
                9 | 10 => (near_compiler(rng), "near-compiler 32-bit"),
                11 | 12 => (it_block(rng), "IT block"),
                13 | 14 => (flag_chain(rng, false), "flag chain"),
                15 | 16 => (mem16(rng).to_le_bytes().to_vec(), "16-bit memory"),
                17 => (fp_op(rng), "floating point"),
                _ => (mem32(rng), "32-bit memory"),
            }
        };
        if !forbidden(&code) && code.len() <= CODE_MAX - 4 {
            return (code, class);
        }
    }
}

// ---------------------------------------------------------------------------------------------
// the reference interpreter on the harness's memory

struct WinMem {
    lay: Layout,
    seed: u32,
    field: Vec<u8>,
    written: HashMap<u32, u8>,
    initial_reads: HashMap<u32, u8>,
    /// An access outside the window (reads may also hit the code field).
    outside: bool,
    /// A halfword or word access at an address that is not a multiple of its size.
    misaligned: bool,
}

impl Bus for WinMem {
    fn read(&mut self, a: u32, size: u32) -> u32 {
        self.misaligned |= !a.is_multiple_of(size);
        (0..size).fold(0, |v, i| v | (self.read8(a.wrapping_add(i)) as u32) << (8 * i))
    }

    fn write(&mut self, a: u32, size: u32, v: u32) {
        self.misaligned |= !a.is_multiple_of(size);
        for i in 0..size {
            self.write8(a.wrapping_add(i), (v >> (8 * i)) as u8);
        }
    }

    fn read8(&mut self, a: u32) -> u8 {
        if let Some(&v) = self.written.get(&a) {
            return v;
        }
        let v = if self.lay.in_field(a) {
            self.field[(a - self.lay.field) as usize]
        } else if self.lay.in_win(a) {
            self.lay.byte(a, self.seed)
        } else {
            self.outside = true;
            0
        };
        self.initial_reads.insert(a, v);
        v
    }

    fn write8(&mut self, a: u32, v: u8) {
        if !self.lay.in_win(a) {
            self.outside = true;
        }
        self.written.insert(a, v);
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum End {
    Return,
    /// UDF executed at this address.
    Trap(u32),
    /// Control left the code field.
    Left,
    /// QEMU: an exception other than a UDF (fault status in the text).
    Fault {
        pc: u32,
        cfsr: u32,
        hfsr: u32,
        ipsr: u32,
    },
}

#[derive(Clone, Debug)]
struct Outcome {
    end: End,
    r: [u32; 15],
    /// NZCV, when known.
    flags: Option<[bool; 4]>,
    /// Final value of every byte written.
    mem: BTreeMap<u32, u8>,
}

struct Reference {
    out: Outcome,
    reads: HashMap<u32, u8>,
    /// Some access was misaligned (a fault on ARMv6-M, and for some instructions on ARMv7-M).
    misaligned: bool,
}

/// Run `armsim`.  `Ok(None)` means the case cannot be run on the harness (it leaves the
/// observed memory or the code field, or loops); `Err` that armsim does not model it.
fn run_armsim(lay: &Layout, seed: u32, field: &[u8], st: &State) -> Result<Option<Reference>, armsim::Stop> {
    let mut mem = WinMem {
        lay: *lay,
        seed,
        field: field.to_vec(),
        written: HashMap::new(),
        initial_reads: HashMap::new(),
        outside: false,
        misaligned: false,
    };
    let mut cpu = Cpu::new();
    cpu.r[..15].copy_from_slice(&st.r);
    (cpu.n, cpu.z, cpu.c, cpu.v) = (st.flags[0], st.flags[1], st.flags[2], st.flags[3]);
    cpu.pc = lay.at;
    let mut steps = 0;
    let end = loop {
        if cpu.pc == lay.retpad {
            break End::Return;
        }
        if !lay.in_field(cpu.pc) {
            return Ok(None);
        }
        steps += 1;
        if steps > 40 {
            return Ok(None);
        }
        let at = cpu.pc;
        match cpu.step(&mut mem) {
            Ok(()) => {}
            Err(armsim::Stop::Udf) => break End::Trap(at),
            Err(armsim::Stop::Unaligned(_)) => {
                mem.misaligned = true;
                break End::Trap(at);
            }
            Err(e) => return Err(e),
        }
        if mem.outside {
            return Ok(None);
        }
    };
    // The exception that ends the case is stacked below the stack pointer.
    let sp = cpu.r[13];
    if !(lay.win + 0x100..=lay.win + WIN_LEN).contains(&sp) || mem.outside {
        return Ok(None);
    }
    let mut r = [0u32; 15];
    r.copy_from_slice(&cpu.r[..15]);
    Ok(Some(Reference {
        out: Outcome {
            end,
            r,
            flags: Some([cpu.n, cpu.z, cpu.c, cpu.v]),
            mem: mem.written.into_iter().collect(),
        },
        reads: mem.initial_reads,
        misaligned: mem.misaligned,
    }))
}

// ---------------------------------------------------------------------------------------------
// the symbolic executor

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Mode {
    Concrete,
    Pinned,
    PrivateStack,
}

fn sym_id(ctx: &Ctx, t: T) -> u32 {
    match ctx.tm.node(t) {
        Node::Sym(id) => *id,
        n => panic!("not a symbol: {n:?}"),
    }
}

struct ExecRun {
    end: End,
    r: [u32; 15],
    trace: Vec<u32>,
    mem: BTreeMap<u32, u8>,
}

/// Run the executor on `code` from `st` and evaluate its terms.  `Err` means it declined.
fn run_exec(
    lay: &Layout,
    seed: u32,
    code: &[u8],
    st: &State,
    mode: Mode,
    reads: &HashMap<u32, u8>,
) -> Result<ExecRun, String> {
    let image = {
        let mut built = Image::default();
        built.segments = vec![{
            let mut seg = Segment::new(".text", lay.field, lay.field_image(code));
            seg.exec = true;
            seg
        }];
        built
    };
    let mut ctx = Ctx::new(Limits::default());
    ctx.set_budget(u64::MAX, 2_000_000, Some(Instant::now() + Duration::from_secs(2)));
    let mut env = Env::default();
    for (&a, &b) in reads {
        env.mem.insert((0, a as u64), b);
        env.mem.insert((UNINIT_EPOCH, a as u64), b);
    }
    let mut regs = [0 as T; 16];
    for i in 0..15 {
        let k = ctx.tm.konst(32, st.r[i] as u64);
        regs[i] = match mode {
            Mode::Concrete => k,
            _ if i == 14 => k,
            Mode::PrivateStack if i == 13 => {
                let s = ctx.private_base("SP0");
                env.syms.insert(sym_id(&ctx, s), st.r[i] as u64);
                let low = ctx.tm.extract(s, 0, 3);
                let zero = ctx.tm.konst(3, 0);
                let aligned = ctx.tm.eq(low, zero);
                ctx.pc.push(aligned);
                s
            }
            _ => {
                let s = ctx.named_sym(&format!("r{i}"), 32);
                env.syms.insert(sym_id(&ctx, s), st.r[i] as u64);
                let e = ctx.tm.eq(s, k);
                ctx.pc.push(e);
                s
            }
        };
    }
    regs[15] = ctx.tm.konst(32, 0);
    // The bytes armsim read are facts of the path; the whole window (given for cases armsim
    // does not model) only serves to evaluate the terms.
    let facts = reads.len() < WIN_LEN as usize;
    for (&a, &b) in reads.iter().filter(|_| facts) {
        let k = ctx.tm.konst(8, b as u64);
        let addr = ctx.tm.konst(32, a as u64);
        let l = ctx.tm.load(0, addr, 1);
        let e = ctx.tm.eq(l, k);
        ctx.pc.push(e);
        if mode == Mode::PrivateStack && a.wrapping_sub(st.r[13]).wrapping_add(0x1000) < 0x2000 {
            let addr = ctx
                .tm
                .add_const(regs[13], a.wrapping_sub(st.r[13]) as i32 as i64 as u64);
            let l = ctx.tm.load(UNINIT_EPOCH, addr, 1);
            let e = ctx.tm.eq(l, k);
            ctx.pc.push(e);
        }
    }
    let lr0 = regs[14];
    let mut m = Machine::new(&mut ctx, lay.at, regs);
    m.profile = lay.profile;
    if lay.has_fpu() {
        // The harness loads s0-s31 from the window and clears FPSCR.
        for i in 0..32 {
            m.fregs[i] = ctx.tm.konst(32, lay.word(lay.win + 4 * i as u32, seed) as u64);
        }
        for name in ["fpflag.n", "fpflag.z", "fpflag.c", "fpflag.v"] {
            let s = ctx.named_sym(name, 1);
            env.syms.insert(sym_id(&ctx, s), 0);
            let k = ctx.tm.konst(1, 0);
            let e = ctx.tm.eq(s, k);
            ctx.pc.push(e);
        }
    }
    for (name, v) in ["flag.n", "flag.z", "flag.c", "flag.v"].iter().zip(st.flags) {
        let s = ctx.named_sym(name, 1);
        env.syms.insert(sym_id(&ctx, s), v as u64);
        let k = ctx.tm.konst(1, v as u64);
        let e = ctx.tm.eq(s, k);
        ctx.pc.push(e);
    }
    let field = lay.field;
    let classify = move |addr: u32| {
        if addr.wrapping_sub(field) < FIELD_LEN {
            Callee::Internal
        } else {
            Callee::External("elsewhere".into())
        }
    };
    let exit = m.run(&mut ctx, &image, lr0, &classify);
    let trace: Vec<u32> = m.covered.iter().map(|c| c.0).collect();
    let end = match exit {
        Ok(Exit::Return) => End::Return,
        // System instructions are events (inline asm); QEMU executes them.
        Ok(Exit::Asm { .. }) => return Err("system instruction".into()),
        Ok(Exit::Call { .. }) => End::Left,
        Ok(Exit::Trap) => End::Trap(*trace.last().unwrap_or(&0)),
        Ok(Exit::Cut(_)) => return Err("loop cut point".into()),
        Ok(Exit::Hang) => return Err("endless loop".into()),
        Ok(_) => return Err("unmodelled exit".into()),
        Err(Stop::Unsupported(s)) => {
            let s = s.split(" at ").next().unwrap_or("");
            return Err(format!("unsupported: {}", s.split(" 0x").next().unwrap_or("")));
        }
        Err(e) => return Err(format!("{e:?}")),
    };
    if !ctx.decisions.is_empty() {
        return Err("forked".into());
    }
    let mut memo = HashMap::new();
    let mut r = [0u32; 15];
    for i in 0..15 {
        r[i] = ctx.tm.eval(m.regs[i], &env, &mut memo) as u32;
    }
    let mut mem = BTreeMap::new();
    let Mem { world, private, .. } = &m.mem;
    for log in std::iter::once(world).chain(private.values()) {
        for w in log {
            let a = ctx.tm.eval(w.addr, &env, &mut memo) as u32;
            let v = ctx.tm.eval(w.val, &env, &mut memo);
            for i in 0..w.size as u32 {
                mem.insert(a.wrapping_add(i), (v >> (8 * i)) as u8);
            }
        }
    }
    Ok(ExecRun { end, r, trace, mem })
}

/// `ite <c>; mov<c> rX, #1; mov<!c> rX, #0` for Z, C, N, V into r8..r11.
fn flag_probe() -> Vec<u8> {
    let mut v = Vec::new();
    for (i, cond) in [0u16, 2, 4, 6].into_iter().enumerate() {
        let rd = 8 + i as u16;
        push16(&mut v, &[0xbf0c | cond << 4, 0xf04f, rd << 8 | 1, 0xf04f, rd << 8]);
    }
    v
}

/// The executor's outcome: registers and memory from a run of the code, flags from a run with
/// the flag probe in place of the final `bx lr` (when the code reaches it).
fn executor_outcome(
    lay: &Layout,
    seed: u32,
    code: &[u8],
    st: &State,
    mode: Mode,
    reads: &HashMap<u32, u8>,
) -> Result<Outcome, String> {
    let plain = run_exec(lay, seed, code, st, mode, reads)?;
    let mut flags = None;
    let fall = lay.at + code.len() as u32;
    if plain.end == End::Return && plain.trace.last() == Some(&fall) {
        let mut probed = code.to_vec();
        probed.extend(flag_probe());
        // The probe is Thumb-2: run it on any core (the code itself ran to its end).
        let any = Layout {
            profile: {
                let mut built = Profile::ANY;
                built.fpu = lay.profile.fpu;
                built
            },
            ..*lay
        };
        if let Ok(p) = run_exec(&any, seed, &probed, st, mode, reads)
            && p.trace.last() == Some(&(fall + flag_probe().len() as u32))
            && p.trace[..plain.trace.len() - 1] == plain.trace[..plain.trace.len() - 1]
            // The probe replaces bytes of the code field that the code may read as data.
            && p.r[..8] == plain.r[..8]
            && p.r[12..] == plain.r[12..]
            && p.mem == plain.mem
        {
            flags = Some([p.r[10] == 1, p.r[8] == 1, p.r[9] == 1, p.r[11] == 1]);
        }
    }
    Ok(Outcome {
        end: plain.end,
        r: plain.r,
        flags,
        mem: plain.mem,
    })
}

// ---------------------------------------------------------------------------------------------
// harness build and QEMU runs

fn have(tool: &str) -> bool {
    Command::new(tool)
        .arg("--version")
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

fn workdir(t: &Target) -> PathBuf {
    let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("qemu_diff").join(t.name);
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

fn build_harness(t: &Target) -> PathBuf {
    let dir = workdir(t);
    let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/qemu");
    let ld = dir.join("link.ld");
    std::fs::write(
        &ld,
        format!(
            "MEMORY {{ FLASH (rx) : ORIGIN = {:#x}, LENGTH = 0x40000\n\
             RAM (rw) : ORIGIN = {:#x}, LENGTH = 0x800 }}\n\
             SECTIONS {{\n\
             .text : {{ KEEP(*(.vectors)) *(.text*) *(.rodata*) }} > FLASH\n\
             .bss (NOLOAD) : {{ __bss_start = .; *(.bss*) *(COMMON) . = ALIGN(4); __bss_end = .; }} > RAM\n\
             .data : {{ *(.data*) }} > RAM\n\
             /DISCARD/ : {{ *(.ARM.exidx*) *(.comment) }}\n}}\n",
            t.flash,
            t.ram + 0x3000
        ),
    )
    .unwrap();
    let elf = dir.join("harness.elf");
    let part = dir.join(format!("harness.elf.{}", std::process::id()));
    let mut cmd = Command::new(GCC);
    cmd.args([
        "-mcpu=cortex-m0",
        "-mthumb",
        "-O2",
        "-ffreestanding",
        "-fno-builtin",
        "-nostdlib",
    ])
    .arg(format!("-DRAM_BASE={:#x}", t.ram))
    .arg("-T")
    .arg(&ld)
    .arg(src.join("harness.c"))
    .arg(src.join("harness.S"))
    .arg("-lgcc")
    .arg("-o")
    .arg(&part);
    if t.arch != Arch::V6M {
        cmd.arg("-DHAS_CFSR");
    }
    if Layout::of(t).has_fpu() {
        cmd.arg("-DHAS_FPU");
    }
    let out = cmd.output().expect("run arm-none-eabi-gcc");
    assert!(
        out.status.success(),
        "building the harness failed:\n{}",
        String::from_utf8_lossy(&out.stderr)
    );
    std::fs::rename(&part, &elf).unwrap();
    elf
}

struct Case {
    code: Vec<u8>,
    class: &'static str,
    st: State,
    /// armsim's outcome, or `None` when armsim does not model the case (it is then run only to
    /// see what QEMU does with an encoding the executor accepts).
    reference: Option<Reference>,
}

#[derive(Debug)]
struct QemuOut {
    regs: [u32; OUT_WORDS],
    /// Changed words (address, value); `mem_total` counts them all.
    mem: Vec<(u32, u32)>,
    mem_total: u32,
}

fn run_qemu(t: &Target, elf: &Path, batch: usize, seed: u32, cases: &[Case]) -> Result<Vec<QemuOut>, String> {
    let dir = workdir(t).join(format!("batch{batch}"));
    std::fs::create_dir_all(&dir).unwrap();
    let mut input = Vec::new();
    for w in [MAGIC, cases.len() as u32, seed, 0] {
        input.extend(w.to_le_bytes());
    }
    for c in cases {
        for w in c.st.r {
            input.extend(w.to_le_bytes());
        }
        let apsr = (c.st.flags[0] as u32) << 31
            | (c.st.flags[1] as u32) << 30
            | (c.st.flags[2] as u32) << 29
            | (c.st.flags[3] as u32) << 28;
        input.extend(apsr.to_le_bytes());
        input.extend((c.code.len() as u32).to_le_bytes());
        let mut code = c.code.clone();
        code.resize(CODE_MAX, 0);
        input.extend(code);
    }
    std::fs::write(dir.join("cases.in"), &input).unwrap();
    let _ = std::fs::remove_file(dir.join("cases.out"));
    let mut child = Command::new(QEMU)
        .current_dir(&dir)
        .args([
            "-M", t.machine, "-display", "none", "-monitor", "none", "-serial", "none",
        ])
        .args(["-semihosting-config", "enable=on,target=native"])
        .arg("-kernel")
        .arg(elf)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|e| format!("cannot start {QEMU}: {e}"))?;
    let deadline = Instant::now() + Duration::from_secs(120);
    let status = loop {
        if let Some(s) = child.try_wait().unwrap() {
            break s;
        }
        if Instant::now() > deadline {
            let _ = child.kill();
            let _ = child.wait();
            return Err("QEMU timed out".into());
        }
        std::thread::sleep(Duration::from_millis(20));
    };
    let out = child.wait_with_output().unwrap();
    let data = std::fs::read(dir.join("cases.out")).unwrap_or_default();
    let words: Vec<u32> = data.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(*c)).collect();
    let mut res = Vec::new();
    let mut i = 0;
    while i + 2 + OUT_WORDS <= words.len() {
        let (total, n) = (words[i], words[i + 1] as usize);
        let mut regs = [0; OUT_WORDS];
        regs.copy_from_slice(&words[i + 2..i + 2 + OUT_WORDS]);
        i += 2 + OUT_WORDS;
        let mem = (0..n).map(|k| (words[i + 2 * k], words[i + 2 * k + 1])).collect();
        i += 2 * n;
        res.push(QemuOut {
            regs,
            mem,
            mem_total: total,
        });
    }
    if res.len() != cases.len() {
        // The harness writes one record per case: the first missing one stopped the run.
        let stuck = &cases[res.len().min(cases.len() - 1)];
        return Err(format!(
            "QEMU ({status}) returned {} results for {} cases (case {}: {} from {:x?}); stderr: {}",
            res.len(),
            cases.len(),
            res.len(),
            hex(&stuck.code),
            stuck.st,
            String::from_utf8_lossy(&out.stderr)
        ));
    }
    Ok(res)
}

// ---------------------------------------------------------------------------------------------
// comparison

const UNDEFINSTR: u32 = 1 << 16;
const INVSTATE: u32 = 1 << 17;
const NOCP: u32 = 1 << 19;
const UNALIGNED: u32 = 1 << 24;
const PRECISERR: u32 = 1 << 9;
const IMPRECISERR: u32 = 1 << 10;
const DIVBYZERO: u32 = 1 << 25;

fn fault_name(cfsr: u32, ipsr: u32) -> String {
    let mut v = Vec::new();
    for (bit, name) in [
        (UNDEFINSTR, "UNDEFINSTR"),
        (INVSTATE, "INVSTATE"),
        (1 << 18, "INVPC"),
        (NOCP, "NOCP"),
        (UNALIGNED, "UNALIGNED"),
        (DIVBYZERO, "DIVBYZERO"),
        (1 << 8, "IBUSERR"),
        (PRECISERR, "PRECISERR"),
        (IMPRECISERR, "IMPRECISERR"),
        (1 << 12, "STKERR"),
        (1 << 0, "IACCVIOL"),
        (1 << 1, "DACCVIOL"),
    ] {
        if cfsr & bit != 0 {
            v.push(name);
        }
    }
    if v.is_empty() {
        format!("exception {ipsr}")
    } else {
        v.join("+")
    }
}

/// What QEMU did, in the models' terms, plus the bytes of memory the exception frame covers.
fn qemu_outcome(lay: &Layout, arch: Arch, q: &QemuOut) -> (Outcome, (u32, u32)) {
    let g = &q.regs;
    let (pc, xpsr, cfsr, ipsr, frame) = (g[15], g[16], g[17], g[20], g[21]);
    let sp = g[13];
    let end = if ipsr == 3 && pc == lay.retpad && (arch == Arch::V6M || cfsr == UNDEFINSTR) {
        End::Return
    } else if ipsr == 3 && (arch == Arch::V6M || matches!(cfsr, UNDEFINSTR | NOCP | UNALIGNED)) {
        // ARMv6-M has no fault status: every HardFault at an instruction is a trap there.
        // Elsewhere a UDF, an instruction the core does not have (UNDEFINSTR, or NOCP for
        // the floating-point unit) and an alignment fault are traps at the faulting
        // instruction, as for the executor.  (The executor declines the encodings that are
        // UNDEFINED on every core, so a UsageFault always means the same to both.)
        End::Trap(pc)
    } else {
        End::Fault {
            pc,
            cfsr,
            hfsr: g[18],
            ipsr,
        }
    };
    let mut r = [0u32; 15];
    r[..13].copy_from_slice(&g[..13]);
    r[13] = sp;
    r[14] = g[14];
    let mut mem = BTreeMap::new();
    for &(a, v) in &q.mem {
        for i in 0..4 {
            mem.insert(a + i, (v >> (8 * i)) as u8);
        }
    }
    (
        Outcome {
            end,
            r,
            flags: Some([
                xpsr >> 31 & 1 != 0,
                xpsr >> 30 & 1 != 0,
                xpsr >> 29 & 1 != 0,
                xpsr >> 28 & 1 != 0,
            ]),
            mem,
        },
        (frame, sp),
    )
}

/// Words of observed memory that differ from their initial value after `writes`.
fn changed_words(lay: &Layout, seed: u32, writes: &BTreeMap<u32, u8>, skip: (u32, u32)) -> BTreeMap<u32, u32> {
    let words: std::collections::BTreeSet<u32> = writes.keys().map(|a| a & !3).collect();
    let mut out = BTreeMap::new();
    for &w in &words {
        if (skip.0..skip.1).contains(&w) {
            continue;
        }
        let mut v = lay.word(w, seed);
        for i in 0..4 {
            if let Some(&b) = writes.get(&(w + i)) {
                v = v & !(0xff << (8 * i)) | (b as u32) << (8 * i);
            }
        }
        if v != lay.word(w, seed) {
            out.insert(w, v);
        }
    }
    out
}

fn differences(lay: &Layout, seed: u32, want: &Outcome, got: &Outcome, skip: (u32, u32)) -> Vec<String> {
    let mut d = Vec::new();
    // A branch to the return pad is a return for QEMU, a trap at its UDF for the models.
    let end = if got.end == End::Trap(lay.retpad) {
        End::Return
    } else {
        got.end
    };
    if want.end != end {
        d.push(format!("end: QEMU {:x?}, model {:x?}", want.end, got.end));
        return d;
    }
    for i in 0..15 {
        if want.r[i] != got.r[i] {
            d.push(format!("r{i}: QEMU {:#x}, model {:#x}", want.r[i], got.r[i]));
        }
    }
    if let (Some(a), Some(b)) = (want.flags, got.flags)
        && a != b
    {
        d.push(format!("nzcv: QEMU {a:?}, model {b:?}"));
    }
    let (mw, mg) = (
        changed_words(lay, seed, &want.mem, skip),
        changed_words(lay, seed, &got.mem, skip),
    );
    if mw != mg {
        let keys: std::collections::BTreeSet<u32> = mw.keys().chain(mg.keys()).copied().collect();
        for a in keys.into_iter().filter(|a| mw.get(a) != mg.get(a)).take(4) {
            d.push(format!("mem[{a:#x}]: QEMU {:x?}, model {:x?}", mw.get(&a), mg.get(&a)));
        }
    }
    d
}

/// Does the code contain an instruction the core does not have?  armsim, the reference
/// interpreter, is not core-specific: it executes them, where the core (and the executor, which
/// is told the core's profile) faults.
fn arch_lacks(p: &Profile, code: &[u8]) -> bool {
    let h = halfwords(code);
    let mut i = 0;
    while i < h.len() {
        let w = h[i] as u32;
        let wide = is_wide(h[i]);
        let w2 = wide.then(|| h.get(i + 1).copied().unwrap_or(0) as u32);
        if p.allows(need(w, w2)) != Some(true) {
            return true;
        }
        i += if wide { 2 } else { 1 };
    }
    false
}

/// CBZ / CBNZ and IT are ARMv7-M additions (ARMv6-M A5.2.5: UNDEFINED there), yet QEMU
/// executes them on its Cortex-M0: a QEMU bug.  The executor traps.
fn qemu_m0_runs_thumb2(code: &[u8]) -> bool {
    halfwords(code)
        .iter()
        .any(|&w| w & 0xf500 == 0xb100 || (w & 0xff00 == 0xbf00 && w & 0xf != 0))
}

/// The DSP extension is ARMv7E-M only (ARMv7-M ARM A7.7: "Encoding T1 ARMv7E-M"), yet QEMU
/// executes most of it on its Cortex-M3 (SXTAH, SMUAD, SMLAWy, SMLSD, SMLALD, USAT16, ...;
/// it faults on SMULxy, SMMLA, UMAAL): a QEMU bug.  The executor traps.
fn qemu_m3_runs_dsp(code: &[u8]) -> bool {
    let h = halfwords(code);
    let mut i = 0;
    while i < h.len() {
        let w = h[i];
        if is_wide(w) {
            let w2 = h.get(i + 1).copied().unwrap_or(0) as u32;
            if need(w as u32, Some(w2)) == Need::Dsp {
                return true;
            }
            i += 2;
        } else {
            i += 1;
        }
    }
    false
}

#[derive(Default)]
struct Tally {
    cases: usize,
    /// armsim outcome compared with QEMU.
    armsim_compared: usize,
    /// Executor outcome compared with QEMU.
    exec_compared: usize,
    exec_declined: usize,
    /// Cases armsim does not model, run for the executor alone.
    exec_only: usize,
    /// Disagreement classes: (who, what, class) -> (count, examples).
    classes: BTreeMap<(String, String, String), (usize, Vec<String>)>,
    known: usize,
    unexpected: usize,
}

impl Tally {
    fn record(&mut self, who: &str, what: String, class: String, known: bool, example: String) {
        if known {
            self.known += 1;
        } else {
            self.unexpected += 1;
        }
        let tag = if known { "known" } else { "UNEXPECTED" };
        let e = self
            .classes
            .entry((tag.to_string(), format!("{who}: {what}"), class))
            .or_default();
        e.0 += 1;
        if e.1.len() < 3 {
            e.1.push(example);
        }
    }
}

fn enc_class(code: &[u8]) -> String {
    let hw1 = u16::from_le_bytes([code[0], code[1]]);
    if is_wide(hw1) {
        format!("{:03x}x", hw1 >> 4)
    } else {
        format!("{:02x}xx", hw1 >> 8)
    }
}

fn compare_case(t: &Target, lay: &Layout, seed: u32, c: &Case, q: &QemuOut, mode: Mode, tally: &mut Tally) {
    tally.cases += 1;
    let (want, skip) = qemu_outcome(lay, t.arch, q);
    let cfsr = q.regs[17];
    let ipsr = q.regs[20];
    let example = |d: &[String]| {
        format!(
            "{} [{}] regs {:x?} nzcv {:?} ({mode:?})\n        {}",
            hex(&c.code),
            c.class,
            c.st.r,
            c.st.flags,
            d.join("\n        ")
        )
    };
    let lacks = arch_lacks(&lay.profile, &c.code);
    // A difference that is expected rather than a bug: armsim is not core-specific; QEMU runs
    // CBZ / CBNZ / IT on its Cortex-M0; ARMv6-M faults on every misaligned access; the
    // executor decides the alignment of LDM / STM / LDRD / STRD only for constant addresses.
    // (The executor is told the core's profile: an instruction the core lacks is a trap for
    // both it and QEMU.)
    let known_kind = |who: &str, want: &Outcome| -> Option<String> {
        let name = fault_name(cfsr, ipsr);
        let exception = !matches!(want.end, End::Return);
        if who == "armsim" && exception && lacks {
            return Some(format!("{name}: instruction not in {:?} (armsim has them all)", t.arch));
        }
        if who == "executor" && t.arch == Arch::V6M && qemu_m0_runs_thumb2(&c.code) {
            return Some("QEMU executes CBZ / CBNZ / IT on the Cortex-M0".into());
        }
        if who == "executor" && t.arch == Arch::V7M && qemu_m3_runs_dsp(&c.code) {
            return Some("QEMU executes DSP instructions on the Cortex-M3".into());
        }
        // Cases armsim does not model (floating point) are filtered only on the memory they
        // write: a read outside the harness's memory is a bus fault the executor cannot see.
        if who == "executor" && c.reference.is_none() && cfsr & (PRECISERR | IMPRECISERR) != 0 {
            return Some(format!("{name}: read outside the harness's memory"));
        }
        if exception && t.arch == Arch::V6M && unaligned_access(c) {
            return Some(format!("{name}: misaligned access (ARMv6-M) not modelled"));
        }
        if cfsr == UNALIGNED && who == "executor" && mode != Mode::Concrete {
            return Some(format!("{name}: alignment of a symbolic address not decided"));
        }
        None
    };
    if q.mem_total as usize > MEM_MAX {
        tally.record(
            "harness",
            "too many memory writes".into(),
            enc_class(&c.code),
            false,
            example(&[]),
        );
        return;
    }
    if let Some(r) = &c.reference {
        tally.armsim_compared += 1;
        let d = differences(lay, seed, &want, &r.out, skip);
        if !d.is_empty() {
            let known = known_kind("armsim", &want);
            let what = known
                .clone()
                .unwrap_or_else(|| d[0].split(':').next().unwrap_or("").to_string());
            tally.record("armsim", what, enc_class(&c.code), known.is_some(), example(&d));
        }
    }
    if c.reference.is_none() {
        tally.exec_only += 1;
    }
    let reads = c
        .reference
        .as_ref()
        .map(|r| r.reads.clone())
        .unwrap_or_else(|| full_window(lay, seed));
    match executor_outcome(lay, seed, &c.code, &c.st, mode, &reads) {
        Err(_) => tally.exec_declined += 1,
        Ok(got) => {
            tally.exec_compared += 1;
            let d = differences(lay, seed, &want, &got, skip);
            if !d.is_empty() {
                let known = known_kind("executor", &want).or_else(|| {
                    (c.class == "floating point" && nan_results(&d, &want, &got))
                        .then(|| "NaN result: which NaN is left open by the model".to_string())
                });
                let what = known
                    .clone()
                    .unwrap_or_else(|| d[0].split(':').next().unwrap_or("").to_string());
                tally.record("executor", what, enc_class(&c.code), known.is_some(), example(&d));
            }
        }
    }
}

/// Do QEMU and the executor differ only in r0 / r1, where both hold a NaN (`fp_op` moves a
/// single-precision result to r0, a double-precision one to r0 and r1)?  Which NaN an
/// operation returns (sign, payload) is left open by the model.
fn nan_results(d: &[String], want: &Outcome, got: &Outcome) -> bool {
    let nan32 = |w: u32| w & 0x7f80_0000 == 0x7f80_0000 && w & 0x007f_ffff != 0;
    let nan64 = |lo: u32, hi: u32| hi & 0x7ff0_0000 == 0x7ff0_0000 && (hi & 0x000f_ffff != 0 || lo != 0);
    let nan = |o: &Outcome| nan32(o.r[0]) || nan64(o.r[0], o.r[1]);
    d.iter().all(|l| l.starts_with("r0:") || l.starts_with("r1:")) && nan(want) && nan(got)
}

/// Did armsim's run of the case make a misaligned access (a fault on ARMv6-M)?
fn unaligned_access(c: &Case) -> bool {
    match &c.reference {
        Some(r) => r.misaligned,
        None => true,
    }
}

fn full_window(lay: &Layout, seed: u32) -> HashMap<u32, u8> {
    (lay.win..lay.win + WIN_LEN).map(|a| (a, lay.byte(a, seed))).collect()
}

// ---------------------------------------------------------------------------------------------
// driver

fn cases_per_core() -> usize {
    std::env::var("CVERIF_QEMU_CASES")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(10000)
}

fn generate(t: &Target, seed: u64, n: usize, batch_seed: u32) -> (Vec<Case>, BTreeMap<&'static str, usize>) {
    let lay = Layout::of(t);
    let mut rng = Rng(seed);
    let mut cases = Vec::new();
    let mut dropped: BTreeMap<&'static str, usize> = BTreeMap::new();
    while cases.len() < n {
        let (code, class) = gen_code(&mut rng, t.arch);
        let st = random_state(&mut rng, &lay);
        let field = lay.field_image(&code);
        match run_armsim(&lay, batch_seed, &field, &st) {
            Ok(Some(r)) => cases.push(Case {
                code,
                class,
                st,
                reference: Some(r),
            }),
            Ok(None) => *dropped.entry("leaves the harness's memory or loops").or_default() += 1,
            Err(armsim::Stop::Event(_) | armsim::Stop::ArmState(_)) => {
                *dropped
                    .entry("system instruction (BKPT, SVC, ...), switch to ARM state")
                    .or_default() += 1
            }
            Err(_) => {
                // armsim does not model it: run it on QEMU if the executor accepts it and stays
                // inside the harness's memory, on this core and on one that has every
                // instruction (QEMU runs some that its core lacks, see `qemu_m3_runs_dsp`).
                let reads = full_window(&lay, batch_seed);
                let any = Layout {
                    profile: {
                        let mut built = Profile::ANY;
                        built.fpu = lay.profile.fpu;
                        built
                    },
                    ..lay
                };
                let stays = |l: &Layout| {
                    run_exec(l, batch_seed, &code, &st, Mode::Concrete, &reads).is_ok_and(|x| {
                        matches!(x.end, End::Return | End::Trap(_))
                            && x.mem.keys().all(|&a| lay.in_win(a))
                            && (lay.win + 0x100..=lay.win + WIN_LEN).contains(&x.r[13])
                    })
                };
                if stays(&lay) && stays(&any) {
                    cases.push(Case {
                        code,
                        class,
                        st,
                        reference: None,
                    });
                } else {
                    *dropped
                        .entry("not modelled by armsim, declined by the executor")
                        .or_default() += 1;
                }
            }
        }
    }
    (cases, dropped)
}

fn campaign(t: &Target, seed: u64) {
    if !have(QEMU) || !have(GCC) {
        eprintln!("{}: {QEMU} or {GCC} not installed, skipped", t.name);
        return;
    }
    let started = Instant::now();
    let elf = build_harness(t);
    let lay = Layout::of(t);
    let total = cases_per_core();
    let batch_size = 1500;
    let batches = total.div_ceil(batch_size);
    let threads = 2;
    let results: Vec<(Tally, BTreeMap<&'static str, usize>)> = std::thread::scope(|s| {
        let handles: Vec<_> = (0..threads)
            .map(|k| {
                let elf = &elf;
                s.spawn(move || {
                    let mut tally = Tally::default();
                    let mut dropped = BTreeMap::new();
                    for b in (k..batches).step_by(threads) {
                        let n = batch_size.min(total - b * batch_size);
                        let bseed = (seed as u32).wrapping_mul(31).wrapping_add(b as u32 * 0x1000_0001);
                        let (cases, d) =
                            generate(t, seed ^ (b as u64 + 1).wrapping_mul(0x9e37_79b9_7f4a_7c15), n, bseed);
                        for (k, v) in d {
                            *dropped.entry(k).or_default() += v;
                        }
                        let out = run_qemu(t, elf, b, bseed, &cases).unwrap_or_else(|e| panic!("{}: {e}", t.name));
                        for (i, (c, q)) in cases.iter().zip(&out).enumerate() {
                            let mode = [Mode::Concrete, Mode::Pinned, Mode::PrivateStack][i % 3];
                            compare_case(t, &lay, bseed, c, q, mode, &mut tally);
                        }
                    }
                    (tally, dropped)
                })
            })
            .collect();
        handles.into_iter().map(|h| h.join().unwrap()).collect()
    });
    let mut tally = Tally::default();
    let mut dropped: BTreeMap<&'static str, usize> = BTreeMap::new();
    for (t, d) in results {
        tally.cases += t.cases;
        tally.armsim_compared += t.armsim_compared;
        tally.exec_compared += t.exec_compared;
        tally.exec_declined += t.exec_declined;
        tally.exec_only += t.exec_only;
        tally.known += t.known;
        tally.unexpected += t.unexpected;
        for (k, (n, ex)) in t.classes {
            let e = tally.classes.entry(k).or_default();
            e.0 += n;
            for x in ex {
                if e.1.len() < 3 {
                    e.1.push(x);
                }
            }
        }
        for (k, v) in d {
            *dropped.entry(k).or_default() += v;
        }
    }
    eprintln!(
        "{} ({}): {} cases run on QEMU in {:.1?}: armsim compared on {}, executor on {} (declined {}; {} cases armsim does not model); {} known differences, {} unexpected",
        t.name,
        t.machine,
        tally.cases,
        started.elapsed(),
        tally.armsim_compared,
        tally.exec_compared,
        tally.exec_declined,
        tally.exec_only,
        tally.known,
        tally.unexpected
    );
    eprintln!("  not run: {dropped:?}");
    let verbose = std::env::var_os("CVERIF_QEMU_VERBOSE").is_some();
    let mut failures = Vec::new();
    for ((tag, what, class), (n, ex)) in &tally.classes {
        if tag == "known" && !verbose {
            continue;
        }
        let line = format!("  {tag} {n:5}  {what}  [{class}]\n      {}", ex.join("\n      "));
        eprintln!("{line}");
        if tag != "known" {
            failures.push(line);
        }
    }
    assert!(
        failures.is_empty(),
        "{}: {} disagreements with QEMU",
        t.name,
        failures.len()
    );
    assert!(
        tally.exec_compared * 3 > tally.cases,
        "{}: too few cases were compared",
        t.name
    );
}

#[test]
fn qemu_cortex_m0() {
    campaign(&M0, 0x0123_4567_89ab_cdef);
}

#[test]
fn qemu_cortex_m3() {
    campaign(&M3, 0x3333_5555_7777_9999);
}

#[test]
fn qemu_cortex_m4() {
    campaign(&M4, 0x4444_6666_8888_aaaa);
}

#[test]
fn qemu_cortex_m33() {
    campaign(&M33, 0x3333_3333_dead_beef);
}

/// The 32-bit LDRH encodings with Rt=15 (Rn not the PC) are unallocated memory hints, to be
/// executed as NOPs (ARMv7-M A5.3.8, table A5-19; the writeback forms are UNPREDICTABLE), but
/// QEMU 11 executes them as halfword loads into the PC, which can jump into the harness.  The
/// LDRSH and LDRB (PLD) hint forms are NOPs in QEMU, as they should be.  Such cases are not run.
fn qemu_ldrh_hint_bug(code: &[u8]) -> bool {
    let h = halfwords(code);
    h.windows(2)
        .any(|w| w[0] & 0xff70 == 0xf830 && w[0] & 15 != 15 && w[1] >> 12 == 15)
}