cverif 0.0.4

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
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
//! 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::INDIRECT;
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::{BTreeMap, 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,
    /// Compare calls to functions that are verified on their own as events before falling
    /// back to following the callee on both sides.
    pub modular: bool,
    /// Keep results in this directory and reuse those whose key still fits (see `cache`).
    pub cache: Option<std::path::PathBuf>,
    /// Which type-based aliasing rules the source is held to (`-fno-strict-aliasing` turns
    /// them off).
    pub aliasing: crate::c::exec::Aliasing,
}

/// 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,
            modular: true,
            aliasing: Default::default(),
            check_solver: false,
            cache: None,
            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>>,
    /// Functions this one calls that were compared as calls, not followed, with the verdict
    /// each got on its own: the result holds provided they behave as their source says.
    pub modulo: Vec<(String, String)>,
    /// Proved, and so is (in the same sense) everything in `modulo`.
    pub unconditional: bool,
    /// The result was taken from the cache (see `Options::cache`), not established by this run.
    pub cached: bool,
    /// Assumptions beyond the letter of the C standard that a proof of this function needed:
    /// `strict-aliasing` is the compilers' reading of the aliasing rules (see
    /// `c::exec::Aliasing::Compiler`).
    pub assumes: Vec<String>,
    /// The function was only verified for the argument values its callers pass (a function
    /// with internal linkage whose address is not taken): which ones, in words.
    pub given: Option<String>,
    /// Accesses below the stack pointer on the paths explored (see `sym::Hazard`).
    pub hazards: Vec<crate::sym::Hazard>,
}

#[derive(Clone, Debug, Default)]
pub struct Report {
    pub funcs: Vec<FuncReport>,
    /// The aliasing rules the source was held to: `compiler`, `standard` or `off`.
    pub aliasing: &'static str,
    /// 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.
    /// Where the image does not say what is code (`Image::soft_bounds`), every loaded byte.
    pub bin_ranges: Vec<BinRange>,
    /// Source files the front end could not parse, with the error: their functions were
    /// not verified (filled in by the caller that parsed the sources).
    pub skipped_sources: Vec<(String, String)>,
    /// Ranges left out of the binary total because someone says they are data: (start, end, why).
    pub set_aside: Vec<(u32, u32, String)>,
    /// Bytes outside the known code that nothing accounts for (counted as unproved).
    pub unexplained: usize,
}

/// 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,
    /// Taken to be data on somebody's word (declared by the user, or classified by discovery
    /// with evidence): listed with the reason in `Report::set_aside`, not counted.
    SetAside,
}

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

/// 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)],
    /// Source-defined functions whose calls are events on both sides (see `callable`).
    opaque: std::sync::Arc<Vec<bool>>,
    /// The same by name (the names are unique among the functions of the image).
    opaque_names: HashMap<String, u32>,
    /// Calls are compared as events wherever possible, instead of following every callee.
    modular: bool,
    /// The opaque function (if any) behind each event of the source on the current path,
    /// and how many events the binary has matched: says which callee to follow instead
    /// when the comparison fails.
    trace: std::cell::RefCell<(Vec<Option<u32>>, usize)>,
    /// An opaque function the binary called where the source calls something else or nothing
    /// (a loop back to the function's own entry, a callee inlined in the source's callee).
    stray: std::cell::Cell<Option<u32>>,
    /// The targets of the source's calls through pointers on the current path, by event.
    targets: std::cell::RefCell<Vec<(usize, T)>>,
    /// Every opaque function some path of the source called.
    used: std::cell::RefCell<BTreeSet<u32>>,
    /// The call being matched is to another entry point of the library function the source
    /// calls: how the two relate.
    call_map: std::cell::RefCell<Option<CallMap>>,
    /// The result of the function under verification is used by none of its callers and is
    /// not compared.
    result_unused: bool,
    /// What the paths explored so far do to the stack frame after calls that may return twice.
    rt: std::cell::RefCell<Vec<RtPath>>,
    /// Routines written in assembly: the caller-saved registers each provably leaves alone.
    asm_keeps: std::cell::RefCell<HashMap<u32, u16>>,
}

/// A library entry point the binary calls in place of the function the source calls.
#[derive(Clone, Debug)]
struct CallMap {
    /// For each argument of the source's call, its position among the binary's arguments
    /// (which are all single words); `GONE` for an argument the entry point does not take
    /// because it stands for one value of it, zero (`__aeabi_memclr`).
    pos: Vec<usize>,
    /// The entry point returns nothing: the binary cannot use the function's result.
    void: bool,
}

/// See `CallMap::pos`.
const GONE: usize = usize::MAX;

impl CallMap {
    /// The entry point `name` when the source calls `plain` with `n` arguments.
    fn of(name: &str, plain: &str, n: usize) -> Option<CallMap> {
        let aeabi = |stem: &str| {
            name.strip_prefix(stem)
                .is_some_and(|rest| matches!(rest, "" | "4" | "8"))
        };
        let (pos, void): (Vec<usize>, bool) = match plain {
            "memcpy" if n == 3 && aeabi("__aeabi_memcpy") => (vec![0, 1, 2], true),
            "memmove" if n == 3 && aeabi("__aeabi_memmove") => (vec![0, 1, 2], true),
            // `__aeabi_memset(dest, n, c)`.
            "memset" if n == 3 && aeabi("__aeabi_memset") => (vec![0, 2, 1], true),
            // `__aeabi_memclr(dest, n)` is `memset(dest, 0, n)`.
            "memset" if n == 3 && aeabi("__aeabi_memclr") => (vec![0, GONE, 1], true),
            _ => {
                // `__snprintf_chk(s, n, flag, size of s, format, ...)`.
                let fortified = name.strip_prefix("__").and_then(|p| p.strip_suffix("_chk"));
                let &(_, at) = FORTIFIED_PRINTF
                    .iter()
                    .find(|f| f.0 == plain && fortified == Some(plain))?;
                ((0..n).map(|i| if i < at { i } else { i + 2 }).collect(), false)
            }
        };
        Some(CallMap { pos, void })
    }
}

impl Job<'_> {
    /// Is `f` an internal function whose result none of its callers uses, with a local
    /// symbol in the binary?
    fn unused_result(&self, f: u32) -> bool {
        unused_result(self.env, self.image, f)
    }

    /// The opaque callee whose treatment as an event most likely made the current path
    /// fail: the one the binary was expected to call next, or else the last one it called.
    fn culprit(&self, ctx: &mut Ctx) -> Option<u32> {
        // An attempt that is not to be retried has no culprit: its failures are the result.
        // (Without this an attempt with callees the linker may replace, run to its end,
        // stopped at the first failure and was read as having proved the function.)
        if !self.modular {
            return None;
        }
        if let Some(f) = self.stray.get() {
            return Some(f);
        }
        let t = self.trace.borrow();
        // The source calls through a pointer that is one function on this path: the binary,
        // having tested for it, may have that function's code inline.
        if let Some(&(_, target)) = self.targets.borrow().iter().find(|x| x.0 == t.1)
            && let Some(v) = ctx.unique_value(target)
            && let Some(f) = (0..self.opaque.len())
                .find(|&f| self.opaque[f] && self.env.func_addr[f].is_some_and(|a| (a | 1) as u64 == v))
        {
            return Some(f as u32);
        }
        t.0.iter().take(t.1 + 1).rev().find_map(|f| *f)
    }
}

/// Functions a caller may treat as an observable call instead of following their code: the
/// source defines them, the binary has their code under a symbol of exactly that name (not
/// a clone the compiler specialised, whose interface differs), and no other function symbol
/// shares the name.  Each is verified on its own against the standard calling convention.
fn callable(prog: &Program, image: &Image, env: &CEnv) -> Vec<bool> {
    let mut count: HashMap<&str, u32> = HashMap::new();
    let mut at: HashMap<u32, &str> = HashMap::new();
    for s in image.symbols.iter().filter(|s| s.kind == SymKind::Func) {
        *count.entry(s.name.as_str()).or_default() += 1;
        at.entry(s.addr).or_insert(s.name.as_str());
    }
    prog.funcs
        .iter()
        .enumerate()
        .map(|(fid, f)| {
            f.body.is_some()
                && f.ty.proto
                && env.func_addr[fid].is_some_and(|a| at.get(&a) == Some(&&*f.name))
                && count.get(&*f.name) == Some(&1)
        })
        .collect()
}

/// The caller-saved registers that the routine at `addr`, written in assembly, leaves as it
/// found them, as a bit mask.
///
/// A compiler that sees the routine in the same translation unit knows from the clobber lists
/// of its assembly statements which registers survive a call to it, and its callers rely on
/// that (gcc's `-fipa-ra`).  The registers counted here are those the routine's actual code
/// leaves unchanged on its one path from entry to return; a routine that branches on its
/// inputs, calls out or cannot be followed keeps nothing.
fn asm_keeps(image: &Image, addr: u32) -> u16 {
    let mut ctx = Ctx::new(Limits::default());
    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);
    }
    regs[13] = ctx.private_base("SP0");
    regs[14] = ctx.named_sym("LR0", 32);
    regs[15] = ctx.tm.konst(32, 0);
    let mut m = Machine::new(&mut ctx, addr, regs);
    let classify = |_: u32| Callee::External("?".into());
    match m.run(&mut ctx, image, regs[14], &classify) {
        Ok(Exit::Return) if ctx.decisions.is_empty() && m.regs[13] == regs[13] => [0usize, 1, 2, 3, 12]
            .into_iter()
            .filter(|&i| m.regs[i] == regs[i])
            .fold(0, |mask, i| mask | 1 << i),
        _ => 0,
    }
}

