cverif 0.0.2

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
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
//! Equivalence driver: for every source function present in the binary, explores
//! all paths of the C function and of the machine code under the same symbolic
//! inputs and proves that every observable effect is identical.

use crate::c::ast::{Program, Type, VOID};
use crate::c::exec::{CEnv, CExec};
use crate::image::{Image, SymKind};
use crate::sym::{ArgLoc, Ctx, Event, Exposed, Limits, Mem, R, Stop, WordLoc, Write, arg_locs, arg_words};
use crate::term::{Env, T};
use crate::thumb::exec::{Callee, Exit, Machine, image_init};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::time::{Duration, Instant};

mod loops;

#[derive(Clone, Debug)]
pub struct Options {
    pub limits: Limits,
    /// Verify only these functions (all when empty).
    pub only: Vec<String>,
    /// Wall-clock budget per function: a safety net behind `work_limit`, which normally
    /// stops a function first and does so reproducibly.
    pub time_limit: Duration,
    /// Address ranges (first, last) of memory-mapped peripherals: the binary may access them
    /// only where the source does.
    pub mmio: Vec<(u32, u32)>,
    /// Worker threads (0 = one per available CPU).
    pub jobs: usize,
    /// Budget per function in deterministic work units: one per term built plus one per
    /// thousand solver propagations.  Unlike `time_limit` it gives the same result on a
    /// fast and on a slow machine; `time_limit` remains as a safety net.
    pub work_limit: u64,
    /// Cap on the number of terms per function (memory guard).
    pub max_terms: usize,
    /// Summarise up to this many paths of every verified function (see `FuncReport::detail`).
    pub dump: usize,
    /// Give up on everything still running or not yet started at this instant.
    pub deadline: Option<Instant>,
    /// Have the SAT solver double-check each of its answers (slow; for tests).
    pub check_solver: bool,
}

/// Peripheral address ranges of the ARMv6-M / ARMv7-M / ARMv8-M memory map: device peripherals
/// and the private peripheral bus with the vendor region above it.
pub const DEFAULT_MMIO: [(u32, u32); 2] = [(0x4000_0000, 0x5fff_ffff), (0xe000_0000, 0xffff_ffff)];

impl Default for Options {
    fn default() -> Self {
        Options {
            limits: Limits::default(),
            only: Vec::new(),
            time_limit: Duration::from_secs(300),
            jobs: 0,
            work_limit: 500_000,
            max_terms: 20_000_000,
            dump: 0,
            deadline: None,
            check_solver: false,
            mmio: DEFAULT_MMIO.to_vec(),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Status {
    /// Every path of the function was explored and proved equivalent.
    Proved,
    /// No difference found, but exploration hit a limit (e.g. an unbounded loop).
    Bounded(String),
    /// The machine code provably behaves differently from the source.
    Mismatch(String),
    /// The prover gave up on some obligation.
    Inconclusive(String),
    /// The function uses something the tool does not model yet.
    Unsupported(String),
}

impl Status {
    pub fn label(&self) -> &'static str {
        match self {
            Status::Proved => "PROVED",
            Status::Bounded(_) => "BOUNDED",
            Status::Mismatch(_) => "MISMATCH",
            Status::Inconclusive(_) => "INCONCLUSIVE",
            Status::Unsupported(_) => "UNSUPPORTED",
        }
    }

    pub fn detail(&self) -> &str {
        match self {
            Status::Proved => "",
            Status::Bounded(s) | Status::Mismatch(s) | Status::Inconclusive(s) | Status::Unsupported(s) => s,
        }
    }
}

#[derive(Clone, Debug)]
pub struct FuncReport {
    pub name: String,
    pub addr: u32,
    pub size: u32,
    pub status: Status,
    /// Paths proved equivalent.
    pub paths: usize,
    /// Paths on which the source has undefined behaviour (nothing to prove).
    pub undefined_paths: usize,
    pub millis: u128,
    /// Solver effort: SAT calls and conflicts.
    pub sat_calls: u64,
    pub conflicts: u64,
    /// Deterministic work units spent (see `Options::work_limit`).
    pub work: u64,
    /// Why the function is not proved, and the path summaries that were asked for.
    pub detail: Option<Box<crate::explain::FuncDetail>>,
}

#[derive(Clone, Debug, Default)]
pub struct Report {
    pub funcs: Vec<FuncReport>,
    /// Source coverage points: (proved, total).
    pub src: (usize, usize),
    /// Code bytes of the binary: (proved, total).
    pub bin: (usize, usize),
    /// Binary functions that no verified path reaches: (name, size).
    pub unmatched: Vec<(String, u32)>,
    /// Source functions that have no symbol in the binary and were not reached through a caller.
    pub absent: Vec<String>,
    /// Initialised data that differs between source and binary.
    pub data_issues: Vec<String>,
    /// Number of source-defined objects whose initial contents were compared.
    pub data_checked: usize,
    /// Source lines never reached by a proved path: (file, line).
    pub uncovered_lines: Vec<(String, u32)>,
    /// Every source coverage point (a statement or a branch condition), in source order.
    pub src_points: Vec<SrcPoint>,
    /// The executable segments as maximal address ranges of one state, in address order.
    pub bin_ranges: Vec<BinRange>,
}

/// One source coverage point and whether a proved path goes through it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SrcPoint {
    pub file: String,
    pub line: u32,
    pub func: String,
    pub proved: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ByteState {
    /// On a proved path (instructions executed, literal-pool and table data read).
    Proved,
    /// Code or data in code that no proved path accounts for.
    Unproved,
    /// Alignment padding between functions; not counted in the coverage.
    Padding,
}

impl ByteState {
    pub fn label(self) -> &'static str {
        match self {
            ByteState::Proved => "proved",
            ByteState::Unproved => "unproved",
            ByteState::Padding => "padding",
        }
    }
}

/// Addresses `start..end` of the binary, all in the same state.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BinRange {
    pub start: u32,
    pub end: u32,
    pub state: ByteState,
}

impl Report {
    pub fn src_coverage(&self) -> f64 {
        if self.src.1 == 0 {
            0.0
        } else {
            self.src.0 as f64 / self.src.1 as f64
        }
    }

    pub fn bin_coverage(&self) -> f64 {
        if self.bin.1 == 0 {
            0.0
        } else {
            self.bin.0 as f64 / self.bin.1 as f64
        }
    }

    pub fn has_mismatch(&self) -> bool {
        !self.data_issues.is_empty() || self.funcs.iter().any(|f| matches!(f.status, Status::Mismatch(_)))
    }

    /// 0..=100: how much of the source and of the binary is accounted for by proofs.
    /// Zero as soon as anything provably differs.
    pub fn score(&self) -> f64 {
        if self.has_mismatch() {
            return 0.0;
        }
        50.0 * (self.src_coverage() + self.bin_coverage())
    }
}

/// Extent of the stack below the entry stack pointer that no pointer argument can point into.
const FRAME_SPAN: u32 = 1 << 20;

/// Strip GCC's function-clone suffixes (`.constprop.0`, `.isra.0`, `.part.0`, `.cold`).
fn base_name(name: &str) -> &str {
    match name.find('.') {
        Some(i) if i > 0 => &name[..i],
        _ => name,
    }
}

struct PathResult {
    cov: Vec<u32>,
    insns: Vec<(u32, u8)>,
    data: Vec<(u32, u8)>,
}

/// Stack words of variable arguments modelled for a variadic function under verification.
const VA_STACK_WORDS: u32 = 8;

struct Job<'a> {
    prog: &'a Program,
    image: &'a Image,
    env: &'a CEnv<'a>,
    fid: u32,
    entry: u32,
    regs: [T; 16],
    args: Vec<T>,
    stack_args: Vec<(u32, T)>,
    /// Structure arguments: (the C-side object, the words the caller passed).
    struct_args: Vec<(T, Vec<T>)>,
    /// Caller-provided memory for a structure result.
    ret_slot: Option<T>,
    lr0: T,
    mmio: &'a [(u32, u32)],
}

/// The memory the caller provides for a structure result ends with the structure: the binary
/// must not store past it.
fn check_result_slot(ctx: &mut Ctx, job: &Job, m: &Machine) -> R<()> {
    let Some(slot) = job.ret_slot else { return Ok(()) };
    let Some(log) = m.mem.private.get(&slot) else {
        return Ok(());
    };
    let f = &job.prog.funcs[job.fid as usize];
    let len = job.prog.size_of(f.ty.ret).unwrap_or(0) as u64;
    let stores: Vec<(T, u8)> = log.iter().map(|w| (w.addr, w.size)).collect();
    for (addr, size) in stores {
        let off = ctx.tm.sub(addr, slot);
        if let Some(o) = ctx.tm.as_const(off)
            && o + size as u64 <= len
        {
            continue;
        }
        let ok = if size as u64 <= len {
            let lim = ctx.tm.konst(32, len - size as u64 + 1);
            ctx.tm.ult(off, lim)
        } else {
            ctx.tm.konst(1, 0)
        };
        match ctx.check(ok) {
            Ok(()) => {}
            Err(Some(env)) => {
                let mut memo = Default::default();
                let o = ctx.tm.eval(off, &env, &mut memo) as u32 as i32;
                return Err(Stop::Mismatch(
                    format!(
                        "binary stores {size} byte(s) outside the {len}-byte result object (offset {o}) for {}",
                        witness(ctx, &env)
                    ),
                    Some(env),
                ));
            }
            Err(None) => {
                return Err(Stop::Inconclusive(
                    "a store relative to the result object: prover gave up on whether it stays inside".into(),
                ));
            }
        }
    }
    Ok(())
}