/// Calls that may return a second time (`setjmp`, MicroPython's `nlr_push`).
///
/// Such a call is modelled as an ordinary call to unknown code that returns an unknown value,
/// and each path that continues from it is proved like any other.  That proof is about the
/// *first* return.  The second return — a callee of a later call jumps back — resumes the same
/// code in a state that differs from the one the proof started from, and the proof carries
/// over only as far as the two states agree on what the path uses:
///
/// * Callee-saved registers and the stack pointer are those of the first return: restoring
///   them is the contract of the routine (assumed, it is assembly).  Caller-saved registers
///   and flags are unknown in both.
/// * World memory is whatever the code that ran in between left there.  The proof assumes
///   nothing about it (every call havocs it), and the two sides agree on it because the paths
///   that ran in between were proved up to the call that jumped.
/// * Locals whose address the callee can reach hold unknown but equal contents on both sides.
/// * The source's other locals hold their values of the first return if the program did not
///   modify them since, and indeterminate values otherwise (C11 7.13.2.1p3): assuming the old
///   values, as the proof does, is one of the behaviours the standard allows.
/// * The binary's stack frame is *not* restored.  A slot the path reads after the call must
///   therefore still hold what it held at the first return: no path may store to it between
///   the first return and a later call.  This is checked here, across all paths of the
///   function; a function for which it fails (a `volatile` local kept across the jump, or a
///   compiler unaware of the second return reusing a slot) is not reported as proved.
struct RtPath {
    /// Address the call returns to.
    site: u32,
    name: String,
    /// Stack ranges (offset from the entry stack pointer, size) the path reads after the call
    /// without having written them since, if the call may have returned a non-zero value on
    /// it (a second return never yields zero).
    reads: Vec<(i64, u8)>,
    reads_unknown: bool,
    /// Stack ranges the path stores to after the call and before a later call.
    writes: Vec<(i64, u8)>,
    writes_unknown: bool,
    /// The highest stack pointer (offset from the entry stack pointer) at a later call:
    /// whatever lies below it then is the callee's to overwrite.
    freed: i64,
}

/// Record what a finished path did to the frame after each call that may return twice.
fn record_rt(
    ctx: &mut Ctx,
    job: &Job,
    m: &Machine,
    esc: &Escapes,
    sites: &[(u32, usize, String, Option<T>)],
    k: usize,
) {
    let Some(trace) = &m.trace else { return };
    for (site, start, name, ret) in sites {
        let reader = match ret {
            Some(r) => {
                let z = ctx.tm.konst(ctx.tm.width(*r), 0);
                let zero = ctx.tm.eq(*r, z);
                !ctx.implied(zero)
            }
            None => true,
        };
        let mut p = RtPath {
            site: *site,
            name: name.clone(),
            reads: Vec::new(),
            reads_unknown: false,
            writes: Vec::new(),
            writes_unknown: false,
            freed: i64::MIN,
        };
        let mut written: Vec<(i64, i64)> = Vec::new();
        for a in &trace[*start..] {
            match (a.write, a.off) {
                // A later call (see `mark_call`): the stack pointer there.
                (true, Some(o)) if a.size == 0 => p.freed = p.freed.max(o),
                (true, Some(o)) => {
                    written.push((o, o + a.size as i64));
                    if (a.ev as usize) < k {
                        p.writes.push((o, a.size));
                    }
                }
                (true, None) => p.writes_unknown |= (a.ev as usize) < k,
                (false, Some(o)) => {
                    let end = o + a.size as i64;
                    // Contents of objects the callee can reach are unknown-but-equal in the model.
                    let escaped = esc.map.values().any(|&(_, d, size)| o >= d && end <= d + size as i64);
                    if reader && !escaped && !written.iter().any(|&(lo, hi)| o >= lo && end <= hi) {
                        p.reads.push((o, a.size));
                    }
                }
                (false, None) => p.reads_unknown |= reader,
            }
        }
        job.rt.borrow_mut().push(p);
    }
}

/// Does some path read, after a call that may return twice, a stack slot that a path
/// overwrites between the first return and a later call?
fn rt_conflict(paths: &[RtPath]) -> Option<String> {
    for p in paths {
        let same = || paths.iter().filter(|q| q.site == p.site);
        let any_write = same().any(|q| q.writes_unknown || !q.writes.is_empty());
        let hit = if p.reads_unknown && any_write || !p.reads.is_empty() && same().any(|q| q.writes_unknown) {
            Some("a computed stack address".to_string())
        } else {
            p.reads.iter().find_map(|&(o, n)| {
                (same().any(|q| o < q.freed)
                    || same()
                        .flat_map(|q| q.writes.iter())
                        .any(|&(w, wn)| o < w + wn as i64 && w < o + n as i64))
                .then(|| format!("offset {o} from the entry stack pointer"))
            })
        };
        if let Some(at) = hit {
            return Some(format!(
                "{} may return a second time: the code after it reads the stack frame at {at}, which the function overwrites or releases before a later call (the frame is not restored by the jump back)",
                p.name
            ));
        }
    }
    None
}

/// 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 same for objects of dynamic size: C object base -> (address in the binary's frame, size).
    dynamic: HashMap<T, (T, T)>,
}

/// Position of a stack address in the megabyte-and-a-bit the function may own: its distance
/// from `FRAME_SPAN` below the entry stack pointer.  Unsigned comparisons of such positions
/// are comparisons of the addresses.
fn frame_pos(ctx: &mut Ctx, job: &Job, a: T) -> T {
    let d = ctx.tm.sub(a, job.regs[13]);
    ctx.tm.add_const(d, FRAME_SPAN as u64)
}

/// Prove a requirement on where the binary keeps things in its frame.
fn frame_rule(ctx: &mut Ctx, cond: T, what: impl Fn() -> String) -> R<()> {
    match ctx.check(cond) {
        Ok(()) => Ok(()),
        Err(Some(env)) => Err(Stop::Mismatch(what(), Some(env))),
        Err(None) => Err(Stop::Inconclusive(format!("{}: prover gave up", what()))),
    }
}

/// The source's object at `base` is about to be identified with the binary's storage at `bb`.
/// What the source run assumed about the object's address (it is aligned for the accesses
/// made through pointers, it differs from other pointers) must be able to hold there:
/// otherwise the identification would make the path condition contradictory and everything
/// after it provable.
fn can_bind(ctx: &mut Ctx, base: T, bb: T, name: &str, what: &str) -> R<()> {
    let differ = ctx.tm.ne(base, bb);
    if ctx.check(differ).is_err() {
        return Ok(());
    }
    // They cannot be equal.  (Unless nothing can: a path on which the source's behaviour is
    // undefined whatever the inputs are, which says nothing about this object.)
    let never = ctx.tm.fals();
    if ctx.check(never).is_ok() {
        return Ok(());
    }
    Err(Stop::Unsupported(format!(
        "{what}: the binary keeps {name} at {}, which contradicts what the source assumes about that address (its alignment, or that other pointers differ from it)",
        ctx.tm.show(bb)
    )))
}

/// The place the binary gives an object whose address a callee receives is aligned as the
/// object's type requires: the callee, compiled for that type, may rely on it (and an
/// unaligned word access faults on ARMv6-M).
fn aligned(ctx: &mut Ctx, bb: T, align: u32, name: &str, what: &str) -> R<()> {
    if align <= 1 {
        return Ok(());
    }
    let mask = ctx.tm.konst(32, align as u64 - 1);
    let low = ctx.tm.and(bb, mask);
    let zero = ctx.tm.konst(32, 0);
    let ok = ctx.tm.eq(low, zero);
    frame_rule(ctx, ok, || {
        format!("{what}: the binary keeps {name} at an address that is not aligned to {align} bytes")
    })
}

/// `[a, a + an)` and `[b, b + bn)` do not overlap, for frame positions.
fn apart(ctx: &mut Ctx, a: T, an: T, b: T, bn: T) -> T {
    let ae = ctx.tm.add(a, an);
    let be = ctx.tm.add(b, bn);
    let x = ctx.tm.ule(ae, b);
    let y = ctx.tm.ule(be, a);
    ctx.tm.or(x, y)
}

/// The binary passes `b` where the source passes the address `base + off` of an object of
/// dynamic size (a variable-length array, an `alloca` block).  The first time, this fixes where
/// the binary keeps the object: it must lie in the function's own frame, be aligned like any
/// allocation and not share storage with another local the callee can reach.
fn bind_dynamic(
    ctx: &mut Ctx,
    job: &Job,
    esc: &mut Escapes,
    ev: &Event,
    obj: &crate::sym::Escaped,
    (off, b): (T, T),
    what: &str,
) -> R<()> {
    let name = obj.name.trim_start_matches('&');
    let size = obj.dynamic.as_ref().expect("dynamic object").size;
    let bb = match esc.dynamic.get(&obj.base) {
        Some(e) => e.0,
        None => {
            let bb = ctx.tm.sub(b, off);
            let sp0 = job.regs[13];
            if !matches!(ctx.private_split(bb), Some((base, _)) if base == sp0) {
                return Err(Stop::Unsupported(format!(
                    "{what}: source passes the address of {name}, binary passes {} which is not an address in its stack frame",
                    ctx.tm.show(b)
                )));
            }
            let top = job.stack_args.iter().map(|a| a.0 + 4).max().unwrap_or(0);
            let pos = frame_pos(ctx, job, bb);
            let lim = ctx.tm.konst(32, (FRAME_SPAN + top) as u64);
            let below = ctx.tm.ule(pos, lim);
            let room = ctx.tm.sub(lim, pos);
            let fits = ctx.tm.ule(size, room);
            let inside = ctx.tm.and(below, fits);
            frame_rule(ctx, inside, || {
                format!("{what}: source passes the address of {name}, binary passes a stack address outside its frame")
            })?;
            // 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);
            let mut others: Vec<(T, T)> = Vec::new();
            for (b2, &(_, d2, s2)) in esc.map.iter().filter(|(b2, _)| live(b2)) {
                let _ = b2;
                let p2 = ctx.tm.konst(32, (FRAME_SPAN as i64 + d2) as u64);
                let n2 = ctx.tm.konst(32, s2 as u64);
                others.push((p2, n2));
            }
            for (_, &(bb2, s2)) in esc.dynamic.iter().filter(|(b2, _)| live(b2)) {
                others.push((frame_pos(ctx, job, bb2), s2));
            }
            for (p2, n2) in others {
                let ok = apart(ctx, pos, size, p2, n2);
                frame_rule(ctx, ok, || {
                    format!("{what}: binary places {name} over another local visible to the callee")
                })?;
            }
            aligned(ctx, bb, obj.align, name, what)?;
            esc.dynamic.insert(obj.base, (bb, size));
            // From here on the source's object and the binary's stack block are the same memory.
            can_bind(ctx, obj.base, bb, name, what)?;
            let same = ctx.tm.eq(obj.base, bb);
            ctx.pc.push(same);
            ctx.bound.insert(obj.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 {name}, binary passes {} instead of {}",
                ctx.tm.show(b),
                ctx.tm.show(expect)
            ),
            None,
        )),
        Err(None) => Err(Stop::Inconclusive(format!("{what}: prover gave up"))),
    }
}

/// An object of dynamic size the callee of event `k` can reach holds the same contents on both
/// sides, wherever either side stored something.  Bytes the source never wrote are
/// indeterminate and are not compared.
fn match_dynamic(
    ctx: &mut Ctx,
    job: &Job,
    cx: &CExec,
    esc: &mut Escapes,
    m: &mut Machine,
    ev: &Event,
    (obj, k): (&crate::sym::Escaped, usize),
) -> R<()> {
    let name = obj.name.trim_start_matches('&');
    let dy = obj.dynamic.as_ref().expect("dynamic object");
    let Some(&(bb, size)) = esc.dynamic.get(&obj.base) else {
        return Err(Stop::Unsupported(format!(
            "call #{} to {}: {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.
    let sp = m.regs[13];
    let (psp, pbb) = (frame_pos(ctx, job, sp), frame_pos(ctx, job, bb));
    let live = ctx.tm.ule(psp, pbb);
    frame_rule(ctx, live, || {
        format!("call #{} to {}: {name} lies below the stack pointer", k + 1, ev.name)
    })?;
    // Where to look: (offset in the object, size, whether the location is known to be inside).
    let mut locs: Vec<(T, u8, bool)> = Vec::new();
    for w in dy.log.iter().filter(|w| w.havoc.is_none()) {
        let off = ctx.tm.sub(w.addr, obj.base);
        let known = w.guard.is_none();
        if !locs.contains(&(off, w.size, known)) {
            locs.push((off, w.size, known));
        }
    }
    let stack: Vec<(T, u8)> = ctx
        .region(bb)
        .and_then(|r| m.mem.private.get(&r))
        .map(|log| {
            log.iter()
                .filter(|w| w.havoc.is_none())
                .map(|w| (w.addr, w.size))
                .collect()
        })
        .unwrap_or_default();
    for (addr, n) in stack {
        let off = ctx.tm.sub(addr, bb);
        if locs.iter().any(|l| l.0 == off && l.1 == n) {
            continue;
        }
        // A store wholly outside the object is none of its contents.
        let nk = ctx.tm.konst(32, n as u64);
        let after = ctx.tm.ule(size, off);
        let back = ctx.tm.sub(bb, addr);
        let before = ctx.tm.ule(nk, back);
        let outside = ctx.tm.and(after, before);
        if ctx.implied(outside) {
            continue;
        }
        // One that may straddle an end of the object is looked at byte by byte.
        for j in 0..n {
            let o = ctx.tm.add_const(off, j as u64);
            if !locs.iter().any(|l| l.0 == o && l.1 == 1) {
                locs.push((o, 1, false));
            }
        }
    }
    for (off, n, known) in locs {
        let ca = ctx.tm.add(obj.base, off);
        let mut c_init = |ctx: &mut Ctx, a: T, s: u8| ctx.tm.load(crate::sym::UNINIT_EPOCH, a, s);
        let cv = ctx.read_world(&dy.log, ca, n, &mut c_init);
        let parts: Vec<(T, u8, T)> = if !ctx.mentions_uninit(cv) {
            vec![(off, n, cv)]
        } else {
            (0..n)
                .filter_map(|j| {
                    let o = ctx.tm.add_const(off, j as u64);
                    let a = ctx.tm.add_const(ca, j as u64);
                    let b = ctx.read_world(&dy.log, a, 1, &mut c_init);
                    (!ctx.mentions_uninit(b)).then_some((o, 1, b))
                })
                .collect()
        };
        for (off, n, cv) in parts {
            let ba = ctx.tm.add(bb, off);
            let mut init = image_init(job.image, m.mem.epoch, None);
            let bv = ctx.mem_read(&m.mem, ba, n, &mut init);
            if cv == bv {
                continue;
            }
            let what = format!("{name} (offset {}) at call #{} to {}", ctx.tm.show(off), k + 1, ev.name);
            if known {
                match_value(ctx, job, cx, esc, ev, (cv, bv), &what)?;
            } else {
                let nk = ctx.tm.konst(32, n as u64);
                let fits = ctx.tm.ule(nk, size);
                let room = ctx.tm.sub(size, nk);
                let low = ctx.tm.ule(off, room);
                let inside = ctx.tm.and(fits, low);
                ctx.pc.push(inside);
                let r = match_value(ctx, job, cx, esc, ev, (cv, bv), &what);
                ctx.pc.pop();
                r?;
            }
        }
    }
    Ok(())
}

/// 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;
    }
    // The solver is asked for the binary's value only once the source's is known to be the
    // address of a literal: `unique_value` is a query, and an expensive one on a product.
    if c != b
        && let Some(ca) = ctx.tm.as_const(c)
        && let Some(lit) = literal_at(job.env, ca as u32)
        && let Some(ba) = ctx.unique_value(b)
        && ca != ba
    {
        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) = ctx.tm.as_const(c)
        && let Some(lit) = literal_at(job.env, ca as u32)
        && let Some(ba) = ctx.unique_value(b)
        && ca != ba
        && 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) = ctx.tm.as_const(off)
            && let Some(ba) = 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);
    };
    if obj.dynamic.is_some() {
        return bind_dynamic(ctx, job, esc, ev, obj, (off, 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];
            // (the path may pin an offset that is not a constant as a term: a frame laid out
            // after an allocation whose size the path determines)
            let rel = ctx.tm.sub(bb, sp0);
            let Some(d) = ctx.unique_value(rel) 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,
                ));
            }
            let live_dyn: Vec<(T, T)> = esc.dynamic.iter().filter(|(b2, _)| live(b2)).map(|(_, v)| *v).collect();
            for (bb2, s2) in live_dyn {
                let p = ctx.tm.konst(32, (FRAME_SPAN as i64 + d) as u64);
                let n = ctx.tm.konst(32, obj.size as u64);
                let p2 = frame_pos(ctx, job, bb2);
                let ok = apart(ctx, p, n, p2, s2);
                frame_rule(ctx, ok, || {
                    format!("{what}: binary places local {name} over another local visible to the callee")
                })?;
            }
            let bb = if ctx.tm.const_diff(bb, sp0).is_some() {
                bb
            } else {
                ctx.tm.add_const(sp0, d as u64)
            };
            aligned(ctx, bb, obj.align, name, what)?;
            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.
            can_bind(ctx, base, bb, name, what)?;
            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"))),
    }
}