fn witness(ctx: &Ctx, env: &Env) -> String {
    let mut items: Vec<(String, u64)> = env
        .syms
        .iter()
        .map(|(id, v)| (ctx.tm.sym_name(*id).to_string(), *v))
        .filter(|(n, _)| {
            let b = n.as_bytes();
            (b.len() == 2 && b[0] == b'r' && b[1] <= b'3') || n.starts_with("stk") || n.starts_with("ret")
        })
        .collect();
    items.sort();
    let mut parts: Vec<String> = items.iter().map(|(n, v)| format!("{n}={v:#x}")).collect();
    let mut mem: Vec<(u64, u8)> = env
        .mem
        .iter()
        .filter(|((m, _), _)| *m < 0x8000_0000)
        .map(|((_, a), v)| (*a, *v))
        .collect();
    mem.sort();
    for (a, v) in mem.iter().take(8) {
        parts.push(format!("mem[{a:#x}]={v:#04x}"));
    }
    if parts.is_empty() {
        "any input".into()
    } else {
        parts.join(" ")
    }
}

fn prove_eq(ctx: &mut Ctx, c: T, b: T, what: &str) -> R<()> {
    if c == b {
        return Ok(());
    }
    let e = ctx.tm.eq(c, b);
    if std::env::var("CVERIF_DEBUG").is_ok_and(|v| v == "2") {
        eprintln!(
            "solver {what}:\n  source: {}\n  binary: {}",
            ctx.tm.show(c),
            ctx.tm.show(b)
        );
        for (n, l) in [("pc", ctx.pc.clone()), ("ub", ctx.ub.clone())] {
            for t in l {
                eprintln!("  {n}: {}", ctx.tm.show(t));
            }
        }
    }
    match ctx.check(e) {
        Ok(()) => Ok(()),
        Err(Some(env)) => {
            if ctx.mentions_unspecified(c) || ctx.mentions_unspecified(b) {
                return Err(Stop::Unsupported(format!(
                    "{what}: depends on the unspecified magnitude of a string comparison result"
                )));
            }
            if ctx.mentions_unbound_private(c) || ctx.mentions_unbound_private(b) {
                return Err(Stop::Unsupported(format!(
                    "{what}: the address of a local object escapes"
                )));
            }
            // An object or function the source uses could not be located in the image: its
            // address is a free symbol on the source side, and no comparison involving it means anything.
            if let Some(name) = env
                .syms
                .keys()
                .map(|id| ctx.tm.sym_name(*id))
                .filter(|n| n.starts_with('&') && (n.contains("#g") || n.contains("#f")))
                .min()
            {
                let name = name[1..].rsplit_once('#').map_or(&name[1..], |p| p.0);
                return Err(Stop::Unsupported(format!(
                    "{what}: uses `{name}`, which could not be located in the binary (no symbol, or several candidates)"
                )));
            }
            crate::explain::report::note_goal(c, b);
            let mut memo = Default::default();
            let (cv, bv) = (ctx.tm.eval(c, &env, &mut memo), ctx.tm.eval(b, &env, &mut memo));
            Err(Stop::Mismatch(
                format!(
                    "{what}: source gives {cv:#x}, binary gives {bv:#x} for {}",
                    witness(ctx, &env)
                ),
                Some(env),
            ))
        }
        Err(None) => {
            if std::env::var_os("CVERIF_DEBUG").is_some() {
                eprintln!(
                    "inconclusive {what}:\n  source: {}\n  binary: {}",
                    ctx.tm.show(c),
                    ctx.tm.show(b)
                );
            }
            crate::explain::report::note_goal(c, b);
            Err(Stop::Inconclusive(format!("{what}: prover gave up")))
        }
    }
}

/// Prove that world memory is the same on both sides for every location either side wrote.
///
/// `exposed` lists the source's local objects that pointers of unknown origin may point into:
/// a store through such a pointer that lands in one of them is not a store to world memory
/// (the object's contents are compared separately).
#[allow(clippy::too_many_arguments)]
fn compare_world(
    ctx: &mut Ctx,
    job: &Job,
    c_log: &[Write],
    c_epoch: u32,
    exposed: &[Exposed],
    m: &Machine,
    what: &str,
    eq: &mut dyn FnMut(&mut Ctx, T, T, &str) -> R<()>,
) -> R<()> {
    let mut seen: HashSet<(T, u8)> = HashSet::new();
    let entries: Vec<(T, u8)> = c_log
        .iter()
        .chain(m.mem.world.iter())
        .map(|w| (w.addr, w.size))
        .collect();
    for (addr, size) in entries {
        if !seen.insert((addr, size)) || ctx.region(addr).is_some() {
            continue;
        }
        let env = job.env;
        let mut c_init = move |ctx: &mut Ctx, a: T, s: u8| env.initial(ctx, a, s, c_epoch);
        let cv = ctx.read_world(c_log, addr, size, &mut c_init);
        let mut b_init = image_init(job.image, m.mem.epoch, None);
        let bv = ctx.read_world(&m.mem.world, addr, size, &mut b_init);
        if size == 4 && cv != bv && same_literal(ctx, job, cv, bv) {
            continue;
        }
        crate::explain::report::note_addr(addr);
        let at = ctx.tm.show(addr);
        let what = format!("{what}: {size}-byte value stored at {at}");
        let mut elsewhere = ctx.tm.fals();
        for e in exposed {
            if ctx.may_point_into(addr, e) {
                let inside = ctx.inside(addr, e);
                elsewhere = ctx.tm.or(elsewhere, inside);
            }
        }
        if ctx.tm.is_false(elsewhere) {
            eq(ctx, cv, bv, &what)?;
        } else if cv != bv {
            // Only required when the store did not land in an exposed local.
            let outside = ctx.tm.not(elsewhere);
            ctx.pc.push(outside);
            let r = eq(ctx, cv, bv, &what);
            ctx.pc.pop();
            r?;
        }
    }
    Ok(())
}

/// Where the binary keeps the C locals whose address is visible to external functions.
#[derive(Default)]
struct Escapes {
    /// C object base -> (address in the binary's frame, its offset from the initial SP, size).
    map: HashMap<T, (T, i64, u32)>,
}

/// The bytes of the string literal a constant C-side pointer points into, from that pointer on.
fn literal_at<'a>(env: &'a CEnv<'a>, addr: u32) -> Option<&'a [u8]> {
    env.prog.strings.iter().zip(&env.str_addr).find_map(|(s, a)| {
        let o = addr.checked_sub((*a)?)? as usize;
        s.get(o..).filter(|r| !r.is_empty())
    })
}

/// Are `c` and `b` pointers to the same string literal?  The source's pointer is where cverif
/// located the literal; the binary may use any read-only copy of the same bytes (which copy is
/// used is not something a C program can rely on).
fn same_literal(ctx: &mut Ctx, job: &Job, c: T, b: T) -> bool {
    if ctx.tm.width(c) != 32 || ctx.tm.width(b) != 32 {
        return false;
    }
    if let (Some(ca), Some(ba)) = (ctx.tm.as_const(c), ctx.unique_value(b))
        && ca != ba
        && let Some(lit) = literal_at(job.env, ca as u32)
    {
        return job.image.read_const(ba as u32, lit.len() as u32) == Some(lit);
    }
    false
}

/// Compare a value the source hands to the outside world with the binary's.  Besides plain
/// equality this accepts pointers that correspond: the address of a C local against its slot in
/// the binary's stack frame (the correspondence is fixed the first time it is seen), and string
/// literals against any read-only copy of the same bytes.
fn match_value(
    ctx: &mut Ctx,
    job: &Job,
    cx: &CExec,
    esc: &mut Escapes,
    ev: &Event,
    (c, b): (T, T),
    what: &str,
) -> R<()> {
    if c == b {
        return Ok(());
    }
    if ctx.tm.width(c) != 32 {
        return prove_eq(ctx, c, b, what);
    }
    // Two different constant addresses of identical read-only string contents.
    if let (Some(ca), Some(ba)) = (ctx.tm.as_const(c), ctx.unique_value(b))
        && ca != ba
        && let Some(lit) = literal_at(job.env, ca as u32)
        && job.image.read_const(ba as u32, lit.len() as u32) == Some(lit)
    {
        return Ok(());
    }
    let Some((base, off)) = ctx.private_split(c) else {
        return prove_eq(ctx, c, b, what);
    };
    if let Some(&sid) = cx.str_bases.get(&base) {
        // A literal that was not located in the image by content search.
        let lit = &job.env.prog.strings[sid as usize];
        if let (Some(o), Some(ba)) = (ctx.tm.as_const(off), ctx.unique_value(b))
            && let Some(rest) = lit.get(o as usize..)
        {
            if job.image.read_const(ba as u32, rest.len() as u32) == Some(rest) {
                return Ok(());
            }
            return Err(Stop::Mismatch(
                format!("{what}: binary passes {ba:#x}, which does not hold the source's string literal"),
                None,
            ));
        }
        return prove_eq(ctx, c, b, what);
    }
    let Some(obj) = ev.escaped.iter().find(|e| e.base == base) else {
        return prove_eq(ctx, c, b, what);
    };
    let name = obj.name.trim_start_matches('&');
    let bb = match esc.map.get(&base) {
        Some(e) => e.0,
        None => {
            let bb = ctx.tm.sub(b, off);
            let sp0 = job.regs[13];
            let Some(d) = ctx.tm.const_diff(bb, sp0) else {
                return Err(Stop::Unsupported(format!(
                    "{what}: source passes the address of local {name}, binary passes {} which is not a fixed stack slot",
                    ctx.tm.show(b)
                )));
            };
            let d = d as u32 as i32 as i64;
            let top = job.stack_args.iter().map(|a| a.0 as i64 + 4).max().unwrap_or(0);
            if d + obj.size as i64 > top {
                return Err(Stop::Mismatch(
                    format!(
                        "{what}: source passes the address of local {name}, binary passes a stack address outside its frame"
                    ),
                    None,
                ));
            }
            // Objects the callee can reach at the same time must not share storage.
            let live = |b: &T| ev.escaped.iter().any(|e| e.base == *b);
            if esc
                .map
                .iter()
                .any(|(b2, &(_, d2, s2))| live(b2) && d < d2 + s2 as i64 && d2 < d + obj.size as i64)
            {
                return Err(Stop::Mismatch(
                    format!("{what}: binary places local {name} over another local visible to the callee"),
                    None,
                ));
            }
            esc.map.insert(base, (bb, d, obj.size));
            // From here on the source's object and the binary's stack slot are the same memory.
            let same = ctx.tm.eq(base, bb);
            ctx.pc.push(same);
            ctx.bound.insert(base);
            ctx.bound.insert(sp0);
            bb
        }
    };
    let expect = ctx.tm.add(bb, off);
    if expect == b {
        return Ok(());
    }
    let e = ctx.tm.eq(expect, b);
    match ctx.check(e) {
        Ok(()) => Ok(()),
        Err(Some(_)) => Err(Stop::Mismatch(
            format!(
                "{what}: source passes the address of local {name}, binary passes {} instead of {}",
                ctx.tm.show(b),
                ctx.tm.show(expect)
            ),
            None,
        )),
        Err(None) => Err(Stop::Inconclusive(format!("{what}: prover gave up"))),
    }
}