/// What the source does at an event, for messages: "calling f", "executing `cpsid i`".
fn doing(ev: &Event) -> String {
    match ev.name.strip_prefix("asm:") {
        Some(insn) if ev.asm.is_some() => format!("executing `{insn}`"),
        _ => format!("calling {}", ev.name),
    }
}

/// Where the binary passes each argument of the source's call.
fn call_locs(ctx: &Ctx, ev: &Event, map: Option<&CallMap>) -> Vec<Option<ArgLoc>> {
    let widths: Vec<u8> = ev.args.iter().map(|a| ctx.tm.width(a.0).max(32)).collect();
    match map {
        Some(map) if map.pos.len() == widths.len() => {
            let n = map.pos.iter().filter(|&&p| p != GONE).max().map_or(0, |m| m + 1);
            let mut theirs = vec![32u8; n];
            for (&p, &w) in map.pos.iter().zip(&widths) {
                if p != GONE {
                    theirs[p] = w;
                }
            }
            let locs = arg_locs(&theirs);
            map.pos.iter().map(|&p| (p != GONE).then(|| locs[p])).collect()
        }
        _ => arg_locs(&widths).into_iter().map(Some).collect(),
    }
}

fn match_call(ctx: &mut Ctx, job: &Job, cx: &CExec, esc: &mut Escapes, m: &mut Machine, ev: &Event, k: usize) -> R<()> {
    let sp = m.regs[13];
    let locs = call_locs(ctx, ev, job.call_map.borrow().as_ref());
    for (i, (&(val, signed), loc)) in ev.args.iter().zip(locs).enumerate() {
        let Some(loc) = loc else {
            // The entry point the binary calls stands for a zero here: a fill byte.
            let byte = ctx.tm.trunc(val, 8);
            let zero = ctx.tm.konst(8, 0);
            prove_eq(
                ctx,
                byte,
                zero,
                &format!("argument {} of call #{} to {}", i + 1, k + 1, ev.name),
            )?;
            continue;
        };
        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)?;
    }
    match_memory(ctx, job, cx, esc, m, ev, k)
}

/// Memory as the callee of event `k` sees it must be the same on both sides.
fn match_memory(
    ctx: &mut Ctx,
    job: &Job,
    cx: &CExec,
    esc: &mut Escapes,
    m: &mut Machine,
    ev: &Event,
    k: usize,
) -> R<()> {
    let sp = m.regs[13];
    // 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 {
        if obj.dynamic.is_some() {
            match_dynamic(ctx, job, cx, esc, m, ev, (obj, k))?;
            continue;
        }
        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, job: &Job, esc: &Escapes, m: &mut Machine, ev: &Event, k: usize) {
    after_escaped(ctx, esc, m, ev);
    let sp = m.regs[13];
    for loc in call_locs(ctx, ev, job.call_map.borrow().as_ref()).into_iter().flatten() {
        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 callee of an event may have written to every local it can reach: both sides continue
/// with the same fresh contents.
fn after_escaped(ctx: &mut Ctx, esc: &Escapes, m: &mut Machine, ev: &Event) {
    for obj in &ev.escaped {
        if let Some(dy) = &obj.dynamic {
            if let (Some(id), Some(&(bb, size))) = (dy.havoc, esc.dynamic.get(&obj.base)) {
                ctx.mem_havoc(&mut m.mem, bb, size, id, obj.base);
            }
            continue;
        }
        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);
        }
    }
}

/// 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.opaque = job.opaque.clone();
    cx.modular = job.modular;
    *job.trace.borrow_mut() = (Vec::new(), 0);
    job.stray.set(None);
    job.targets.borrow_mut().clear();
    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);
    if job.modular {
        *job.targets.borrow_mut() = cx.indirect.clone();
        job.used
            .borrow_mut()
            .extend((cx.events.iter()).filter_map(|ev| job.opaque_names.get(ev.name.as_str()).copied()));
        job.trace.borrow_mut().0 = (cx.events.iter())
            .map(|ev| job.opaque_names.get(ev.name.as_str()).copied())
            .collect();
    }
    // --- binary side ---
    let classify = |addr: u32| -> Callee {
        if let Some(name) = job.image.externals.get(&addr) {
            return Callee::External(name.clone());
        }
        if let Some(&fid) = job.env.addr_to_func.get(&addr)
            && job.opaque[fid as usize]
        {
            return Callee::External(p.funcs[fid as usize].name.to_string());
        }
        match job.image.func_at(addr) {
            Some(s) => {
                let has_body = p
                    .funcs
                    .iter()
                    .any(|f| f.body.is_some() && !f.opaque && *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.
                // The same goes for code that discovery found and nothing names.
                if job.modular && crate::discover::is_anonymous(&s.name) && UNIFIED.with(|u| u.borrow().is_some()) {
                    // Discovery: which function of the source this is, is what is being found out.
                    return Callee::External(format!("?{addr:08x}"));
                }
                if has_body || s.name.starts_with("OUTLINED_FUNCTION_") || crate::discover::is_anonymous(&s.name) {
                    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.modular = job.modular;
    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();
    // Calls that may return twice made so far: (return address, position in the machine's
    // trace of stack accesses, callee, the symbol standing for the value returned).
    let mut rt_sites: Vec<(u32, usize, String, Option<T>)> = Vec::new();
    // The binary's copies of the locals the outside world can reach after an event.
    let exposed_in_binary = |esc: &Escapes, ev: &Event| -> Vec<Exposed> {
        ev.exposed
            .iter()
            .filter_map(|e| {
                if let Some(&(bb, size)) = esc.dynamic.get(&e.base) {
                    return Some(Exposed {
                        base: bb,
                        size: 0,
                        dyn_size: Some(size),
                        since: e.since,
                    });
                }
                esc.map.get(&e.base).map(|&(bb, _, size)| Exposed {
                    base: bb,
                    size,
                    dyn_size: None,
                    since: e.since,
                })
            })
            .collect()
    };
    loop {
        job.trace.borrow_mut().1 = k;
        m.nev = k as u32;
        match m.run(ctx, job.image, job.lr0, &classify)? {
            Exit::Asm { name, arg, out } => {
                check_result_slot(ctx, job, &m)?;
                let full = format!("asm:{name}");
                let Some(ev) = cx.events.get(k).filter(|ev| ev.asm.is_some() && ev.name == full) else {
                    return Err(Stop::Mismatch(
                        match cx.events.get(k) {
                            Some(ev) => format!("binary executes `{name}` where the source is {}", doing(ev)),
                            None => format!("binary executes `{name}`, which the source does not do at this point"),
                        },
                        None,
                    ));
                };
                check_volatile(ctx, &cx, &m, k)?;
                match (arg, ev.args.first()) {
                    (Some(got), Some(&(want, _))) => {
                        let want = ctx.tm.resize(want, 32, false);
                        prove_eq(ctx, want, got, &format!("value written by `{name}` (event #{})", k + 1))?;
                    }
                    (None, None) => {}
                    _ => {
                        return Err(Stop::Mismatch(
                            format!("binary executes `{name}` with different operands than the source"),
                            None,
                        ));
                    }
                }
                if ev.asm == Some(true) {
                    // The statement clobbers memory: what was stored before it must be in
                    // place, and nothing read before it is known afterwards.
                    match_memory(ctx, job, &cx, &mut esc, &mut m, ev, k)?;
                    m.mem.world.clear();
                    m.mem.epoch = ev.epoch + 1;
                    m.mem.exposed = exposed_in_binary(&esc, ev);
                    after_escaped(ctx, &esc, &mut m, ev);
                }
                if let Some(rd) = out {
                    let Some((sym, _)) = ev.ret else {
                        return Err(Stop::Mismatch(
                            format!("binary executes `{name}` with different operands than the source"),
                            None,
                        ));
                    };
                    m.regs[rd as usize] = ctx.tm.resize(sym, 32, false);
                }
                k += 1;
            }
            Exit::Call { name } => {
                let name = if name.starts_with('?') {
                    unify_call(job, &name, cx.events.get(k))?
                } else {
                    name
                };
                let called = m.call_addr.take();
                // A fortified library call (`__memcpy_chk(d, s, n, size of d)`) is the plain
                // call the source makes: it differs only where the plain one would overflow
                // the destination, which is undefined.  The size is the compiler's knowledge.
                let differs = cx.events.get(k).filter(|ev| ev.name != name);
                let map = differs.and_then(|ev| CallMap::of(&name, &ev.name, ev.args.len()));
                let plain = (name.strip_prefix("__").and_then(|n| n.strip_suffix("_chk"))).map(str::to_string);
                let plain = plain.as_deref();
                let name = match (differs, &map, plain) {
                    (Some(ev), Some(_), _) => ev.name.clone(),
                    (_, _, Some(plain))
                        if cx.events.get(k).is_none_or(|ev| ev.name != name) && FORTIFIED.contains(&plain) =>
                    {
                        plain.to_string()
                    }
                    _ => name,
                };
                // After a call that may return twice, the stack below the stack pointer of a
                // later call is no longer the function's to read back.
                if let Some(t) = &mut m.trace {
                    let off = ctx.tm.const_diff(m.regs[13], job.regs[13]);
                    t.push(crate::thumb::exec::StackAcc {
                        write: true,
                        off: off.map(|d| d as u32 as i32 as i64),
                        size: 0,
                        ev: k as u32,
                    });
                }
                // The size the binary passes decides when the fortified function refuses to
                // run: it must not refuse a call the source defines.
                let fortified = match plain {
                    Some(plain) if name == plain => fortified_size(ctx, job, &m, plain)?,
                    _ => None,
                };
                let void = map.as_ref().is_some_and(|m| m.void);
                *job.call_map.borrow_mut() = map;
                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))
                {
                    if let Some((dest, size)) = fortified {
                        fortified_local(ctx, job, &esc, dest, size, &name)?;
                    }
                    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 {
                    job.stray.set(job.opaque_names.get(name.as_str()).copied());
                    return Err(Stop::Mismatch(
                        format!("binary calls {name}, which the source does not call at this point"),
                        None,
                    ));
                };
                // The source calls through a pointer where the binary, having narrowed the
                // pointer down, calls a function directly: the same call if the pointer is
                // that function on this path.
                let direct = (ev.name == INDIRECT && name != INDIRECT && m.indirect.is_none())
                    .then(|| job.opaque_names.get(name.as_str()))
                    .flatten()
                    .and_then(|&fid| job.env.func_addr[fid as usize]);
                if let Some(addr) = direct {
                    let want = cx
                        .indirect
                        .iter()
                        .find(|t| t.0 == k)
                        .expect("indirect event has a target")
                        .1;
                    let got = ctx.tm.konst(32, (addr | 1) as u64);
                    prove_eq(ctx, want, got, &format!("target of call #{} through a pointer", k + 1))?;
                } else if ev.name != name || ev.asm.is_some() {
                    if !job.opaque_names.contains_key(ev.name.as_str()) {
                        job.stray.set(job.opaque_names.get(name.as_str()).copied());
                    }
                    if name.starts_with("__") && name.ends_with("_chk") {
                        return Err(Stop::Unsupported(format!(
                            "fortified library call {name} where the source calls {}",
                            ev.name
                        )));
                    }
                    return Err(Stop::Mismatch(
                        format!("binary calls {name} where the source is {}", doing(ev)),
                        None,
                    ));
                }
                check_volatile(ctx, &cx, &m, k)?;
                if ctx.tm.const_diff(m.regs[13], job.regs[13]).is_none() {
                    // A stack pointer moved by a computed amount: the callee's frame starts
                    // there, so it must be below everything the caller of this function owns.
                    let down = ctx.tm.sub(job.regs[13], m.regs[13]);
                    let span = ctx.tm.konst(32, FRAME_SPAN as u64);
                    let ok = ctx.tm.ule(down, span);
                    frame_rule(ctx, ok, || {
                        format!(
                            "stack pointer at call #{} to {name}: it may lie outside the function's own frame",
                            k + 1
                        )
                    })?;
                }
                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)?;
                if let Some((dest, size)) = fortified {
                    fortified_local(ctx, job, &esc, dest, size, &name)?;
                }
                m.mem.world.clear();
                m.mem.epoch = ev.epoch + 1;
                m.mem.exposed = exposed_in_binary(&esc, ev);
                k += 1;
                if ev.noreturn {
                    break;
                }
                let (lo, hi) = match ev.ret {
                    None => (None, None),
                    // The entry point the binary called returns nothing in r0.
                    Some(_) if void => (None, None),
                    // An internal function whose result no caller uses: the binary's need
                    // not compute it (see `c::callers`).
                    Some(_) if (job.opaque_names.get(name.as_str())).is_some_and(|&f| job.unused_result(f)) => {
                        (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, job, &esc, &mut m, ev, k - 1);
                // A routine written in assembly in this program: its callers may rely on the
                // registers its code does not touch.
                // (The code analysed is the code this call reaches: two routines may share a name.)
                let keeps = match (
                    p.funcs.iter().find(|f| f.opaque && *f.name == *base_name(&name)),
                    called,
                ) {
                    (Some(_), Some(addr)) if !job.image.meta.weak_funcs.contains(&name) => *job
                        .asm_keeps
                        .borrow_mut()
                        .entry(addr)
                        .or_insert_with(|| asm_keeps(job.image, addr)),
                    _ => 0,
                };
                let before = m.regs;
                m.finish_call(ctx, k - 1, lo, hi);
                for i in [0usize, 1, 2, 3, 12] {
                    let result = (i == 0 && lo.is_some()) || (i == 1 && hi.is_some());
                    if keeps >> i & 1 == 1 && !result {
                        m.regs[i] = before[i];
                    }
                }
                if ev.returns_twice {
                    if ctl.init.is_some() || !ctl.c_cuts.is_empty() || !ctl.m_cuts.is_empty() {
                        return Err(cut_error("the loop calls a function that may return twice"));
                    }
                    let at = m.trace.get_or_insert_with(Vec::new).len();
                    rt_sites.push((m.resume_pc(), at, ev.name.clone(), ev.ret.map(|r| r.0)));
                }
            }
            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,
                });
            }
            ref e @ (Exit::Trap | Exit::Hang) => {
                let (does, name) = match e {
                    Exit::Trap => ("traps (udf)", "<trap>"),
                    _ => ("loops for ever", "<hang>"),
                };
                check_result_slot(ctx, job, &m)?;
                if c_cut.is_some() {
                    return Err(cut_error(&format!(
                        "the binary {does} where the source reaches a loop head"
                    )));
                }
                let Some(ev) = cx.events.get(k) else {
                    return Err(Stop::Mismatch(format!("binary {does} where the source does not"), None));
                };
                if ev.name != name {
                    return Err(Stop::Mismatch(
                        format!("binary {does} where the source is {}", doing(ev)),
                        None,
                    ));
                }
                check_volatile(ctx, &cx, &m, k)?;
                // In a loop that never ends and does nothing, no part of the C program reads
                // memory again: stores made on the way in (other than volatile ones, compared
                // above) cannot be observed, and compilers drop them.
                if matches!(e, Exit::Trap) {
                    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 {}", doing(ev)), 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.filter(|_| !job.result_unused) {
                    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) = ctx.tm.as_const(off)
                            && let Some(ba) = 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]) {
                            {
                                // Two inputs that take this path and give the binary different
                                // results: the prover tries the inputs it has seen before
                                // anything else, and a wrong result often shows on one of them.
                                // A probe on a small budget; its answer is not used.
                                let full = std::mem::replace(&mut ctx.prover.budget, 2_000);
                                let _ = ctx.unique_value(m.regs[0]);
                                ctx.prover.budget = full;
                            }
                            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"),
                    )?;
                }
                record_rt(ctx, job, &m, &esc, &rt_sites, k);
                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,
        ));
    }
    record_rt(ctx, job, &m, &esc, &rt_sites, k);
    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>,
}

/// Verify one function.  Calls to functions that are verified on their own are first
/// compared as events; where that fails because the compiler did not treat a callee as a
/// black box (it inlined it, or relied on what it does), that callee is followed on both
/// sides instead, and as a last resort every callee is, as far as the budget goes.
fn verify_function(prog: &Program, image: &Image, env: &CEnv, fid: u32, opts: &Options) -> FuncOutcome {
    verify_following(prog, image, env, fid, opts, &[])
}

/// The same with the callees in `follow` never compared as calls.
fn verify_following(
    prog: &Program,
    image: &Image,
    env: &CEnv,
    fid: u32,
    opts: &Options,
    follow: &[u32],
) -> FuncOutcome {
    // Callees followed on both sides when comparing their calls does not do: all but those
    // the linker may replace, and those the model cannot execute (inline assembly, an
    // unmodelled construct) where the binary has them under their own symbol: their calls
    // stay events whatever the mode, and they are reported on their own as unverified.
    let pinned = |f: usize| {
        env.replaceable.get(f).copied().unwrap_or(false)
            || (f as u32 != fid && prog.funcs[f].unsupported.is_some() && env.callable.get(f).copied().unwrap_or(false))
    };
    let none = std::sync::Arc::new((0..prog.funcs.len()).map(pinned).collect::<Vec<bool>>());
    if std::env::var_os("CVERIF_DEBUG").is_some() {
        eprintln!("verifying {}", prog.funcs[fid as usize].name);
    }
    if !opts.modular || env.callable.is_empty() {
        // Every callee is followed, but a call to one of the program's own `memcpy`,
        // `memmove` or `memset` is first taken for the library call the compiler may have
        // made of it (see `CEnv::is_library`).
        let lib: Vec<bool> = (env.library.iter().enumerate())
            .map(|(i, &l)| l && !follow.contains(&(i as u32)))
            .collect();
        if lib.iter().any(|&l| l) {
            let (o, culprit) = verify_attempt(prog, image, env, fid, opts, (std::sync::Arc::new(lib), true));
            if culprit.is_none() {
                return o;
            }
        }
        return verify_attempt(prog, image, env, fid, opts, (none, false)).0;
    }
    let start = Instant::now();
    let mut opaque = env.callable.clone();
    for &f in follow {
        opaque[f as usize] = false;
    }
    let mut spent = (0u64, 0u64, 0u64);
    let finish = |mut o: FuncOutcome, spent: (u64, u64, u64)| {
        o.report.millis = start.elapsed().as_millis();
        o.report.sat_calls += spent.0;
        o.report.conflicts += spent.1;
        o.report.work += spent.2;
        o
    };
    for _ in 0..MODULAR_RETRIES {
        let (o, culprit) = verify_attempt(prog, image, env, fid, opts, (std::sync::Arc::new(opaque.clone()), true));
        let Some(c) = culprit else { return finish(o, spent) };
        if std::env::var_os("CVERIF_DEBUG").is_some() {
            eprintln!("  following {}", prog.funcs[c as usize].name);
        }
        spent = (
            spent.0 + o.report.sat_calls,
            spent.1 + o.report.conflicts,
            spent.2 + o.report.work,
        );
        if pinned(c as usize) {
            // The callee to follow is one that cannot be followed: the attempt stands, and
            // is run to its end (an attempt that names a callee stops early).
            let o = verify_attempt(prog, image, env, fid, opts, (std::sync::Arc::new(opaque), false)).0;
            return finish(o, spent);
        }
        opaque[c as usize] = false;
    }
    let o = verify_attempt(prog, image, env, fid, opts, (none, false)).0;
    finish(o, spent)
}