fn match_call(ctx: &mut Ctx, job: &Job, cx: &CExec, esc: &mut Escapes, m: &mut Machine, ev: &Event, k: usize) -> R<()> {
    let widths: Vec<u8> = ev.args.iter().map(|a| ctx.tm.width(a.0).max(32)).collect();
    let sp = m.regs[13];
    for (i, (&(val, signed), loc)) in ev.args.iter().zip(arg_locs(&widths)).enumerate() {
        let (expect, got) = match loc {
            ArgLoc::Reg(n) => (ctx.tm.resize(val, 32, signed), m.regs[n as usize]),
            ArgLoc::RegPair(n) => (val, ctx.tm.concat(m.regs[n as usize + 1], m.regs[n as usize])),
            ArgLoc::Stack(off) => {
                let a = ctx.tm.add_const(sp, off as u64);
                (ctx.tm.resize(val, 32, signed), m.read32(ctx, job.image, a))
            }
            ArgLoc::Stack64(off) => {
                let a = ctx.tm.add_const(sp, off as u64);
                let lo = m.read32(ctx, job.image, a);
                let a = ctx.tm.add_const(sp, off as u64 + 4);
                let hi = m.read32(ctx, job.image, a);
                (val, ctx.tm.concat(hi, lo))
            }
        };
        let what = format!("argument {} of call #{} to {}", i + 1, k + 1, ev.name);
        let (expect, got) = match ev.arg_masks.iter().find(|m| m.0 == i) {
            Some(&(_, mask)) => {
                let km = ctx.tm.konst(ctx.tm.width(expect), mask);
                (ctx.tm.and(expect, km), ctx.tm.and(got, km))
            }
            None => (expect, got),
        };
        match_value(ctx, job, cx, esc, ev, (expect, got), &what)?;
    }
    // World memory first: a pointer to a local stored there tells where the binary keeps the local.
    compare_world(
        ctx,
        job,
        &ev.writes,
        ev.epoch,
        &ev.exposed,
        m,
        &format!("memory at call #{} to {}", k + 1, ev.name),
        &mut |ctx, c, b, what| match_value(ctx, job, cx, esc, ev, (c, b), what),
    )?;
    // Locals the callee can reach must hold the same contents on both sides.
    for obj in &ev.escaped {
        let name = obj.name.trim_start_matches('&');
        let Some(&(bb, d, _)) = esc.map.get(&obj.base) else {
            return Err(Stop::Unsupported(format!(
                "call #{} to {}: local {name} is reachable by the callee but its place in the binary's frame is unknown",
                k + 1,
                ev.name
            )));
        };
        // The object must still be inside the live part of the frame.
        if let Some(s) = ctx.tm.const_diff(sp, job.regs[13])
            && d < s as u32 as i32 as i64
        {
            return Err(Stop::Mismatch(
                format!(
                    "call #{} to {}: local {name} lies below the stack pointer",
                    k + 1,
                    ev.name
                ),
                None,
            ));
        }
        for &(off, size, v) in &obj.pre {
            let Some(v) = v else { continue };
            let a = ctx.tm.add_const(bb, off as u64);
            let mut init = image_init(job.image, m.mem.epoch, None);
            let bv = ctx.mem_read(&m.mem, a, size, &mut init);
            let what = format!("local {name} (offset {off}) at call #{} to {}", k + 1, ev.name);
            match_value(ctx, job, cx, esc, ev, (v, bv), &what)?;
        }
    }
    Ok(())
}

/// Effects of an external call that returned, on the binary's private memory: the callee may have
/// written to every local it can reach (both sides continue with the same fresh contents) and to
/// its own stack arguments.
fn after_call(ctx: &mut Ctx, esc: &Escapes, m: &mut Machine, ev: &Event, k: usize) {
    for obj in &ev.escaped {
        let Some(&(bb, _, _)) = esc.map.get(&obj.base) else {
            continue;
        };
        for &(off, size, v) in &obj.post {
            let a = ctx.tm.add_const(bb, off as u64);
            ctx.mem_write(&mut m.mem, a, size, v);
        }
    }
    let widths: Vec<u8> = ev.args.iter().map(|a| ctx.tm.width(a.0).max(32)).collect();
    let sp = m.regs[13];
    for loc in arg_locs(&widths) {
        let (off, n) = match loc {
            ArgLoc::Stack(off) => (off, 1),
            ArgLoc::Stack64(off) => (off, 2),
            _ => continue,
        };
        for i in 0..n {
            let off = off + 4 * i;
            let v = ctx.event_sym(&format!("clob{k}.stk{off}"), 32);
            let a = ctx.tm.add_const(sp, off as u64);
            ctx.mem_write(&mut m.mem, a, 4, v);
        }
    }
}

/// The binary calls a memory helper the source does not call at this point (the compiler
/// turned a loop or an aggregate copy into a library call).  With a known length it is a
/// plain memory effect; apply it to the machine state.  Returns false if it cannot be modelled.
fn model_mem_call(ctx: &mut Ctx, job: &Job, m: &mut Machine, name: &str, count: &mut usize) -> bool {
    use crate::c::exec::{MAX_MEM_INLINE, mem_fill};
    let (r0, r1, r2) = (m.regs[0], m.regs[1], m.regs[2]);
    let zero = ctx.tm.konst(32, 0);
    // (destination, source or fill value, length, is a fill)
    let (dst, arg, len, fill) = match name {
        "memset" => (r0, r1, r2, true),
        "__aeabi_memset" | "__aeabi_memset4" | "__aeabi_memset8" => (r0, r2, r1, true),
        "__aeabi_memclr" | "__aeabi_memclr4" | "__aeabi_memclr8" => (r0, zero, r1, true),
        "memcpy" | "memmove" | "__aeabi_memcpy" | "__aeabi_memcpy4" | "__aeabi_memcpy8" | "__aeabi_memmove"
        | "__aeabi_memmove4" | "__aeabi_memmove8" => (r0, r1, r2, false),
        _ => return false,
    };
    let Some(n) = ctx.unique_value(len).filter(|&n| n <= MAX_MEM_INLINE) else {
        return false;
    };
    let n = n as u32;
    if fill {
        let byte = ctx.tm.trunc(arg, 8);
        mem_fill(ctx, &mut m.mem, dst, byte, n);
    } else {
        let mut chunks = Vec::new();
        let mut off = 0;
        while off < n {
            let sz = if n - off >= 4 { 4u8 } else { 1 };
            let a = ctx.tm.add_const(arg, off as u64);
            let mut init = image_init(job.image, m.mem.epoch, None);
            chunks.push((off, sz, ctx.mem_read(&m.mem, a, sz, &mut init)));
            off += sz as u32;
        }
        for (off, sz, v) in chunks {
            let a = ctx.tm.add_const(dst, off as u64);
            ctx.mem_write(&mut m.mem, a, sz, v);
        }
    }
    *count += 1;
    // mem* return the destination; the __aeabi_ variants return nothing.
    let ret = if name.starts_with("__aeabi") { None } else { Some(dst) };
    m.finish_call(ctx, 1000 + *count, ret, None);
    true
}

/// libgcc's Thumb-1 switch dispatchers: the jump table follows the call instruction and the
/// routine continues at the selected entry, preserving every register but LR.
fn model_switch_helper(ctx: &mut Ctx, job: &Job, m: &mut Machine, name: &str, count: &mut usize) -> R<bool> {
    let (esize, signed) = match name {
        "__gnu_thumb1_case_sqi" => (1u32, true),
        "__gnu_thumb1_case_uqi" => (1, false),
        "__gnu_thumb1_case_shi" => (2, true),
        "__gnu_thumb1_case_uhi" => (2, false),
        "__gnu_thumb1_case_si" => (4, true),
        _ => return Ok(false),
    };
    let ret = m.resume_pc();
    let idx = m.regs[0];
    let mut found = None;
    for i in 0..1024u32 {
        let k = ctx.tm.konst(32, i as u64);
        let e = ctx.tm.eq(idx, k);
        if ctx.branch(e)? {
            found = Some(i);
            break;
        }
    }
    let Some(i) = found else {
        return Err(Stop::Unsupported(format!(
            "switch table with more than 1024 entries at {ret:#x}"
        )));
    };
    // Word tables are aligned and hold offsets from the table; the others hold half the offset from the return address.
    let base = if esize == 4 { (ret + 3) & !3 } else { ret };
    let eaddr = base + esize * i;
    let Some(bytes) = job.image.read_const(eaddr, esize) else {
        return Err(Stop::Unsupported(format!(
            "switch table entry outside the image at {eaddr:#x}"
        )));
    };
    let mut v = 0u32;
    for (j, &b) in bytes.iter().enumerate() {
        v |= (b as u32) << (8 * j);
    }
    let target = match (esize, signed) {
        (4, _) => base.wrapping_add(v),
        (1, true) => ret.wrapping_add((v as u8 as i8 as i32 as u32) << 1),
        (2, true) => ret.wrapping_add((v as u16 as i16 as i32 as u32) << 1),
        _ => ret.wrapping_add(v << 1),
    };
    m.data_covered.push((eaddr, esize as u8));
    *count += 1;
    m.resume_at(ctx, 1000 + *count, target);
    Ok(true)
}