/// A fortified library call (`__memcpy_chk(d, s, n, size)`) in the binary where the source
/// makes the plain call: the function stops the program when the operation needs more than
/// `size` bytes, so `size` must be at least what is left of the destination object, or the
/// binary would stop where the source goes on.  Settled here when the size is "unknown", when
/// the length is provably within it, or when the destination is a static object; otherwise
/// the destination and the size are returned, for a local object (`fortified_local`).
fn fortified_size(ctx: &mut Ctx, job: &Job, m: &Machine, plain: &str) -> R<Option<(T, u64)>> {
    // (register holding the length, register holding the size of the destination)
    let (len, size) = match plain {
        "memcpy" | "memmove" | "mempcpy" | "memset" | "strncpy" | "stpncpy" => (Some(2), 3),
        "strncat" => (None, 3),
        "snprintf" | "vsnprintf" => (Some(1), 3),
        _ => (None, 2),
    };
    let os = m.regs[size];
    let Some(os) = ctx.tm.as_const(os) else {
        return Err(Stop::Unsupported(format!(
            "fortified library call __{plain}_chk: the size of the destination is not a constant"
        )));
    };
    if os == 0xffff_ffff {
        return Ok(None);
    }
    if let Some(len) = len {
        let k = ctx.tm.konst(32, os);
        let fits = ctx.tm.ule(m.regs[len], k);
        if ctx.implied(fits) {
            return Ok(None);
        }
    }
    let dest = m.regs[0];
    if let Some(a) = ctx.tm.as_const(dest) {
        let whole = (job.image.symbols.iter())
            .filter(|s| s.kind == SymKind::Object && s.size > 0)
            .find(|s| (s.addr as u64..s.addr as u64 + s.size as u64).contains(&a));
        return match whole {
            Some(s) if os >= s.addr as u64 + s.size as u64 - a => Ok(None),
            _ => Err(Stop::Unsupported(format!(
                "fortified library call __{plain}_chk: it stops the program beyond {os} bytes, which may be less than the destination holds"
            ))),
        };
    }
    Ok(Some((dest, os)))
}

/// The rest of `fortified_size`, for a destination in the function's frame: once the
/// arguments are matched, the local objects the callee can reach have a known place.
fn fortified_local(ctx: &mut Ctx, job: &Job, esc: &Escapes, dest: T, os: u64, name: &str) -> R<()> {
    if let Some(off) = ctx.tm.const_diff(dest, job.regs[13]) {
        let off = off as u32 as i32 as i64;
        if (esc.map.values())
            .any(|&(_, d, size)| d <= off && off < d + size as i64 && os as i64 >= d + size as i64 - off)
        {
            return Ok(());
        }
    }
    Err(Stop::Unsupported(format!(
        "fortified form of library call {name}: it stops the program beyond {os} bytes, which may be less than the destination holds"
    )))
}

fn vacuity_audit() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var_os("CVERIF_CHECK_VACUOUS").is_some())
}

/// Library functions with a fortified variant taking the size of the destination last.
const FORTIFIED: [&str; 10] = [
    "memcpy", "memmove", "mempcpy", "memset", "strcpy", "stpcpy", "strcat", "strncpy", "stpncpy", "strncat",
];

/// `printf` functions with a fortified variant, and where it takes a flag and the size of
/// the destination.
const FORTIFIED_PRINTF: [(&str, usize); 4] = [("sprintf", 1), ("vsprintf", 1), ("snprintf", 2), ("vsnprintf", 2)];

/// Callees followed one after the other before every callee is followed.
const MODULAR_RETRIES: usize = 6;

fn unused_result(env: &CEnv, image: &Image, f: u32) -> bool {
    env.callers.result_unused.get(f as usize).copied().unwrap_or(false)
        && env.func_addr[f as usize]
            .and_then(|a| image.func_at(a))
            .is_some_and(|s| !s.global)
}

/// One attempt with the given set of opaque callees.  Also returns the callee to follow
/// instead when the attempt failed in a way that treating it as an event could explain.
fn verify_attempt(
    prog: &Program,
    image: &Image,
    env: &CEnv,
    fid: u32,
    opts: &Options,
    (opaque, modular): (std::sync::Arc<Vec<bool>>, bool),
) -> (FuncOutcome, Option<u32>) {
    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,
            modulo: Vec::new(),
            unconditional: false,
            cached: false,
            assumes: Vec::new(),
            given: None,
            hazards: Vec::new(),
        },
        cov: BTreeSet::new(),
        bytes: BTreeSet::new(),
    };
    let mut ctx = Ctx::new(opts.limits);
    // (Each attempt assumes afresh which unnamed functions are which.)
    UNIFIED.with(|u| {
        if let Some(map) = u.borrow_mut().as_mut() {
            map.clear();
        }
    });
    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, None);
    }
    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, None);
    }
    // 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));
    // The stack is not at the very bottom or top of the address space: no address in the
    // function's frame or in its incoming arguments is null or wraps around.
    let floor = ctx.tm.konst(32, 2 * FRAME_SPAN as u64);
    let ceil = ctx.tm.konst(32, (FRAME_SPAN as u64).wrapping_neg() & 0xffff_ffff);
    pre.push(ctx.tm.ule(floor, regs[13]));
    pre.push(ctx.tm.ule(regs[13], ceil));
    // 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);
    }
    // A function that can only be entered from the calls in its translation unit is
    // verified for the argument values those calls pass: the compiler specialises it for
    // them (see `c::callers` for why that is the whole truth).
    if !sym.global
        && let Some(given) = env.callers.given.get(fid as usize)
    {
        let mut said = Vec::new();
        for (i, set) in given.iter().enumerate() {
            let (Some(set), Some(&v)) = (set, args.get(i)) else {
                continue;
            };
            let w = ctx.tm.width(v);
            let mut any = ctx.tm.fals();
            for &c in set {
                let k = ctx.tm.konst(w, c);
                let eq = ctx.tm.eq(v, k);
                any = ctx.tm.or(any, eq);
            }
            pre.push(any);
            let vals: Vec<String> = set.iter().map(|c| c.to_string()).collect();
            let name = f
                .locals
                .get(i)
                .map_or_else(|| format!("argument {}", i + 1), |l| l.name.to_string());
            said.push(match (set.first(), set.last()) {
                (Some(&a), Some(&b)) if set.len() > 2 && b - a + 1 == set.len() as u64 => format!("{name} in {a}..{b}"),
                _ if set.len() == 1 => format!("{name} = {}", vals[0]),
                _ => format!("{name} in {{{}}}", vals.join(", ")),
            });
        }
        if !said.is_empty() {
            out.report.given = Some(format!("for {}: all callers", said.join(", ")));
        }
    }
    let result_unused = unused_result(env, image, fid);
    if result_unused {
        let said = "result not compared: no caller uses it".to_string();
        out.report.given = Some(match out.report.given.take() {
            Some(g) => format!("{g}; {said}"),
            None => said,
        });
    }
    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,
        opaque_names: (opaque.iter().enumerate())
            .filter(|o| *o.1)
            .map(|(i, _)| (prog.funcs[i].name.to_string(), i as u32))
            .collect(),
        opaque,
        modular,
        trace: Default::default(),
        stray: Default::default(),
        targets: Default::default(),
        used: Default::default(),
        call_map: Default::default(),
        result_unused,
        rt: Default::default(),
        asm_keeps: Default::default(),
    };
    let mut retry: Option<u32> = None;
    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();
        job.rt.borrow_mut().clear();
        out.report.paths = 0;
        out.report.undefined_paths = 0;
        loop {
            ctx.restart(&pre);
            crate::explain::report::begin_path(pre.len());
            explored += 1;
            let res = match run_path(&mut ctx, &job) {
                // A difference in the shape of the two executions (one side calls or returns
                // where the other does not) comes without a witness.  Branches are followed
                // without asking whether the path as a whole is still feasible, so make sure
                // some input takes this path before reporting it.
                Err(Stop::Mismatch(why, None)) => {
                    let never = ctx.tm.fals();
                    match ctx.check(never) {
                        Ok(()) => Err(Stop::Undefined),
                        Err(Some(env)) => Err(Stop::Mismatch(why, Some(env))),
                        Err(None) => Err(Stop::Inconclusive(format!(
                            "{why}: prover gave up on whether the path is feasible"
                        ))),
                    }
                }
                r => r,
            };
            crate::explain::report::end_path(&ctx, Some(prog), fid, &res);
            // Audit aid (`CVERIF_CHECK_VACUOUS=1`): a path counted as proved although no input
            // takes it under the assumptions made is reported; it proves nothing.
            if res.is_ok() && vacuity_audit() {
                let never = ctx.tm.fals();
                if ctx.check(never).is_ok() {
                    let pc = ctx.pc.clone();
                    let plain = matches!(ctx.prover.prove(&mut ctx.tm, &pc, never), crate::bv::Verdict::Proved);
                    eprintln!(
                        "vacuous: {}: a proved path that no input takes ({})",
                        f.name,
                        if plain {
                            "its branch conditions contradict each other"
                        } else {
                            "only because of what the source is assumed not to do"
                        }
                    );
                }
            }
            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(e @ (Stop::Mismatch(..) | Stop::Unsupported(_))) if job.culprit(&mut ctx).is_some() => {
                    if std::env::var_os("CVERIF_DEBUG").is_some() {
                        match &e {
                            Stop::Mismatch(w, _) => eprintln!("  attempt failed: mismatch: {w}"),
                            Stop::Unsupported(w) => eprintln!("  attempt failed: unsupported: {w}"),
                            _ => {}
                        }
                    }
                    retry = job.culprit(&mut ctx);
                    break 'rounds;
                }
                Err(Stop::Inconclusive(_)) if ctx.check_deadline().is_ok() && job.culprit(&mut ctx).is_some() => {
                    retry = job.culprit(&mut ctx);
                    break 'rounds;
                }
                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) = rt_conflict(&job.rt.borrow()) {
            // The proofs of the paths hold for the first return only: none of them counts.
            out.report.status = Status::Inconclusive(why);
            out.cov.clear();
            out.bytes.clear();
        } else 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;
    if ctx.model_used {
        out.report.assumes.push("strict-aliasing".into());
    }
    out.report.hazards = ctx.hazards.iter().copied().collect();
    if std::env::var_os("CVERIF_DEBUG").is_some() {
        eprintln!(
            "attempt: {:?} after {} ms: {} terms, {} thousand propagations, {} solver calls, {} paths explored, retry {:?}",
            out.report.status,
            out.report.millis,
            ctx.tm.len(),
            props / 1000,
            sat_calls,
            explored,
            retry.map(|f| &*prog.funcs[f as usize].name)
        );
    }
    out.report.modulo = (job.used.borrow().iter())
        .map(|&f| (prog.funcs[f as usize].name.to_string(), String::new()))
        .collect();
    (out, retry)
}