/// The binary calls a library string function on read-only constants where the source side
/// evaluated the call itself (the compiler may fold such calls, or not).
fn model_string_call(ctx: &mut Ctx, job: &Job, m: &mut Machine, name: &str, count: &mut usize) -> bool {
    use crate::c::exec::{c_str, compare_result};
    // The read-only bytes from a constant address to the end of its segment.
    let rom = |ctx: &mut Ctx, t: T| -> Option<&[u8]> {
        let a = ctx.unique_value(t)? as u32;
        let s = job.image.segment_at(a).filter(|s| !s.writable)?;
        s.data.get((a - s.addr) as usize..)
    };
    let (r0, r1, r2) = (m.regs[0], m.regs[1], m.regs[2]);
    let v = match name {
        "strlen" => {
            let Some(s) = rom(ctx, r0).and_then(c_str) else {
                return false;
            };
            ctx.tm.konst(32, s.len() as u64)
        }
        "strcmp" => {
            let (Some(a), Some(b)) = (rom(ctx, r0).and_then(c_str), rom(ctx, r1).and_then(c_str)) else {
                return false;
            };
            compare_result(ctx, a, b)
        }
        "memcmp" => {
            let Some(n) = ctx.unique_value(r2) else { return false };
            let (Some(a), Some(b)) = (
                rom(ctx, r0).and_then(|s| s.get(..n as usize)),
                rom(ctx, r1).and_then(|s| s.get(..n as usize)),
            ) else {
                return false;
            };
            compare_result(ctx, a, b)
        }
        _ => return false,
    };
    *count += 1;
    m.finish_call(ctx, 1000 + *count, Some(v), None);
    true
}

/// The binary calls a compiler runtime routine (libgcc / AEABI) where the source has an operator:
/// apply the routine's defined result to the machine state.  Division by zero follows the term
/// convention; the source's own no-undefined-behaviour conditions exclude it.
pub(crate) fn model_runtime_call(ctx: &mut Ctx, m: &mut Machine, name: &str, count: &mut usize) -> bool {
    let r = m.regs;
    // Soft-float arithmetic, comparisons and conversions.
    if let Some(o) = crate::fp::runtime_call(&mut ctx.tm, name, [r[0], r[1], r[2], r[3]]) {
        *count += 1;
        match o {
            crate::fp::Outcome::Value(v) if ctx.tm.width(v) == 64 => {
                let (lo, hi) = (ctx.tm.extract(v, 0, 32), ctx.tm.extract(v, 32, 32));
                m.finish_call(ctx, 1000 + *count, Some(lo), Some(hi));
            }
            crate::fp::Outcome::Value(v) => m.finish_call(ctx, 1000 + *count, Some(v), None),
            crate::fp::Outcome::Flags { z, c } => {
                m.finish_call(ctx, 1000 + *count, Some(r[0]), Some(r[1]));
                m.regs[2] = r[2];
                m.regs[3] = r[3];
                m.set_zc(ctx, z, c);
            }
        }
        return true;
    }
    // Where the routine's result is not defined (a zero divisor: the library raises
    // __aeabi_idiv0 and returns what that returns; a zero operand of a bit count) the binary
    // gets a value nothing is known about.  When the source performs the same operation its
    // own no-undefined-behaviour condition excludes the case; when it does not, the binary is
    // not allowed to rely on what the routine happens to return.
    let undefined_at: Option<T> = {
        let tm = &mut ctx.tm;
        match name {
            "__aeabi_uidiv" | "__udivsi3" | "__aeabi_idiv" | "__divsi3" | "__umodsi3" | "__modsi3"
            | "__aeabi_uidivmod" | "__aeabi_idivmod" => Some(r[1]),
            "__aeabi_uldivmod" | "__aeabi_ldivmod" | "__udivdi3" | "__divdi3" | "__umoddi3" | "__moddi3" => {
                Some(tm.concat(r[3], r[2]))
            }
            "__clzsi2" | "__ctzsi2" => Some(r[0]),
            _ => None,
        }
    };
    let unknown: Option<(T, [T; 4])> = undefined_at.and_then(|v| {
        let zero = ctx.tm.konst(ctx.tm.width(v), 0);
        let z = ctx.tm.eq(v, zero);
        let nz = ctx.tm.not(z);
        if ctx.implied(nz) {
            // Excluded on this path (typically by the source's own division).
            return None;
        }
        // The same routine called with the same arguments returns the same thing, whatever it
        // is: the unknown is named after the argument terms, not after the call.
        let key = format!("{}.{}.{}.{}", r[0], r[1], r[2], r[3]);
        Some((
            z,
            std::array::from_fn(|i| ctx.named_sym(&format!("undefined.{name}.{key}.r{i}"), 32)),
        ))
    });
    let tm = &mut ctx.tm;
    let a64 = tm.concat(r[1], r[0]);
    let b64 = tm.concat(r[3], r[2]);
    let halves = |tm: &mut crate::term::Terms, v: T| (tm.extract(v, 0, 32), tm.extract(v, 32, 32));
    // Results for r0..r3; None leaves the register clobbered.
    let mut out: [Option<T>; 4] = [None; 4];
    match name {
        "__aeabi_uidiv" | "__udivsi3" => out[0] = Some(tm.udiv(r[0], r[1])),
        "__aeabi_idiv" | "__divsi3" => out[0] = Some(tm.sdiv(r[0], r[1])),
        "__umodsi3" => out[0] = Some(tm.urem(r[0], r[1])),
        "__modsi3" => out[0] = Some(tm.srem(r[0], r[1])),
        "__aeabi_uidivmod" => {
            out[0] = Some(tm.udiv(r[0], r[1]));
            out[1] = Some(tm.urem(r[0], r[1]));
        }
        "__aeabi_idivmod" => {
            out[0] = Some(tm.sdiv(r[0], r[1]));
            out[1] = Some(tm.srem(r[0], r[1]));
        }
        "__aeabi_uldivmod" | "__aeabi_ldivmod" => {
            let signed = name == "__aeabi_ldivmod";
            let q = if signed { tm.sdiv(a64, b64) } else { tm.udiv(a64, b64) };
            let rem = if signed { tm.srem(a64, b64) } else { tm.urem(a64, b64) };
            let (q0, q1) = halves(tm, q);
            let (r0, r1) = halves(tm, rem);
            out = [Some(q0), Some(q1), Some(r0), Some(r1)];
        }
        "__udivdi3" | "__divdi3" | "__umoddi3" | "__moddi3" | "__aeabi_lmul" | "__muldi3" => {
            let v = match name {
                "__udivdi3" => tm.udiv(a64, b64),
                "__divdi3" => tm.sdiv(a64, b64),
                "__umoddi3" => tm.urem(a64, b64),
                "__moddi3" => tm.srem(a64, b64),
                _ => crate::sym::mul64(tm, a64, b64),
            };
            let (lo, hi) = halves(tm, v);
            out[0] = Some(lo);
            out[1] = Some(hi);
        }
        "__aeabi_llsl" | "__aeabi_llsr" | "__aeabi_lasr" | "__ashldi3" | "__lshrdi3" | "__ashrdi3" => {
            let amt = tm.zext(r[2], 64);
            let v = match name {
                "__aeabi_llsl" | "__ashldi3" => tm.shl(a64, amt),
                "__aeabi_llsr" | "__lshrdi3" => tm.lshr(a64, amt),
                _ => tm.ashr(a64, amt),
            };
            let (lo, hi) = halves(tm, v);
            out[0] = Some(lo);
            out[1] = Some(hi);
        }
        "__aeabi_lcmp" | "__aeabi_ulcmp" => {
            let signed = name == "__aeabi_lcmp";
            let lt = if signed { tm.slt(a64, b64) } else { tm.ult(a64, b64) };
            let gt = if signed { tm.slt(b64, a64) } else { tm.ult(b64, a64) };
            let g = tm.zext(gt, 32);
            let m1 = tm.konst(32, 0xffff_ffff);
            out[0] = Some(tm.ite(lt, m1, g));
        }
        "__clzsi2" => out[0] = Some(tm.clz(r[0])),
        "__ctzsi2" => out[0] = Some(tm.ctz(r[0])),
        "__popcountsi2" => out[0] = Some(tm.popcount(r[0])),
        "__bswapsi2" => out[0] = Some(tm.bswap(r[0])),
        "__paritysi2" => {
            let c = tm.popcount(r[0]);
            let b = tm.extract(c, 0, 1);
            out[0] = Some(tm.zext(b, 32));
        }
        "__ffssi2" => {
            let c = tm.ctz(r[0]);
            let c1 = tm.add_const(c, 1);
            let z = tm.konst(32, 0);
            let nz = tm.nonzero(r[0]);
            out[0] = Some(tm.ite(nz, c1, z));
        }
        "__clzdi2" | "__ctzdi2" | "__popcountdi2" => {
            let v = tm.concat(r[1], r[0]);
            let c = match name {
                "__clzdi2" => tm.clz(v),
                "__ctzdi2" => tm.ctz(v),
                _ => tm.popcount(v),
            };
            out[0] = Some(tm.trunc(c, 32));
        }
        _ => return false,
    }
    if let Some((z, fresh)) = unknown {
        for (o, f) in out.iter_mut().zip(fresh) {
            if let Some(v) = *o {
                *o = Some(tm.ite(z, f, v));
            }
        }
    }
    *count += 1;
    m.finish_call(ctx, 1000 + *count, out[0], out[1]);
    for i in 2..4 {
        if let Some(v) = out[i] {
            m.regs[i] = v;
        }
    }
    true
}

/// The machine code must have made exactly the volatile accesses the source makes before its
/// event number `k` (all of them when the path ends).
fn check_volatile(ctx: &Ctx, cx: &CExec, m: &Machine, k: usize) -> R<()> {
    let due = cx.volatile.iter().filter(|a| a.event <= k).count();
    if m.vol_pos == due {
        return Ok(());
    }
    let a = &cx.volatile[m.vol_pos.min(due)];
    let what = if a.write { "write to" } else { "read of" };
    let at = ctx.tm.show(a.addr);
    Err(Stop::Mismatch(
        if m.vol_pos < due {
            format!(
                "binary omits the source's {}-byte {what} the volatile object at {at}",
                a.size
            )
        } else {
            format!(
                "binary performs the {}-byte {what} the volatile object at {at} too early",
                a.size
            )
        },
        None,
    ))
}

fn run_path(ctx: &mut Ctx, job: &Job) -> R<PathResult> {
    run_seg(ctx, job, &SegCtl::default()).map(|e| e.res)
}

/// State both sides start a proof segment from, when that is not the function entry.
struct SegInit {
    c_block: usize,
    c_mem: Mem,
    m_pc: u32,
    m_regs: [T; 16],
    m_mem: Mem,
    /// Prefix of the symbols standing for unknown flags.
    tag: String,
}

/// What a proof segment is: where it starts and where it may end besides the function's return.
#[derive(Default)]
struct SegCtl<'s> {
    init: Option<&'s SegInit>,
    /// Branch conditions of the source known to hold at the start: (expression, truth value).
    assume: Vec<(&'s crate::c::ast::Expr, bool)>,
    c_cuts: &'s [usize],
    m_cuts: &'s [u32],
    /// Arrivals at cut points after which the source stops (0: never, the cut points are only watched).
    stop: usize,
    /// The same for the machine code.
    m_stop: usize,
}

struct SegEnd<'a> {
    res: PathResult,
    /// Both sides stopped at cut points: (source block, machine address).
    cut: Option<(usize, u32)>,
    cx: CExec<'a>,
    m: Machine,
}

fn cut_error(what: &str) -> Stop {
    Stop::Unsupported(format!("loop proof: {what}"))
}

fn run_seg<'a>(ctx: &mut Ctx, job: &Job<'a>, ctl: &SegCtl) -> R<SegEnd<'a>> {
    use crate::c::exec::BodyEnd;
    let p = job.prog;
    let f = &p.funcs[job.fid as usize];
    let stop = if ctl.stop == 0 { usize::MAX } else { ctl.stop };
    let m_stop = if ctl.m_stop == 0 { usize::MAX } else { ctl.m_stop };
    // --- source side ---
    let mut cx = CExec::new(job.env);
    cx.cut_blocks = ctl.c_cuts.to_vec();
    cx.cut_stop = stop;
    let c_end = match ctl.init {
        None => {
            for (base, words) in &job.struct_args {
                for (i, &w) in words.iter().enumerate() {
                    let a = ctx.tm.add_const(*base, 4 * i as u64);
                    ctx.mem_write(&mut cx.mem, a, 4, w);
                }
            }
            cx.run_segment(ctx, job.fid, Some(&job.args), 0, &[])
        }
        Some(init) => {
            cx.mem = init.c_mem.clone();
            cx.run_segment(ctx, job.fid, None, init.c_block, &ctl.assume)
        }
    };
    let (ret, halted, c_cut) = match c_end {
        Ok(BodyEnd::Ret(r)) => (r, false, None),
        Ok(BodyEnd::Cut(b)) => (None, false, Some(b)),
        Err(Stop::Halt) => (None, true, None),
        Err(e) => return Err(e),
    };
    crate::explain::report::note_source(&cx, ret, halted);
    // --- binary side ---
    let classify = |addr: u32| -> Callee {
        if let Some(name) = job.image.externals.get(&addr) {
            return Callee::External(name.clone());
        }
        match job.image.func_at(addr) {
            Some(s) => {
                let has_body = p
                    .funcs
                    .iter()
                    .any(|f| f.body.is_some() && *f.name == *base_name(&s.name));
                // Code the compiler factored out of several functions (machine outliner) has
                // no counterpart in the source: follow it like any other part of the caller.
                if has_body || s.name.starts_with("OUTLINED_FUNCTION_") {
                    Callee::Internal
                } else {
                    Callee::External(s.name.clone())
                }
            }
            None => Callee::Internal,
        }
    };
    let mut m = match ctl.init {
        None => {
            let mut m = Machine::new(ctx, job.entry, job.regs);
            for &(off, v) in &job.stack_args {
                let a = ctx.tm.add_const(job.regs[13], off as u64);
                ctx.mem_write(&mut m.mem, a, 4, v);
            }
            m
        }
        Some(init) => {
            let mut m = Machine::new(ctx, init.m_pc, init.m_regs);
            m.mem = init.m_mem.clone();
            // The frame is measured from the stack pointer at function entry, not from the
            // one at the loop head this path starts at.
            m.sp0 = job.regs[13];
            m.havoc_flags(ctx, &init.tag);
            m.at_start = true;
            m
        }
    };
    m.cuts = ctl.m_cuts.to_vec();
    m.cut_stop = m_stop;
    m.targets = job.env.targets.iter().map(|t| t.0).collect();
    m.known_indirect = cx.indirect.iter().map(|t| t.1).collect();
    m.vol = cx.volatile.clone();
    m.mmio = job.mmio.to_vec();
    m.plain = cx.plain_accesses(ctx);
    m.stack_top = job.stack_args.iter().map(|a| a.0 + 4).max().unwrap_or(0);
    let mut k = 0usize;
    let mut helper_calls = 0usize;
    let mut esc = Escapes::default();
    loop {
        match m.run(ctx, job.image, job.lr0, &classify)? {
            Exit::Call { name } => {
                check_result_slot(ctx, job, &m)?;
                if model_switch_helper(ctx, job, &mut m, &name, &mut helper_calls)? {
                    continue;
                }
                if cx.events.get(k).is_none_or(|ev| ev.name != name)
                    && (model_mem_call(ctx, job, &mut m, &name, &mut helper_calls)
                        || model_runtime_call(ctx, &mut m, &name, &mut helper_calls)
                        || model_string_call(ctx, job, &mut m, &name, &mut helper_calls))
                {
                    continue;
                }
                crate::explain::report::note_call(&m, &name, cx.events.get(k).map(|e| e.args.len()));
                let Some(ev) = cx.events.get(k) else {
                    return Err(Stop::Mismatch(
                        format!("binary calls {name}, which the source does not call at this point"),
                        None,
                    ));
                };
                if ev.name != name {
                    return Err(Stop::Mismatch(
                        format!("binary calls {name} where the source calls {}", ev.name),
                        None,
                    ));
                }
                check_volatile(ctx, &cx, &m, k)?;
                if let Some(got) = m.indirect.take() {
                    let want = cx
                        .indirect
                        .iter()
                        .find(|t| t.0 == k)
                        .expect("indirect event has a target")
                        .1;
                    prove_eq(ctx, want, got, &format!("target of call #{} through a pointer", k + 1))?;
                }
                match_call(ctx, job, &cx, &mut esc, &mut m, ev, k)?;
                m.mem.world.clear();
                m.mem.epoch = ev.epoch + 1;
                // The binary's copies of the locals the outside world can now reach.
                m.mem.exposed = ev
                    .exposed
                    .iter()
                    .filter_map(|e| {
                        esc.map.get(&e.base).map(|&(bb, _, size)| Exposed {
                            base: bb,
                            size,
                            since: e.since,
                        })
                    })
                    .collect();
                k += 1;
                if ev.noreturn {
                    break;
                }
                let (lo, hi) = match ev.ret {
                    None => (None, None),
                    Some((sym, signed)) => {
                        if ctx.tm.width(sym) == 64 {
                            (Some(ctx.tm.extract(sym, 0, 32)), Some(ctx.tm.extract(sym, 32, 32)))
                        } else {
                            (Some(ctx.tm.resize(sym, 32, signed)), None)
                        }
                    }
                };
                after_call(ctx, &esc, &mut m, ev, k - 1);
                m.finish_call(ctx, k - 1, lo, hi);
            }
            Exit::Cut(pc) => {
                let Some(b) = c_cut else {
                    return Err(cut_error(
                        "the binary reaches a loop head where the source leaves the function",
                    ));
                };
                if k != cx.events.len() {
                    return Err(cut_error("the binary reaches a loop head before the source's calls"));
                }
                check_volatile(ctx, &cx, &m, usize::MAX)?;
                let res = PathResult {
                    cov: cx.cov.clone(),
                    insns: m.covered.clone(),
                    data: m.data_covered.clone(),
                };
                return Ok(SegEnd {
                    res,
                    cut: Some((b, pc)),
                    cx,
                    m,
                });
            }
            Exit::Trap => {
                check_result_slot(ctx, job, &m)?;
                if c_cut.is_some() {
                    return Err(cut_error("the binary traps where the source reaches a loop head"));
                }
                let Some(ev) = cx.events.get(k) else {
                    return Err(Stop::Mismatch(
                        "binary traps (udf) where the source does not".into(),
                        None,
                    ));
                };
                if ev.name != "<trap>" {
                    return Err(Stop::Mismatch(
                        format!("binary traps (udf) where the source calls {}", ev.name),
                        None,
                    ));
                }
                check_volatile(ctx, &cx, &m, k)?;
                compare_world(
                    ctx,
                    job,
                    &ev.writes,
                    ev.epoch,
                    &ev.exposed,
                    &m,
                    "memory at trap",
                    &mut |ctx, c, b, what| prove_eq(ctx, c, b, what),
                )?;
                k += 1;
                break;
            }
            Exit::Return => {
                check_result_slot(ctx, job, &m)?;
                crate::explain::report::note_return(&m, ret.map(|v| ctx.tm.width(v)));
                if c_cut.is_some() {
                    return Err(cut_error("the binary returns where the source reaches a loop head"));
                }
                if let Some(ev) = cx.events.get(k) {
                    return Err(Stop::Mismatch(
                        format!("binary returns without calling {}", ev.name),
                        None,
                    ));
                }
                if halted {
                    return Err(Stop::Mismatch(
                        "binary returns where the source does not return".into(),
                        None,
                    ));
                }
                check_volatile(ctx, &cx, &m, usize::MAX)?;
                if let Some(v) = ret
                    && matches!(p.ty(f.ty.ret), Type::Record(_))
                {
                    // `v` is the address of the C-side result.  Compare the bits that hold values
                    // (padding is unspecified) with r0, or with the memory the caller provided.
                    let size = p.size_of(f.ty.ret).unwrap_or(0);
                    let mask = p.value_mask(f.ty.ret);
                    let mut off = 0;
                    while off < size {
                        let n = (size - off).min(4);
                        let bits = (0..n).fold(0u64, |b, i| b | (mask[(off + i) as usize] as u64) << (8 * i));
                        let a = ctx.tm.add_const(v, off as u64);
                        let want = cx.read_bytes(ctx, a, n as u8);
                        let got = match job.ret_slot {
                            Some(slot) => {
                                let a = ctx.tm.add_const(slot, off as u64);
                                let mut init = image_init(job.image, m.mem.epoch, None);
                                ctx.mem_read(&m.mem, a, n as u8, &mut init)
                            }
                            None => ctx.tm.trunc(m.regs[0], n as u8 * 8),
                        };
                        let k = ctx.tm.konst(n as u8 * 8, bits);
                        let (want, got) = (ctx.tm.and(want, k), ctx.tm.and(got, k));
                        prove_eq(
                            ctx,
                            want,
                            got,
                            &format!("bytes {off}..{} of the returned structure", off + n),
                        )?;
                        off += n;
                    }
                    // The AAPCS does not require the callee to hand the result address back in r0
                    // (GCC does, clang does not), so r0 is not compared here.
                } else if let Some(v) = ret {
                    let w = ctx.tm.width(v);
                    if w == 64 {
                        let got = ctx.tm.concat(m.regs[1], m.regs[0]);
                        prove_eq(ctx, v, got, "return value")?;
                    } else {
                        let expect = ctx.tm.resize(v, 32, p.is_signed(f.ty.ret));
                        if let Some((base, off)) = ctx.private_split(expect)
                            && let Some(&sid) = cx.str_bases.get(&base)
                            && let (Some(o), Some(ba)) = (ctx.tm.as_const(off), ctx.unique_value(m.regs[0]))
                            && let Some(rest) = job.env.prog.strings[sid as usize].get(o as usize..)
                        {
                            // A literal whose bytes are nowhere in the image as the source has them.
                            if job.image.read_const(ba as u32, rest.len() as u32) != Some(rest) {
                                return Err(Stop::Mismatch(
                                    format!(
                                        "return value: binary returns {ba:#x}, which does not hold the source's string literal"
                                    ),
                                    None,
                                ));
                            }
                        } else if !same_literal(ctx, job, expect, m.regs[0]) {
                            prove_eq(ctx, expect, m.regs[0], "return value")?;
                        }
                    }
                }
                compare_world(
                    ctx,
                    job,
                    &cx.mem.world,
                    cx.mem.epoch,
                    &cx.mem.exposed,
                    &m,
                    "memory at return",
                    &mut |ctx, c, b, what| prove_eq(ctx, c, b, what),
                )?;
                for r in (4..=11).chain([13]) {
                    let name = if r == 13 { "sp".to_string() } else { format!("r{r}") };
                    if r == 13
                        && let Some(d) = ctx.tm.const_diff(m.regs[13], job.regs[13])
                        && d != 0
                    {
                        return Err(Stop::Mismatch(
                            format!(
                                "stack pointer at return: the binary leaves it {} bytes from its value at entry",
                                d as u32 as i32
                            ),
                            None,
                        ));
                    }
                    prove_eq(
                        ctx,
                        job.regs[r],
                        m.regs[r],
                        &format!("callee-saved register {name} at return"),
                    )?;
                }
                let res = PathResult {
                    cov: cx.cov.clone(),
                    insns: m.covered.clone(),
                    data: m.data_covered.clone(),
                };
                return Ok(SegEnd { res, cut: None, cx, m });
            }
        }
    }
    // The path ended in a call that does not return.
    if c_cut.is_some() {
        return Err(cut_error("the binary stops where the source reaches a loop head"));
    }
    if k != cx.events.len() {
        return Err(Stop::Mismatch(
            "binary stops before the source's remaining calls".into(),
            None,
        ));
    }
    let res = PathResult {
        cov: cx.cov.clone(),
        insns: m.covered.clone(),
        data: m.data_covered.clone(),
    };
    Ok(SegEnd { res, cut: None, cx, m })
}