/// 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()
}

/// Where source functions and objects are in the image, decided outside the symbol table
/// (by discovery): (index in `Program::funcs` / `Program::globals`, address).
#[derive(Clone, Debug, Default)]
pub struct Preset {
    pub funcs: Vec<(u32, u32)>,
    pub globals: Vec<(u32, u32)>,
}

/// One equivalence proof of source function `fid` against the code `env` places it at, for
/// discovery to try candidates with: the status and the number of paths proved.
///
/// With `env.callable` set, calls to those functions are compared as calls; the last value
/// names the callees the result rests on.
pub(crate) fn trial(
    prog: &Program,
    image: &Image,
    env: &CEnv,
    fid: u32,
    opts: &Options,
) -> (Status, usize, Vec<String>) {
    let o = verify_function(prog, image, env, fid, opts);
    let modulo = o.report.modulo.into_iter().map(|m| m.0).collect();
    (o.report.status, o.report.paths, modulo)
}

thread_local! {
    /// Set during [`trial_unifying`]: the functions of the source that the proof under way
    /// took the unnamed functions of the binary for, by name.
    static UNIFIED: std::cell::RefCell<Option<BTreeMap<String, u32>>> = const { std::cell::RefCell::new(None) };
}

/// [`trial`] for an image in which most functions have no name yet.  A call of the binary to
/// an unnamed function is taken for the call the source makes at that point, if that is a
/// call to a function that has no address yet, and compared as such (same arguments, same
/// memory); the pairs this assumes come back with the result.  The proof then says: the code
/// is the source function *if* those functions are what the proof took them for.
pub(crate) fn trial_unifying(
    prog: &Program,
    image: &Image,
    env: &CEnv,
    fid: u32,
    opts: &Options,
) -> (Status, usize, Vec<String>, Vec<(String, u32)>) {
    UNIFIED.with(|u| *u.borrow_mut() = Some(BTreeMap::new()));
    let o = verify_function(prog, image, env, fid, opts);
    let bound = UNIFIED.with(|u| u.borrow_mut().take()).unwrap_or_default();
    let modulo = o.report.modulo.into_iter().map(|m| m.0).collect();
    (o.report.status, o.report.paths, modulo, bound.into_iter().collect())
}

/// The name a call of the binary to the unnamed function `wild` (`?address`) goes by: that of
/// the function the source calls at this point, where the two can be the same function.
fn unify_call(job: &Job, wild: &str, ev: Option<&Event>) -> R<String> {
    let addr = u32::from_str_radix(&wild[1..], 16).unwrap_or(0);
    let fail = || {
        Err(Stop::Mismatch(
            format!(
                "binary calls the unnamed function at {addr:#x} where the source does not call a function that has no address yet"
            ),
            None,
        ))
    };
    let Some(ev) = ev.filter(|ev| ev.asm.is_none() && ev.name != INDIRECT) else {
        return fail();
    };
    let mut named = job
        .prog
        .funcs
        .iter()
        .enumerate()
        .filter(|(_, f)| *f.name == *ev.name)
        .peekable();
    if named.peek().is_none() || named.any(|(i, _)| job.env.func_addr[i].is_some()) {
        return fail();
    }
    let ok = UNIFIED.with(|u| {
        let mut u = u.borrow_mut();
        let Some(map) = u.as_mut() else { return false };
        match map.get(&ev.name) {
            Some(a) => *a == addr,
            None if map.values().any(|a| *a == addr) => false,
            None => {
                map.insert(ev.name.clone(), addr);
                true
            }
        }
    });
    if ok { Ok(ev.name.clone()) } else { fail() }
}

pub fn verify(prog: &Program, image: &Image, opts: &Options) -> Report {
    verify_with(prog, image, opts, &Preset::default())
}