struct FuncOutcome {
    report: FuncReport,
    cov: BTreeSet<u32>,
    bytes: BTreeSet<u32>,
}

fn verify_function(prog: &Program, image: &Image, env: &CEnv, fid: u32, opts: &Options) -> FuncOutcome {
    let f = &prog.funcs[fid as usize];
    let sym = env.func_addr[fid as usize]
        .and_then(|a| image.func_at(a))
        .expect("entry has a symbol");
    let start = Instant::now();
    let mut out = FuncOutcome {
        report: FuncReport {
            name: f.name.to_string(),
            addr: sym.addr,
            size: sym.size,
            status: Status::Proved,
            paths: 0,
            undefined_paths: 0,
            millis: 0,
            sat_calls: 0,
            conflicts: 0,
            work: 0,
            detail: None,
        },
        cov: BTreeSet::new(),
        bytes: BTreeSet::new(),
    };
    let mut ctx = Ctx::new(opts.limits);
    crate::explain::report::begin_function(opts.dump);
    // Explanations of the first path that failed in each way.
    let mut why_inconclusive: Option<crate::explain::Explanation> = None;
    let mut why_bounded: Option<crate::explain::Explanation> = None;
    let mut why_mismatch: Option<crate::explain::Explanation> = None;
    if opts.check_solver {
        ctx.prover = crate::bv::Prover::new_checked();
    }
    let mut deadline = start + opts.time_limit;
    if let Some(d) = opts.deadline {
        deadline = deadline.min(d);
    }
    ctx.set_budget(opts.work_limit, opts.max_terms, Some(deadline));
    ctx.prover.rom = image
        .segments
        .iter()
        .filter(|s| !s.writable)
        .map(|s| (s.addr, s.data.clone()))
        .collect();
    // Objects nothing can modify hold their initial contents on the binary side as well.
    ctx.prover.rom.extend(env.frozen.iter().cloned());
    // Signature check.
    let scalar = |t| prog.is_scalar(t);
    let record = |t| matches!(prog.ty(t), Type::Record(_)) && prog.size_of(t).is_some_and(|s| s > 0);
    let passable = |t| scalar(t) || record(t);
    if !(f.ty.ret == VOID || passable(f.ty.ret)) || !f.ty.params.iter().all(|&t| passable(t)) {
        out.report.status = Status::Unsupported("non-integer parameter or return type".into());
        return out;
    }
    if image.hard_float && (has_float(prog, f.ty.ret) || f.ty.params.iter().any(|&t| has_float(prog, t))) {
        out.report.status = Status::Unsupported("hard-float calling convention".into());
        return out;
    }
    // Shared symbolic inputs.
    let mut regs = [0 as T; 16];
    for (i, r) in regs.iter_mut().enumerate().take(13) {
        *r = ctx.named_sym(&format!("r{i}"), 32);
    }
    if let Some(sb) = image.static_base {
        // Read-write position independence: r9 holds the base of the data area.
        regs[9] = ctx.tm.konst(32, sb as u64);
    }
    regs[13] = ctx.private_base("SP0");
    regs[14] = ctx.named_sym("LR0", 32);
    regs[15] = ctx.tm.konst(32, 0);
    let lr0 = regs[14];
    let mut pre = Vec::new();
    // The public interface keeps the stack 8-byte aligned.
    let low = ctx.tm.extract(regs[13], 0, 3);
    let z3 = ctx.tm.konst(3, 0);
    pre.push(ctx.tm.eq(low, z3));
    // A structure larger than four bytes is returned in memory the caller provides: r0 holds
    // its address.  The caller guarantees that nothing else designates that memory, so it is
    // modelled as a private object.
    let ret_slot = if record(f.ty.ret) && prog.size_of(f.ty.ret).unwrap_or(0) > 4 {
        let slot = ctx.private_base("RET0");
        regs[0] = slot;
        let low = ctx.tm.extract(slot, 0, 2);
        let z2 = ctx.tm.konst(2, 0);
        pre.push(ctx.tm.eq(low, z2));
        Some(slot)
    } else {
        None
    };
    let shapes: Vec<(u32, bool)> =
        f.ty.params
            .iter()
            .map(|&t| (prog.size_of(t).unwrap_or(4), prog.align_of(t) == 8))
            .collect();
    let mut args = Vec::new();
    let mut stack_args = Vec::new();
    let mut struct_args = Vec::new();
    for (i, (&ty, locs)) in
        f.ty.params
            .iter()
            .zip(arg_words(&shapes, ret_slot.is_some() as u8))
            .enumerate()
    {
        let words: Vec<T> = locs
            .iter()
            .map(|loc| match *loc {
                WordLoc::Reg(n) => regs[n as usize],
                WordLoc::Stack(off) => {
                    let s = ctx.named_sym(&format!("stk{off}"), 32);
                    stack_args.push((off, s));
                    s
                }
            })
            .collect();
        if record(ty) {
            // Passed by value: the C side sees an object holding the words the caller passed.
            let base = ctx.private_base(&format!("&arg{i}"));
            struct_args.push((base, words));
            args.push(base);
            continue;
        }
        let raw = if words.len() == 2 {
            ctx.tm.concat(words[1], words[0])
        } else {
            words[0]
        };
        let w = prog.bits(ty);
        if w < 32 && locs.len() == 1 {
            // The caller passes narrow arguments already extended to a full register: the
            // word *is* the extension of a narrow value (a fact the terms can then use, which
            // a side condition on a 32-bit symbol would hide from the normaliser).
            let is_bool = ty == crate::c::ast::BOOL;
            let (name, vw) = match locs[0] {
                WordLoc::Reg(n) => (format!("r{n}"), if is_bool { 1 } else { w }),
                WordLoc::Stack(off) => (format!("stk{off}"), if is_bool { 1 } else { w }),
            };
            let narrow = ctx.named_sym(&format!("{name}:{vw}"), vw);
            let v = ctx.tm.resize(narrow, w, false);
            let word = ctx.tm.resize(v, 32, prog.is_signed(ty));
            match locs[0] {
                WordLoc::Reg(n) => regs[n as usize] = word,
                WordLoc::Stack(off) => {
                    if let Some(slot) = stack_args.iter_mut().rev().find(|s| s.0 == off) {
                        slot.1 = word;
                    }
                }
            }
            args.push(v);
            continue;
        }
        let v = ctx.tm.trunc(raw, w);
        if prog.is_ptr(ty) {
            // A pointer the caller passes cannot point into stack the function has yet to allocate.
            let below = ctx.tm.add_const(regs[13], (FRAME_SPAN as u64).wrapping_neg());
            let d = ctx.tm.sub(v, below);
            let span = ctx.tm.konst(32, FRAME_SPAN as u64);
            pre.push(ctx.tm.ule(span, d));
        }
        args.push(v);
    }
    if f.variadic_def {
        // The variable arguments: whatever the caller left in the remaining argument
        // registers and in the first stack words after the named arguments.
        let start = crate::c::exec::va_start_word(&shapes, ret_slot.is_some() as u8);
        for w in start..start.max(4) + VA_STACK_WORDS {
            if w < 4 {
                args.push(regs[w as usize]);
            } else {
                let off = (w - 4) * 4;
                let s = ctx.named_sym(&format!("stk{off}"), 32);
                stack_args.push((off, s));
                args.push(s);
            }
        }
    }
    let job = Job {
        prog,
        image,
        env,
        fid,
        entry: sym.addr,
        regs,
        args,
        stack_args,
        struct_args,
        ret_slot,
        lr0,
        mmio: &opts.mmio,
    };
    let mut bounded: Option<String> = None;
    let mut inconclusive: Option<String> = None;
    let mut explored = 0usize;
    // Iterative deepening on the number of undetermined branches per path, so that loops with an
    // input-dependent trip count are proved for small counts first.
    let max_depth = opts.limits.max_depth;
    let mut schedule: Vec<usize> = [1, 2, 3, 4, 6, 8, 12, 16, 24, 32]
        .into_iter()
        .filter(|&d| d < max_depth)
        .collect();
    schedule.push(max_depth);
    let mut best_paths = 0usize;
    let mut tried_induction = false;
    'rounds: for (round, &depth) in schedule.iter().enumerate() {
        ctx.limits.max_depth = depth;
        ctx.decisions.clear();
        let mut depth_hit = false;
        inconclusive = None;
        why_inconclusive = None;
        crate::explain::report::begin_round();
        out.report.paths = 0;
        out.report.undefined_paths = 0;
        loop {
            ctx.restart(&pre);
            crate::explain::report::begin_path(pre.len());
            explored += 1;
            let res = run_path(&mut ctx, &job);
            crate::explain::report::end_path(&ctx, Some(prog), fid, &res);
            match res {
                Ok(r) => {
                    out.report.paths += 1;
                    out.cov.extend(r.cov);
                    for (a, n) in r.insns.into_iter().chain(r.data) {
                        out.bytes.extend(a..a + n as u32);
                    }
                }
                Err(Stop::Undefined) => out.report.undefined_paths += 1,
                Err(Stop::Halt) => unreachable!("Halt is handled by run_path"),
                Err(Stop::Truncated(why)) => {
                    if why == "branch depth limit" {
                        depth_hit = true;
                        if round + 1 == schedule.len() && why_bounded.is_none() && bounded.is_none() {
                            // Where the exploration gave up: usually inside the loop it cannot bound.
                            why_bounded = Some(crate::explain::report::capture(
                                &ctx,
                                Some(prog),
                                fid,
                                "bounded",
                                &why,
                                None,
                            ));
                        }
                    } else {
                        if bounded.is_none() {
                            why_bounded = Some(crate::explain::report::capture(
                                &ctx,
                                Some(prog),
                                fid,
                                "bounded",
                                &why,
                                None,
                            ));
                        }
                        bounded.get_or_insert(why);
                    }
                }
                Err(Stop::Inconclusive(why)) => {
                    // A prover that gave up because the function's budget ran out is a
                    // limit, not a hard obligation.
                    match ctx.check_deadline() {
                        Err(Stop::Truncated(limit)) => {
                            if bounded.is_none() {
                                // The goal the prover was working on when the budget ran out.
                                let mut e =
                                    crate::explain::report::capture(&ctx, Some(prog), fid, "inconclusive", &why, None);
                                e.outcome = "bounded".into();
                                why_bounded = Some(e);
                            }
                            bounded.get_or_insert(limit);
                        }
                        _ => {
                            if inconclusive.is_none() {
                                why_inconclusive = Some(crate::explain::report::capture(
                                    &ctx,
                                    Some(prog),
                                    fid,
                                    "inconclusive",
                                    &why,
                                    None,
                                ));
                            }
                            inconclusive.get_or_insert(why);
                        }
                    }
                }
                Err(Stop::Mismatch(why, model)) => {
                    why_mismatch = Some(crate::explain::report::capture(
                        &ctx,
                        Some(prog),
                        fid,
                        "mismatch",
                        &why,
                        model.as_deref(),
                    ));
                    // A difference found while an object or function the source uses could not be
                    // located in the image (its address was a free symbol on the source side)
                    // says nothing about the code.
                    let unlocated = ctx
                        .names()
                        .filter(|n| n.starts_with('&') && (n.contains("#g") || n.contains("#f")))
                        .min()
                        .map(|n| n[1..].rsplit_once('#').map_or(&n[1..], |p| p.0).to_string());
                    out.report.status = match unlocated {
                        Some(name) => Status::Unsupported(format!(
                            "uses `{name}`, which could not be located in the binary (no symbol, or several candidates)"
                        )),
                        None => Status::Mismatch(why),
                    };
                    break 'rounds;
                }
                Err(Stop::Unsupported(why)) => {
                    out.report.status = Status::Unsupported(why);
                    break 'rounds;
                }
            }
            best_paths = best_paths.max(out.report.paths);
            if let Err(Stop::Truncated(limit)) = ctx.check_deadline() {
                bounded.get_or_insert(limit);
                break 'rounds;
            }
            if explored >= opts.limits.max_paths {
                bounded.get_or_insert_with(|| "path limit".into());
                break 'rounds;
            }
            if !ctx.next_path() {
                break;
            }
        }
        if !depth_hit {
            break;
        }
        // A loop whose trip count depends on the input: try a proof by induction once the
        // shallow paths have shown no difference.
        let last = round + 1 == schedule.len();
        if !tried_induction && bounded.is_none() && inconclusive.is_none() && (depth >= 3 || last) {
            tried_induction = true;
            // The attempt gets half of what is left of the budget, in work and in time.
            let saved = (ctx.work_limit, ctx.max_terms, ctx.deadline);
            let now = Instant::now();
            let half_time = saved.2.map(|d| if d > now { now + (d - now) / 2 } else { d });
            let used = ctx.work();
            let half_work = match saved.0 {
                u64::MAX => u64::MAX,
                limit => used + limit.saturating_sub(used) / 2,
            };
            ctx.set_budget(half_work, saved.1, half_time);
            let proof = loops::prove(&mut ctx, &job, &pre, (sym.addr, sym.addr + sym.size.max(2)));
            ctx.set_budget(saved.0, saved.1, saved.2);
            // What the prover gave up on under the reduced budget is not settled.
            ctx.prover.forget_unknown();
            if let Some(proof) = proof {
                out.report.paths += proof.paths;
                out.cov.extend(proof.cov);
                for (a, n) in proof.bytes {
                    out.bytes.extend(a..a + n as u32);
                }
                break;
            }
        }
        if last {
            bounded.get_or_insert_with(|| format!("loop bound ({depth} branches per path)"));
        }
    }
    out.report.paths = out.report.paths.max(best_paths);
    if out.report.status == Status::Proved {
        if let Some(why) = inconclusive {
            out.report.status = Status::Inconclusive(why);
        } else if let Some(why) = bounded {
            out.report.status = Status::Bounded(format!("{why}; {} paths proved", out.report.paths));
        }
    }
    if matches!(out.report.status, Status::Mismatch(_) | Status::Unsupported(_)) {
        // Nothing about this function counts as verified.
        out.cov.clear();
        out.bytes.clear();
    }
    let explanation = match &out.report.status {
        Status::Mismatch(_) => why_mismatch,
        Status::Inconclusive(_) => why_inconclusive,
        Status::Bounded(why) => {
            let limit = why.split(';').next().unwrap_or(why);
            let mut e = why_bounded.unwrap_or_else(|| crate::explain::report::limit_only(limit));
            e.reason = limit.to_string();
            e.induction = Some(tried_induction);
            Some(e)
        }
        _ => None,
    };
    let (paths, skipped_paths) = crate::explain::report::take_paths();
    if explanation.is_some() || !paths.is_empty() {
        out.report.detail = Some(Box::new(crate::explain::FuncDetail {
            explanation,
            paths,
            skipped_paths,
        }));
    }
    out.report.millis = start.elapsed().as_millis();
    let (_, sat_calls, conflicts, props) = ctx.prover.counters();
    out.report.sat_calls = sat_calls;
    out.report.conflicts = conflicts;
    out.report.work = props / 1000 + ctx.tm.len() as u64;
    out
}

/// Compare the initial contents of every source-defined object with the binary.
fn check_data(prog: &Program, image: &Image, env: &CEnv, report: &mut Report) {
    report.data_issues.extend(env.data_notes.iter().cloned());
    for (i, g) in prog.globals.iter().enumerate() {
        if !g.defined {
            continue;
        }
        let Some(addr) = env.global_addr[i] else { continue };
        let Some(expect) = env.init_bytes(i as u32) else {
            continue;
        };
        let Some(got) = image.read(addr, expect.len() as u32) else {
            if env.is_synthetic(addr) {
                // The compiler folded every use of the object: it has no storage to compare.
                continue;
            }
            if image.segments.iter().all(|s| !s.writable) {
                // Raw image: RAM contents are not part of the file.
                continue;
            }
            report
                .data_issues
                .push(format!("{}: object at {addr:#x} is outside the image", g.name));
            continue;
        };
        report.data_checked += 1;
        if let Some(off) = expect.iter().zip(got).position(|(a, b)| a != b) {
            report.data_issues.push(format!(
                "{}: initial value differs at offset {off}: source has {:#04x}, binary has {:#04x}",
                g.name, expect[off], got[off]
            ));
        }
    }
}

/// Internal-linkage functions that several symbols of the image could be (the same static name
/// in several translation units, and no record of which file a symbol comes from): try each
/// candidate and keep the assignment under which the code proves to be the function.
fn resolve_ambiguous(prog: &Program, image: &Image, env: &mut CEnv, opts: &Options) {
    let pending = std::mem::take(&mut env.ambiguous);
    if pending.is_empty() {
        return;
    }
    let trial = Options {
        only: Vec::new(),
        time_limit: opts.time_limit.min(Duration::from_secs(5)),
        ..opts.clone()
    };
    let mut fits: Vec<(u32, Vec<u32>)> = Vec::new();
    for (fid, cands) in &pending {
        let mut ok = Vec::new();
        for &a in cands {
            env.func_addr[*fid as usize] = Some(a);
            let o = verify_function(prog, image, env, *fid, &trial);
            let good = match o.report.status {
                Status::Proved => true,
                Status::Bounded(_) => o.report.paths > 0,
                _ => false,
            };
            if good {
                ok.push(a);
            }
        }
        env.func_addr[*fid as usize] = None;
        fits.push((*fid, ok));
    }
    // Most constrained first; identical bodies may fit several symbols, any pairing will do.
    fits.sort_by_key(|f| f.1.len());
    let mut taken: HashSet<u32> = HashSet::new();
    for (fid, ok) in fits {
        if let Some(&a) = ok.iter().find(|a| !taken.contains(a)) {
            taken.insert(a);
            env.bind_func(fid, a);
        }
    }
}