/// [`verify`] with some functions and objects placed by `preset` instead of by their symbols.
pub fn verify_with(prog: &Program, image: &Image, opts: &Options, preset: &Preset) -> Report {
    let mut env = CEnv::new(prog, image);
    for &(g, a) in &preset.globals {
        env.set_global(image, g, a);
    }
    for &(f, a) in &preset.funcs {
        if image.func_at(a).is_some() {
            env.set_func(f, Some(a));
        }
    }
    crate::timing::mark("source environment");
    resolve_ambiguous(prog, image, &mut env, opts);
    crate::timing::mark("resolve ambiguous");
    let events = callable(prog, image, &env);
    env.library = (events.iter().enumerate())
        .map(|(i, &c)| c && env.is_library(&prog.funcs[i]))
        .collect();
    if !image.meta.weak_funcs.is_empty() {
        env.replaceable = (prog.funcs.iter().zip(&events))
            .map(|(f, &c)| c && image.meta.weak_funcs.iter().any(|w| **w == *f.name))
            .collect();
    }
    // A function the source defines and this image only refers to (an object of the program
    // that is not part of it): the code the call reaches is not here, and the call is
    // compared as a call, like one to a function that is only declared.
    let elsewhere: Vec<bool> = (prog.funcs.iter().enumerate())
        .map(|(i, f)| {
            f.body.is_some()
                && !f.is_static
                && env.func_addr[i].is_none()
                && image.meta.undefined.iter().any(|u| **u == *f.name)
        })
        .collect();
    if elsewhere.contains(&true) {
        env.replaceable.resize(prog.funcs.len(), false);
        for (r, e) in env.replaceable.iter_mut().zip(&elsewhere) {
            *r |= *e;
        }
    }
    if opts.modular {
        env.borrowed = crate::c::borrow::borrowed_params_except(prog, &env.replaceable);
    }
    crate::timing::mark("callable");
    if opts.modular {
        env.callable = events.iter().zip(&elsewhere).map(|(&c, &e)| c || e).collect();
    }
    env.aliasing = opts.aliasing;
    env.callers = crate::c::callers::callers(prog);
    let env = env;
    let mut report = Report {
        aliasing: match opts.aliasing {
            crate::c::exec::Aliasing::Compiler => "compiler",
            crate::c::exec::Aliasing::Standard => "standard",
            crate::c::exec::Aliasing::Off => "off",
        },
        ..Default::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();
    // Results kept from earlier runs, where everything they can depend on is unchanged.
    // (Not when path summaries are asked for: those are not stored.)
    let cache = match &opts.cache {
        Some(dir) if opts.dump == 0 => match crate::cache::Cache::open(dir, prog, image, &env, opts) {
            Ok(c) => Some(c),
            Err(e) => {
                eprintln!("cverif: warning: cache {}: {e}; not used", dir.display());
                None
            }
        },
        _ => None,
    };
    crate::timing::mark("cache keys");
    let one = |fid: u32| {
        let key = cache.as_ref().and_then(|c| c.key(fid));
        if let (Some(c), Some(k)) = (&cache, &key)
            && let Some(e) = c.get(k)
            && *e.report.name == *prog.funcs[fid as usize].name
        {
            let mut report = e.report;
            // (The limit that was hit is kept; the terms left undecided are not.)
            if let Status::Bounded(why) = &report.status {
                let limit = why.split(';').next().unwrap_or(why);
                report.detail = Some(Box::new(crate::explain::FuncDetail {
                    explanation: Some(crate::explain::report::limit_only(limit)),
                    paths: Vec::new(),
                    skipped_paths: 0,
                }));
            }
            return FuncOutcome {
                report,
                cov: e.cov,
                bytes: e.bytes,
            };
        }
        let o = verify_function(prog, image, &env, fid, opts);
        // A difference or an undecided proof comes with an explanation that is not stored:
        // those are established afresh every time.
        if let (Some(c), Some(k)) = (&cache, &key)
            && matches!(
                o.report.status,
                Status::Proved | Status::Bounded(_) | Status::Unsupported(_)
            )
        {
            c.put(
                k,
                &crate::cache::Entry {
                    report: o.report.clone(),
                    cov: o.cov.clone(),
                    bytes: o.bytes.clone(),
                },
            );
        }
        o
    };
    let mut outs = run_jobs(&todo, opts.jobs, one);
    private_conventions(prog, image, &env, opts, &todo, &mut outs);
    for o in outs {
        cov.extend(o.cov);
        bytes.extend(o.bytes);
        report.funcs.push(o.report);
    }
    crate::timing::mark("verify functions");
    // What each result rests on: the verdicts of the callees compared as calls.
    let verdict: HashMap<String, String> = (report.funcs.iter())
        .map(|f| (f.name.clone(), f.status.label().to_string()))
        .collect();
    for f in &mut report.funcs {
        for m in &mut f.modulo {
            m.1 = verdict.get(&m.0).cloned().unwrap_or_else(|| "NOT VERIFIED".to_string());
        }
    }
    // Proved outright: the greatest set of proved functions closed under "calls" (a
    // recursive function rests on itself, which is the usual induction).
    let mut solid: HashSet<String> = (report.funcs.iter())
        .filter(|f| matches!(f.status, Status::Proved))
        .map(|f| f.name.clone())
        .collect();
    loop {
        let drop: Vec<String> = (report.funcs.iter())
            .filter(|f| solid.contains(&f.name) && f.modulo.iter().any(|m| !solid.contains(&m.0)))
            .map(|f| f.name.clone())
            .collect();
        if drop.is_empty() {
            break;
        }
        for d in drop {
            solid.remove(&d);
        }
    }
    for f in &mut report.funcs {
        f.unconditional = solid.contains(&f.name);
    }
    check_data(prog, image, &env, &mut report);
    crate::timing::mark("check data");

    // 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.
    // Where the boundaries between code and data are not authoritative, the other loaded bytes
    // count as well unless something accounts for them: a proved path reads them, they equal
    // the source's initial value of an object or a string literal, or they were set aside.
    let mut total = 0usize;
    let mut proved = 0usize;
    if image.soft_bounds {
        for (i, g) in prog.globals.iter().enumerate() {
            if let (true, Some(addr), Some(expect)) = (g.defined, env.global_addr[i], env.init_bytes(i as u32))
                && image.read(addr, expect.len() as u32) == Some(&expect[..])
            {
                bytes.extend(addr..addr + expect.len() as u32);
            }
        }
        for (addr, expect) in &env.rom {
            if image.read(*addr, expect.len() as u32) == Some(&expect[..]) {
                bytes.extend(*addr..*addr + expect.len() as u32);
            }
        }
    }
    let aside = |a: u32| image.set_aside.iter().find(|r| a >= r.0 && a < r.1);
    for seg in image.segments.iter().filter(|s| s.exec || image.soft_bounds) {
        if !seg.exec && seg.writable && seg.load_addr.is_none() {
            continue; // zero-initialised memory: not in the files
        }
        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 fill = if seg.exec {
                matches!(hw, 0 | 0xbf00 | 0x46c0)
            } else {
                matches!(hw, 0 | 0xffff) || (n == 1 && matches!(hw, 0 | 0xff))
            };
            let padding = covered == 0 && !in_func(a) && fill;
            let set_aside = !padding && (0..n as u32).all(|i| !bytes.contains(&(a + i)) && aside(a + i).is_some());
            if !padding && !set_aside {
                total += n;
                proved += covered;
                if !seg.exec {
                    report.unexplained += n - covered;
                }
            }
            for i in 0..n as u32 {
                let state = if padding {
                    ByteState::Padding
                } else if set_aside {
                    ByteState::SetAside
                } 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 r in &report.bin_ranges {
        if r.state == ByteState::SetAside {
            let why = aside(r.start).map(|x| x.2.clone()).unwrap_or_default();
            report.set_aside.push((r.start, r.end, why));
        }
    }
    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
}

/// Functions with internal linkage that differ from their source when compared on their own.
///
/// How a function is called that only the calls of its translation unit can enter is the
/// compiler's business: clang drops an argument the function does not use, or the result
/// when every caller ignores it, and keeps the symbol's name.  Compared under the source's
/// signature such a function differs, yet nothing is wrong.  What is meaningful is the
/// function together with its callers, so each caller is verified again with the function
/// followed on both sides:
///
/// * every caller is proved: the function does what its source says wherever it is
///   called, and is reported proved as called;
/// * a caller differs: the difference stands;
/// * otherwise the function is inconclusive, since a difference in the convention and a
///   wrong function cannot be told apart.
fn private_conventions(
    prog: &Program,
    image: &Image,
    env: &CEnv,
    opts: &Options,
    todo: &[u32],
    outs: &mut [FuncOutcome],
) {
    let info = &env.callers;
    let verified = |f: u32| prog.funcs[f as usize].body.is_some() && env.func_addr[f as usize].is_some();
    for i in 0..todo.len() {
        let fid = todo[i];
        let Status::Mismatch(why) = &outs[i].report.status else {
            continue;
        };
        let why = why.clone();
        let local = env.func_addr[fid as usize]
            .and_then(|a| image.func_at(a))
            .is_some_and(|s| !s.global);
        if !local || !info.private.get(fid as usize).copied().unwrap_or(false) {
            continue;
        }
        // The callers that exist in the binary; a caller that does not (it was inlined) is
        // part of its own callers.
        let (mut callers, mut seen, mut stack) = (Vec::new(), HashSet::new(), info.callers[fid as usize].clone());
        while let Some(c) = stack.pop() {
            if c == fid || !seen.insert(c) {
                continue;
            }
            if verified(c) {
                callers.push(c);
            } else {
                stack.extend(info.callers[c as usize].iter().copied());
            }
        }
        if callers.is_empty() {
            continue;
        }
        callers.sort_unstable();
        let again = run_jobs(&callers, opts.jobs, |c| {
            verify_following(prog, image, env, c, opts, &[fid])
        });
        if again.iter().any(|o| matches!(o.report.status, Status::Mismatch(_))) {
            continue;
        }
        let names: Vec<String> = callers
            .iter()
            .map(|&c| prog.funcs[c as usize].name.to_string())
            .collect();
        if again.iter().all(|o| matches!(o.report.status, Status::Proved)) {
            let mut modulo: Vec<(String, String)> = Vec::new();
            let mut paths = 0;
            for (o, &c) in again.into_iter().zip(&callers) {
                paths += o.report.paths;
                for m in &o.report.modulo {
                    if !modulo.contains(m) {
                        modulo.push(m.clone());
                    }
                }
                match todo.iter().position(|&t| t == c) {
                    Some(k) => outs[k] = o,
                    None => {
                        outs[i].cov.extend(o.cov);
                        outs[i].bytes.extend(o.bytes);
                    }
                }
            }
            let r = &mut outs[i].report;
            r.status = Status::Proved;
            r.paths = paths;
            r.modulo = modulo;
            r.detail = None;
            r.given = Some(format!(
                "as called from {}: the compiler changed how this internal function is called",
                names.join(", ")
            ));
        } else {
            let r = &mut outs[i].report;
            r.status = Status::Inconclusive(format!(
                "an internal function the compiler may call in its own way: on its own it differs ({why}), and followed from its callers ({}) not all of them are proved",
                names.join(", ")
            ));
        }
    }
}

/// 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,
    }
}