/// Stack size of a verification thread.  Terms are built and walked recursively and a long
/// path nests them deeply.  The whole test suite passes with 2 MB; this leaves a wide margin
/// while keeping a full pool of workers small enough to run under an address-space limit.
const WORKER_STACK: usize = 32 << 20;

/// Process-wide limit on functions being verified at once, so that several `verify` calls
/// running concurrently (as in the test suite) share the CPUs instead of each starting one
/// thread per CPU.
struct Permit;

static RUNNING: std::sync::Mutex<usize> = std::sync::Mutex::new(0);
static FREED: std::sync::Condvar = std::sync::Condvar::new();

impl Permit {
    fn acquire(cap: usize) -> Permit {
        let mut n = RUNNING.lock().unwrap_or_else(|e| e.into_inner());
        while *n >= cap {
            n = FREED.wait(n).unwrap_or_else(|e| e.into_inner());
        }
        *n += 1;
        Permit
    }
}

impl Drop for Permit {
    fn drop(&mut self) {
        *RUNNING.lock().unwrap_or_else(|e| e.into_inner()) -= 1;
        FREED.notify_one();
    }
}

/// Run `work` on every item, on up to `jobs` threads (0 = one per CPU), and return the results
/// in the order of the items.  Each call is independent: it builds its own term store and
/// solver and only reads the shared program and image.
pub(crate) fn run_jobs<R: Send>(items: &[u32], jobs: usize, work: impl Fn(u32) -> R + Sync) -> Vec<R> {
    use std::sync::Mutex;
    use std::sync::atomic::{AtomicUsize, Ordering};
    let cpus = std::thread::available_parallelism().map_or(1, |n| n.get());
    let jobs = match jobs {
        0 => cpus,
        n => n,
    }
    .min(items.len().max(1));
    let cap = jobs.max(cpus);
    let next = AtomicUsize::new(0);
    let results: Mutex<Vec<Option<R>>> = Mutex::new(items.iter().map(|_| None).collect());
    std::thread::scope(|s| {
        let handles: Vec<_> = (0..jobs)
            .map(|_| {
                std::thread::Builder::new()
                    .stack_size(WORKER_STACK)
                    .spawn_scoped(s, || {
                        loop {
                            let i = next.fetch_add(1, Ordering::Relaxed);
                            let Some(&item) = items.get(i) else { break };
                            let permit = Permit::acquire(cap);
                            let r = work(item);
                            drop(permit);
                            results.lock().unwrap()[i] = Some(r);
                        }
                    })
                    .expect("spawn verification thread")
            })
            .collect();
        for h in handles {
            if let Err(e) = h.join() {
                std::panic::resume_unwind(e);
            }
        }
    });
    results
        .into_inner()
        .unwrap()
        .into_iter()
        .map(|r| r.expect("every item was processed"))
        .collect()
}

pub fn verify(prog: &Program, image: &Image, opts: &Options) -> Report {
    let mut env = CEnv::new(prog, image);
    resolve_ambiguous(prog, image, &mut env, opts);
    let env = env;
    let mut report = Report::default();
    let mut cov: BTreeSet<u32> = BTreeSet::new();
    let mut bytes: BTreeSet<u32> = BTreeSet::new();
    let todo: Vec<u32> = prog
        .funcs
        .iter()
        .enumerate()
        .filter(|(fid, f)| f.body.is_some() && env.func_addr[*fid].is_some())
        .filter(|(_, f)| opts.only.is_empty() || opts.only.iter().any(|n| **n == *f.name))
        .map(|(fid, _)| fid as u32)
        .collect();
    for o in run_jobs(&todo, opts.jobs, |fid| verify_function(prog, image, &env, fid, opts)) {
        cov.extend(o.cov);
        bytes.extend(o.bytes);
        report.funcs.push(o.report);
    }
    check_data(prog, image, &env, &mut report);

    // Source coverage.
    report.src = (cov.len(), prog.ncov as usize);
    let mut lines: BTreeSet<(String, u32)> = BTreeSet::new();
    let mut hit: HashSet<(u16, u32)> = HashSet::new();
    for &c in &cov {
        let loc = prog.cov_info[c as usize].1;
        hit.insert((loc.file, loc.line));
    }
    for (c, (_, loc)) in prog.cov_info.iter().enumerate() {
        if !cov.contains(&(c as u32)) && !hit.contains(&(loc.file, loc.line)) {
            lines.insert((prog.files.get(loc.file as usize).cloned().unwrap_or_default(), loc.line));
        }
    }
    report.uncovered_lines = lines.into_iter().collect();
    for (c, (fid, loc)) in prog.cov_info.iter().enumerate() {
        // Only functions that were candidates for verification have meaningful points.
        report.src_points.push(SrcPoint {
            file: prog.files.get(loc.file as usize).cloned().unwrap_or_default(),
            line: loc.line,
            func: prog.funcs[*fid as usize].name.to_string(),
            proved: cov.contains(&(c as u32)),
        });
    }
    let reached_funcs: HashSet<u32> = cov.iter().map(|&c| prog.cov_info[c as usize].0).collect();
    for (fid, f) in prog.funcs.iter().enumerate() {
        if f.body.is_some() && env.func_addr[fid].is_none() && !reached_funcs.contains(&(fid as u32)) {
            report.absent.push(f.name.to_string());
        }
    }

    // Binary coverage: code bytes are everything in executable segments except alignment padding.
    let mut total = 0usize;
    let mut proved = 0usize;
    for seg in image.segments.iter().filter(|s| s.exec) {
        let in_func = |a: u32| {
            image
                .symbols
                .iter()
                .any(|s| s.kind == SymKind::Func && a >= s.addr && a - s.addr < s.size)
        };
        let mut o = 0usize;
        while o < seg.data.len() {
            let a = seg.addr + o as u32;
            let n = if o + 1 < seg.data.len() { 2 } else { 1 };
            let hw = if n == 2 {
                u16::from_le_bytes([seg.data[o], seg.data[o + 1]])
            } else {
                seg.data[o] as u16
            };
            let covered = (0..n as u32).filter(|i| bytes.contains(&(a + i))).count();
            let padding = covered == 0 && !in_func(a) && matches!(hw, 0 | 0xbf00 | 0x46c0);
            if !padding {
                total += n;
                proved += covered;
            }
            for i in 0..n as u32 {
                let state = if padding {
                    ByteState::Padding
                } else if bytes.contains(&(a + i)) {
                    ByteState::Proved
                } else {
                    ByteState::Unproved
                };
                match report.bin_ranges.last_mut() {
                    Some(r) if r.end == a + i && r.state == state => r.end += 1,
                    _ => report.bin_ranges.push(BinRange {
                        start: a + i,
                        end: a + i + 1,
                        state,
                    }),
                }
            }
            o += n;
        }
    }
    report.bin = (proved, total);
    for s in image.symbols.iter().filter(|s| s.kind == SymKind::Func && s.size > 0) {
        if image.segment_at(s.addr).is_some() && !(s.addr..s.addr + s.size).any(|a| bytes.contains(&a)) {
            let verified = report.funcs.iter().any(|f| f.name == s.name);
            if !verified {
                report.unmatched.push((s.name.clone(), s.size));
            }
        }
    }
    report
}

/// Does a value of this type contain a floating-point number?
fn has_float(prog: &Program, t: crate::c::ast::TypeId) -> bool {
    match prog.ty(t) {
        Type::Float { .. } => true,
        Type::Array(e, _) => has_float(prog, *e),
        Type::Record(r) => prog.records[*r as usize].fields.iter().any(|f| has_float(prog, f.ty)),
        _ => false,
    }
}