binscout 0.9.2

Headless, agent-first binary analysis: functions, CFGs, xrefs, strings, and IR over a JSON CLI or MCP server
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
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
//! M4 analysis: function discovery, CFGs, callgraph, xrefs, queries.
//!
//! [`analyze`] runs recursive descent over [`LoadedBinary`]: starting from
//! the entry point and export addresses, it decodes one instruction at a time
//! (`decode_one()`), follows direct branches and calls, and falls back to a
//! prologue scan for functions unreachable from those seeds. Decoded code is
//! split into basic blocks, each function gets a CFG and the whole binary a
//! callgraph (both `petgraph` maps), and cross-references are split into
//! code, data, string, and import refs. Calls to known-noreturn imports
//! (`exit`, `abort`, `ExitProcess`, and similar) cut the fall-through CFG
//! edge and flag the function row; wrappers propagate to a bounded
//! fixpoint (see `plan_noreturn`).
//!
//! Control flow reuses the M3 lift ([`lift`](crate::ir::lift)): `Branch`/`CBranch`/`Call`
//! carry their direct target, `Return` ends a path, everything else
//! (including unlifted `Nop`) falls through. Known gaps: indirect jumps and
//! `loop`-style branches have no target, so those edges are missing rather
//! than guessed.
//!
//! Function boundaries are entry/export addresses, direct call targets, and
//! prologue-scan hits outside already-decoded code; every other block belongs
//! to the nearest entry at or below its start. Shared tails can therefore be
//! attributed to one function only.

use std::cmp::Reverse;
use std::collections::{BTreeMap, BTreeSet, BinaryHeap};
use std::sync::OnceLock;

use memchr::{memchr2, memchr3};
use petgraph::graphmap::DiGraphMap;
use serde::{Deserialize, Serialize};

use crate::disasm::{Arch, Insn, arm_base_mnem, resolve_const_pair, resolve_movw_pair};
use crate::error::{Error, Result};
use crate::ir::IrOp;
use crate::loader::strings::{self, Encoding, StringHit};
use crate::loader::{ArmHints, BinaryFormat, LoadedBinary, RawOptions, Section, Segment, load_raw};

/// Cap on decoded instructions per [`analyze`] call.
pub const MAX_TOTAL_INSNS: usize = 1_000_000;
/// Cap on discovered function entries per [`analyze`] call.
pub const MAX_FUNCTIONS: usize = 100_000;
/// Cap on cross-references of each kind per [`analyze`] call.
pub const MAX_XREFS_PER_KIND: usize = 1_000_000;
/// Cap on discovery seeds (entry/exports/prologues) per call.
pub const MAX_SEEDS: usize = 100_000;
/// Cap on pointer-scan seeds per [`analyze_with_options`] call.
///
/// Lower-confidence aligned-pointer hits stop here so hostile data cannot
/// inflate the authoritative seed budget; the global [`MAX_SEEDS`] cap
/// still bounds the combined set.
pub const MAX_POINTER_SEEDS: usize = 10_000;
/// Revision of the analysis engine covered by cached snapshots.
///
/// Bumped whenever [`analyze`] output for identical bytes and mappings can
/// change; [`crate::db`] treats a stored revision mismatch as stale and
/// re-analyzes while carrying same-mapping annotations forward.
pub const ANALYSIS_REVISION: u32 = 15;
/// Cap on retained diagnostic records per [`analyze`] call.
///
/// When discovery yields more sites than this, analysis continues and the
/// excess is counted in [`Diagnostics::omitted`] with [`Diagnostics::truncated`]
/// set; hard analysis budgets still
/// return [`Error::Limit`].
pub const MAX_DIAGNOSTICS: usize = 100_000;
/// Cap on recovered single-slot indirect-jump edges per site.
///
/// The approved single-slot pattern is a singleton by construction (one slot
/// holds one target), so a site yields at most one edge; the constant states
/// that structural bound against the investigation's 1024/site ceiling
/// (`1 <= 1024`). Multi-entry tables have their own per-site cap (see
/// [`MAX_TABLE_ENTRIES_PER_SITE`]).
pub const MAX_INFERRED_PER_SITE: usize = 1;
/// Cap on recovered table entries per guarded switch site.
///
/// The scan reads exactly the guard bound (`cmp idx, max; ja/jb default`
/// gives `max + 1` entries) up to this ceiling; every slot must validate
/// (mapped, file-backed, executable, decodable, same-function) or the whole
/// site stays unresolved (exact-or-reject). Bounds above the ceiling are
/// unrecoverable without truncating the table, so those sites stay
/// unresolved too. Runs shorter than [`MIN_TABLE_ENTRIES_PER_SITE`]
/// are indistinguishable from stray pointers and stay unresolved.
pub const MAX_TABLE_ENTRIES_PER_SITE: usize = 1024;
/// Minimum consecutive valid slots for a table site to resolve.
///
/// Singleton runs fall back to the single-slot path (which owns the typed
/// `mem_target` shapes); an indexed site with fewer valid slots than this
/// keeps its diagnostic.
pub const MIN_TABLE_ENTRIES_PER_SITE: usize = 2;
/// How far back from a table site the index-guard and sequence search walks.
///
/// Counts decoded instructions in reverse address order within the site's
/// function. A guarded switch checks its index just before indexing
/// (`cmp` + a direct conditional branch to the default path); multi-step
/// dispatch sequences (PIE `lea`/`movsxd`/`add`, AArch64
/// `adrp`/`add`/`adr`/`ldrb`/`add`) span up to eight instructions, so the
/// window covers the whole shape. An unguarded index has an unbounded index
/// and is unrecoverable; detected-but-unbounded sites keep their
/// [`DiagnosticKind::UnresolvedIndirectJump`].
pub const MAX_TABLE_GUARD_BACKTRACK: usize = 10;
/// Cap on recovered single-slot indirect-jump edges per [`analyze`] call.
///
/// On exhaustion the site stays unresolved with its diagnostic retained and
/// the excess is counted in [`Diagnostics::inferred_omitted`] with
/// [`Diagnostics::inferred_truncated`] set, never silently clipped from the
/// inferred graph.
pub const MAX_INFERRED_EDGES: usize = 100_000;
/// Query pages longer than this are truncated.
pub const MAX_PAGE: usize = 1024;
/// Cap on transitive callgraph hops per query.
///
/// Bounds BFS in [`Analysis::callees_transitive`] and
/// [`Analysis::callers_transitive`]: deeper requests clip to this depth
/// so a large depth cannot inflate work past one bounded walk over the
/// function set.
pub const MAX_CALL_DEPTH: usize = 64;
/// Cap on backward-slice hops per query.
///
/// Bounds BFS in [`Analysis::slice_to`]: deeper requests clip to this
/// depth so a large depth cannot inflate work past one bounded walk
/// over the instruction set. Mirrors [`MAX_CALL_DEPTH`]: direct
/// predecessors are depth 1, zero yields an empty set.
pub const MAX_SLICE_DEPTH: usize = 64;
/// Default `slice` depth for the CLI and MCP: wide enough for a few hops
/// of xrefs, narrow enough to stay readable.
pub const DEFAULT_SLICE_DEPTH: usize = 8;
/// Cap on noreturn propagation rounds per `plan_noreturn` call.
///
/// Each round marks every dirty function whose entry can no longer reach
/// a return; a chain of wrappers around `exit` needs one round per link.
/// Real chains are a handful deep; past this bound the leftovers stay
/// returning (today's behavior), never guessed noreturn.
pub const MAX_NORETURN_ROUNDS: usize = 64;

/// Largest Mach-O stub entry (`__auth_stubs` is 16 bytes, arm64 `__stubs`
/// 12, x86-64 6).
const MACHO_STUB_MAX: u64 = 16;

/// What a cross-reference points through.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum XrefKind {
    /// Branch/call target reference.
    Code,
    /// Data access reference (PC-relative slot or absolute pointer).
    Data,
    /// Reference into an extracted string.
    String,
    /// Import call-site reference: an indirect `call`/`jmp` through a PE
    /// IAT or ELF GOT slot, or a direct `call`/`jmp` to a PLT stub or
    /// import thunk. `to` is the import's slot address (see
    /// [`ImportRef::address`](crate::loader::ImportRef::address)); the
    /// `Data` slot row (indirect sites) and the `Code` stub row (direct
    /// sites) are retained alongside, so import rows are purely additive.
    Import,
    /// Provenance-marked inferred code edge: a resolved single-slot
    /// absolute indirect jump or a resolved guarded table entry
    /// (`site -> target`). Direct edges stay
    /// [`XrefKind::Code`]; counts jointly against the `Code` per-kind
    /// budget so inferred rows cannot evade the cap by relabeling.
    /// Wire form is kebab-case (`inferred-code`); the direct kinds keep
    /// their historical CamelCase spelling.
    #[serde(rename = "inferred-code")]
    InferredCode,
}

/// One cross-reference: instruction at `from` refers to `to`.
///
/// JSON pairs each endpoint with its `0x`-hex twin (`from_hex`, `to_hex`);
/// old rows without the twins still deserialize.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
pub struct Xref {
    /// Address of the referring instruction.
    pub from: u64,
    /// Referenced address (code target, data address, or string start).
    pub to: u64,
    /// How the reference is made.
    pub kind: XrefKind,
}

impl Serialize for Xref {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        let mut st = serializer.serialize_struct("Xref", 5)?;
        st.serialize_field("from", &self.from)?;
        st.serialize_field("from_hex", &crate::addr_hex(self.from))?;
        st.serialize_field("to", &self.to)?;
        st.serialize_field("to_hex", &crate::addr_hex(self.to))?;
        st.serialize_field("kind", &self.kind)?;
        st.end()
    }
}

/// Why a function entry was discovered.
///
/// Evidence about how analysis reached an entry, not a confidence score
/// or a verified-boundary claim. Reasons coexist: one entry can be the
/// binary entry point, an export, a direct-call target, and a prologue
/// hit at once. Stored sorted and deduplicated.
///
/// Wire form is kebab-case (`entry`, `export`, `symbol`, `direct-call`,
/// `prologue`, `pdata`, `tls-callback`, `init-array`, `function-starts`,
/// `pointer`); pre-provenance rows in the historical CamelCase spelling
/// still decode via aliases.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum DiscoveryReason {
    /// Binary entry point (or the fallback first executable byte when no
    /// entry or export seeds analysis).
    #[serde(alias = "Entry")]
    Entry,
    /// Export address resolving to executable code.
    #[serde(alias = "Export")]
    Export,
    /// Symbol-table address (locals included) resolving to executable
    /// code.
    #[serde(alias = "Symbol")]
    Symbol,
    /// Direct call target followed during recursive descent.
    #[serde(alias = "DirectCall")]
    DirectCall,
    /// Prologue-scan hit outside round-one reached code.
    #[serde(alias = "Prologue")]
    Prologue,
    /// User-defined seed from `define-func`: an agent asserted there is
    /// code at this address (shellcode, firmware vectors, obfuscated
    /// code, missed callbacks).
    #[serde(alias = "User")]
    User,
    /// PE `.pdata` `RUNTIME_FUNCTION` start resolving to executable code.
    ///
    /// Exact starts for every non-leaf function on 64-bit Windows.
    #[serde(alias = "Pdata")]
    Pdata,
    /// PE TLS callback resolving to executable code.
    ///
    /// `IMAGE_TLS_DIRECTORY.AddressOfCallBacks` entry: a common
    /// malware anti-debug entry point.
    #[serde(alias = "TlsCallback")]
    TlsCallback,
    /// ELF init/fini address resolving to executable code.
    ///
    /// `.init_array`/`.fini_array`/`.ctors`/`.dtors` entries plus `DT_INIT`,
    /// `DT_FINI`, and `DT_INIT_ARRAY`/`DT_FINI_ARRAY` slots.
    #[serde(alias = "InitArray")]
    InitArray,
    /// Mach-O `LC_FUNCTION_STARTS` address resolving to executable code.
    ///
    /// Exact starts decoded from ULEB deltas off the `__TEXT` base.
    #[serde(alias = "FunctionStarts")]
    FunctionStarts,
    /// Aligned pointer-sized value in non-executable data landing on
    /// decodable executable code (vtables, callback tables).
    ///
    /// Lower confidence than table-derived seeds: opt-in via
    /// [`AnalyzeOptions::pointer_scan`], never on by default.
    #[serde(alias = "Pointer")]
    Pointer,
    /// Debug-info address (DWARF `DW_TAG_subprogram` or PDB public /
    /// procedure row) resolving to executable code.
    ///
    /// Compiler-emitted starts and names; exact like symbol-table seeds.
    #[serde(alias = "Debug")]
    Debug,
}

/// Decode mode of one user-defined function seed (`define-func --mode`).
///
/// Only meaningful on 32-bit ARM projects (`Arm32`/`Thumb`): `Thumb`
/// decodes the seed's function as Thumb instead of masking the
/// interworking bit and decoding as ARM. On other architectures the
/// mode is rejected at the project boundary and coerced away here.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SeedMode {
    /// Decode as 32-bit ARM.
    Arm,
    /// Decode as Thumb.
    Thumb,
}

impl SeedMode {
    /// Canonical flag spelling (`arm`/`thumb`).
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Arm => "arm",
            Self::Thumb => "thumb",
        }
    }

    /// Disassembler target this mode decodes with.
    #[must_use]
    pub fn arch(self) -> Arch {
        match self {
            Self::Arm => Arch::Arm32,
            Self::Thumb => Arch::Thumb,
        }
    }

    /// Parse a `--mode`/`mode` value (case-insensitive, trimmed).
    ///
    /// # Errors
    /// [`Error::Invalid`] for anything but `arm`/`thumb`.
    pub fn parse(s: &str) -> Result<Self> {
        match s.trim().to_lowercase().as_str() {
            "arm" => Ok(Self::Arm),
            "thumb" => Ok(Self::Thumb),
            _ => Err(Error::Invalid(format!(
                "unknown seed mode: {s:?} (expected one of arm, thumb)"
            ))),
        }
    }
}

/// One user-defined function seed: an agent-asserted code address plus an
/// optional 32-bit ARM decode-mode override.
///
/// `mode` is `None` for the default decode (project arch with the usual
/// ARM Thumb-bit normalization); `excluded` rows never reach analysis
/// (see [`crate::db::FuncSeed`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UserSeed {
    /// Seed address (canonical: Thumb bit cleared on 32-bit ARM).
    pub addr: u64,
    /// Decode-mode override, if any.
    pub mode: Option<SeedMode>,
}

/// Analysis options selecting opt-in discovery sources.
///
/// Only the pointer scan is gated: table-derived seeds (`.pdata`, TLS
/// callbacks, ELF init/fini, `LC_FUNCTION_STARTS`) are authoritative and
/// always on, while aligned-pointer hits are lower confidence and stay
/// off unless requested.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct AnalyzeOptions {
    /// Scan aligned pointer-sized values in non-executable data for
    /// decodable executable targets ([`DiscoveryReason::Pointer`]).
    ///
    /// Off by default; enable only when hunting vtables or callback
    /// tables that no table names.
    pub pointer_scan: bool,
}

impl AnalyzeOptions {
    /// Default options: pointer scan off.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Options with the pointer scan enabled.
    #[must_use]
    pub fn with_pointer_scan() -> Self {
        Self { pointer_scan: true }
    }
}

/// What an analysis diagnostic records.
///
/// Evidence about where analysis is incomplete, not a confidence score.
/// Unresolved sites stay unresolved: they never become proven CFG or
/// callgraph edges. A clean decode with a `Return` terminator is valid
/// termination, never a [`DiagnosticKind::DecodeFailure`].
///
/// Wire form is kebab-case (`unresolved-indirect-jump`,
/// `unresolved-indirect-call`, `decode-failure`); rows persisted under
/// the historical CamelCase spelling still decode via aliases.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum DiagnosticKind {
    /// Branch without a direct target (`Branch`/`CBranch` with no target
    /// from the lift: indirect forms and unsupported `loop`-style
    /// branches). The site stays edgeless.
    #[serde(alias = "UnresolvedIndirectJump")]
    UnresolvedIndirectJump,
    /// Call without a direct target. The site stays edgeless.
    #[serde(alias = "UnresolvedIndirectCall")]
    UnresolvedIndirectCall,
    /// Call to a target that never returns (a known-noreturn import or a
    /// function with no return-reachable exit). The fall-through edge is
    /// cut: the site keeps its callgraph and import edges, but the next
    /// instruction is not a successor.
    #[serde(alias = "NoreturnCut")]
    NoreturnCut,
    /// Executable bytes at a discovery address that did not decode.
    /// Only queued discovery addresses are recorded, never every
    /// undecoded byte in the binary.
    #[serde(alias = "DecodeFailure")]
    DecodeFailure,
}

/// One analysis diagnostic: an incomplete-analysis site.
///
/// JSON pairs `addr` with `addr_hex`; old rows without the twin still
/// deserialize.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize)]
pub struct Diagnostic {
    /// Address of the unresolved instruction or failed decode.
    pub addr: u64,
    /// What is incomplete at `addr`.
    pub kind: DiagnosticKind,
}

impl Serialize for Diagnostic {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        let mut st = serializer.serialize_struct("Diagnostic", 3)?;
        st.serialize_field("addr", &self.addr)?;
        st.serialize_field("addr_hex", &crate::addr_hex(self.addr))?;
        st.serialize_field("kind", &self.kind)?;
        st.end()
    }
}

/// One diagnostics row: the site plus its containing function and detail.
///
/// JSON pairs `addr` with `addr_hex` and `func` with `func_hex` (`func`
/// is null on both sides when the site lies in no function).
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct DiagnosticRow {
    /// What is incomplete at `addr`.
    pub kind: DiagnosticKind,
    /// Address of the unresolved instruction or failed decode.
    pub addr: u64,
    /// Entry of the function containing `addr`, if any.
    pub func: Option<u64>,
    /// Kind-specific detail: what is incomplete at the site.
    pub detail: String,
}

impl Serialize for DiagnosticRow {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        let mut st = serializer.serialize_struct("DiagnosticRow", 6)?;
        st.serialize_field("kind", &self.kind)?;
        st.serialize_field("addr", &self.addr)?;
        st.serialize_field("addr_hex", &crate::addr_hex(self.addr))?;
        st.serialize_field("func", &self.func)?;
        st.serialize_field("func_hex", &self.func.map(crate::addr_hex))?;
        st.serialize_field("detail", &self.detail)?;
        st.end()
    }
}

/// Kind-specific detail for a diagnostics row: what is incomplete at the site.
///
/// Static evidence text derived from the kind itself, never a fabricated
/// confidence claim or a proof of complete recovery.
#[must_use]
pub fn diagnostic_detail(kind: DiagnosticKind) -> &'static str {
    match kind {
        DiagnosticKind::UnresolvedIndirectJump => {
            "indirect jump without a direct target; the site stays edgeless"
        }
        DiagnosticKind::UnresolvedIndirectCall => {
            "indirect call without a direct target; the site stays edgeless"
        }
        DiagnosticKind::DecodeFailure => {
            "executable bytes at a queued discovery address that did not decode"
        }
        DiagnosticKind::NoreturnCut => "call to a noreturn target; the fall-through edge is cut",
    }
}

/// Bounded diagnostic record set for one analysis.
///
/// `records` stay sorted by `(addr, kind)` with at most [`MAX_DIAGNOSTICS`]
/// entries; on cap exhaustion analysis continues and the excess is counted
/// in [`Diagnostics::omitted`] with [`Diagnostics::truncated`] set. Hard
/// analysis budgets still return [`Error::Limit`]
/// rather than a truncated partial result.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Diagnostics {
    /// Retained records sorted by `(addr, kind)`.
    pub records: Vec<Diagnostic>,
    /// Whether discovery produced more records than [`MAX_DIAGNOSTICS`].
    pub truncated: bool,
    /// Records omitted by the [`MAX_DIAGNOSTICS`] cap (zero unless
    /// [`Diagnostics::truncated`]).
    pub omitted: usize,
    /// Whether indirect-jump resolution produced more edges than
    /// [`MAX_INFERRED_EDGES`].
    pub inferred_truncated: bool,
    /// Edges omitted by the [`MAX_INFERRED_EDGES`] cap (zero unless
    /// [`Diagnostics::inferred_truncated`]); skipped sites stay unresolved
    /// with their diagnostic retained.
    pub inferred_omitted: usize,
}

impl Diagnostics {
    /// Empty record set: no diagnostics, nothing omitted.
    #[must_use]
    pub fn empty() -> Self {
        Self::default()
    }

    /// Sort, deduplicate, and cap `records`.
    ///
    /// Fresh analysis passes `false`/`0` and learns the flags here; the
    /// rebuild path re-applies the cap defensively so a forged snapshot
    /// cannot smuggle an unbounded record list past the reader.
    #[must_use]
    pub fn collect(records: Vec<Diagnostic>, truncated: bool, omitted: usize) -> Self {
        let mut sorted = records;
        sorted.sort_unstable();
        sorted.dedup();
        if sorted.len() > MAX_DIAGNOSTICS {
            let excess = sorted.len() - MAX_DIAGNOSTICS;
            sorted.truncate(MAX_DIAGNOSTICS);
            Self {
                records: sorted,
                truncated: true,
                omitted: omitted.saturating_add(excess),
                inferred_truncated: false,
                inferred_omitted: 0,
            }
        } else {
            Self {
                records: sorted,
                truncated,
                omitted,
                inferred_truncated: false,
                inferred_omitted: 0,
            }
        }
    }
}

/// One basic block: a maximal run with a single entry at `start`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BasicBlock {
    /// Address of the first instruction; the block's stable key.
    pub start: u64,
    /// Decoded instructions in address order.
    pub insns: Vec<Insn>,
}

impl BasicBlock {
    /// End address (one past the last instruction's last byte).
    #[must_use]
    pub fn end(&self) -> u64 {
        self.insns
            .last()
            .map(|i| i.addr.wrapping_add(u64::from(i.size)))
            .unwrap_or(self.start)
    }

    /// Stable ID: `block@{func_entry:#x}+{start:#x}`.
    #[must_use]
    pub fn id(&self, func_entry: u64) -> String {
        format!("block@{func_entry:#x}+{:#x}", self.start)
    }
}

/// One discovered function with its control-flow graph.
#[derive(Debug, Clone)]
pub struct Function {
    /// Function entry address; the stable key.
    pub entry: u64,
    /// Export, debug-info, symbol, stub-import, PLT (`sym@plt`), or thunk
    /// name when one resolves to `entry`.
    pub name: Option<String>,
    /// Basic blocks keyed by start address.
    pub blocks: BTreeMap<u64, BasicBlock>,
    cfg: DiGraphMap<u64, ()>,
    /// Provenance-marked inferred block edges (`from_block -> to_block`)
    /// from resolved single-slot indirect jumps and guarded table entries.
    /// Direct edges stay in
    /// `cfg` (see [`Function::edges`]); inferred edges never become
    /// callgraph edges or new function entries.
    inferred: BTreeSet<(u64, u64)>,
    /// How this entry was discovered, sorted and deduplicated.
    ///
    /// Evidence, not confidence: coexisting [`DiscoveryReason`]s record
    /// every seed path that reached this entry.
    pub reasons: BTreeSet<DiscoveryReason>,
    /// Decode-arch override for this function, if it differs from the
    /// project arch.
    ///
    /// Set when the entry decoded under an explicit [`SeedMode`], an
    /// ARM interworking seed (Thumb bit, mapping symbol, Thumb-function
    /// mark), or a mode-switch edge (direct `blx`, resolved `bx`).
    /// `None` means the project arch. Persisted per function so snapshot
    /// reload re-decodes identical bytes.
    pub decode_arch: Option<Arch>,
    /// Whether this function never returns: no path from the entry
    /// reaches a return or an unknown exit (see `plan_noreturn`).
    pub noreturn: bool,
}

impl Function {
    /// Stable ID: `func@{entry:#x}`.
    #[must_use]
    pub fn id(&self) -> String {
        format!("func@{:#x}", self.entry)
    }

    /// Total instructions across all blocks.
    #[must_use]
    pub fn insn_count(&self) -> usize {
        self.blocks.values().map(|b| b.insns.len()).sum()
    }

    /// Successor block starts of `block`, sorted.
    ///
    /// Sorted so fresh and snapshot-rebuilt analyses answer identically:
    /// graph neighbor order follows edge insertion, which differs between
    /// the walk (target before fallthrough) and the snapshot replay.
    #[must_use]
    pub fn successors(&self, block: u64) -> Vec<u64> {
        let mut succs: Vec<u64> = self.cfg.neighbors(block).collect();
        succs.sort_unstable();
        succs
    }

    /// Predecessor block starts of `block`.
    ///
    /// Reverse of [`Function::successors`] over the direct CFG only;
    /// inferred single-slot resolutions are covered separately through
    /// their provenance-marked [`XrefKind::InferredCode`] xrefs, so the
    /// backward slice needs no second edge set here.
    #[must_use]
    pub fn predecessors(&self, block: u64) -> Vec<u64> {
        self.cfg
            .neighbors_directed(block, petgraph::Direction::Incoming)
            .collect()
    }

    /// All CFG edges as sorted `(from_block, to_block)` pairs.
    ///
    /// Direct edges only; inferred single-slot resolutions live in
    /// [`Function::inferred_edges`]. Sorted for the same fresh/rebuilt
    /// determinism as [`Function::successors`].
    #[must_use]
    pub fn edges(&self) -> Vec<(u64, u64)> {
        let mut edges: Vec<(u64, u64)> = self.cfg.all_edges().map(|(a, b, _)| (a, b)).collect();
        edges.sort_unstable();
        edges
    }

    /// Inferred block edges as sorted `(from_block, to_block)` pairs.
    ///
    /// Provenance-marked indirect-jump resolutions: at most one per site
    /// for the single-slot shape (see [`MAX_INFERRED_PER_SITE`]), up to
    /// [`MAX_TABLE_ENTRIES_PER_SITE`] for a guarded table site.
    /// Same-function only: these never become callgraph edges or new
    /// function entries.
    #[must_use]
    pub fn inferred_edges(&self) -> Vec<(u64, u64)> {
        self.inferred.iter().copied().collect()
    }

    /// Targets inferred from `block`, in address order.
    ///
    /// The same rows [`Function::inferred_edges`] reports, restricted to one
    /// source block without materializing the whole set.
    #[must_use]
    pub fn inferred_succs(&self, block: u64) -> Vec<u64> {
        self.inferred
            .range((block, 0)..=(block, u64::MAX))
            .map(|(_, t)| *t)
            .collect()
    }

    /// Count of inferred block edges (see [`Function::inferred_edges`]).
    ///
    /// The same count `inferred_edges().len()` reports, without allocating
    /// the pair vector.
    #[must_use]
    pub fn inferred_len(&self) -> usize {
        self.inferred.len()
    }

    /// Sorted, deduplicated discovery reasons.
    #[must_use]
    pub fn reason_list(&self) -> Vec<DiscoveryReason> {
        self.reasons.iter().copied().collect()
    }

    /// Rebuild a function from persisted rows (M5 redb round-trip).
    ///
    /// `edges` are `(from_block, to_block)` pairs within this function;
    /// `inferred` are the provenance-marked inferred pairs, replayed with
    /// the same unknown-endpoint drop as `edges`. `reasons` may arrive in
    /// any order with duplicates and are stored sorted and deduplicated.
    /// `decode_arch` is the per-function decode override (`None` means the
    /// project arch); callers replaying a snapshot pass the persisted
    /// value so mixed-mode functions re-decode identically.
    #[must_use]
    pub fn from_parts(
        entry: u64,
        name: Option<String>,
        blocks: BTreeMap<u64, BasicBlock>,
        edges: &[(u64, u64)],
        reasons: Vec<DiscoveryReason>,
        inferred: &[(u64, u64)],
        decode_arch: Option<Arch>,
    ) -> Self {
        let mut cfg = DiGraphMap::new();
        for &start in blocks.keys() {
            cfg.add_node(start);
        }
        for &(a, b) in edges {
            if blocks.contains_key(&a) && blocks.contains_key(&b) {
                cfg.add_edge(a, b, ());
            }
        }
        let mut inferred_set = BTreeSet::new();
        for &(a, b) in inferred {
            if blocks.contains_key(&a) && blocks.contains_key(&b) {
                inferred_set.insert((a, b));
            }
        }
        Self {
            entry,
            name,
            blocks,
            cfg,
            inferred: inferred_set,
            reasons: reasons.into_iter().collect(),
            decode_arch,
            noreturn: false,
        }
    }
}

/// Approximate per-function structural warning.
///
/// Loops and ifs are syntactic patterns over the direct CFG plus the M3
/// lift (`Branch`/`CBranch` targets): a back edge is not a proven loop and
/// a two-successor `CBranch` site is not a proven if. Agents must treat the
/// rows as hints, never as decompiler output.
pub const STRUCTURE_WARNING: &str = "approximate structure over CFG+IR: back edges and two-successor branch sites are syntactic hints, not verified loops/ifs; not a decompiler";

/// One syntactic loop: CFG back edges into a shared header.
///
/// `header` is the back-edge target (the cycle entry); `latches` are the
/// sorted sources of back edges into it. A self-edge (`header` in
/// `latches`) is the tightest loop shape.
///
/// JSON pairs `header` with `header_hex`; `latches` stays a plain integer
/// array.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct LoopInfo {
    /// Back-edge target: the loop header block start.
    pub header: u64,
    /// Sorted sources of back edges into `header`.
    pub latches: Vec<u64>,
}

impl Serialize for LoopInfo {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        let mut st = serializer.serialize_struct("LoopInfo", 3)?;
        st.serialize_field("header", &self.header)?;
        st.serialize_field("header_hex", &crate::addr_hex(self.header))?;
        st.serialize_field("latches", &self.latches)?;
        st.end()
    }
}

/// One syntactic if: a `CBranch`-terminated block with two successors.
///
/// `then_target` is the taken branch (the lift's direct target when it is
/// one of the successors, else the lower successor); `else_target` is the
/// other successor (usually fallthrough).
///
/// JSON pairs each address with its `0x`-hex twin (`cond`/`cond_hex`,
/// `then_target`/`then_hex`, `else_target`/`else_hex`).
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct IfInfo {
    /// Start of the branching block.
    pub cond: u64,
    /// Taken-branch successor.
    pub then_target: u64,
    /// Fallthrough/other successor.
    pub else_target: u64,
}

impl Serialize for IfInfo {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        let mut st = serializer.serialize_struct("IfInfo", 6)?;
        st.serialize_field("cond", &self.cond)?;
        st.serialize_field("cond_hex", &crate::addr_hex(self.cond))?;
        st.serialize_field("then_target", &self.then_target)?;
        st.serialize_field("then_hex", &crate::addr_hex(self.then_target))?;
        st.serialize_field("else_target", &self.else_target)?;
        st.serialize_field("else_hex", &crate::addr_hex(self.else_target))?;
        st.end()
    }
}

/// Approximate control-flow structure of one function.
///
/// `loops` sort by header, `ifs` by `cond`, so repeated queries agree.
/// `warning` is always [`STRUCTURE_WARNING`]: the rows are syntactic
/// hints over the CFG plus the M3 lift, never verified control flow.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FuncStructure {
    /// Syntactic loops ordered by header.
    pub loops: Vec<LoopInfo>,
    /// Syntactic ifs ordered by `cond`.
    pub ifs: Vec<IfInfo>,
    /// Always [`STRUCTURE_WARNING`].
    pub warning: String,
}

impl Function {
    /// Approximate control-flow structure: syntactic loops and ifs.
    ///
    /// Loops are direct-CFG back edges: one iterative depth-first walk over
    /// ascending block starts (gray means on the DFS stack); an edge to a
    /// gray node closes a cycle, grouped by header with sorted latches.
    /// Ifs are blocks whose terminator lifts (see [`crate::ir::lift`]) to
    /// [`IrOp::CBranch`] with exactly two direct-CFG successors. Pure
    /// read-only pass over `blocks`/`cfg` plus the control-flow check; inferred
    /// single-slot edges never participate.
    #[must_use]
    pub fn structure(&self, arch: Arch) -> FuncStructure {
        // Iterative DFS with sorted successors for deterministic output.
        // `gray` holds the current stack path; an edge into it is a back
        // edge (latch = source, header = target).
        let mut gray: BTreeSet<u64> = BTreeSet::new();
        let mut black: BTreeSet<u64> = BTreeSet::new();
        let mut back_edges: Vec<(u64, u64)> = Vec::new();
        for &root in self.blocks.keys() {
            if gray.contains(&root) || black.contains(&root) {
                continue;
            }
            gray.insert(root);
            let mut stack: Vec<(u64, std::vec::IntoIter<u64>)> =
                vec![(root, sorted_succs(self, root))];
            while let Some((node, nexts)) = stack.last_mut() {
                let node = *node;
                match nexts.next() {
                    Some(next) => {
                        if gray.contains(&next) {
                            back_edges.push((node, next));
                        } else if !black.contains(&next) {
                            gray.insert(next);
                            stack.push((next, sorted_succs(self, next)));
                        }
                    }
                    None => {
                        let (done, _) = stack.pop().expect("nonempty stack pops");
                        gray.remove(&done);
                        black.insert(done);
                    }
                }
            }
        }
        let mut by_header: BTreeMap<u64, Vec<u64>> = BTreeMap::new();
        for (latch, header) in back_edges {
            by_header.entry(header).or_default().push(latch);
        }
        let loops = by_header
            .into_iter()
            .map(|(header, mut latches)| {
                latches.sort_unstable();
                latches.dedup();
                LoopInfo { header, latches }
            })
            .collect();

        let mut ifs: Vec<IfInfo> = Vec::new();
        for (start, block) in &self.blocks {
            let Some(ctrl) = block_control(arch, block) else {
                continue;
            };
            let Some((IrOp::CBranch, target)) = crate::ir::control_op(arch, ctrl) else {
                continue;
            };
            let mut succs = self.successors(*start);
            if succs.len() != 2 {
                continue;
            }
            succs.sort_unstable();
            let (then_target, else_target) = match target {
                Some(t) if succs.contains(&t) => {
                    (t, if succs[0] == t { succs[1] } else { succs[0] })
                }
                _ => (succs[0], succs[1]),
            };
            ifs.push(IfInfo {
                cond: *start,
                then_target,
                else_target,
            });
        }
        ifs.sort_by_key(|i| i.cond);

        FuncStructure {
            loops,
            ifs,
            warning: STRUCTURE_WARNING.to_string(),
        }
    }
}

/// Sorted direct-CFG successors of `block` for deterministic DFS order.
fn sorted_succs(func: &Function, block: u64) -> std::vec::IntoIter<u64> {
    let mut succs = func.successors(block);
    succs.sort_unstable();
    succs.into_iter()
}

/// Whole-binary analysis result.
#[derive(Debug, Clone)]
pub struct Analysis {
    /// Disassembler target the binary was decoded as.
    pub arch: Arch,
    /// Discovered functions keyed by entry address.
    pub functions: BTreeMap<u64, Function>,
    callgraph: DiGraphMap<u64, ()>,
    /// Code, data, string, and import xrefs sorted by `(from, kind, to)`.
    pub xrefs: Vec<Xref>,
    /// Lazily built secondary index: positions into [`xrefs`](Self::xrefs)
    /// sorted by (`to`, `from`, `kind`), so `to` queries binary-search
    /// instead of scanning. Built once on first use; never persisted (the
    /// sidecar stores rows in `from` order and the index rebuilds on open).
    to_index: OnceLock<Vec<u32>>,
    /// PLT-stub/import-thunk sites: `jmp [slot]` address to `imports`
    /// index on x86 PE/ELF (see [`import_slots`]), stub-entry address to
    /// `imports` index on Mach-O (see `macho_import_stubs`).
    pub import_stubs: BTreeMap<u64, usize>,
    /// Extracted strings sorted by address.
    pub strings: Vec<StringHit>,
    /// Bounded discovery evidence: unresolved sites and decode failures.
    pub diagnostics: Diagnostics,
}

impl Analysis {
    /// Entry of the function containing `va`, if any.
    ///
    /// Takes the nearest entry at or below `va` (the same attribution
    /// [`analyze`] uses for block ownership) and returns it only when `va`
    /// lies inside one of that function's blocks. Gaps between functions
    /// report `None` rather than snapping to a neighbor.
    #[must_use]
    pub fn containing_function(&self, va: u64) -> Option<u64> {
        let (&entry, func) = self.functions.range(..=va).next_back()?;
        func.blocks
            .range(..=va)
            .next_back()
            .filter(|(_, b)| va < b.end())
            .map(|_| entry)
    }

    /// Direct callees of `entry` (function entries only).
    #[must_use]
    pub fn calls_of(&self, entry: u64) -> Vec<u64> {
        let mut v: Vec<u64> = self.callgraph.neighbors(entry).collect();
        v.sort_unstable();
        v
    }

    /// Count of direct callees of `entry` (function entries only).
    ///
    /// The same set as [`Analysis::calls_of`] without materializing the
    /// sorted target array, for compact metadata over large callgraphs.
    #[must_use]
    pub fn calls_count(&self, entry: u64) -> usize {
        self.callgraph.neighbors(entry).count()
    }

    /// Direct callers of `entry` (function entries only).
    #[must_use]
    pub fn callers_of(&self, entry: u64) -> Vec<u64> {
        let mut v: Vec<u64> = self
            .callgraph
            .neighbors_directed(entry, petgraph::Direction::Incoming)
            .collect();
        v.sort_unstable();
        v
    }

    /// Transitive callees of `entry` as `(target, depth)` pairs.
    ///
    /// Breadth-first walk over the callgraph out to `max_depth` edges from
    /// `entry`; `depth` is the shortest distance (direct callees are depth
    /// 1). The walk clips `max_depth` to [`MAX_CALL_DEPTH`], guards cycles
    /// with a visited set, and never reports `entry` itself even when a
    /// cycle reaches it. Pairs sort by target entry for deterministic
    /// paging; a depth of zero yields an empty set, as does an unknown
    /// entry.
    #[must_use]
    pub fn callees_transitive(&self, entry: u64, max_depth: usize) -> Vec<(u64, usize)> {
        self.reachable(entry, max_depth, petgraph::Direction::Outgoing)
    }

    /// Transitive callers of `entry` as `(target, depth)` pairs.
    ///
    /// Mirror of [`Analysis::callees_transitive`] over incoming edges:
    /// breadth-first, clipped to [`MAX_CALL_DEPTH`], cycle-guarded, never
    /// reporting `entry` itself, sorted by target entry. Depth zero or an
    /// unknown entry yields an empty set.
    #[must_use]
    pub fn callers_transitive(&self, entry: u64, max_depth: usize) -> Vec<(u64, usize)> {
        self.reachable(entry, max_depth, petgraph::Direction::Incoming)
    }

    /// Backward slice of `addr` as `(addr, depth)` pairs.
    ///
    /// Bounded reverse walk over xref edges (every [`XrefKind`]: code,
    /// data, string, and inferred-code) plus intra-function CFG
    /// predecessors at instruction granularity: the previous
    /// instruction in the same block, or the last instruction of each
    /// predecessor block (see [`Function::predecessors`]) at block
    /// starts. Breadth-first out to `max_depth` hops, clipped to
    /// [`MAX_SLICE_DEPTH`], cycle-guarded with a visited set, never
    /// reporting `addr` itself even when a cycle reaches it. Pairs sort
    /// by address for deterministic paging; a depth of zero yields an
    /// empty set. Any address is a valid root (data/string targets lie
    /// in no function and contribute only xref predecessors), so unlike
    /// the callgraph walks there is no unknown-entry case.
    #[must_use]
    pub fn slice_to(&self, addr: u64, max_depth: usize) -> Vec<(u64, usize)> {
        use std::collections::{HashSet, VecDeque};
        let cap = max_depth.min(MAX_SLICE_DEPTH);
        if cap == 0 {
            return Vec::new();
        }
        let idx = self.to_index();
        let mut seen: HashSet<u64> = HashSet::from([addr]);
        let mut queue: VecDeque<(u64, usize)> = VecDeque::from([(addr, 0)]);
        let mut out: Vec<(u64, usize)> = Vec::new();
        while let Some((cur, depth)) = queue.pop_front() {
            if depth >= cap {
                continue;
            }
            let mut next: Vec<u64> = Vec::new();
            let (lo, hi) = self.span_to(idx, cur);
            next.extend(idx[lo..hi].iter().map(|&i| self.xrefs[i as usize].from));
            next.extend(self.insn_preds(cur));
            next.sort_unstable();
            next.dedup();
            for n in next {
                if seen.insert(n) {
                    out.push((n, depth + 1));
                    queue.push_back((n, depth + 1));
                }
            }
        }
        out.sort_unstable();
        out
    }

    /// Instruction predecessors of `cur` within its function, if any.
    ///
    /// The previous instruction in the same block, or at a block start
    /// the last instruction of each direct predecessor block. Empty
    /// when `cur` lies in no function, in no block, or mid-instruction
    /// (an arbitrary root with only xref predecessors).
    fn insn_preds(&self, cur: u64) -> Vec<u64> {
        let Some(entry) = self.containing_function(cur) else {
            return Vec::new();
        };
        let Some(f) = self.functions.get(&entry) else {
            return Vec::new();
        };
        let Some((&start, block)) = f
            .blocks
            .range(..=cur)
            .next_back()
            .filter(|(_, b)| cur < b.end())
        else {
            return Vec::new();
        };
        match block.insns.iter().position(|i| i.addr == cur) {
            Some(i) if i > 0 => vec![block.insns[i - 1].addr],
            Some(_) => {
                let mut preds = f.predecessors(start);
                preds.sort_unstable();
                let mut out = Vec::new();
                for p in preds {
                    if let Some(last) = f.blocks.get(&p).and_then(|b| b.insns.last()) {
                        out.push(last.addr);
                    }
                }
                out
            }
            None => Vec::new(),
        }
    }

    /// Breadth-first reachable set in one callgraph direction.
    fn reachable(
        &self,
        entry: u64,
        max_depth: usize,
        dir: petgraph::Direction,
    ) -> Vec<(u64, usize)> {
        use std::collections::{HashSet, VecDeque};
        let cap = max_depth.min(MAX_CALL_DEPTH);
        if cap == 0 || !self.callgraph.contains_node(entry) {
            return Vec::new();
        }
        let mut seen: HashSet<u64> = HashSet::from([entry]);
        let mut queue: VecDeque<(u64, usize)> = VecDeque::new();
        queue.push_back((entry, 0));
        let mut out: Vec<(u64, usize)> = Vec::new();
        while let Some((cur, depth)) = queue.pop_front() {
            if depth >= cap {
                continue;
            }
            let mut next: Vec<u64> = self.callgraph.neighbors_directed(cur, dir).collect();
            next.sort_unstable();
            for n in next {
                if seen.insert(n) {
                    out.push((n, depth + 1));
                    queue.push_back((n, depth + 1));
                }
            }
        }
        out.sort_unstable();
        out
    }

    /// Approximate control-flow structure of the function at `entry`, if known.
    ///
    /// Read-only [`Function::structure`] over the direct CFG plus the M3
    /// lift: syntactic loops and ifs with the [`STRUCTURE_WARNING`]
    /// marker. Decodes control ops with the function's own decode arch
    /// when a user seed mode overrode it. `None` for an unknown entry
    /// (callers snap addresses with
    /// [`Analysis::containing_function`] first, as
    /// [`crate::Project::structure_of`] does).
    #[must_use]
    pub fn structure_of(&self, entry: u64) -> Option<FuncStructure> {
        self.functions
            .get(&entry)
            .map(|f| f.structure(f.decode_arch.unwrap_or(self.arch)))
    }

    /// All callgraph edges as `(caller, callee)` pairs.
    #[must_use]
    pub fn call_edges(&self) -> Vec<(u64, u64)> {
        self.callgraph.all_edges().map(|(a, b, _)| (a, b)).collect()
    }

    /// Rebuild analysis from persisted rows (M5 redb round-trip).
    ///
    /// Drops call edges pointing at unknown functions, mirroring [`analyze`].
    /// `diagnostics` records are sorted, deduplicated, and capped at
    /// [`MAX_DIAGNOSTICS`] via [`Diagnostics::collect`]. `xrefs` are sorted
    /// into `(from, kind, to)` order when the caller passes them unsorted
    /// (snapshot rows already arrive sorted, so the check is one linear
    /// pass); the binary-search queries require that order.
    #[must_use]
    pub fn from_parts(
        arch: Arch,
        functions: BTreeMap<u64, Function>,
        call_edges: &[(u64, u64)],
        xrefs: Vec<Xref>,
        strings: Vec<StringHit>,
        diagnostics: Diagnostics,
    ) -> Self {
        let mut xrefs = xrefs;
        if !xrefs.is_sorted_by_key(|x| (x.from, x.kind, x.to)) {
            xrefs.sort_by_key(|x| (x.from, x.kind, x.to));
        }
        let mut callgraph = DiGraphMap::<u64, ()>::new();
        for e in functions.keys() {
            callgraph.add_node(*e);
        }
        for &(a, b) in call_edges {
            if functions.contains_key(&a) && functions.contains_key(&b) {
                callgraph.add_edge(a, b, ());
            }
        }
        let inferred_truncated = diagnostics.inferred_truncated;
        let inferred_omitted = diagnostics.inferred_omitted;
        let mut diagnostics = Diagnostics::collect(
            diagnostics.records,
            diagnostics.truncated,
            diagnostics.omitted,
        );
        diagnostics.inferred_truncated = inferred_truncated;
        diagnostics.inferred_omitted = inferred_omitted;
        Self {
            arch,
            functions,
            callgraph,
            xrefs,
            to_index: OnceLock::new(),
            import_stubs: BTreeMap::new(),
            strings,
            diagnostics,
        }
    }
}

/// Persisted block shape: address range, per-instruction boundaries, and
/// successors — no rendered instructions.
///
/// Snapshots store layouts and re-decode instructions from the binary on
/// open (see [`rebuild`]): caching rendered [`Insn`] rows as JSON made a
/// 1.5 MB binary produce a 70+ MB snapshot, so derived text is never
/// persisted. Boundaries are per instruction (not just the range) because
/// recursive descent can record overlapping decodes of one region from
/// different paths; replaying each recorded address reproduces the block
/// bit-identically.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BlockLayout {
    /// Address of the first instruction.
    pub start: u64,
    /// End address (one past the last byte).
    pub end: u64,
    /// `(address, size)` of every instruction in address order.
    pub insns: Vec<InsnLayout>,
    /// Successor block starts.
    pub succs: Vec<u64>,
    /// Inferred successor block starts from resolved single-slot indirect
    /// jumps and guarded table entries; direct successors stay in
    /// [`BlockLayout::succs`].
    ///
    /// Defaults to empty so layouts written before inference still decode;
    /// such snapshots never hit the cache (their analysis revision
    /// mismatches) and re-analyze instead.
    #[serde(default)]
    pub inferred_succs: Vec<u64>,
}

/// Persisted instruction boundary: address plus byte length.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct InsnLayout {
    /// Virtual address of the first byte.
    pub addr: u64,
    /// Length in bytes.
    pub size: u8,
}

/// Persisted function shape: entry, name, callees, and block layouts.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FunctionLayout {
    /// Function entry address.
    pub entry: u64,
    /// Export name or rename, if any.
    pub name: Option<String>,
    /// Sorted direct callees.
    pub calls: Vec<u64>,
    /// Block layouts in address order.
    pub blocks: Vec<BlockLayout>,
    /// Sorted, deduplicated discovery reasons.
    ///
    /// Defaults to empty so layouts written before provenance tracking
    /// still decode; such snapshots never hit the cache (their analysis
    /// revision mismatches) and re-analyze instead.
    #[serde(default)]
    pub reasons: Vec<DiscoveryReason>,
    /// Canonical decode-arch override (`"arm32"`/`"thumb"`), if the
    /// function decoded under a user seed mode rather than the project
    /// arch.
    ///
    /// Defaults to `None` (project arch) so older rows still decode;
    /// such snapshots never hit the cache (their analysis revision
    /// mismatches) and re-analyze instead.
    #[serde(default)]
    pub arch: Option<String>,
}

/// Flatten an analysis into persistable layouts.
///
/// Successor lists and call targets are sorted so snapshots are
/// deterministic across processes.
#[must_use]
pub fn layout(analysis: &Analysis) -> Vec<FunctionLayout> {
    analysis
        .functions
        .values()
        .map(|f| {
            let mut calls = analysis.calls_of(f.entry);
            calls.sort_unstable();
            let blocks = f
                .blocks
                .values()
                .map(|b| {
                    let mut succs = f.successors(b.start);
                    succs.sort_unstable();
                    let insns = b
                        .insns
                        .iter()
                        .map(|i| InsnLayout {
                            addr: i.addr,
                            size: i.size,
                        })
                        .collect();
                    let inferred_succs: Vec<u64> = f.inferred_succs(b.start);
                    BlockLayout {
                        start: b.start,
                        end: b.end(),
                        insns,
                        succs,
                        inferred_succs,
                    }
                })
                .collect();
            FunctionLayout {
                entry: f.entry,
                name: f.name.clone(),
                calls,
                blocks,
                reasons: f.reason_list(),
                arch: match f.decode_arch {
                    Some(a) if a != analysis.arch => Some(crate::db::arch_name(a).to_string()),
                    _ => None,
                },
            }
        })
        .collect()
}

/// Rebuild an analysis from persisted layouts by re-decoding each recorded
/// instruction address from `bin`.
///
/// Each address decodes independently with [`crate::disasm::disasm_first`]
/// exactly as the analysis walker does, so the reproduced instructions are
/// bit-identical to a fresh analysis of the same bytes — including blocks
/// where recursive descent recorded overlapping decodes from different
/// paths. A boundary that does not decode, or decodes to a different size,
/// is snapshot corruption and errors with [`Error::Storage`]. Total range
/// bytes are bounded by the mapped segments, so a forged snapshot cannot
/// decode past the binary.
///
/// `diagnostics` records are sorted, deduplicated, and capped at
/// [`MAX_DIAGNOSTICS`] via [`Diagnostics::collect`].
///
/// # Errors
/// [`Error::Storage`] on corrupt layouts (unknown function references are
/// dropped as in [`analyze`], but undecodable ranges error),
/// [`Error::Limit`] when layouts exceed analysis budgets.
pub fn rebuild(
    arch: Arch,
    bin: &LoadedBinary,
    functions: &[FunctionLayout],
    call_edges: &[(u64, u64)],
    xrefs: Vec<Xref>,
    strings: Vec<StringHit>,
    diagnostics: Diagnostics,
) -> Result<Analysis> {
    if functions.len() > MAX_FUNCTIONS {
        return Err(Error::Limit(format!("more than {MAX_FUNCTIONS} functions")));
    }
    if diagnostics.records.len() > MAX_DIAGNOSTICS + diagnostics.omitted {
        // Defensive: a forged snapshot cannot smuggle an unbounded list;
        // the db reader already caps rows, this guards direct callers.
        return Err(Error::Limit(format!(
            "more than {MAX_DIAGNOSTICS} diagnostics"
        )));
    }
    let space = AddrSpace::new(bin);
    let mapped: u64 = bin.segments.iter().map(|s| s.data.len() as u64).sum();
    let mut ranged: u64 = 0;
    let mut rebuilt: BTreeMap<u64, Function> = BTreeMap::new();
    for f in functions {
        let mut blocks: BTreeMap<u64, BasicBlock> = BTreeMap::new();
        let mut edges: Vec<(u64, u64)> = Vec::new();
        let mut inferred: Vec<(u64, u64)> = Vec::new();
        let func_arch = f
            .arch
            .as_deref()
            .map(crate::db::parse_arch)
            .transpose()?
            .unwrap_or(arch);
        for b in &f.blocks {
            let len = b.end.wrapping_sub(b.start);
            ranged = ranged
                .checked_add(len)
                .filter(|m| *m <= mapped)
                .ok_or_else(|| {
                    Error::Storage(format!(
                        "snapshot block {:#x} exceeds mapped bytes",
                        b.start
                    ))
                })?;
            blocks.insert(b.start, decode_block(func_arch, &space, b)?);
            edges.extend(b.succs.iter().map(|s| (b.start, *s)));
            inferred.extend(b.inferred_succs.iter().map(|s| (b.start, *s)));
        }
        rebuilt.insert(
            f.entry,
            Function::from_parts(
                f.entry,
                f.name.clone(),
                blocks,
                &edges,
                f.reasons.clone(),
                &inferred,
                (func_arch != arch).then_some(func_arch),
            ),
        );
    }
    Ok({
        let mut analysis =
            Analysis::from_parts(arch, rebuilt, call_edges, xrefs, strings, diagnostics);
        // Snapshots persist layouts, not rendered rows: re-decoded
        // instructions need the same import tags and stub map `analyze`
        // applies, so cached opens answer identically to fresh ones.
        let slots = import_slots(bin);
        let stubs: BTreeMap<u64, usize> = if bin.format == BinaryFormat::MachO {
            macho_import_stubs(bin)
        } else if matches!(arch, Arch::X86_64 | Arch::X86_32) {
            collect_stubs(
                analysis
                    .functions
                    .values()
                    .flat_map(|f| f.blocks.values())
                    .flat_map(|b| b.insns.iter())
                    .map(|insn| {
                        (
                            insn.addr,
                            flow_of(arch, insn),
                            insn.mem_target,
                            insn.mnem.as_str(),
                            insn.size,
                        )
                    }),
                &slots,
            )
        } else {
            BTreeMap::new()
        };
        for f in analysis.functions.values_mut() {
            for b in f.blocks.values_mut() {
                for insn in &mut b.insns {
                    if let Some(i) =
                        import_index(&slots, &stubs, insn.branch_target, insn.mem_target)
                        && let Some(imp) = bin.imports.get(i)
                    {
                        insn.import = Some(imp.name.clone());
                    }
                }
            }
        }
        // Noreturn flags over the replayed graphs: the persisted edges
        // already exclude cut fall-throughs and pruned blocks are absent,
        // so the same fixpoint over fresh lifts reproduces the flags of
        // a fresh analysis (see `plan_noreturn`).
        let mut flows: BTreeMap<(u64, u64), Flow> = BTreeMap::new();
        for (entry, f) in &analysis.functions {
            let func_arch = f.decode_arch.unwrap_or(arch);
            for (start, block) in &f.blocks {
                if let Some(last) = block.insns.last() {
                    flows.insert((*entry, *start), flow_of(func_arch, last));
                }
            }
        }
        let mut seeds = BTreeSet::new();
        for (&site, &i) in &stubs {
            if analysis.functions.contains_key(&site)
                && let Some(imp) = bin.imports.get(i)
                && is_noreturn_import(&imp.name)
            {
                seeds.insert(site);
            }
        }
        let plan = plan_noreturn(&analysis.functions, &flows, &seeds);
        for (entry, f) in analysis.functions.iter_mut() {
            f.noreturn = plan.noreturn.contains(entry);
        }
        analysis.import_stubs = stubs;
        analysis
    })
}

/// Re-decode one persisted block instruction by instruction.
///
/// Replays every recorded `(address, size)` boundary independently, so
/// overlapping decodes reproduce exactly. Anything but a clean replay that
/// ends at the stored `end` is corruption.
fn decode_block(arch: Arch, space: &AddrSpace, layout: &BlockLayout) -> Result<BasicBlock> {
    let mut insns = Vec::with_capacity(layout.insns.len());
    for boundary in &layout.insns {
        let bytes = space.code_bytes(boundary.addr).ok_or_else(|| {
            Error::Storage(format!(
                "snapshot block {:#x} leaves executable bytes",
                layout.start
            ))
        })?;
        let Some(insn) = crate::disasm::disasm_first(arch, bytes, boundary.addr).map_err(|e| {
            Error::Storage(format!(
                "snapshot block {:#x} does not decode: {e}",
                layout.start
            ))
        })?
        else {
            return Err(Error::Storage(format!(
                "snapshot block {:#x} has no bytes at {:#x}",
                layout.start, boundary.addr
            )));
        };
        if insn.size != boundary.size {
            return Err(Error::Storage(format!(
                "snapshot block {:#x} decodes {:#x} as {} bytes, not {}",
                layout.start, boundary.addr, insn.size, boundary.size
            )));
        }
        insns.push(insn);
    }
    let block = BasicBlock {
        start: layout.start,
        insns,
    };
    if block.end() != layout.end {
        return Err(Error::Storage(format!(
            "snapshot block {:#x} ends at {:#x}, not {:#x}",
            layout.start,
            block.end(),
            layout.end
        )));
    }
    Ok(block)
}

/// Outcome counts for agent planning and golden tests.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct AnalysisSummary {
    /// Discovered functions.
    pub functions: usize,
    /// Basic blocks across all functions.
    pub blocks: usize,
    /// Decoded instructions across all blocks.
    pub insns: usize,
    /// Recorded cross-references.
    pub xrefs: usize,
    /// Extracted strings.
    pub strings: usize,
}

/// One function row for list views.
///
/// JSON pairs `entry` with `entry_hex`; `calls` stays a plain integer array
/// (positional address lists have no per-element twins).
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct FunctionSummary {
    /// Stable ID (`func@0x...`).
    pub id: String,
    /// Function entry address.
    pub entry: u64,
    /// Rename, if one is set.
    pub name: Option<String>,
    /// Basic block count.
    pub blocks: usize,
    /// Instruction count across all blocks.
    pub insns: usize,
    /// Sorted direct call targets.
    pub calls: Vec<u64>,
    /// Whether this function never returns (see [`Function::noreturn`]).
    ///
    /// Defaults to `false` so rows written before noreturn tracking
    /// still decode.
    #[serde(default)]
    pub noreturn: bool,
}

impl Serialize for FunctionSummary {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        let mut st = serializer.serialize_struct("FunctionSummary", 8)?;
        st.serialize_field("id", &self.id)?;
        st.serialize_field("entry", &self.entry)?;
        st.serialize_field("entry_hex", &crate::addr_hex(self.entry))?;
        st.serialize_field("name", &self.name)?;
        st.serialize_field("blocks", &self.blocks)?;
        st.serialize_field("insns", &self.insns)?;
        st.serialize_field("calls", &self.calls)?;
        st.serialize_field("noreturn", &self.noreturn)?;
        st.end()
    }
}

/// One block row for list views (instructions come via [`Analysis::block_insns`]).
///
/// JSON pairs `start`/`end` with `start_hex`/`end_hex`; `succs` stays a
/// plain integer array.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct BlockSummary {
    /// Stable ID (`block@func+start`, both hex).
    pub id: String,
    /// Address of the first instruction.
    pub start: u64,
    /// End address (one past the last instruction's last byte).
    pub end: u64,
    /// Instruction count.
    pub insns: usize,
    /// Successor block starts.
    pub succs: Vec<u64>,
}

impl Serialize for BlockSummary {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        let mut st = serializer.serialize_struct("BlockSummary", 7)?;
        st.serialize_field("id", &self.id)?;
        st.serialize_field("start", &self.start)?;
        st.serialize_field("start_hex", &crate::addr_hex(self.start))?;
        st.serialize_field("end", &self.end)?;
        st.serialize_field("end_hex", &crate::addr_hex(self.end))?;
        st.serialize_field("insns", &self.insns)?;
        st.serialize_field("succs", &self.succs)?;
        st.end()
    }
}

fn truncate_limit(limit: usize) -> usize {
    limit.min(MAX_PAGE)
}

/// Filters for [`Analysis::strings_page_filtered`]: every present field must
/// match. Paging (`start`/`limit`) applies after filtering.
#[derive(Debug, Clone)]
pub struct StringsFilter {
    /// Case-sensitive substring, or `regex:`-prefixed expression; `None`
    /// disables. An explicit pattern also shows executable-memory hits.
    pub pattern: Option<String>,
    /// Keep strings with at least this many characters; `None` disables.
    /// Filters stored hits (extracted at length 4), so smaller values show
    /// everything stored.
    pub min_len: Option<usize>,
    /// Keep strings in exactly this section; `None` hides executable-memory
    /// hits instead of narrowing. Naming an executable section (e.g.
    /// `.text`) shows its strings.
    pub section: Option<String>,
    /// Show strings in executable memory (hidden by default).
    pub include_code: bool,
    /// Rows to skip after filtering (`start` replaces the old `offset`
    /// paging name, which collided with the per-row file offset).
    pub start: usize,
    /// Max rows (capped at [`MAX_PAGE`]).
    pub limit: usize,
}

impl Default for StringsFilter {
    fn default() -> Self {
        Self {
            pattern: None,
            min_len: None,
            section: None,
            include_code: false,
            start: 0,
            limit: 50,
        }
    }
}

fn page_slice<T: Clone>(items: &[T], offset: usize, limit: usize) -> Vec<T> {
    items
        .iter()
        .skip(offset)
        .take(truncate_limit(limit))
        .cloned()
        .collect()
}

/// Count a match stream while collecting one page: one pass, no intermediate
/// vector. `offset` skips that many matches, `cap` is the already-clipped
/// page size, so `limit == 0` still reports the exact count.
fn count_and_page(
    matches: impl Iterator<Item = Xref>,
    offset: usize,
    cap: usize,
) -> (usize, Vec<Xref>) {
    let mut total = 0usize;
    let mut page = Vec::new();
    for x in matches {
        if total >= offset && page.len() < cap {
            page.push(x);
        }
        total += 1;
    }
    (total, page)
}

impl Analysis {
    /// Counters over the whole result.
    #[must_use]
    pub fn summary(&self) -> AnalysisSummary {
        AnalysisSummary {
            functions: self.functions.len(),
            blocks: self.functions.values().map(|f| f.blocks.len()).sum(),
            insns: self.functions.values().map(|f| f.insn_count()).sum(),
            xrefs: self.xrefs.len(),
            strings: self.strings.len(),
        }
    }

    /// Function rows ordered by entry, paged.
    #[must_use]
    pub fn functions_page(&self, offset: usize, limit: usize) -> Vec<FunctionSummary> {
        self.functions
            .values()
            .skip(offset)
            .take(truncate_limit(limit))
            .map(|f| FunctionSummary {
                id: f.id(),
                entry: f.entry,
                name: f.name.clone(),
                blocks: f.blocks.len(),
                insns: f.insn_count(),
                calls: self.calls_of(f.entry),
                noreturn: f.noreturn,
            })
            .collect()
    }

    /// Block rows for one function ordered by start, paged.
    #[must_use]
    pub fn blocks_page(
        &self,
        func_entry: u64,
        offset: usize,
        limit: usize,
    ) -> Option<Vec<BlockSummary>> {
        let f = self.functions.get(&func_entry)?;
        Some(
            f.blocks
                .values()
                .skip(offset)
                .take(truncate_limit(limit))
                .map(|b| BlockSummary {
                    id: b.id(func_entry),
                    start: b.start,
                    end: b.end(),
                    insns: b.insns.len(),
                    succs: f.successors(b.start),
                })
                .collect(),
        )
    }

    /// Instructions of one block in address order, paged.
    #[must_use]
    pub fn block_insns(
        &self,
        func_entry: u64,
        block_start: u64,
        offset: usize,
        limit: usize,
    ) -> Option<Vec<Insn>> {
        let b = self.functions.get(&func_entry)?.blocks.get(&block_start)?;
        Some(page_slice(&b.insns, offset, limit))
    }

    /// Xrefs of one kind (or all when `kind` is `None`), paged.
    #[must_use]
    pub fn xrefs_page(&self, kind: Option<XrefKind>, offset: usize, limit: usize) -> Vec<Xref> {
        let cap = truncate_limit(limit);
        match kind {
            Some(k) => self
                .xrefs
                .iter()
                .copied()
                .filter(|x| x.kind == k)
                .skip(offset)
                .take(cap)
                .collect(),
            None => self.xrefs.iter().copied().skip(offset).take(cap).collect(),
        }
    }

    /// Positions into [`xrefs`](Self::xrefs) sorted by (`to`, `from`,
    /// `kind`), built once on first use.
    ///
    /// Repeated `to` queries and slices share this one build plus a binary
    /// search each instead of paying a linear scan per request.
    fn to_index(&self) -> &[u32] {
        self.to_index.get_or_init(|| {
            let mut idx: Vec<u32> = (0..self.xrefs.len()).map(|i| i as u32).collect();
            idx.sort_by_key(|&i| {
                let x = &self.xrefs[i as usize];
                (x.to, x.from, x.kind)
            });
            idx
        })
    }

    /// Half-open span of [`xrefs`](Self::xrefs) with `from == addr`, via
    /// binary search (rows are sorted `(from, kind, to)`).
    fn span_from(&self, addr: u64) -> (usize, usize) {
        let lo = self.xrefs.partition_point(|x| x.from < addr);
        let hi = self.xrefs.partition_point(|x| x.from <= addr);
        (lo, hi)
    }

    /// Half-open span of `idx` (see [`to_index`](Self::to_index)) whose rows
    /// point at `addr`.
    fn span_to(&self, idx: &[u32], addr: u64) -> (usize, usize) {
        let lo = idx.partition_point(|&i| self.xrefs[i as usize].to < addr);
        let hi = idx.partition_point(|&i| self.xrefs[i as usize].to <= addr);
        (lo, hi)
    }

    /// Xrefs pointing at `addr`, in `(from, kind)` order.
    ///
    /// Binary-searches the `to_index` span instead of
    /// scanning: for a fixed `to` the index order is `(from, kind)`, the
    /// same rows the old linear filter returned.
    #[must_use]
    pub fn xrefs_to(&self, addr: u64) -> Vec<Xref> {
        let idx = self.to_index();
        let (lo, hi) = self.span_to(idx, addr);
        idx[lo..hi]
            .iter()
            .map(|&i| self.xrefs[i as usize])
            .collect()
    }

    /// Xrefs originating at `addr`, in `(kind, to)` order.
    ///
    /// Binary-searches the `(from, kind, to)`-sorted rows instead of
    /// scanning; the span keeps storage order, as before.
    #[must_use]
    pub fn xrefs_from(&self, addr: u64) -> Vec<Xref> {
        let (lo, hi) = self.span_from(addr);
        self.xrefs[lo..hi].to_vec()
    }

    /// Xrefs matching the endpoint/kind filters with the pre-page count, in
    /// one pass.
    ///
    /// Rows come in storage order, as the old filter-then-page path
    /// reported: a `from` filter narrows to one binary-searched span, the
    /// unfiltered case scans, and a `to`-only filter walks the `to_index`
    /// span when it is already built (same row
    /// order for a fixed `to`) but falls back to one linear scan while it
    /// is cold — a single request does one lookup, which a scan answers
    /// faster than building the index, while slices and repeated lookups
    /// amortize the build. `limit` clips to [`MAX_PAGE`]; an `offset` past
    /// the end yields an empty page with the exact count.
    #[must_use]
    pub fn xrefs_matching_page(
        &self,
        to: Option<u64>,
        from: Option<u64>,
        kind: Option<XrefKind>,
        offset: usize,
        limit: usize,
    ) -> (usize, Vec<Xref>) {
        let cap = truncate_limit(limit);
        if let Some(f) = from {
            let (lo, hi) = self.span_from(f);
            return count_and_page(
                self.xrefs[lo..hi]
                    .iter()
                    .copied()
                    .filter(move |x| to.is_none_or(|t| x.to == t))
                    .filter(move |x| kind.is_none_or(|k| x.kind == k)),
                offset,
                cap,
            );
        }
        if let Some(t) = to {
            if let Some(idx) = self.to_index.get() {
                let (lo, hi) = self.span_to(idx, t);
                return count_and_page(
                    idx[lo..hi]
                        .iter()
                        .map(|&i| self.xrefs[i as usize])
                        .filter(move |x| kind.is_none_or(|k| x.kind == k)),
                    offset,
                    cap,
                );
            }
            return count_and_page(
                self.xrefs
                    .iter()
                    .copied()
                    .filter(|x| x.to == t)
                    .filter(move |x| kind.is_none_or(|k| x.kind == k)),
                offset,
                cap,
            );
        }
        count_and_page(
            self.xrefs
                .iter()
                .copied()
                .filter(move |x| kind.is_none_or(|k| x.kind == k)),
            offset,
            cap,
        )
    }

    /// Diagnostics filtered by kind and containing function, ordered by
    /// (`kind`, `addr`).
    ///
    /// Filtering precedes paging: callers page this exact set, so the
    /// reported total is the filtered count. `func` is an already-snapped
    /// function entry; sites whose
    /// [`Analysis::containing_function`] differs are dropped. Storage
    /// keeps `(addr, kind)` order; this re-sorts by `(kind, addr)` per
    /// the protocol-1 contract.
    #[must_use]
    pub fn diagnostics_matching(
        &self,
        kind: Option<DiagnosticKind>,
        func: Option<u64>,
    ) -> Vec<Diagnostic> {
        let mut out: Vec<Diagnostic> = self
            .diagnostics
            .records
            .iter()
            .copied()
            .filter(|d| kind.is_none_or(|k| d.kind == k))
            .filter(|d| func.is_none_or(|e| self.containing_function(d.addr) == Some(e)))
            .collect();
        out.sort_by_key(|d| (d.kind, d.addr));
        out
    }

    /// Extracted strings ordered by address, paged.
    ///
    /// Shows every hit, including executable-memory noise;
    /// [`Analysis::strings_page_filtered`] is the default-view query behind
    /// the CLI/MCP `strings` command.
    #[must_use]
    pub fn strings_page(&self, offset: usize, limit: usize) -> Vec<StringHit> {
        page_slice(&self.strings, offset, limit)
    }

    /// Extracted strings ordered by address, filtered then paged.
    ///
    /// Strings in executable memory (code bytes decoded as text) are hidden
    /// unless the query opts back in with [`StringsFilter::include_code`]
    /// or narrows with `section`/`pattern` — an explicit search sees
    /// everything. `section` is an exact name match, `min_len` counts
    /// characters, and `pattern` is a case-sensitive substring unless
    /// `regex:`-prefixed (see [`strings::matches_pattern`]).
    /// Filtering happens before paging so `start`/`limit` apply to dense
    /// matching rows.
    ///
    /// # Errors
    /// [`Error::Invalid`] when `pattern` is overlong or a `regex:`
    /// expression fails to compile.
    pub fn strings_page_filtered(&self, filter: &StringsFilter) -> Result<Vec<StringHit>> {
        filter_string_hits(&self.strings, filter)
    }

    /// Exact count of [`Analysis::strings_page_filtered`] matches, before
    /// paging. Lets agents learn the string count without paging to the
    /// end; the envelope reports this as `total`.
    ///
    /// # Errors
    /// Same as [`Analysis::strings_page_filtered`].
    pub fn strings_count_filtered(&self, filter: &StringsFilter) -> Result<usize> {
        count_string_hits(&self.strings, filter)
    }

    /// Decoded-view strings: re-extract over an in-memory decoded copy.
    ///
    /// Each segment's bytes are transformed with `decode` (see
    /// [`strings::DecodeSpec`]), then extracted and section-tagged exactly
    /// like [`analyze`], so single-byte XOR/add/rot- and rolling
    /// multi-byte XOR-obfuscated text shows up with its original offsets
    /// and virtual addresses. [`strings::DecodeSpec::Base64`] instead
    /// detects base64 blobs per segment (see [`strings::extract_base64`])
    /// and reports their plaintext. The same [`StringsFilter`] semantics
    /// apply to the decoded rows (a `pattern` matches decoded text).
    /// Strictly read-only: the binary and the sidecar are never written.
    ///
    /// # Errors
    /// [`Error::Invalid`] when `pattern` is overlong or a `regex:`
    /// expression fails to compile.
    pub fn strings_decoded_view(
        &self,
        bin: &LoadedBinary,
        filter: &StringsFilter,
        decode: strings::DecodeSpec,
    ) -> Result<Vec<StringHit>> {
        let hits = decoded_string_hits(bin, decode);
        filter_string_hits(&hits, filter)
    }

    /// Exact count of [`Analysis::strings_decoded_view`] matches.
    ///
    /// # Errors
    /// Same as [`Analysis::strings_decoded_view`].
    pub fn strings_decoded_count(
        &self,
        bin: &LoadedBinary,
        filter: &StringsFilter,
        decode: strings::DecodeSpec,
    ) -> Result<usize> {
        let hits = decoded_string_hits(bin, decode);
        count_string_hits(&hits, filter)
    }
}

/// Decoded-view hits over a per-segment decoded copy, section-tagged
/// exactly like [`analyze`].
///
/// Free of `self` (only the binary matters), so the loader-only open
/// serves `strings --decode` without a decoded analysis; the count and
/// the page agree on the underlying rows via the shared filter helpers.
pub(crate) fn decoded_string_hits(
    bin: &LoadedBinary,
    decode: strings::DecodeSpec,
) -> Vec<StringHit> {
    let mut hits: Vec<StringHit> = Vec::new();
    for seg in &bin.segments {
        // Base64 is detection, not a byte transform: scan the raw
        // segment for blobs instead of decoding a transformed copy.
        if matches!(decode, strings::DecodeSpec::Base64) {
            for mut h in strings::extract_base64(
                &seg.data,
                strings::DEFAULT_MIN_LEN,
                strings::DEFAULT_MAX_HITS,
                Some(seg.vaddr),
            ) {
                let (section, executable) = locate_hit(&bin.sections, seg, h.vaddr);
                h.section = section;
                h.executable = executable;
                hits.push(h);
            }
            continue;
        }
        let decoded = decode.apply(&seg.data);
        for mut h in strings::extract(
            &decoded,
            strings::DEFAULT_MIN_LEN,
            strings::DEFAULT_MAX_HITS,
            Some(seg.vaddr),
        ) {
            // Same tagging as `analyze`: sections win, raw blobs and
            // unmapped hits inherit the segment's flags.
            let (section, executable) = locate_hit(&bin.sections, seg, h.vaddr);
            h.section = section;
            h.executable = executable;
            hits.push(h);
        }
    }
    hits.sort_by_key(|h| h.vaddr.unwrap_or(u64::MAX));
    hits
}

/// Filter stored or decoded-view string hits, then page.
///
/// Shared by [`Analysis::strings_page_filtered`] and
/// [`Analysis::strings_decoded_view`] (plus the loader-only open, which
/// filters stored snapshot rows without a decoded analysis) so the
/// `strings --decode` view keeps the default-view semantics
/// (executable-memory hiding, lazy pattern compile, filter-before-page).
///
/// # Errors
/// [`Error::Invalid`] when `filter.pattern` is overlong or a `regex:`
/// expression fails to compile.
pub(crate) fn filter_string_hits(
    hits: &[StringHit],
    filter: &StringsFilter,
) -> Result<Vec<StringHit>> {
    let show_code = filter.include_code || filter.section.is_some() || filter.pattern.is_some();
    // Compiled once, lazily at the first row reaching pattern evaluation:
    // a malformed/overlong pattern errors only when a row survives the
    // earlier filters, and costs zero compilations otherwise.
    let mut matcher: Option<strings::PatternMatcher<'_>> = None;
    let cap = truncate_limit(filter.limit);
    let start = filter.start;
    let mut out: Vec<StringHit> = Vec::new();
    let mut matched: usize = 0;
    for h in hits {
        if h.executable && !show_code {
            continue;
        }
        if let Some(sec) = &filter.section
            && h.section.as_deref() != Some(sec.as_str())
        {
            continue;
        }
        if let Some(min) = filter.min_len
            && h.value.chars().count() < min
        {
            continue;
        }
        if let Some(pat) = &filter.pattern {
            if matcher.is_none() {
                matcher = Some(strings::PatternMatcher::compile(pat)?);
            }
            let Some(m) = matcher.as_ref() else {
                continue;
            };
            if !m.is_match(&h.value) {
                continue;
            }
        }
        // Storage-order match at dense index `matched`; clone only the
        // selected page. Comparisons stay split (`matched >= start` plus
        // `out.len() < cap`) so `start + cap` can never overflow.
        if matched >= start && out.len() < cap {
            out.push(h.clone());
        }
        matched += 1;
        // No future row can fail once the matcher outcome is settled, so
        // a filled page ends the scan. With an uncompiled pattern the
        // outcome is unset (no eligible row seen yet), and the scan must
        // continue: this keeps zero-limit/beyond-end error semantics
        // identical to the old collect-all pass.
        if out.len() >= cap && (filter.pattern.is_none() || matcher.is_some()) {
            break;
        }
    }
    Ok(out)
}

/// Exact count of [`filter_string_hits`] matches, before paging.
///
/// Mirrors the filter loop row-for-row (executable-memory hiding, section,
/// length, lazy pattern compile) without the page cap or the filled-page
/// early exit, so the count and the page agree on the match set and on
/// pattern error semantics.
///
/// # Errors
/// [`Error::Invalid`] when `filter.pattern` is overlong or a `regex:`
/// expression fails to compile.
pub(crate) fn count_string_hits(hits: &[StringHit], filter: &StringsFilter) -> Result<usize> {
    let show_code = filter.include_code || filter.section.is_some() || filter.pattern.is_some();
    // Compiled once, lazily at the first row reaching pattern evaluation:
    // a malformed/overlong pattern errors only when a row survives the
    // earlier filters, matching `filter_string_hits`.
    let mut matcher: Option<strings::PatternMatcher<'_>> = None;
    let mut matched: usize = 0;
    for h in hits {
        if h.executable && !show_code {
            continue;
        }
        if let Some(sec) = &filter.section
            && h.section.as_deref() != Some(sec.as_str())
        {
            continue;
        }
        if let Some(min) = filter.min_len
            && h.value.chars().count() < min
        {
            continue;
        }
        if let Some(pat) = &filter.pattern {
            if matcher.is_none() {
                matcher = Some(strings::PatternMatcher::compile(pat)?);
            }
            let Some(m) = matcher.as_ref() else {
                continue;
            };
            if !m.is_match(&h.value) {
                continue;
            }
        }
        matched += 1;
    }
    Ok(matched)
}

/// Control-flow effect of one instruction, from its M3 lift.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Flow {
    Seq,
    Branch { target: Option<u64> },
    CBranch { target: Option<u64> },
    Call { target: Option<u64> },
    Ret,
}

impl Flow {
    fn ends_block(self) -> bool {
        !matches!(self, Self::Seq)
    }
}

/// Control-flow effect of one instruction, without lifting (see
/// [`crate::ir::control_op`]). Matches `crate::ir::lift` restricted to
/// the control ops (see `control_op_matches_lift` in `tests/ir.rs`);
/// hot paths call this instead of lifting per instruction to skip the
/// IR allocation and the full mnemonic-table walk.
fn flow_of(arch: Arch, insn: &Insn) -> Flow {
    match crate::ir::control_op(arch, insn) {
        Some((IrOp::Branch, target)) => Flow::Branch { target },
        Some((IrOp::CBranch, target)) => Flow::CBranch { target },
        Some((IrOp::Call, target)) => Flow::Call { target },
        Some((IrOp::Return, _)) => Flow::Ret,
        _ => Flow::Seq,
    }
}

/// Control instruction of `block`: the last row, except on MIPS32 where a
/// block ends with its branch's delay slot (see Pass B), so the branch —
/// second-to-last — carries the control flow. A trailing sequential row
/// that is not a delay slot has a sequential predecessor as well, so the
/// fallback reads the same flow there.
fn block_control(arch: Arch, block: &BasicBlock) -> Option<&Insn> {
    let last = block.insns.last()?;
    if arch == Arch::Mips32 && block.insns.len() >= 2 && crate::ir::control_op(arch, last).is_none()
    {
        block.insns.get(block.insns.len() - 2)
    } else {
        Some(last)
    }
}

/// Whether `name` is a known-noreturn import: `exit`, `abort`, `_exit`,
/// `__assert_fail`, `__stack_chk_fail`, `ExitProcess`, and similar across
/// glibc, msvcrt, kernel32, and libSystem.
///
/// Exact names only, plus one stripped leading underscore for the Mach-O
/// `_`-prefix convention (`_exit` calls `exit`, `___stack_chk_fail` calls
/// `__stack_chk_fail`). Substrings never match: `myexit` is not `exit`.
fn is_noreturn_import(name: &str) -> bool {
    const NORETURN: &[&str] = &[
        "exit",
        "_exit",
        "_Exit",
        "abort",
        "quick_exit",
        "longjmp",
        "siglongjmp",
        "pthread_exit",
        "exit_group",
        "__assert_fail",
        "__assert_rtn",
        "__stack_chk_fail",
        "__fortify_fail",
        "_Unwind_Resume",
        "__cxa_throw",
        "__cxa_rethrow",
        "ExitProcess",
        "ExitThread",
        "TerminateProcess",
        "TerminateThread",
        "FatalExit",
        "os_fatal",
    ];
    if NORETURN.contains(&name) {
        return true;
    }
    name.strip_prefix('_')
        .is_some_and(|rest| NORETURN.contains(&rest))
}

/// Noreturn plan: which functions never return and which call
/// fall-throughs to cut (see [`plan_noreturn`]).
struct NoreturnPlan {
    /// Entries with no return-reachable exit.
    noreturn: BTreeSet<u64>,
    /// `(func, block)` call sites whose fall-through edge is cut.
    cuts: BTreeSet<(u64, u64)>,
}

/// Shared context for [`end_facts`]: the noreturn set under
/// consideration plus the maps that resolve exits.
struct EndCtx<'a> {
    noreturn: &'a BTreeSet<u64>,
    owner: &'a dyn Fn(u64) -> Option<u64>,
    code: &'a BTreeSet<u64>,
    apply_cuts: bool,
}

/// Successors of one block end under a noreturn set.
///
/// `blocks` is the containing function's block map; `last` is its last
/// instruction ending at `end` with `flow`. Returns `(succs, cut,
/// poison)`: `succs` holds the in-function block starts control may
/// reach next; `cut` marks a call whose fall-through is severed (its
/// target never returns); `poison` marks a possible return or an exit
/// through unknown code (a `Return`, an unresolved jump, a truncated
/// path, or a jump out to a function that may return).
///
/// Unknown exits poison rather than diverge: only positive evidence (a
/// noreturn call or a tail jump to a noreturn function) ends a path
/// silently. `apply_cuts` selects the cut graph (`true`) or the uncut
/// graph (`false`, for delta pruning); poison is reported either way.
fn end_facts(
    blocks: &BTreeMap<u64, BasicBlock>,
    last: &Insn,
    end: u64,
    flow: Flow,
    ctx: &EndCtx,
) -> (Vec<u64>, bool, bool) {
    match flow {
        Flow::Ret => (Vec::new(), false, true),
        Flow::Seq => {
            if blocks.contains_key(&end) {
                (vec![end], false, false)
            } else {
                (Vec::new(), false, true)
            }
        }
        Flow::Branch { target: None } => (Vec::new(), false, true),
        Flow::Branch { target: Some(t) } => {
            if blocks.contains_key(&t) {
                (vec![t], false, false)
            } else if ctx.code.contains(&t)
                && (ctx.owner)(t).is_some_and(|g| ctx.noreturn.contains(&g))
            {
                (Vec::new(), false, false)
            } else {
                (Vec::new(), false, true)
            }
        }
        Flow::CBranch { target } => {
            let mut succs = Vec::new();
            let mut poison = false;
            match target {
                Some(t) if blocks.contains_key(&t) => succs.push(t),
                Some(t)
                    if ctx.code.contains(&t)
                        && (ctx.owner)(t).is_some_and(|g| ctx.noreturn.contains(&g)) => {}
                _ => poison = true,
            }
            if blocks.contains_key(&end) {
                succs.push(end);
            } else {
                poison = true;
            }
            (succs, false, poison)
        }
        Flow::Call { target } => {
            let import_nr = last.import.as_deref().is_some_and(is_noreturn_import);
            let callee = target.filter(|t| ctx.code.contains(t)).and_then(ctx.owner);
            let cut = import_nr || callee.is_some_and(|g| ctx.noreturn.contains(&g));
            if cut && ctx.apply_cuts {
                (Vec::new(), true, false)
            } else if blocks.contains_key(&end) {
                (vec![end], cut, false)
            } else {
                (Vec::new(), cut, true)
            }
        }
    }
}

/// Blocks reachable from the entry over `func`'s blocks, following
/// [`end_facts`] successors plus `inferred` edges with or without
/// noreturn cuts, and whether any reached block end poisons (a possible
/// return or unknown exit; the prune pass ignores the flag).
fn walk_function(
    func: &Function,
    flows: &BTreeMap<(u64, u64), Flow>,
    inferred: &BTreeMap<u64, Vec<u64>>,
    noreturn: &BTreeSet<u64>,
    owner: &dyn Fn(u64) -> Option<u64>,
    code: &BTreeSet<u64>,
    apply_cuts: bool,
) -> (BTreeSet<u64>, bool) {
    let ctx = EndCtx {
        noreturn,
        owner,
        code,
        apply_cuts,
    };
    let mut seen = BTreeSet::new();
    let mut poison = false;
    let mut stack = vec![func.entry];
    while let Some(b) = stack.pop() {
        if !seen.insert(b) {
            continue;
        }
        let Some(block) = func.blocks.get(&b) else {
            continue;
        };
        let Some(last) = block.insns.last() else {
            continue;
        };
        let flow = flows[&(func.entry, b)];
        let (mut succs, _cut, poisoned) = end_facts(&func.blocks, last, block.end(), flow, &ctx);
        poison |= poisoned;
        if let Some(extra) = inferred.get(&b) {
            succs.extend(extra.iter().copied());
        }
        stack.extend(succs.into_iter().filter(|s| !seen.contains(s)));
    }
    (seen, poison)
}

/// Inferred block edges per function: entry to `from_block` to targets.
///
/// Shared by [`plan_noreturn`] and delta pruning so both follow the same
/// same-function resolutions.
fn inferred_map(functions: &BTreeMap<u64, Function>) -> BTreeMap<u64, BTreeMap<u64, Vec<u64>>> {
    let mut map: BTreeMap<u64, BTreeMap<u64, Vec<u64>>> = BTreeMap::new();
    for (e, f) in functions {
        for (a, b) in f.inferred_edges() {
            map.entry(*e).or_default().entry(a).or_default().push(b);
        }
    }
    map
}

/// Find functions that never return and the call fall-throughs to cut.
///
/// A function is noreturn when no path from its entry reaches a return
/// or an unknown exit; every terminating path instead ends in a call to
/// a noreturn target or a tail jump to one. `seeds` are import-stub
/// entries for known-noreturn imports (`exit@plt` and friends); direct
/// callers and tail jumps propagate to a fixpoint bounded by
/// [`MAX_NORETURN_ROUNDS`]. Anything unproven stays returning: a cut is
/// only ever added on positive evidence.
///
/// `flows` carries each block's end flow: stored walker flows in
/// [`analyze`], fresh lifts in [`rebuild`]. Both run this over the same
/// block ends, so fresh and cached analyses flag identically: pruning
/// only drops blocks no cut-graph path reaches, and verdicts only
/// consult cut-graph-reachable blocks.
fn plan_noreturn(
    functions: &BTreeMap<u64, Function>,
    flows: &BTreeMap<(u64, u64), Flow>,
    seeds: &BTreeSet<u64>,
) -> NoreturnPlan {
    let entries: Vec<u64> = functions.keys().copied().collect();
    let owner = |va: u64| function_owner(&entries, va);
    let code: BTreeSet<u64> = functions
        .values()
        .flat_map(|f| f.blocks.keys().copied())
        .collect();
    let inferred = inferred_map(functions);
    // Reverse callgraph for dirty propagation: callee to callers. Only
    // direct-target calls matter here; import-noreturn sites are static.
    let mut callers: BTreeMap<u64, BTreeSet<u64>> = BTreeMap::new();
    for (e, f) in functions {
        for (b, block) in &f.blocks {
            if !matches!(flows[&(*e, *b)], Flow::Call { .. }) {
                continue;
            }
            let target = block.insns.last().and_then(|i| i.branch_target);
            if let Some(t) = target.filter(|t| code.contains(t))
                && let Some(g) = owner(t)
            {
                callers.entry(g).or_default().insert(*e);
            }
        }
    }
    let mut noreturn: BTreeSet<u64> = seeds
        .iter()
        .copied()
        .filter(|e| functions.contains_key(e))
        .collect();
    let mut dirty: BTreeSet<u64> = functions.keys().copied().collect();
    for _ in 0..MAX_NORETURN_ROUNDS {
        let mut fresh = Vec::new();
        for &e in &dirty {
            if noreturn.contains(&e) {
                continue;
            }
            let f = &functions[&e];
            let empty: BTreeMap<u64, Vec<u64>> = BTreeMap::new();
            let inf = inferred.get(&e).unwrap_or(&empty);
            let (_, poison) = walk_function(f, flows, inf, &noreturn, &owner, &code, true);
            if !poison {
                fresh.push(e);
            }
        }
        if fresh.is_empty() {
            break;
        }
        dirty.clear();
        for e in fresh {
            noreturn.insert(e);
            if let Some(cs) = callers.get(&e) {
                dirty.extend(cs.iter().copied());
            }
        }
    }
    let ctx = EndCtx {
        noreturn: &noreturn,
        owner: &owner,
        code: &code,
        apply_cuts: true,
    };
    let mut cuts = BTreeSet::new();
    for (e, f) in functions {
        for (b, block) in &f.blocks {
            let Some(last) = block.insns.last() else {
                continue;
            };
            let (_, cut, _) = end_facts(&f.blocks, last, block.end(), flows[&(*e, *b)], &ctx);
            if cut {
                cuts.insert((*e, *b));
            }
        }
    }
    NoreturnPlan { noreturn, cuts }
}

/// Resolve a string hit's section name and executability.
///
/// The first section containing `vaddr` wins; hits outside every section
/// (raw blobs, which have no table) inherit their segment's flags, and
/// unmapped hits fail open as non-executable data.
fn locate_hit(sections: &[Section], seg: &Segment, vaddr: Option<u64>) -> (Option<String>, bool) {
    let Some(va) = vaddr else {
        return (None, false);
    };
    if let Some(sec) = sections
        .iter()
        .find(|s| va >= s.vaddr && va.wrapping_sub(s.vaddr) < s.size)
    {
        return (Some(sec.name.clone()), sec.executable);
    }
    (None, seg.executable)
}

/// Addressable view over loaded segments.
struct AddrSpace<'a> {
    exec: Vec<&'a Segment>,
    all: Vec<&'a Segment>,
    hints: &'a ArmHints,
}

impl<'a> AddrSpace<'a> {
    fn new(bin: &'a LoadedBinary) -> Self {
        let mut exec: Vec<&Segment> = bin.segments.iter().filter(|s| s.executable).collect();
        exec.sort_by_key(|s| s.vaddr);
        let mut all: Vec<&Segment> = bin.segments.iter().collect();
        all.sort_by_key(|s| s.vaddr);
        Self {
            exec,
            all,
            hints: &bin.arm_hints,
        }
    }

    fn seg_at(segs: &[&'a Segment], va: u64) -> Option<&'a Segment> {
        let idx = segs.partition_point(|s| s.vaddr <= va);
        segs.get(idx.checked_sub(1)?)
            .filter(|s| va.wrapping_sub(s.vaddr) < s.mem_size)
            .copied()
    }

    /// File-backed bytes at `va` within an executable segment, if any.
    fn code_bytes(&self, va: u64) -> Option<&'a [u8]> {
        let seg = Self::seg_at(&self.exec, va)?;
        let off = va.wrapping_sub(seg.vaddr) as usize;
        seg.data.get(off..)
    }

    /// Exactly `len` file-backed bytes at `va` within a single segment, if
    /// any.
    ///
    /// Data slots live outside executable segments, so unlike
    /// [`AddrSpace::code_bytes`] every segment is eligible; unlike
    /// `bytes_at` this never zero-pads. BSS/zero-fill tails, truncated
    /// tables, and cross-segment spans report `None` so the single-slot
    /// resolver rejects them instead of reading phantom bytes.
    fn file_bytes_at(&self, va: u64, len: usize) -> Option<&'a [u8]> {
        for seg in &self.all {
            let Some(off) = va.checked_sub(seg.vaddr) else {
                continue;
            };
            let Ok(off) = usize::try_from(off) else {
                continue;
            };
            let Some(end) = off.checked_add(len) else {
                continue;
            };
            if end <= seg.data.len() {
                return seg.data.get(off..end);
            }
        }
        None
    }

    /// Whether `va` lies in any loaded segment (backed or zero-fill).
    fn contains(&self, va: u64) -> bool {
        Self::seg_at(&self.all, va).is_some()
    }

    fn first_exec_base(&self) -> Option<u64> {
        self.exec.iter().map(|s| s.vaddr).min()
    }
}

/// Decode the single instruction at `va`.
///
/// Returns `None` when `va` has no executable bytes or they do not decode;
/// undecodable bytes end that path, they are not an error. Decodes only the
/// first instruction via [`crate::disasm::disasm_first`]: trailing bytes
/// cannot change the first decode, so no shrink-and-retry window over the
/// whole executable tail is needed.
fn decode_one(arch: Arch, space: &AddrSpace, va: u64) -> Result<Option<Insn>> {
    let bytes = match space.code_bytes(va) {
        Some(b) if !b.is_empty() => b,
        _ => return Ok(None),
    };
    match crate::disasm::disasm_first(arch, bytes, va) {
        Ok(v) => Ok(v),
        Err(Error::Invalid(_)) => Ok(None),
        Err(e) => Err(e),
    }
}

struct Decoded {
    insn: Insn,
    flow: Flow,
    /// Disassembler target this address decoded with: the project arch,
    /// a Thumb-mode ARM seed, a mode-switch edge target, or a user seed's
    /// explicit [`SeedMode`] propagated along its walk.
    arch: Arch,
}

/// Normalize a seed address for `arch`, clearing the ARM Thumb
/// interworking bit.
///
/// On ARM ELF, `e_entry` and `STT_FUNC` values carry bit 0 set for Thumb
/// functions, but ARM containers decode as [`Arch::Arm32`]: an odd seed
/// would read misaligned garbage. Returns the (possibly masked) address
/// plus whether the bit was set; [`arm_seed`] turns a set bit into a
/// Thumb-mode seed.
fn normalize_arm_seed(arch: Arch, addr: u64) -> (u64, bool) {
    if arch == Arch::Arm32 && addr & 1 == 1 {
        (addr & !1, true)
    } else {
        (addr, false)
    }
}

/// Whether `va` lies in one of the sorted `(start, end)` mapping `ranges`.
fn range_contains(ranges: &[(u64, u64)], va: u64) -> bool {
    let idx = ranges.partition_point(|(start, _)| *start <= va);
    idx.checked_sub(1).is_some_and(|i| va < ranges[i].1)
}

/// Canonical address plus decode mode for one ARM seed.
///
/// The Thumb bit (bit 0), a loader Thumb-function mark, or a `$t`
/// mapping range selects [`Arch::Thumb`]; anything else keeps the project
/// arch. Non-ARM projects pass through unchanged.
fn arm_seed(bin: &LoadedBinary, addr: u64) -> (u64, Arch) {
    if bin.arch != Arch::Arm32 {
        return (addr, bin.arch);
    }
    let (canon, bit) = normalize_arm_seed(bin.arch, addr);
    let thumb = bit
        || bin.arm_hints.thumb_seeds.binary_search(&canon).is_ok()
        || range_contains(&bin.arm_hints.thumb_ranges, canon);
    (canon, if thumb { Arch::Thumb } else { bin.arch })
}

/// Mode of the mapping range starting exactly at `va`, if any.
///
/// Linear fallthrough never changes mode (see [`Walker::run`]): when the
/// next address opens a range of the other mode, that range has its own
/// seed and the path stops here instead of decoding Thumb bytes as ARM
/// (or vice versa).
fn range_start_mode(hints: &ArmHints, va: u64) -> Option<Arch> {
    if hints
        .thumb_ranges
        .binary_search_by_key(&va, |(start, _)| *start)
        .is_ok()
    {
        Some(Arch::Thumb)
    } else if hints
        .arm_ranges
        .binary_search_by_key(&va, |(start, _)| *start)
        .is_ok()
    {
        Some(Arch::Arm32)
    } else {
        None
    }
}

/// Aligned pointer-scan seeds: pointer-sized values in non-executable
/// data landing on decodable executable code.
///
/// Scans every non-executable segment at VA-aligned pointer strides (8
/// bytes on 64-bit targets, 4 otherwise), reading little-endian values.
/// A value seeds only when it lies in executable file-backed bytes that
/// decode via [`crate::disasm::disasm_first`]. Zeroes, unmapped targets,
/// and undecodable targets are skipped, never guessed. Output is sorted,
/// deduplicated, and stops at [`MAX_POINTER_SEEDS`].
///
/// Lower confidence than table-derived seeds (vtables and callback tables
/// share the shape with stray pointers), so callers gate it behind
/// [`AnalyzeOptions::pointer_scan`].
fn pointer_seeds(space: &AddrSpace, bin: &LoadedBinary) -> Vec<(u64, Arch)> {
    let ptr: usize = match bin.arch {
        Arch::X86_64 | Arch::Aarch64 | Arch::Riscv64 | Arch::Ppc64 => 8,
        _ => 4,
    };
    let mut out: Vec<(u64, Arch)> = Vec::new();
    for seg in &space.all {
        if seg.executable || seg.data.is_empty() {
            continue;
        }
        let misalign = (seg.vaddr % ptr as u64) as usize;
        let mut off = if misalign == 0 { 0 } else { ptr - misalign };
        while off.saturating_add(ptr) <= seg.data.len() {
            if out.len() >= MAX_POINTER_SEEDS {
                break;
            }
            let raw = &seg.data[off..off + ptr];
            let target: u64 = if ptr == 8 {
                u64::from_le_bytes(raw.try_into().unwrap_or([0; 8]))
            } else {
                u64::from(u32::from_le_bytes(raw.try_into().unwrap_or([0; 4])))
            };
            off += ptr;
            if target == 0 {
                continue;
            }
            // A set Thumb bit selects Thumb decode first (ARM vtables hold
            // odd function pointers); anything else decodes as the project
            // arch. The first mode that decodes wins.
            let (canon, bit) = normalize_arm_seed(bin.arch, target);
            if canon == 0 {
                continue;
            }
            let modes: &[Arch] = if bit {
                &[Arch::Thumb, Arch::Arm32]
            } else {
                &[bin.arch]
            };
            let Some(bytes) = space.code_bytes(canon) else {
                continue;
            };
            for mode in modes {
                if matches!(
                    crate::disasm::disasm_first(*mode, bytes, canon),
                    Ok(Some(_))
                ) {
                    out.push((canon, *mode));
                    break;
                }
            }
        }
        if out.len() >= MAX_POINTER_SEEDS {
            break;
        }
    }
    out.sort_by_key(|(a, _)| *a);
    out.dedup();
    out.truncate(MAX_POINTER_SEEDS);
    out
}

// Mach-O header symbols mark the mach_header, not code.
const MACHO_HEADER_SYMBOLS: &[&str] = &[
    "__mh_execute_header",
    "__mh_dylib_header",
    "__mh_bundle_header",
    "__mh_dylinker_header",
    "__mh_object_header",
    "__mh_preload_header",
];

/// Seed addresses from the entry point, exports, symbol-table entries,
/// ARM mapping ranges, Mach-O stub entries, `.pdata`/`TLS`/init/
/// `LC_FUNCTION_STARTS` tables, and optional pointer-scan hits resolving
/// to executable code, plus user seeds from `define-func`. When none
/// exists (raw blobs, stripped objects), the first executable byte seeds
/// analysis so some function is always found.
///
/// Every seed carries its decode mode: the project arch, or Thumb on
/// 32-bit ARM when the seed's Thumb bit is set, a loader Thumb-function
/// mark names it, or a `$t` mapping range covers it (see [`arm_seed`]).
/// Mapping range starts seed their own mode so interworking boundaries
/// decode correctly even when nothing calls them. Same-address seeds
/// under different arches both queue; the walk decodes first-wins from a
/// stably address-sorted stack, so an explicit user mode wins over the
/// project-arch seed.
///
/// User seeds carry an explicit [`SeedMode`] instead: `Thumb` decodes as
/// Thumb (bit cleared), `Arm` masks to ARM. Modes only apply on 32-bit
/// ARM; elsewhere the project arch decodes (the project boundary rejects
/// modes there, so this is a backstop for direct API use, never a silent
/// success).
///
/// Table seeds (`.pdata` starts, TLS callbacks, ELF init/fini,
/// `LC_FUNCTION_STARTS`) are authoritative and always on; pointer-scan
/// hits join only when `options.pointer_scan` holds.
fn authoritative_seeds(
    space: &AddrSpace,
    bin: &LoadedBinary,
    user: &[UserSeed],
    options: AnalyzeOptions,
) -> (Vec<(u64, Arch)>, Vec<Diagnostic>) {
    let mut seeds: Vec<(u64, Arch)> = Vec::new();
    let push = |seeds: &mut Vec<(u64, Arch)>, addr: u64, arch: Arch| {
        if seeds.len() < MAX_SEEDS && space.code_bytes(addr).is_some() {
            seeds.push((addr, arch));
        }
    };
    if let Some(entry) = bin.entry {
        let (addr, mode) = arm_seed(bin, entry);
        push(&mut seeds, addr, mode);
    }
    for exp in &bin.exports {
        if bin.format == BinaryFormat::MachO && MACHO_HEADER_SYMBOLS.contains(&exp.name.as_str()) {
            continue;
        }
        if let Some(addr) = exp.address {
            let (addr, mode) = arm_seed(bin, addr);
            push(&mut seeds, addr, mode);
        }
    }
    // Symbol-table code addresses (locals included): the only seed path
    // for static functions nothing calls. Loader-canonical already
    // (Thumb bit cleared); the mode still comes from the bit and the
    // loader's Thumb-function marks (see `arm_seed`).
    for sym in &bin.symbols {
        if bin.format == BinaryFormat::MachO && MACHO_HEADER_SYMBOLS.contains(&sym.name.as_str()) {
            continue;
        }
        let (addr, mode) = arm_seed(bin, sym.address);
        push(&mut seeds, addr, mode);
    }
    // Mapping ranges: each region start seeds its own mode.
    for (start, _) in &bin.arm_hints.thumb_ranges {
        push(&mut seeds, *start, Arch::Thumb);
    }
    for (start, _) in &bin.arm_hints.arm_ranges {
        push(&mut seeds, *start, bin.arch);
    }
    // PE `.pdata` starts: exact starts for every non-leaf function.
    for (start, _) in &bin.pdata_funcs {
        let (addr, mode) = arm_seed(bin, *start);
        push(&mut seeds, addr, mode);
    }
    // PE TLS callbacks: malware anti-debug entry points.
    for addr in &bin.tls_callbacks {
        let (addr, mode) = arm_seed(bin, *addr);
        push(&mut seeds, addr, mode);
    }
    // ELF init/fini addresses: constructors and destructors nothing calls.
    for addr in &bin.init_funcs {
        let (addr, mode) = arm_seed(bin, *addr);
        push(&mut seeds, addr, mode);
    }
    // Mach-O `LC_FUNCTION_STARTS`: exact starts off the `__TEXT` base.
    for addr in &bin.func_starts {
        let (addr, mode) = arm_seed(bin, *addr);
        push(&mut seeds, addr, mode);
    }
    // Debug info (DWARF subprograms, PDB publics/procedures): exact
    // compiler-emitted starts.
    for f in &bin.debug_funcs {
        let (addr, mode) = arm_seed(bin, f.address);
        push(&mut seeds, addr, mode);
    }
    // Pointer scan (opt-in): aligned data pointers to decodable code.
    if options.pointer_scan {
        for (addr, mode) in pointer_seeds(space, bin) {
            if seeds.len() >= MAX_SEEDS {
                break;
            }
            push(&mut seeds, addr, mode);
        }
    }
    // Mach-O stub entries carry their import's address (see
    // `LoadedBinary.imports`): seeding them makes each stub its own
    // function even when no call targets it. Unmapped imports
    // (`address: None`) contribute nothing. PE/ELF addresses are data
    // slots, never code, so they must not seed.
    if bin.format == BinaryFormat::MachO {
        for imp in &bin.imports {
            if let Some(addr) = imp.address {
                push(&mut seeds, addr, bin.arch);
            }
        }
    }
    if seeds.is_empty()
        && let Some(base) = space.first_exec_base()
    {
        seeds.push((base, bin.arch));
    }
    seeds.sort_by_key(|(a, _)| *a);
    seeds.dedup();
    // User seeds join the authoritative set with their explicit decode
    // mode: an agent assertion that there is code at an address the
    // loader never seeded (shellcode, firmware vectors, obfuscated code,
    // missed callbacks). Modes only apply on 32-bit ARM; elsewhere the
    // project arch decodes (the project boundary rejects modes there, so
    // this is a backstop for direct API use, never a silent success).
    let mixed = matches!(bin.arch, Arch::Arm32 | Arch::Thumb);
    for s in user {
        if seeds.len() >= MAX_SEEDS {
            break;
        }
        let seed_arch = match (mixed, s.mode) {
            (true, Some(m)) => m.arch(),
            _ => bin.arch,
        };
        let addr = match (bin.arch, s.mode) {
            (Arch::Arm32, Some(SeedMode::Thumb)) => s.addr & !1,
            (Arch::Arm32, _) => normalize_arm_seed(bin.arch, s.addr).0,
            _ => s.addr,
        };
        if space.code_bytes(addr).is_none() {
            continue;
        }
        seeds.push((addr, seed_arch));
    }
    seeds.sort_by_key(|(a, _)| *a);
    seeds.dedup();
    (seeds, Vec::new())
}

/// Prologue-scan hits outside `reached` that decode. These seed the second
/// round and become entries; hits inside already-reached code stay plain code
/// so mid-function frame setups never split their function.
///
/// Candidates stream in ascending address order through a bounded k-way
/// merge over the executable segments (see [`CandStream`]): only the heap
/// (one entry per segment), the last address, and the accepted seeds are
/// stored, so dense prologue runs cannot inflate collection memory.
/// Rejected candidates (reached or undecodable) consume no budget: the
/// emitted seeds equal the sorted, deduped, filtered prefix the old
/// collect-all pass produced. x86 inputs past the budget previously stopped
/// in collection order; they now stop in the same sorted order as
/// below-budget inputs.
fn prologue_seeds(
    arch: Arch,
    space: &AddrSpace,
    is_reached: impl Fn(u64) -> bool,
) -> Result<Vec<u64>> {
    let mut streams: Vec<CandStream<'_>> = space
        .exec
        .iter()
        .map(|seg| CandStream::new(seg, arch))
        .collect();
    let mut heap: BinaryHeap<(Reverse<u64>, usize)> = BinaryHeap::with_capacity(streams.len());
    for (idx, stream) in streams.iter_mut().enumerate() {
        if let Some(va) = stream.next_candidate() {
            heap.push((Reverse(va), idx));
        }
    }
    let mut seeds: Vec<u64> = Vec::new();
    let mut last: Option<u64> = None;
    while seeds.len() < MAX_SEEDS {
        let Some((Reverse(va), idx)) = heap.pop() else {
            break;
        };
        if let Some(nxt) = streams[idx].next_candidate() {
            heap.push((Reverse(nxt), idx));
        }
        if last == Some(va) {
            continue;
        }
        last = Some(va);
        if !is_reached(va) && decode_one(arch, space, va)?.is_some() {
            seeds.push(va);
        }
    }
    Ok(seeds)
}

/// Multi-byte prologue patterns per architecture. Bare single-byte pushes are
/// deliberately excluded: they fire mid-function and would split functions at
/// every frame setup. `0x55`-led frames are still found via the following
/// `mov rbp, rsp`, adjusted back one byte.
fn prologue_patterns(arch: Arch) -> &'static [&'static [u8]] {
    match arch {
        Arch::X86_64 => &[
            &[0x48, 0x89, 0xE5],
            &[0x48, 0x83, 0xEC],
            &[0x48, 0x81, 0xEC],
            &[0xF3, 0x0F, 0x1E, 0xFA],
        ],
        Arch::X86_32 => &[&[0x89, 0xE5], &[0x83, 0xEC], &[0x81, 0xEC]],
        Arch::Aarch64
        | Arch::Arm32
        | Arch::Thumb
        | Arch::Riscv32
        | Arch::Riscv64
        | Arch::Mips32
        | Arch::Ppc32
        | Arch::Ppc64 => &[],
    }
}

/// How one [`CandStream`] recognizes a prologue at a byte offset.
#[derive(Debug, Clone, Copy)]
enum CandMatch {
    /// AArch64 `stp x29, x30, [sp, #imm]!` word under a mask.
    Aarch64,
    /// ARM32 `stmdb sp!, {..., lr}` word under a mask (any condition,
    /// including never-executed ones the decoder rejects).
    ArmPush,
    /// Thumb 16-bit `push {..., lr}` halfword, else the 32-bit ARM-form
    /// word, at halfword steps.
    Thumb,
    /// RISC-V `addi sp, sp, <imm>` word under a mask, else the
    /// `c.addi16sp` halfword (nonzero immediate), at halfword steps.
    Riscv,
    /// MIPS32 `addiu sp, sp, <imm>` word under a mask, at word steps.
    Mips,
    /// PowerPC `stwu rS, <imm>(r1)` big-endian word under a mask, at word
    /// steps (any source register; the base is always the stack pointer).
    Ppc,
    /// x86 byte patterns with a one-byte `push rbp`/`push ebp` step-back.
    X86,
}

/// Next offset at or after `from` (below `limit`) holding a possible x86
/// prologue first byte: `0x48`/`0xF3` on x86-64, `0x89`/`0x83`/`0x81` on
/// x86-32 (see [`prologue_patterns`]). SIMD scan via `memchr`; every
/// [`CandStream::match_at`] hit starts with one of these bytes, so skipped
/// offsets cannot match and the yielded candidates are unchanged.
fn next_x86_first_byte(arch: Arch, data: &[u8], from: usize, limit: usize) -> Option<usize> {
    let hay = data.get(from..limit)?;
    let rel = match arch {
        Arch::X86_64 => memchr2(0x48, 0xF3, hay)?,
        Arch::X86_32 => memchr3(0x89, 0x83, 0x81, hay)?,
        Arch::Aarch64
        | Arch::Arm32
        | Arch::Thumb
        | Arch::Riscv32
        | Arch::Riscv64
        | Arch::Mips32
        | Arch::Ppc32
        | Arch::Ppc64 => {
            return None;
        }
    };
    Some(from + rel)
}

/// One executable segment's prologue candidates in ascending address order.
///
/// Streams pattern matches without materializing them: offsets are visited
/// in the order their wrapped addresses sort, so merging streams with a
/// min-heap reproduces the old collect-sort-dedup order. Each address maps
/// as `vaddr.wrapping_add(offset)` (x86 additionally `wrapping_sub(1)` over
/// a leading `0x55`); offsets at or past `2^64 - vaddr` wrap low and sort
/// first, so iteration runs in two phases split at that boundary. Holds
/// only a cursor plus at most one deferred x86 edge address.
struct CandStream<'a> {
    data: &'a [u8],
    vaddr: u64,
    arch: Arch,
    kind: CandMatch,
    stride: usize,
    min_width: usize,
    split: usize,
    cur: usize,
    phase: u8,
    stash: Option<u64>,
}

impl<'a> CandStream<'a> {
    /// Stream over `seg`'s matches for `arch`, starting at the lowest
    /// sorting address.
    fn new(seg: &'a Segment, arch: Arch) -> Self {
        let (kind, stride, min_width) = match arch {
            Arch::Aarch64 => (CandMatch::Aarch64, 4, 4),
            Arch::Arm32 => (CandMatch::ArmPush, 4, 4),
            Arch::Thumb => (CandMatch::Thumb, 2, 2),
            Arch::Riscv32 | Arch::Riscv64 => (CandMatch::Riscv, 2, 2),
            Arch::Mips32 => (CandMatch::Mips, 4, 4),
            Arch::Ppc32 | Arch::Ppc64 => (CandMatch::Ppc, 4, 4),
            Arch::X86_64 | Arch::X86_32 => (CandMatch::X86, 1, 2),
        };
        let len = seg.data.len();
        // First offset whose wrapped address sorts low (`0` when `vaddr`
        // is `0`: no wrap, everything sorts in offset order).
        let wrap_off = u64::MAX.wrapping_sub(seg.vaddr).wrapping_add(1);
        let split = (wrap_off.min(len as u64) as usize)
            .div_ceil(stride)
            .saturating_mul(stride)
            .min(len);
        Self {
            data: &seg.data,
            vaddr: seg.vaddr,
            arch,
            kind,
            stride,
            min_width,
            split,
            cur: split,
            phase: 0,
            stash: None,
        }
    }

    /// Next candidate address in ascending order, if any.
    fn next_candidate(&mut self) -> Option<u64> {
        loop {
            if self.phase == 0 {
                if self.cur >= self.data.len() {
                    self.phase = 1;
                    self.cur = 0;
                    continue;
                }
                let off = if matches!(self.kind, CandMatch::X86) {
                    let Some(hit) =
                        next_x86_first_byte(self.arch, self.data, self.cur, self.data.len())
                    else {
                        self.cur = self.data.len();
                        continue;
                    };
                    self.cur = hit + 1;
                    hit
                } else {
                    let off = self.cur;
                    self.cur += self.stride;
                    off
                };
                if off + self.min_width > self.data.len() {
                    self.cur = self.data.len();
                    continue;
                }
                if let Some(va) = self.match_at(off) {
                    // An x86 step-back exactly on the wrap point lands on
                    // `u64::MAX`, which sorts after the high run: defer it
                    // past phase 1. Only x86 adjusts, so other kinds never
                    // take this branch.
                    if matches!(self.kind, CandMatch::X86)
                        && va == u64::MAX
                        && self.vaddr.wrapping_add(off as u64) == 0
                    {
                        self.stash = Some(va);
                        continue;
                    }
                    return Some(va);
                }
            } else if self.phase == 1 {
                if self.cur >= self.split {
                    self.phase = 2;
                    continue;
                }
                let off = if matches!(self.kind, CandMatch::X86) {
                    let Some(hit) = next_x86_first_byte(self.arch, self.data, self.cur, self.split)
                    else {
                        self.cur = self.split;
                        continue;
                    };
                    self.cur = hit + 1;
                    hit
                } else {
                    let off = self.cur;
                    self.cur += self.stride;
                    off
                };
                if off + self.min_width > self.data.len() {
                    self.cur = self.split;
                    continue;
                }
                if let Some(va) = self.match_at(off) {
                    return Some(va);
                }
            } else {
                return self.stash.take();
            }
        }
    }

    /// Candidate address at `off`, if the bytes match. Bounds-checked per
    /// pattern; mirrors the old eager scan's match rules exactly.
    fn match_at(&self, off: usize) -> Option<u64> {
        let va = self.vaddr.wrapping_add(off as u64);
        match self.kind {
            CandMatch::Aarch64 => {
                let raw = self.data.get(off..off + 4)?;
                let w = u32::from_le_bytes(raw.try_into().ok()?);
                ((w & 0xFFC0_7FFF) == 0xA980_7BFD).then_some(va)
            }
            CandMatch::ArmPush => {
                let raw = self.data.get(off..off + 4)?;
                let w = u32::from_le_bytes(raw.try_into().ok()?);
                is_arm_push_lr(w).then_some(va)
            }
            CandMatch::Thumb => {
                let raw = self.data.get(off..off + 2)?;
                let hw = u16::from_le_bytes(raw.try_into().ok()?);
                if (hw & 0xFF00) == 0xB500 && (hw & 0x0100) != 0 {
                    Some(va)
                } else if off + 4 <= self.data.len() {
                    let raw = self.data.get(off..off + 4)?;
                    let w = u32::from_le_bytes(raw.try_into().ok()?);
                    is_arm_push_lr(w).then_some(va)
                } else {
                    None
                }
            }
            CandMatch::Riscv => {
                let raw = self.data.get(off..off + 2)?;
                let hw = u16::from_le_bytes(raw.try_into().ok()?);
                if is_riscv_c_addi16sp(hw) {
                    Some(va)
                } else if off + 4 <= self.data.len() {
                    let raw = self.data.get(off..off + 4)?;
                    let w = u32::from_le_bytes(raw.try_into().ok()?);
                    is_riscv_addi_sp(w).then_some(va)
                } else {
                    None
                }
            }
            CandMatch::Mips => {
                let raw = self.data.get(off..off + 4)?;
                let w = u32::from_le_bytes(raw.try_into().ok()?);
                is_mips_addiu_sp(w).then_some(va)
            }
            CandMatch::X86 => {
                for pat in prologue_patterns(self.arch) {
                    let Some(win) = self.data.get(off..off + pat.len()) else {
                        continue;
                    };
                    if win == *pat {
                        // `push rbp`/`push ebp` is 0x55 on both x86 targets.
                        if off > 0 && self.data[off - 1] == 0x55 {
                            return Some(va.wrapping_sub(1));
                        }
                        return Some(va);
                    }
                }
                None
            }
            CandMatch::Ppc => {
                let raw = self.data.get(off..off + 4)?;
                let w = u32::from_be_bytes(raw.try_into().ok()?);
                is_ppc_stwu_sp(w).then_some(va)
            }
        }
    }
}

/// Whether a word is `stmdb sp!, {..., lr}` (any condition): the ARM32
/// frame-setup push, also valid as the 32-bit Thumb `push` encoding.
fn is_arm_push_lr(word: u32) -> bool {
    (word & 0x0FFF_4000) == 0x092D_4000
}

/// Whether a word is RISC-V `addi sp, sp, <imm>` for any 12-bit immediate:
/// the standard frame-setup prologue. The low 20 bits are fixed (rs1 and
/// rd both `sp`, `funct3` zero, `OP-IMM` opcode); the immediate rides in
/// the high 12.
fn is_riscv_addi_sp(word: u32) -> bool {
    word & 0x000F_FFFF == 0x0001_0113
}

/// Whether a halfword is RISC-V `c.addi16sp <nzimm>` with a nonzero
/// 16-aligned immediate: the compressed frame-setup prologue. The
/// all-zero immediate is the reserved encoding, never a prologue.
fn is_riscv_c_addi16sp(hw: u16) -> bool {
    hw & 0xEF83 == 0x6101 && hw & 0x107C != 0
}

/// Whether a word is MIPS32 `addiu sp, sp, <imm>` for any 16-bit
/// immediate: the standard frame-setup prologue. The high 16 bits are
/// fixed (opcode `addiu`, rs and rt both `sp`); the immediate rides in
/// the low 16.
fn is_mips_addiu_sp(word: u32) -> bool {
    word & 0xFFFF_0000 == 0x27BD_0000
}

/// Whether a big-endian word is PowerPC `stwu rS, <imm>(r1)` for any
/// source register and any 16-bit immediate: the standard frame-setup
/// prologue (store with update off the stack pointer `r1`). The opcode
/// (`stwu`) and base register (`r1`) are fixed; the source register and
/// immediate ride in the remaining fields.
fn is_ppc_stwu_sp(word: u32) -> bool {
    word & 0xFC1F_0000 == 0x9401_0000
}

/// Recursive-descent worklist state shared across seed rounds.
///
/// The project arch rides on each queued seed (see [`Walker::run`]), so
/// the walker itself holds no arch: mixed-mode walks decode each address
/// with its own seed's arch.
struct Walker<'a> {
    space: &'a AddrSpace<'a>,
    decoded: BTreeMap<u64, Decoded>,
    jump_targets: BTreeSet<u64>,
    fallthroughs: BTreeSet<u64>,
    call_targets: BTreeSet<u64>,
    /// Mode-switch edge targets: direct `blx` immediates and resolved
    /// `bx`-register constants land in the other state, so they start
    /// their own function (see [`Walker::run`]). Without this, one
    /// function would span both modes and snapshot rebuild — which
    /// re-decodes each function under its entry arch — would mis-decode
    /// the switched rows.
    switch_targets: BTreeSet<u64>,
    diagnostics: BTreeSet<Diagnostic>,
    /// Remaining predicated slots in the open Thumb IT block, with the
    /// address expecting the next one. The single-instruction decoder is
    /// stateless, so the worklist carries the IT state instead; the address
    /// check keeps stale state from predicating unrelated decodes when the
    /// worklist visits out of linear order (a branch into an IT block then
    /// fails open to the old stateless decode).
    it_remaining: u8,
    it_next: Option<u64>,
    /// Last two decoded instructions, for the `bx`-register constant
    /// chain (see [`Walker::bx_const_target`]). Updated on every
    /// successful decode; adjacency guards keep interleaved worklist
    /// paths from fusing unrelated rows.
    prev: Option<Insn>,
    prev_prev: Option<Insn>,
}

impl<'a> Walker<'a> {
    fn new(space: &'a AddrSpace<'a>) -> Self {
        Self {
            space,
            decoded: BTreeMap::new(),
            jump_targets: BTreeSet::new(),
            fallthroughs: BTreeSet::new(),
            call_targets: BTreeSet::new(),
            switch_targets: BTreeSet::new(),
            diagnostics: BTreeSet::new(),
            it_remaining: 0,
            it_next: None,
            prev: None,
            prev_prev: None,
        }
    }

    /// Constant and mode of a `bx reg` interworking branch, if the two
    /// linearly-adjacent predecessors materialize the register via
    /// `movw`/`movt` (see [`resolve_movw_pair`]).
    ///
    /// Bit 0 of the constant selects the mode (set is Thumb), the way a
    /// hardware `bx` does; the masked address must hold executable bytes.
    /// Predicated rows never resolve here (callers gate on the IT state),
    /// and anything but an adjacent `movw`/`movt`-then-`bx` triple returns
    /// `None`: register sources, gaps, and mismatched destinations stay
    /// unresolved indirect jumps.
    fn bx_const_target(&self, insn: &Insn) -> Option<(u64, Arch)> {
        let reg = insn.ops.first()?;
        let (prev, prev_prev) = (self.prev.as_ref()?, self.prev_prev.as_ref()?);
        if prev.addr.wrapping_add(u64::from(prev.size)) != insn.addr {
            return None;
        }
        if prev_prev.addr.wrapping_add(u64::from(prev_prev.size)) != prev.addr {
            return None;
        }
        let value = resolve_movw_pair(prev_prev, prev)?;
        if prev.ops.first()? != reg {
            return None;
        }
        self.space.code_bytes(value & !1)?;
        let mode = if value & 1 == 1 {
            Arch::Thumb
        } else {
            Arch::Arm32
        };
        Some((value & !1, mode))
    }

    /// Queue a fallthrough edge, stopping at interworking boundaries.
    ///
    /// A linear path never changes mode: when `next` opens a mapping
    /// range of the other mode, that range has its own seed and the path
    /// stops here instead of decoding those bytes in the wrong mode.
    fn push_fallthrough(&self, stack: &mut Vec<(u64, Arch)>, next: u64, arch: Arch) {
        if range_start_mode(self.space.hints, next).is_some_and(|m| m != arch) {
            return;
        }
        stack.push((next, arch));
    }

    /// Decode from `seeds`, following direct branches, calls, and fallthrough.
    ///
    /// Each seed carries its decode arch: the project arch, a Thumb-mode
    /// ARM seed (bit 0, mapping symbol, or Thumb-function mark), a
    /// direct `blx` target in the other state, or a user seed's explicit
    /// [`SeedMode`]. Direct successors inherit the address's arch, so one
    /// Thumb seed walks Thumb code even inside an ARM32 project; an
    /// address decoded under one arch is never re-decoded under another
    /// (first wins). Linear fallthrough never changes mode: a path
    /// reaching a mapping range of the other mode stops (see
    /// [`Walker::push_fallthrough`]); that range has its own seed.
    ///
    /// Records bounded evidence while walking: executable bytes at a queued
    /// address that do not decode become [`DiagnosticKind::DecodeFailure`],
    /// and decoded branches/calls without a direct target become unresolved
    /// jump/call sites. Valid termination (`Return`) and fallthrough record
    /// nothing. Unmapped queued addresses record nothing: they end that
    /// path, they are not decode failures.
    ///
    /// Returns the newly recorded [`DiagnosticKind::UnresolvedIndirectJump`]
    /// sites (re-inserts of already-known sites are not repeated), so
    /// [`resolve_indirect_jumps`] can queue continuations without rescanning
    /// the whole diagnostic set.
    fn run(&mut self, seeds: Vec<(u64, Arch)>) -> Result<Vec<u64>> {
        let mut stack = seeds;
        let mut fresh_jumps: Vec<u64> = Vec::new();
        while let Some((va, item_arch)) = stack.pop() {
            if self.decoded.contains_key(&va) {
                continue;
            }
            if self.decoded.len() >= MAX_TOTAL_INSNS {
                return Err(Error::Limit(format!(
                    "more than {MAX_TOTAL_INSNS} instructions"
                )));
            }
            let Some(bytes) = self.space.code_bytes(va).filter(|b| !b.is_empty()) else {
                continue;
            };
            let insn = match crate::disasm::disasm_first(item_arch, bytes, va) {
                Ok(Some(insn)) => insn,
                Ok(None) => continue,
                Err(Error::Invalid(_)) => {
                    self.diagnostics.insert(Diagnostic {
                        addr: va,
                        kind: DiagnosticKind::DecodeFailure,
                    });
                    continue;
                }
                Err(e) => return Err(e),
            };
            let flow = flow_of(item_arch, &insn);
            // Thumb IT predication: the decoder prints no condition suffix
            // inside an IT block, so a predicated `bx lr` (or `pop {.., pc}`)
            // lifts as an unconditional return. Downgrade predicated
            // terminators to conditional branches: the site keeps its
            // indirect-jump diagnostic and the fallthrough stays reachable.
            // The stored `Insn` keeps its faithful decode; only the flow is
            // predicated (edge building reuses it below).
            let opens_it = if item_arch == Arch::Thumb {
                crate::disasm::it_block_len(&insn.mnem)
            } else {
                None
            };
            let predicated =
                opens_it.is_none() && self.it_remaining > 0 && self.it_next == Some(va);
            if predicated {
                self.it_remaining -= 1;
                self.it_next = Some(va.wrapping_add(u64::from(insn.size)));
            }
            if let Some(n) = opens_it {
                self.it_remaining = n;
                self.it_next = Some(va.wrapping_add(u64::from(insn.size)));
            }
            // Interworking mode switches (32-bit ARM only, unconditional
            // forms): a direct `blx` immediate always changes state, and a
            // `bx reg` whose register the adjacent `movw`/`movt` pair just
            // materialized branches to that constant in bit-0-selected
            // state. Anything else inherits the address's arch.
            let mut flow = flow;
            let mut follow_arch = item_arch;
            if matches!(item_arch, Arch::Arm32 | Arch::Thumb) && !predicated {
                let base = arm_base_mnem(&insn.mnem);
                if base == "blx" && matches!(flow, Flow::Call { target: Some(_) }) {
                    follow_arch = if item_arch == Arch::Arm32 {
                        Arch::Thumb
                    } else {
                        Arch::Arm32
                    };
                } else if base == "bx"
                    && insn.ops.len() == 1
                    && insn.ops[0] != "lr"
                    && insn.ops[0] != "pc"
                    && let Some((target, mode)) = self.bx_const_target(&insn)
                {
                    flow = Flow::Branch {
                        target: Some(target),
                    };
                    follow_arch = mode;
                }
            }
            let flow = if predicated {
                match flow {
                    Flow::Ret => Flow::CBranch { target: None },
                    Flow::Branch { target } => Flow::CBranch { target },
                    other => other,
                }
            } else {
                flow
            };
            match flow {
                Flow::Branch { target: None } | Flow::CBranch { target: None } => {
                    if self.diagnostics.insert(Diagnostic {
                        addr: va,
                        kind: DiagnosticKind::UnresolvedIndirectJump,
                    }) {
                        fresh_jumps.push(va);
                    }
                }
                Flow::Call { target: None } => {
                    self.diagnostics.insert(Diagnostic {
                        addr: va,
                        kind: DiagnosticKind::UnresolvedIndirectCall,
                    });
                }
                _ => {}
            }
            let mut next = va.wrapping_add(u64::from(insn.size));
            if item_arch == Arch::Mips32 && flow.ends_block() {
                // MIPS executes the word after a branch even when the
                // branch is taken (delay slot): decode it as part of this
                // step and continue from the word after it, so the delay
                // slot never starts its own block (see Pass B). A branch
                // in the delay slot is UNPREDICTABLE hardware behavior
                // (assemblers forbid it); its target still joins the walk
                // so coverage stays over- rather than under-approximate.
                let delay = va.wrapping_add(4);
                let mut delay_ok = self.decoded.contains_key(&delay);
                if !delay_ok
                    && let Some(bytes) = self.space.code_bytes(delay).filter(|b| !b.is_empty())
                {
                    match crate::disasm::disasm_first(item_arch, bytes, delay) {
                        Ok(Some(dinsn)) => {
                            let dflow = flow_of(item_arch, &dinsn);
                            match dflow {
                                Flow::Branch { target: Some(t) }
                                | Flow::CBranch { target: Some(t) } => {
                                    self.jump_targets.insert(t);
                                    stack.push((t, item_arch));
                                }
                                Flow::Call { target: Some(t) } => {
                                    self.jump_targets.insert(t);
                                    self.call_targets.insert(t);
                                    stack.push((t, item_arch));
                                }
                                _ => {}
                            }
                            self.decoded.insert(
                                delay,
                                Decoded {
                                    insn: dinsn,
                                    flow: dflow,
                                    arch: item_arch,
                                },
                            );
                            delay_ok = true;
                        }
                        Ok(None) => {}
                        Err(Error::Invalid(_)) => {
                            self.diagnostics.insert(Diagnostic {
                                addr: delay,
                                kind: DiagnosticKind::DecodeFailure,
                            });
                        }
                        Err(e) => return Err(e),
                    }
                }
                if delay_ok {
                    next = delay.wrapping_add(4);
                }
            }
            match flow {
                Flow::Seq => self.push_fallthrough(&mut stack, next, item_arch),
                Flow::Branch { target } => {
                    if let Some(t) = target {
                        self.jump_targets.insert(t);
                        if follow_arch != item_arch {
                            self.switch_targets.insert(t);
                        }
                        stack.push((t, follow_arch));
                    }
                }
                Flow::CBranch { target } => {
                    if let Some(t) = target {
                        self.jump_targets.insert(t);
                        stack.push((t, item_arch));
                    }
                    self.fallthroughs.insert(next);
                    self.push_fallthrough(&mut stack, next, item_arch);
                }
                Flow::Call { target } => {
                    if let Some(t) = target {
                        self.jump_targets.insert(t);
                        self.call_targets.insert(t);
                        if follow_arch != item_arch {
                            self.switch_targets.insert(t);
                        }
                        stack.push((t, follow_arch));
                    }
                    self.fallthroughs.insert(next);
                    self.push_fallthrough(&mut stack, next, item_arch);
                }
                Flow::Ret => {}
            }
            if matches!(item_arch, Arch::Arm32 | Arch::Thumb) {
                self.prev_prev = self.prev.take();
                self.prev = Some(insn.clone());
            }
            self.decoded.insert(
                va,
                Decoded {
                    insn,
                    flow,
                    arch: item_arch,
                },
            );
        }
        Ok(fresh_jumps)
    }
}

/// Owner entry for an address: greatest entry at or below `va`.
///
/// `entries` must be sorted ascending (as built in [`analyze`]).
/// Addresses below the first entry — and every address when `entries`
/// is empty — have no owner (`None`), matching
/// [`Analysis::containing_function`], which reports `None` there so
/// block ownership and `func`/`blocks` lookups agree. Binary search,
/// so block/edge attribution is `O(log F)` per lookup instead of
/// `O(F)`.
#[must_use]
pub fn function_owner(entries: &[u64], va: u64) -> Option<u64> {
    let idx = entries.partition_point(|e| *e <= va);
    if idx == 0 {
        None
    } else {
        Some(entries[idx - 1])
    }
}

/// Recovered indirect-jump resolutions: `(site, target)` pairs in ascending
/// site order plus explicit cap accounting.
///
/// Single-slot sites contribute one pair; guarded table sites contribute one
/// pair per unique entry target (at most [`MAX_TABLE_ENTRIES_PER_SITE`]).
/// `slots` holds the scanned `(site, slot)` table addresses backing the
/// table pairs' `Data` evidence xrefs.
struct InferredJumps {
    /// Resolved `(site, target)` pairs, unique per tuple.
    pairs: Vec<(u64, u64)>,
    /// Scanned `(site, slot)` table addresses for resolved table sites.
    slots: Vec<(u64, u64)>,
    /// Whether the edge budget cut resolution short.
    truncated: bool,
    /// Sites skipped by the edge budget (each keeps its diagnostic).
    omitted: usize,
}

/// Slot width for the single-slot resolver, or `None` when it cannot apply.
///
/// Raw x86 mappings only: container slot values are not known final until
/// relocations apply, which never happens to segment bytes. x86-32 absolute
/// slots are 4 bytes, x86-64 RIP-relative slots 8; other arches report no
/// typed slot. Tables have their own gate (see [`absolute_table_width`]).
fn indirect_slot_width(arch: Arch, format: BinaryFormat) -> Option<usize> {
    if format != BinaryFormat::Raw {
        return None;
    }
    match arch {
        Arch::X86_32 => Some(4),
        Arch::X86_64 => Some(8),
        Arch::Aarch64
        | Arch::Arm32
        | Arch::Thumb
        | Arch::Riscv32
        | Arch::Riscv64
        | Arch::Mips32
        | Arch::Ppc32
        | Arch::Ppc64 => None,
    }
}

/// Slot width for absolute-index tables (x86, any format).
///
/// Unlike the single-slot path, absolute tables are enabled for containers:
/// a linked `ET_EXEC` image holds final absolute addresses, while a `PIE`
/// image holds relocation addends that fail the decodability and
/// same-function checks, so exact-or-reject stays safe. x86-32 slots are 4
/// bytes, x86-64 slots 8; other arches have no absolute-index shape.
fn absolute_table_width(arch: Arch) -> Option<usize> {
    match arch {
        Arch::X86_32 => Some(4),
        Arch::X86_64 => Some(8),
        Arch::Aarch64
        | Arch::Arm32
        | Arch::Thumb
        | Arch::Riscv32
        | Arch::Riscv64
        | Arch::Mips32
        | Arch::Ppc32
        | Arch::Ppc64 => None,
    }
}

/// Map an x86 register name to its index family (0-15), or `None`.
///
/// `rax`/`eax` share family 0 through `r15`/`r15d` sharing 15, so a 32-bit
/// guard register aliases its 64-bit indexed use. Lowercase only; the
/// decoder already lowercases mnemonics and registers.
fn x86_reg_num(name: &str) -> Option<u8> {
    match name {
        "rax" | "eax" => Some(0),
        "rcx" | "ecx" => Some(1),
        "rdx" | "edx" => Some(2),
        "rbx" | "ebx" => Some(3),
        "rsp" | "esp" => Some(4),
        "rbp" | "ebp" => Some(5),
        "rsi" | "esi" => Some(6),
        "rdi" | "edi" => Some(7),
        "r8" | "r8d" => Some(8),
        "r9" | "r9d" => Some(9),
        "r10" | "r10d" => Some(10),
        "r11" | "r11d" => Some(11),
        "r12" | "r12d" => Some(12),
        "r13" | "r13d" => Some(13),
        "r14" | "r14d" => Some(14),
        "r15" | "r15d" => Some(15),
        _ => None,
    }
}

/// Map an iced-x86 [`iced_x86::Register`] to its index family (0-15).
///
/// Covers the 32/64-bit general registers the switch shapes use; segment,
/// control, and vector registers report `None` and never alias.
fn x86_iced_num(reg: iced_x86::Register) -> Option<u8> {
    use iced_x86::Register as R;
    match reg {
        R::RAX | R::EAX => Some(0),
        R::RCX | R::ECX => Some(1),
        R::RDX | R::EDX => Some(2),
        R::RBX | R::EBX => Some(3),
        R::RSP | R::ESP => Some(4),
        R::RBP | R::EBP => Some(5),
        R::RSI | R::ESI => Some(6),
        R::RDI | R::EDI => Some(7),
        R::R8 | R::R8D => Some(8),
        R::R9 | R::R9D => Some(9),
        R::R10 | R::R10D => Some(10),
        R::R11 | R::R11D => Some(11),
        R::R12 | R::R12D => Some(12),
        R::R13 | R::R13D => Some(13),
        R::R14 | R::R14D => Some(14),
        R::R15 | R::R15D => Some(15),
        _ => None,
    }
}

/// Map an AArch64 register name to its number (0-30), or `None`.
///
/// `xN` and `wN` alias (same number); `xzr`/`wzr`/`sp` never alias a table
/// index and report `None`.
fn aarch64_reg_num(name: &str) -> Option<u8> {
    let digits = name.strip_prefix('x').or_else(|| name.strip_prefix('w'))?;
    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    let n: u8 = digits.parse().ok()?;
    (n <= 30).then_some(n)
}

/// Decode the single x86 instruction at `addr` with iced-x86.
///
/// Typed register/memory facts for the switch-sequence matchers, which the
/// [`Insn`] rows do not carry (base/index/scale/displacement). Returns
/// `None` for unmapped addresses and invalid encodings: the site stays
/// unresolved.
fn x86_insn_at(space: &AddrSpace, addr: u64, bitness: u32) -> Option<iced_x86::Instruction> {
    let bytes = space.code_bytes(addr)?;
    let win = &bytes[..bytes.len().min(15)];
    let mut decoder = iced_x86::Decoder::new(bitness, win, iced_x86::DecoderOptions::NONE);
    decoder.set_ip(addr);
    let insn = decoder.decode();
    if insn.is_invalid() {
        return None;
    }
    Some(insn)
}

/// Check one `UnresolvedIndirectJump` site against the single-slot absolute
/// indirect-jump pattern, returning its target when every check passes.
///
/// All evidence is typed decoder facts, never operand text. Rejections:
/// - R1: `insn.mnem == "jmp"` with a `Branch { None }` lift (excludes
///   immediate-reporting `mov`/`push`, calls, and predicated forms).
/// - R2: `branch_target` is `None` (direct jumps never reach this set).
/// - R3: `mem_target == Some(slot)` (excludes indexed/multi-entry and
///   register-indirect shapes, which report no typed slot; guarded
///   scaled-index tables go through [`resolve_table_site`] instead).
/// - R4: raw mappings only (container and LE slot values are not known
///   final: relocations are never applied to segment bytes).
/// - R5: the arch-width slot bytes are fully file-backed in one segment
///   (excludes truncated slots, BSS tails, and cross-segment spans; a
///   `Data` xref via `contains` is necessary but not sufficient here).
/// - R6: the little-endian slot value lies in executable file-backed bytes.
/// - R7: those bytes decode via `disasm_first`.
/// - R8: the target attributes to the site's function under the Pass-A
///   entry set (same-function only: no new entries, no callgraph edges).
///
/// Slot width is the arch pointer width (4 for x86-32, 8 for x86-64); other
/// arches have no approved shape and are rejected outright.
fn resolve_indirect_site(
    arch: Arch,
    format: BinaryFormat,
    space: &AddrSpace,
    decoded: &BTreeMap<u64, Decoded>,
    entries: &[u64],
    site: u64,
) -> Option<u64> {
    let found = decoded.get(&site)?;
    if found.insn.mnem != "jmp" {
        return None;
    }
    if !matches!(found.flow, Flow::Branch { target: None }) {
        return None;
    }
    if found.insn.branch_target.is_some() {
        return None;
    }
    let slot = found.insn.mem_target?;
    let width = indirect_slot_width(arch, format)?;
    let raw = space.file_bytes_at(slot, width)?;
    let target = match width {
        4 => u64::from(u32::from_le_bytes(raw.try_into().ok()?)),
        _ => u64::from_le_bytes(raw.try_into().ok()?),
    };
    let target_bytes = space.code_bytes(target)?;
    if !matches!(
        crate::disasm::disasm_first(arch, target_bytes, target),
        Ok(Some(_))
    ) {
        return None;
    }
    if entries.is_empty() {
        return None;
    }
    match (
        function_owner(entries, target),
        function_owner(entries, site),
    ) {
        (Some(t), Some(s)) if t == s => {}
        _ => return None,
    }
    Some(target)
}

/// Check one `UnresolvedIndirectJump` site against the guarded absolute
/// scaled-index table pattern, returning its unique entry targets.
///
/// Covers x86 absolute tables in any format: x86-32 `jmp [T+eax*4]` and
/// x86-64 `jmp [T+rax*8]`, where the decoder reports the displacement as
/// [`Insn::table_base`]. Rejections:
/// - T1: `insn.mnem == "jmp"` with a `Branch { None }` lift.
/// - T2: `branch_target` is `None`.
/// - T3: `table_base == Some(base)` (single-slot shapes report `mem_target`
///   instead, strided scales report `None`).
/// - T4: x86 only (other arches have no absolute-index shape).
/// - T5: a `cmp idx, max` plus a direct conditional branch (the index bound
///   check) within [`MAX_TABLE_GUARD_BACKTRACK`] predecessors, with the
///   compared register aliasing the indexed register. Unguarded indexes are
///   unbounded: unrecoverable (the site keeps its diagnostic).
/// - T6: the bound `max + 1` fits [`MAX_TABLE_ENTRIES_PER_SITE`] and reaches
///   [`MIN_TABLE_ENTRIES_PER_SITE`]; oversized bounds and singleton bounds
///   stay unresolved rather than partially recovered (exact-or-reject).
/// - T7: every one of the bound slots validates (same file-backed,
///   executable, decodable, same-function rules as the single-slot R5-R8).
///   One bad slot rejects the whole site.
fn resolve_table_site(
    arch: Arch,
    space: &AddrSpace,
    decoded: &BTreeMap<u64, Decoded>,
    entries: &[u64],
    site: u64,
) -> Option<TableResolution> {
    let found = decoded.get(&site)?;
    if found.insn.mnem != "jmp" {
        return None;
    }
    if !matches!(found.flow, Flow::Branch { target: None }) {
        return None;
    }
    if found.insn.branch_target.is_some() {
        return None;
    }
    let base = found.insn.table_base?;
    let width = absolute_table_width(arch)?;
    if entries.is_empty() {
        return None;
    }
    let owner = function_owner(entries, site)?;
    let bitness = match arch {
        Arch::X86_32 => 32,
        Arch::X86_64 => 64,
        Arch::Aarch64
        | Arch::Arm32
        | Arch::Thumb
        | Arch::Riscv32
        | Arch::Riscv64
        | Arch::Mips32
        | Arch::Ppc32
        | Arch::Ppc64 => return None,
    };
    let iced = x86_insn_at(space, site, bitness)?;
    if iced.mnemonic() != iced_x86::Mnemonic::Jmp {
        return None;
    }
    let index_num = x86_iced_num(iced.memory_index())?;
    let (bound, cmp_reg) = guard_bound(decoded, entries, site, owner)?;
    if x86_reg_num(&cmp_reg) != Some(index_num) {
        return None;
    }
    if !bound_in_range(bound) {
        return None;
    }
    let mut targets = BTreeSet::new();
    let mut slots = Vec::with_capacity(bound);
    for i in 0..bound {
        let slot = base.wrapping_add((i as u64).wrapping_mul(width as u64));
        let target = table_slot_target(arch, space, entries, owner, slot, width)?;
        slots.push(slot);
        targets.insert(target);
    }
    Some(TableResolution {
        targets: targets.into_iter().collect(),
        slots,
    })
}

/// Unique entry targets plus scanned slot addresses of one table site.
struct TableResolution {
    /// Unique entry targets in ascending order.
    targets: Vec<u64>,
    /// Scanned slot addresses in table order (evidence for `Data` xrefs).
    slots: Vec<u64>,
}

/// Parse a `cmp reg, imm` bound immediate from operand text.
///
/// x86 `cmp eax, 3` reports `["eax", "3"]` (imm8, decimal) while imm32
/// reports `["ecx", "0x100"]`; Thumb `cmp r0, 0x8`; AArch64 `cmp w0, #0x13`.
/// Strips one `#` prefix, then hex (`0x`) or decimal. Anything else
/// (negative, symbolic, malformed) is `None`: the site stays unresolved.
fn parse_cmp_imm(ops: &[String]) -> Option<u64> {
    if ops.len() != 2 {
        return None;
    }
    let raw = ops[1].strip_prefix('#').unwrap_or(&ops[1]);
    if let Some(hex) = raw.strip_prefix("0x").or_else(|| raw.strip_prefix("0X")) {
        if hex.is_empty() || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
            return None;
        }
        u64::from_str_radix(hex, 16).ok()
    } else {
        if raw.is_empty() || !raw.bytes().all(|b| b.is_ascii_digit()) {
            return None;
        }
        raw.parse::<u64>().ok()
    }
}

/// Bound and compared register of the guard dominating `site`, if any.
///
/// Scans [`MAX_TABLE_GUARD_BACKTRACK`] same-function predecessors for a
/// direct conditional branch (the bound check) immediately preceded by a
/// `cmp reg, max` with a parseable immediate. Returns `max + 1` (valid
/// indexes `0..=max`) plus the compared register name for the caller's
/// alias check against the indexed register. `None` covers every
/// unbounded shape: no branch, no adjacent `cmp`, or an unparseable
/// immediate. Detected-but-unbounded sites keep their
/// [`DiagnosticKind::UnresolvedIndirectJump`].
fn guard_bound(
    decoded: &BTreeMap<u64, Decoded>,
    entries: &[u64],
    site: u64,
    owner: u64,
) -> Option<(usize, String)> {
    let preds: Vec<(u64, &Decoded)> = decoded
        .range(..site)
        .rev()
        .take(MAX_TABLE_GUARD_BACKTRACK)
        .take_while(|(va, _)| function_owner(entries, **va) == Some(owner))
        .map(|(va, d)| (*va, d))
        .collect();
    for (i, (_, d)) in preds.iter().enumerate() {
        if !matches!(d.flow, Flow::CBranch { target: Some(_) }) {
            continue;
        }
        for prior in preds.iter().skip(i + 1).take(2) {
            if prior.1.insn.mnem != "cmp" {
                continue;
            }
            if let Some(max) = parse_cmp_imm(&prior.1.insn.ops) {
                let bound = usize::try_from(max).ok()?.checked_add(1)?;
                return Some((bound, prior.1.insn.ops[0].clone()));
            }
        }
    }
    None
}

/// Whether a guard bound is a recoverable table size: at least a pair
/// (singleton runs are stray pointers) and at most
/// [`MAX_TABLE_ENTRIES_PER_SITE`] (oversized bounds stay unresolved rather
/// than partially recovered).
fn bound_in_range(bound: usize) -> bool {
    (MIN_TABLE_ENTRIES_PER_SITE..=MAX_TABLE_ENTRIES_PER_SITE).contains(&bound)
}

/// Validate one table slot: file-backed width bytes in a single segment,
/// a little-endian value in executable file-backed bytes that decodes and
/// attributes to the site's function. Mirrors the single-slot R5-R8 rules.
fn table_slot_target(
    arch: Arch,
    space: &AddrSpace,
    entries: &[u64],
    owner: u64,
    slot: u64,
    width: usize,
) -> Option<u64> {
    let raw = space.file_bytes_at(slot, width)?;
    let target = match width {
        4 => u64::from(u32::from_le_bytes(raw.try_into().ok()?)),
        _ => u64::from_le_bytes(raw.try_into().ok()?),
    };
    let target_bytes = space.code_bytes(target)?;
    if !matches!(
        crate::disasm::disasm_first(arch, target_bytes, target),
        Ok(Some(_))
    ) {
        return None;
    }
    if function_owner(entries, target) != Some(owner) {
        return None;
    }
    Some(target)
}

/// Validate one relative-table target: executable file-backed bytes that
/// decode and attribute to the site's function. Shared by the PIE, MSVC,
/// Thumb, and AArch64 relative shapes, whose slots hold offsets rather than
/// absolute addresses.
fn relative_slot_target(
    arch: Arch,
    space: &AddrSpace,
    entries: &[u64],
    owner: u64,
    target: u64,
) -> Option<u64> {
    let target_bytes = space.code_bytes(target)?;
    if !matches!(
        crate::disasm::disasm_first(arch, target_bytes, target),
        Ok(Some(_))
    ) {
        return None;
    }
    if function_owner(entries, target) != Some(owner) {
        return None;
    }
    Some(target)
}

/// Same-function predecessors of `site`, nearest first, up to `n`.
fn site_preds<'a>(
    decoded: &'a BTreeMap<u64, Decoded>,
    entries: &[u64],
    site: u64,
    owner: u64,
    n: usize,
) -> Vec<(u64, &'a Decoded)> {
    decoded
        .range(..site)
        .rev()
        .take(n)
        .take_while(|(va, _)| function_owner(entries, **va) == Some(owner))
        .map(|(va, d)| (*va, d))
        .collect()
}

/// Whether a `mov` copying the guard index into the table index sits in
/// `preds`: destination aliases `index_num`, source aliases `cmp_num.
/// Accepts the compiler's index copy (`mov eax, edi` before the sequence)
/// as well as the copy-free shape (both registers already alias).
fn index_copy_present(preds: &[(u64, &Decoded)], index_num: u8, cmp_num: u8) -> bool {
    if index_num == cmp_num {
        return true;
    }
    preds.iter().any(|(_, d)| {
        d.insn.mnem == "mov"
            && d.insn.ops.len() == 2
            && x86_reg_num(&d.insn.ops[0]) == Some(index_num)
            && x86_reg_num(&d.insn.ops[1]) == Some(cmp_num)
    })
}

/// Check one site against the GCC/Clang PIE x86-64 switch shape, returning
/// its entry targets.
///
/// ```text
/// cmp edi, max; ja default
/// [mov eax, edi]
/// lea rcx, [rip+T]; movsxd rax, [rcx+rax*4]; add rax, rcx; jmp rax
/// ```
///
/// The table holds 32-bit signed offsets from its own base (`add` adds the
/// `lea` base back), so `target[i] = T + sext32(slot[i])`. Register linkage
/// is exact: the `jmp` register is the `add`/`movsxd` destination, the `add`
/// source is the `lea` destination, and the `movsxd` memory is
/// `[base + index*4]` with zero displacement (typed iced-x86 facts). The
/// compared register must alias the `movsxd` index, directly or through one
/// `mov` copy. The guard bound fixes the entry count; every slot must
/// validate or the site stays unresolved.
fn resolve_pie_table_site(
    arch: Arch,
    space: &AddrSpace,
    decoded: &BTreeMap<u64, Decoded>,
    entries: &[u64],
    site: u64,
) -> Option<TableResolution> {
    if arch != Arch::X86_64 {
        return None;
    }
    let found = decoded.get(&site)?;
    if found.insn.mnem != "jmp" {
        return None;
    }
    if !matches!(found.flow, Flow::Branch { target: None }) {
        return None;
    }
    if found.insn.branch_target.is_some() || found.insn.ops.len() != 1 {
        return None;
    }
    let jmp_reg = found.insn.ops[0].clone();
    if entries.is_empty() {
        return None;
    }
    let owner = function_owner(entries, site)?;
    let preds = site_preds(decoded, entries, site, owner, MAX_TABLE_GUARD_BACKTRACK);
    if preds.len() < 3 {
        return None;
    }
    if preds[0].1.insn.mnem != "add"
        || preds[1].1.insn.mnem != "movsxd"
        || preds[2].1.insn.mnem != "lea"
    {
        return None;
    }
    let table = preds[2].1.insn.mem_target?;
    if preds[2].1.insn.ops.len() != 2 {
        return None;
    }
    let base_reg = preds[2].1.insn.ops[0].clone();
    if preds[1].1.insn.ops.len() != 2 || preds[1].1.insn.ops[0] != jmp_reg {
        return None;
    }
    if preds[0].1.insn.ops.len() != 2
        || preds[0].1.insn.ops[0] != jmp_reg
        || preds[0].1.insn.ops[1] != base_reg
    {
        return None;
    }
    let site_iced = x86_insn_at(space, site, 64)?;
    if site_iced.mnemonic() != iced_x86::Mnemonic::Jmp
        || x86_iced_num(site_iced.op_register(0)).is_none_or(|n| x86_reg_num(&jmp_reg) != Some(n))
    {
        return None;
    }
    let movsxd_iced = x86_insn_at(space, preds[1].0, 64)?;
    if movsxd_iced.mnemonic() != iced_x86::Mnemonic::Movsxd
        || movsxd_iced.memory_index_scale() != 4
        || movsxd_iced.memory_displacement32() != 0
    {
        return None;
    }
    let mem_base = x86_iced_num(movsxd_iced.memory_base())?;
    let mem_index = x86_iced_num(movsxd_iced.memory_index())?;
    if x86_reg_num(&base_reg) != Some(mem_base) {
        return None;
    }
    let (bound, cmp_reg) = guard_bound(decoded, entries, site, owner)?;
    if !bound_in_range(bound) {
        return None;
    }
    let cmp_num = x86_reg_num(&cmp_reg)?;
    if !index_copy_present(&preds, mem_index, cmp_num) {
        return None;
    }
    let mut targets = BTreeSet::new();
    let mut slots = Vec::with_capacity(bound);
    for i in 0..bound {
        let slot = table.wrapping_add((i as u64).wrapping_mul(4));
        let raw = space.file_bytes_at(slot, 4)?;
        let off = i32::from_le_bytes(raw.try_into().ok()?);
        let target = table.wrapping_add_signed(i64::from(off));
        relative_slot_target(arch, space, entries, owner, target)?;
        slots.push(slot);
        targets.insert(target);
    }
    Some(TableResolution {
        targets: targets.into_iter().collect(),
        slots,
    })
}

/// Check one site against the MSVC x64 switch shape, returning its targets.
///
/// ```text
/// cmp eax, max; ja default
/// mov ecx, [r8+rax*4+T_rva]; add rcx, r8; jmp rcx
/// ```
///
/// The table holds 32-bit RVAs from the image base (`r8`); the displacement
/// is the table RVA, so `table_va = image_base + disp` with `image_base`
/// approximated as the lowest mapped address (exact for single-segment
/// images and header-mapped PEs; anything else fails validation rather than
/// guessing). Register linkage mirrors the PIE path: the `jmp` register is
/// the `add` destination (32-bit `mov` alias accepted), the `add` source is
/// the `mov` base, and the `mov` memory is `[base + index*4]` with a typed
/// iced-x86 scale of 4. Guard-bound and exact-or-reject as above.
fn resolve_msvc_table_site(
    arch: Arch,
    space: &AddrSpace,
    decoded: &BTreeMap<u64, Decoded>,
    entries: &[u64],
    site: u64,
) -> Option<TableResolution> {
    if arch != Arch::X86_64 {
        return None;
    }
    let found = decoded.get(&site)?;
    if found.insn.mnem != "jmp" {
        return None;
    }
    if !matches!(found.flow, Flow::Branch { target: None }) {
        return None;
    }
    if found.insn.branch_target.is_some() || found.insn.ops.len() != 1 {
        return None;
    }
    let jmp_reg = found.insn.ops[0].clone();
    let jmp_num = x86_reg_num(&jmp_reg)?;
    if entries.is_empty() {
        return None;
    }
    let owner = function_owner(entries, site)?;
    let preds = site_preds(decoded, entries, site, owner, MAX_TABLE_GUARD_BACKTRACK);
    if preds.len() < 2 {
        return None;
    }
    if preds[0].1.insn.mnem != "add" || preds[1].1.insn.mnem != "mov" {
        return None;
    }
    if preds[0].1.insn.ops.len() != 2 || preds[1].1.insn.ops.len() != 2 {
        return None;
    }
    if x86_reg_num(&preds[0].1.insn.ops[0]) != Some(jmp_num) {
        return None;
    }
    let base_reg = preds[0].1.insn.ops[1].clone();
    let base_num = x86_reg_num(&base_reg)?;
    if x86_reg_num(&preds[1].1.insn.ops[0]) != Some(jmp_num) {
        return None;
    }
    let mov_iced = x86_insn_at(space, preds[1].0, 64)?;
    if mov_iced.mnemonic() != iced_x86::Mnemonic::Mov || mov_iced.memory_index_scale() != 4 {
        return None;
    }
    if x86_iced_num(mov_iced.memory_base()) != Some(base_num) {
        return None;
    }
    let mem_index = x86_iced_num(mov_iced.memory_index())?;
    let disp = mov_iced.memory_displacement32();
    let image_base = space.all.iter().map(|s| s.vaddr).min()?;
    let table = image_base.wrapping_add(u64::from(disp));
    let (bound, cmp_reg) = guard_bound(decoded, entries, site, owner)?;
    if !bound_in_range(bound) {
        return None;
    }
    let cmp_num = x86_reg_num(&cmp_reg)?;
    if !index_copy_present(&preds, mem_index, cmp_num) {
        return None;
    }
    let mut targets = BTreeSet::new();
    let mut slots = Vec::with_capacity(bound);
    for i in 0..bound {
        let slot = table.wrapping_add((i as u64).wrapping_mul(4));
        let raw = space.file_bytes_at(slot, 4)?;
        let rva = u32::from_le_bytes(raw.try_into().ok()?);
        let target = image_base.wrapping_add(u64::from(rva));
        relative_slot_target(arch, space, entries, owner, target)?;
        slots.push(slot);
        targets.insert(target);
    }
    Some(TableResolution {
        targets: targets.into_iter().collect(),
        slots,
    })
}

/// Check one site against the ARM Thumb switch shape.
///
/// `tbb [pc, rN]` holds byte offsets, `tbh [pc, rN, lsl #1]` halfword
/// offsets, both `target = base + 2 * value` with
/// `base = (site + 4) & !3` (the table follows the 4-byte instruction).
/// The compared register must equal the indexed register; the guard bound
/// fixes the count. Every slot validates or the site stays unresolved.
fn resolve_thumb_table_site(
    arch: Arch,
    space: &AddrSpace,
    decoded: &BTreeMap<u64, Decoded>,
    entries: &[u64],
    site: u64,
) -> Option<TableResolution> {
    if arch != Arch::Thumb {
        return None;
    }
    let found = decoded.get(&site)?;
    if !matches!(found.flow, Flow::Branch { target: None }) {
        return None;
    }
    let width = match found.insn.mnem.as_str() {
        "tbb" => 1,
        "tbh" => 2,
        _ => return None,
    };
    if found.insn.ops.len() != 1 {
        return None;
    }
    let inner = found.insn.ops[0].strip_prefix('[')?.strip_suffix(']')?;
    let mut parts = inner.split(',').map(str::trim);
    if parts.next() != Some("pc") {
        return None;
    }
    let index_reg = parts.next()?.to_string();
    match width {
        1 => {
            if parts.next().is_some() {
                return None;
            }
        }
        _ => {
            if parts.next() != Some("lsl 1") || parts.next().is_some() {
                return None;
            }
        }
    }
    if entries.is_empty() {
        return None;
    }
    let owner = function_owner(entries, site)?;
    let (bound, cmp_reg) = guard_bound(decoded, entries, site, owner)?;
    if cmp_reg != index_reg {
        return None;
    }
    if !bound_in_range(bound) {
        return None;
    }
    let table = site.wrapping_add(4) & !3;
    let mut targets = BTreeSet::new();
    let mut slots = Vec::with_capacity(bound);
    for i in 0..bound {
        let slot = table.wrapping_add((i as u64).wrapping_mul(width as u64));
        let raw = space.file_bytes_at(slot, width)?;
        let value: u64 = match width {
            1 => u64::from(raw[0]),
            _ => u64::from(u16::from_le_bytes(raw.try_into().ok()?)),
        };
        let target = table.wrapping_add(value.wrapping_mul(2));
        relative_slot_target(arch, space, entries, owner, target)?;
        slots.push(slot);
        targets.insert(target);
    }
    Some(TableResolution {
        targets: targets.into_iter().collect(),
        slots,
    })
}

/// Check one site against the AArch64 switch shape, returning its targets.
///
/// ```text
/// cmp w0, max; b.hi default
/// [mov w8, w0]
/// adrp x9, JT; add x9, x9, #lo12; adr x10, base
/// ldrb w11, [x9, x8]; add x10, x10, x11, lsl #2; br x10
/// ```
///
/// (`ldrh` with 2-byte slots decodes the same way.) The table holds byte or
/// halfword offsets scaled by 4: `target[i] = base + (slot[i] << 2`, where
/// `base` is the `adr` target and the table base reuses
/// [`crate::disasm::resolve_adrp_pair`]. Register linkage is by number
/// (`xN`/`wN` alias); the `lsl #2` shift is the only accepted scale.
/// Optional `mov` index copy and guard-bound exact-or-reject as above.
fn resolve_aarch64_table_site(
    arch: Arch,
    space: &AddrSpace,
    decoded: &BTreeMap<u64, Decoded>,
    entries: &[u64],
    site: u64,
) -> Option<TableResolution> {
    if arch != Arch::Aarch64 {
        return None;
    }
    let found = decoded.get(&site)?;
    if found.insn.mnem != "br" {
        return None;
    }
    if !matches!(found.flow, Flow::Branch { target: None }) {
        return None;
    }
    if found.insn.ops.len() != 1 {
        return None;
    }
    let jmp_num = aarch64_reg_num(&found.insn.ops[0])?;
    if entries.is_empty() {
        return None;
    }
    let owner = function_owner(entries, site)?;
    let preds = site_preds(decoded, entries, site, owner, MAX_TABLE_GUARD_BACKTRACK);
    if preds.len() < 5 {
        return None;
    }
    if preds[0].1.insn.mnem != "add" || preds[0].1.insn.ops.len() != 4 {
        return None;
    }
    if aarch64_reg_num(&preds[0].1.insn.ops[0]) != Some(jmp_num)
        || preds[0].1.insn.ops[3] != "lsl #2"
    {
        return None;
    }
    let base_num = aarch64_reg_num(&preds[0].1.insn.ops[1])?;
    let slot_num = aarch64_reg_num(&preds[0].1.insn.ops[2])?;
    let load = &preds[1].1.insn;
    let width = match load.mnem.as_str() {
        "ldrb" => 1,
        "ldrh" => 2,
        _ => return None,
    };
    if load.ops.len() != 2 || aarch64_reg_num(&load.ops[0]) != Some(slot_num) {
        return None;
    }
    let inner = load.ops[1].strip_prefix('[')?.strip_suffix(']')?;
    let mut parts = inner.split(',').map(str::trim);
    let table_reg = parts.next()?.to_string();
    let table_num = aarch64_reg_num(&table_reg)?;
    let index_name = parts.next()?.to_string();
    let index_num = aarch64_reg_num(&index_name)?;
    if parts.next().is_some() {
        return None;
    }
    let adr = &preds[2].1.insn;
    if adr.mnem != "adr" || adr.ops.len() != 2 || aarch64_reg_num(&adr.ops[0]) != Some(base_num) {
        return None;
    }
    let base = adr.mem_target?;
    let add = &preds[3].1.insn;
    let adrp = &preds[4].1.insn;
    if add.mnem != "add"
        || add.ops.len() != 3
        || aarch64_reg_num(&add.ops[0]) != Some(table_num)
        || aarch64_reg_num(&add.ops[1]) != Some(table_num)
    {
        return None;
    }
    if adrp.mnem != "adrp"
        || adrp.ops.len() != 2
        || aarch64_reg_num(&adrp.ops[0]) != Some(table_num)
    {
        return None;
    }
    let table = crate::disasm::resolve_adrp_pair(adrp, add)?;
    let (bound, cmp_reg) = guard_bound(decoded, entries, site, owner)?;
    if !bound_in_range(bound) {
        return None;
    }
    let cmp_num = aarch64_reg_num(&cmp_reg)?;
    if index_num != cmp_num
        && !preds.iter().any(|(_, d)| {
            d.insn.mnem == "mov"
                && d.insn.ops.len() == 2
                && aarch64_reg_num(&d.insn.ops[0]) == Some(index_num)
                && aarch64_reg_num(&d.insn.ops[1]) == Some(cmp_num)
        })
    {
        return None;
    }
    let space_table = table;
    let mut targets = BTreeSet::new();
    let mut slots = Vec::with_capacity(bound);
    for i in 0..bound {
        let slot = space_table.wrapping_add((i as u64).wrapping_mul(width as u64));
        let raw = space.file_bytes_at(slot, width)?;
        let value: u64 = match width {
            1 => u64::from(raw[0]),
            _ => u64::from(u16::from_le_bytes(raw.try_into().ok()?)),
        };
        let target = base.wrapping_add(value.wrapping_mul(4));
        relative_slot_target(arch, space, entries, owner, target)?;
        slots.push(slot);
        targets.insert(target);
    }
    Some(TableResolution {
        targets: targets.into_iter().collect(),
        slots,
    })
}

/// Resolve indirect jumps over the walker's `UnresolvedIndirectJump` sites.
///
/// Each site is checked once, in order, via [`resolve_indirect_site`]
/// (single-slot, raw x86 only), [`resolve_table_site`] (absolute x86
/// tables, any format), [`resolve_pie_table_site`] (GCC/Clang PIE x86-64),
/// [`resolve_msvc_table_site`] (MSVC x64), [`resolve_thumb_table_site`]
/// (`tbb`/`tbh`), and [`resolve_aarch64_table_site`] (`adrp`/`adr` relative
/// tables); a pass decodes each target's continuation with the existing
/// [`Walker::run`] (so case bodies decode normally) and registers the
/// targets for block splitting. Continuation decoding can surface further
/// indirect sites, which join the same ascending worklist. Single-slot
/// sites contribute at most one edge ([`MAX_INFERRED_PER_SITE`], singleton
/// by construction); table sites contribute up to
/// [`MAX_TABLE_ENTRIES_PER_SITE`] unique edges. Past `max_edges` (normally
/// [`MAX_INFERRED_EDGES`]) sites stay unresolved with `truncated` set and
/// each omission counted, never silently clipped.
///
/// # Errors
/// [`Error::Limit`] when continuation decoding exceeds the analysis
/// instruction budget (hard budgets stay errors, as in [`Walker::run`]).
fn resolve_indirect_jumps(
    walk: &mut Walker,
    arch: Arch,
    format: BinaryFormat,
    space: &AddrSpace,
    entries: &[u64],
    max_edges: usize,
) -> Result<InferredJumps> {
    let mut pairs: Vec<(u64, u64)> = Vec::new();
    let mut slots: Vec<(u64, u64)> = Vec::new();
    let mut processed: BTreeSet<u64> = BTreeSet::new();
    // Ascending worklist (the old scan's `next()` pick was the smallest
    // unprocessed address): one initial pass over diagnostics, then only
    // the newly surfaced sites each continuation `run` reports.
    let mut pending: BTreeSet<u64> = walk
        .diagnostics
        .iter()
        .filter(|d| d.kind == DiagnosticKind::UnresolvedIndirectJump)
        .map(|d| d.addr)
        .collect();
    let mut truncated = false;
    let mut omitted: usize = 0;
    while let Some(site) = pending.pop_first() {
        // Each site contributes at most one single-slot edge, or one table
        // row set; the check returns at most one resolution per visit and
        // the processed set keeps sites single-visit.
        let inserted = processed.insert(site);
        debug_assert!(inserted);
        if let Some(target) =
            resolve_indirect_site(arch, format, space, &walk.decoded, entries, site)
        {
            if pairs.len() >= max_edges {
                truncated = true;
                omitted += 1;
                continue;
            }
            pairs.push((site, target));
            for fresh in walk.run(vec![(target, arch)])? {
                if !processed.contains(&fresh) {
                    pending.insert(fresh);
                }
            }
            walk.jump_targets.insert(target);
        } else if let Some(table) = resolve_table_site(arch, space, &walk.decoded, entries, site)
            .or_else(|| resolve_pie_table_site(arch, space, &walk.decoded, entries, site))
            .or_else(|| resolve_msvc_table_site(arch, space, &walk.decoded, entries, site))
            .or_else(|| resolve_thumb_table_site(arch, space, &walk.decoded, entries, site))
            .or_else(|| resolve_aarch64_table_site(arch, space, &walk.decoded, entries, site))
        {
            let cost = table.targets.len();
            if pairs.len().saturating_add(cost) > max_edges {
                truncated = true;
                omitted += cost;
                continue;
            }
            for target in &table.targets {
                pairs.push((site, *target));
                walk.jump_targets.insert(*target);
            }
            for slot in &table.slots {
                slots.push((site, *slot));
            }
            for fresh in walk.run(table.targets.iter().map(|&t| (t, arch)).collect())? {
                if !processed.contains(&fresh) {
                    pending.insert(fresh);
                }
            }
        }
    }
    // Unique by construction: single-slot sites resolve once, table
    // targets are a per-site set, and each site takes the first matching
    // shape.
    debug_assert_eq!(pairs.iter().collect::<BTreeSet<_>>().len(), pairs.len());
    Ok(InferredJumps {
        pairs,
        slots,
        truncated,
        omitted,
    })
}

/// Index over string spans preserving the linear scan's first-match rule.
///
/// Holds `(start, exclusive end)` spans sorted ascending by start, with ends
/// computed by the caller via `wrapping_add` (as in [`analyze`]).
/// [`StringSpanIndex::lookup`] returns the start of the earliest span with
/// `start <= target < end`, using plain `u64` comparisons exactly like the
/// old linear scan. A naive last-start predecessor lookup misses nested spans
/// (an early wide span can contain a target past a later narrow span's end);
/// the prefix-maximum ends array recovers the earliest span with `end >
/// target`, and the starts upper bound enforces `start <= target`. Build is
/// `O(S)`, each query `O(log S)`.
#[derive(Debug, Clone, Default)]
pub struct StringSpanIndex {
    spans: Vec<(u64, u64)>,
    prefix_max: Vec<u64>,
}

impl StringSpanIndex {
    /// Build the index over `spans` sorted ascending by start.
    #[must_use]
    pub fn new(spans: Vec<(u64, u64)>) -> Self {
        let mut prefix_max = Vec::with_capacity(spans.len());
        let mut running: u64 = 0;
        for (_, e) in &spans {
            running = running.max(*e);
            prefix_max.push(running);
        }
        Self { spans, prefix_max }
    }

    /// Start of the earliest span containing `target`, if any.
    ///
    /// `None` when no span satisfies `start <= target < end`; empty and
    /// wrapped-empty (`end <= start` in plain `u64` order) spans never match,
    /// matching the old linear scan.
    #[must_use]
    pub fn lookup(&self, target: u64) -> Option<u64> {
        let cand = self.prefix_max.partition_point(|&m| m <= target);
        if cand >= self.spans.len() {
            return None;
        }
        let upto = self.spans.partition_point(|&(s, _)| s <= target);
        if cand < upto {
            let (s, e) = self.spans[cand];
            if target >= s && target < e {
                return Some(s);
            }
        }
        None
    }

    /// Number of indexed spans.
    #[must_use]
    pub fn len(&self) -> usize {
        self.spans.len()
    }

    /// Whether the index holds no spans.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.spans.is_empty()
    }
}

/// Import slot map: slot VA to `imports` index for PE/ELF binaries.
///
/// Slots are the loader-resolved call pointers (PE IAT, ELF GOT; see
/// [`ImportRef::address`](crate::loader::ImportRef::address)). Mach-O
/// addresses are code stubs rather than slots, so they stay out: a data
/// reference can never legitimately target them.
#[must_use]
pub fn import_slots(bin: &LoadedBinary) -> BTreeMap<u64, usize> {
    if !matches!(bin.format, BinaryFormat::Pe | BinaryFormat::Elf) {
        return BTreeMap::new();
    }
    let mut map = BTreeMap::new();
    for (i, imp) in bin.imports.iter().enumerate() {
        if let Some(slot) = imp.address {
            map.entry(slot).or_insert(i);
        }
    }
    map
}

/// Import index serving one call site, if any.
///
/// Indirect sites match by slot (`mem_target`); direct sites match by
/// PLT-stub/thunk target (`branch_target` against `stubs`). The slot rule
/// runs first so a site carrying both resolves to the slot.
#[must_use]
pub fn import_index(
    slots: &BTreeMap<u64, usize>,
    stubs: &BTreeMap<u64, usize>,
    branch_target: Option<u64>,
    mem_target: Option<u64>,
) -> Option<usize> {
    if let Some(m) = mem_target
        && let Some(&i) = slots.get(&m)
    {
        return Some(i);
    }
    if let Some(t) = branch_target
        && let Some(&i) = stubs.get(&t)
    {
        return Some(i);
    }
    None
}

/// Mach-O stub map: stub-entry VA to `imports` index, for direct calls.
///
/// Mach-O loader addresses are code stubs (unlike PE/ELF data slots), so
/// [`import_slots`] stays empty for Mach-O; direct `bl`/`call` targets
/// resolve through this map instead (see [`import_index`]). First import
/// wins on duplicate addresses; the loader never double-maps, so this is
/// a backstop for direct API use.
fn macho_import_stubs(bin: &LoadedBinary) -> BTreeMap<u64, usize> {
    let mut stubs = BTreeMap::new();
    if bin.format != BinaryFormat::MachO {
        return stubs;
    }
    for (i, imp) in bin.imports.iter().enumerate() {
        if let Some(addr) = imp.address {
            stubs.entry(addr).or_insert(i);
        }
    }
    stubs
}

/// PLT-stub/import-thunk sites from decoded rows: `jmp [slot]` address
/// to `imports` index (x86 only; snapshot rebuilds run the same
/// predicate over re-decoded rows).
///
/// A bare `jmp` with no direct target whose slot resolves is a stub;
/// calls through slots are callers, not stubs. A CET `endbr32`/`endbr64`
/// immediately before the jump (`.plt.sec` entries) maps too, so direct
/// calls landing on the `endbr` resolve to the same import.
fn collect_stubs<'a>(
    rows: impl Iterator<Item = (u64, Flow, Option<u64>, &'a str, u8)>,
    slots: &BTreeMap<u64, usize>,
) -> BTreeMap<u64, usize> {
    // No import slots, no stubs: every match below needs `slots.get(&m)`,
    // so skipping the walk (and the caller's per-row flow computation)
    // is exact, not a heuristic.
    if slots.is_empty() {
        return BTreeMap::new();
    }
    let mut stubs = BTreeMap::new();
    let mut prev: Option<(u64, &'a str, u8)> = None;
    for (addr, flow, mem, mnem, size) in rows {
        if matches!(flow, Flow::Branch { target: None })
            && let Some(m) = mem
            && let Some(&i) = slots.get(&m)
        {
            stubs.insert(addr, i);
            if let Some((pa, pm, ps)) = prev
                && (pm == "endbr64" || pm == "endbr32")
                && pa.wrapping_add(ps as u64) == addr
            {
                stubs.insert(pa, i);
            }
        }
        prev = Some((addr, mnem, size));
    }
    stubs
}

/// Run recursive descent and build functions, CFGs, callgraph, and xrefs.
///
/// # Errors
/// [`Error::Limit`] when instruction, function, or seed caps are exceeded.
pub fn analyze(bin: &LoadedBinary) -> Result<Analysis> {
    analyze_with_seeds(bin, &[])
}

/// Run recursive descent with user-defined function seeds, and build
/// functions, CFGs, callgraph, and xrefs.
///
/// `user` holds the active (non-excluded) `define-func` rows: each joins
/// the authoritative seed set with its [`SeedMode`] decode arch, and
/// entries it reaches gain [`DiscoveryReason::User`]. Undecodable seeds
/// are inert (no function, no error), exactly like any other seed that
/// fails to decode.
///
/// Pointer-scan seeds stay off: use [`analyze_with_options`] with
/// [`AnalyzeOptions::pointer_scan`] to opt in.
///
/// # Errors
/// [`Error::Limit`] when instruction, function, or seed caps are exceeded.
pub fn analyze_with_seeds(bin: &LoadedBinary, user: &[UserSeed]) -> Result<Analysis> {
    analyze_with_options(bin, user, AnalyzeOptions::default())
}

/// Run recursive descent with user-defined function seeds and analysis
/// options, and build functions, CFGs, callgraph, and xrefs.
///
/// `options.pointer_scan` enables the lower-confidence aligned-pointer
/// scan ([`DiscoveryReason::Pointer`]); table-derived seeds (`.pdata`,
/// TLS callbacks, ELF init/fini, `LC_FUNCTION_STARTS`) are always on.
/// Entries reached through an enabled source gain its reason.
///
/// # Errors
/// [`Error::Limit`] when instruction, function, or seed caps are exceeded.
pub fn analyze_with_options(
    bin: &LoadedBinary,
    user: &[UserSeed],
    options: AnalyzeOptions,
) -> Result<Analysis> {
    let arch = bin.arch;
    let space = AddrSpace::new(bin);

    // Pass A: recursive descent over a plain VA worklist. Round one starts
    // from entry/exports/user seeds (or the segment base); round two picks
    // up prologue hits in code round one never reached. Both rounds' seeds
    // become entries; incidental pattern matches inside reached code do not.
    let mut walk = Walker::new(&space);
    let (seeds1, seed_diags) = authoritative_seeds(&space, bin, user, options);
    walk.diagnostics.extend(seed_diags);
    walk.run(seeds1.clone())?;
    let seeds2 = prologue_seeds(arch, &space, |va| walk.decoded.contains_key(&va))?;
    // Round-two hits decode in their own mode, like round-one seeds.
    walk.run(seeds2.iter().map(|&a| (a, arm_seed(bin, a).1)).collect())?;

    if walk.decoded.is_empty() {
        let diagnostics = Diagnostics::collect(walk.diagnostics.into_iter().collect(), false, 0);
        return Ok(Analysis {
            arch,
            functions: BTreeMap::new(),
            callgraph: DiGraphMap::new(),
            xrefs: Vec::new(),
            to_index: OnceLock::new(),
            import_stubs: BTreeMap::new(),
            strings: Vec::new(),
            diagnostics,
        });
    }

    // Function entries: both rounds' seeds that decoded, plus direct call
    // targets and interworking switch targets (which start their own
    // function so no function spans both modes). Round-one hits are
    // excluded by construction: `seeds2` only holds prologue matches
    // outside round-one code.
    let mut entries: BTreeSet<u64> = BTreeSet::new();
    for s in seeds1.iter().map(|(a, _)| a).chain(seeds2.iter()) {
        if walk.decoded.contains_key(s) {
            entries.insert(*s);
        }
    }
    for t in &walk.call_targets {
        if walk.decoded.contains_key(t) {
            entries.insert(*t);
        }
    }
    // Mode-switch targets start their own function so no function spans
    // both modes (see `Walker::switch_targets`).
    for t in &walk.switch_targets {
        if walk.decoded.contains_key(t) {
            entries.insert(*t);
        }
    }
    if entries.is_empty()
        && let Some((&first, _)) = walk.decoded.iter().next()
    {
        entries.insert(first);
    }
    if entries.len() > MAX_FUNCTIONS {
        return Err(Error::Limit(format!("more than {MAX_FUNCTIONS} functions")));
    }
    // Discovery provenance: every seed path that reached an entry.
    // `seeds1` holds the entry point, exports, symbol-table addresses,
    // table-derived seeds (`.pdata`, TLS, init, function-starts, pointer),
    // user seeds, or the fallback base; `seeds2` holds prologue hits;
    // `call_targets` holds direct calls. A fallback base that is neither
    // entry nor export still counts as `Entry`: it seeded analysis as the
    // entry point.
    let seeds1_set: BTreeSet<u64> = seeds1.iter().map(|(a, _)| *a).collect();
    let seeds2_set: BTreeSet<u64> = seeds2.iter().copied().collect();
    // Normalized like the seeds: an odd ARM export address and its masked
    // seed are the same function.
    let export_addrs: BTreeSet<u64> = bin
        .exports
        .iter()
        .filter_map(|e| e.address.map(|a| normalize_arm_seed(arch, a).0))
        .collect();
    let entry_norm = bin.entry.map(|e| normalize_arm_seed(arch, e).0);
    let symbol_addrs: BTreeSet<u64> = bin.symbols.iter().map(|s| s.address).collect();
    let pdata_addrs: BTreeSet<u64> = bin
        .pdata_funcs
        .iter()
        .map(|(s, _)| normalize_arm_seed(arch, *s).0)
        .collect();
    let tls_addrs: BTreeSet<u64> = bin
        .tls_callbacks
        .iter()
        .map(|a| normalize_arm_seed(arch, *a).0)
        .collect();
    let init_addrs: BTreeSet<u64> = bin
        .init_funcs
        .iter()
        .map(|a| normalize_arm_seed(arch, *a).0)
        .collect();
    let starts_addrs: BTreeSet<u64> = bin
        .func_starts
        .iter()
        .map(|a| normalize_arm_seed(arch, *a).0)
        .collect();
    let debug_addrs: BTreeSet<u64> = bin
        .debug_funcs
        .iter()
        .map(|f| normalize_arm_seed(arch, f.address).0)
        .collect();
    let pointer_addrs: BTreeSet<u64> = if options.pointer_scan {
        pointer_seeds(&space, bin)
            .into_iter()
            .map(|(a, _)| a)
            .collect()
    } else {
        BTreeSet::new()
    };
    let user_set: BTreeSet<u64> = user
        .iter()
        .map(|s| match (arch, s.mode) {
            (Arch::Arm32, _) => normalize_arm_seed(arch, s.addr).0,
            _ => s.addr,
        })
        .collect();
    let mut reasons: BTreeMap<u64, BTreeSet<DiscoveryReason>> = BTreeMap::new();
    for e in &entries {
        let mut r = BTreeSet::new();
        if Some(*e) == entry_norm {
            r.insert(DiscoveryReason::Entry);
        }
        if export_addrs.contains(e) {
            r.insert(DiscoveryReason::Export);
        }
        if symbol_addrs.contains(e) {
            r.insert(DiscoveryReason::Symbol);
        }
        if walk.call_targets.contains(e) {
            r.insert(DiscoveryReason::DirectCall);
        }
        if seeds2_set.contains(e) {
            r.insert(DiscoveryReason::Prologue);
        }
        if user_set.contains(e) {
            r.insert(DiscoveryReason::User);
        }
        if pdata_addrs.contains(e) {
            r.insert(DiscoveryReason::Pdata);
        }
        if tls_addrs.contains(e) {
            r.insert(DiscoveryReason::TlsCallback);
        }
        if init_addrs.contains(e) {
            r.insert(DiscoveryReason::InitArray);
        }
        if starts_addrs.contains(e) {
            r.insert(DiscoveryReason::FunctionStarts);
        }
        if debug_addrs.contains(e) {
            r.insert(DiscoveryReason::Debug);
        }
        if pointer_addrs.contains(e) {
            r.insert(DiscoveryReason::Pointer);
        }
        if r.is_empty() && seeds1_set.contains(e) {
            r.insert(DiscoveryReason::Entry);
        }
        if r.is_empty() {
            r.insert(DiscoveryReason::Entry);
        }
        reasons.insert(*e, r);
    }
    let entry_list: Vec<u64> = entries.iter().copied().collect();
    let owner = |va: u64| -> Option<u64> { function_owner(&entry_list, va) };

    // Pass A2: resolve single-slot absolute indirect jumps and guarded
    // scaled-index tables (raw x86 only). Entries are fixed above so the
    // resolvers can check same-function attribution without creating
    // entries; resolved targets decode next via the walker's continuation
    // and join block splitting below.
    let jumps = resolve_indirect_jumps(
        &mut walk,
        arch,
        bin.format,
        &space,
        &entry_list,
        MAX_INFERRED_EDGES,
    )?;
    let Walker {
        mut decoded,
        jump_targets,
        fallthroughs,
        diagnostics: mut diagnostic_set,
        ..
    } = walk;

    // Import call sites: the slot map comes from loader-resolved
    // addresses (PE IAT / ELF GOT); stub sites come from decoded
    // `jmp [slot]` shapes, CET `endbr` preludes included (see
    // `collect_stubs`), on Mach-O straight from the loader's stub-entry
    // addresses (see `macho_import_stubs`), or on relocatable objects
    // from the loader's synthetic stub addresses for undefined symbols.
    // Calls through slots are callers, not stubs.
    let slots = import_slots(bin);
    let stubs: BTreeMap<u64, usize> = if bin.relocatable {
        let mut map: BTreeMap<u64, usize> = BTreeMap::new();
        for (i, imp) in bin.imports.iter().enumerate() {
            if let Some(addr) = imp.address {
                map.entry(addr).or_insert(i);
            }
        }
        map
    } else if bin.format == BinaryFormat::MachO {
        macho_import_stubs(bin)
    } else if matches!(arch, Arch::X86_64 | Arch::X86_32) {
        collect_stubs(
            decoded.iter().map(|(&va, d)| {
                (
                    va,
                    d.flow,
                    d.insn.mem_target,
                    d.insn.mnem.as_str(),
                    d.insn.size,
                )
            }),
            &slots,
        )
    } else {
        BTreeMap::new()
    };
    if bin.format == BinaryFormat::MachO && !bin.relocatable {
        let in_stub: Vec<Diagnostic> = diagnostic_set
            .iter()
            .filter(|d| d.kind == DiagnosticKind::UnresolvedIndirectJump)
            .filter(|d| {
                stubs
                    .range(..=d.addr)
                    .next_back()
                    .is_some_and(|(&s, _)| d.addr - s < MACHO_STUB_MAX)
            })
            .copied()
            .collect();
        for d in in_stub {
            diagnostic_set.remove(&d);
        }
    }
    // Tag decoded rows with the import each site calls through.
    for d in decoded.values_mut() {
        if let Some(i) = import_index(&slots, &stubs, d.insn.branch_target, d.insn.mem_target)
            && let Some(imp) = bin.imports.get(i)
        {
            d.insn.import = Some(imp.name.clone());
        }
    }

    // Pass B: split decoded runs into blocks at seeds, targets, fallthroughs.
    let mut starts: BTreeSet<u64> = BTreeSet::new();
    starts.extend(entries.iter().copied());
    starts.extend(jump_targets.iter().copied());
    starts.extend(fallthroughs.iter().copied());
    // MIPS delay slots never start a block: the word after a control
    // instruction executes as part of its branch (see `Walker::run`), so
    // it joins the branch's block instead of splitting it. Function
    // entries keep their start (a call into a delay slot is pathological
    // input, and entries must stay addressable).
    let delay_slots: BTreeSet<u64> = if arch == Arch::Mips32 {
        decoded
            .iter()
            .filter(|(_, d)| d.flow.ends_block())
            .map(|(&va, d)| va.wrapping_add(u64::from(d.insn.size)))
            .filter(|next| decoded.contains_key(next) && !entries.contains(next))
            .collect()
    } else {
        BTreeSet::new()
    };
    for slot in &delay_slots {
        starts.remove(slot);
    }
    let mut blocks: BTreeMap<u64, BasicBlock> = BTreeMap::new();
    let mut cur_start: Option<u64> = None;
    let mut cur: Vec<Insn> = Vec::new();
    let flush =
        |start: &mut Option<u64>, cur: &mut Vec<Insn>, blocks: &mut BTreeMap<u64, BasicBlock>| {
            if let Some(s) = start.take()
                && !cur.is_empty()
            {
                blocks.insert(
                    s,
                    BasicBlock {
                        start: s,
                        insns: std::mem::take(cur),
                    },
                );
            }
        };
    for (&va, d) in &decoded {
        if starts.contains(&va) {
            flush(&mut cur_start, &mut cur, &mut blocks);
            cur_start = Some(va);
        } else if cur_start.is_none() {
            cur_start = Some(va);
        }
        cur.push(d.insn.clone());
        // A MIPS control instruction holds its block open for the delay
        // slot; the flush lands after the slot instead.
        let continues = delay_slots.contains(&va.wrapping_add(u64::from(d.insn.size)));
        if d.flow.ends_block() && !continues {
            flush(&mut cur_start, &mut cur, &mut blocks);
        }
    }
    flush(&mut cur_start, &mut cur, &mut blocks);

    // Export names for entries, then debug-info names, then symbol-table
    // names, then import addresses (Mach-O stubs; PE slots are data and
    // never collide). ELF stubs take `sym@plt` from the stub map below.
    // Precedence per address: export > debug > symbol > import; annotation
    // renames win over all four at display time (see
    // `Project::function_name`). Export addresses normalize like seeds so
    // an odd ARM export still names its function.
    let mut names: BTreeMap<u64, String> = BTreeMap::new();
    for exp in &bin.exports {
        if let Some(addr) = exp.address {
            names
                .entry(normalize_arm_seed(arch, addr).0)
                .or_insert_with(|| exp.name.clone());
        }
    }
    for f in &bin.debug_funcs {
        if let Some(name) = &f.name {
            names.entry(f.address).or_insert_with(|| name.clone());
        }
    }
    for sym in &bin.symbols {
        names.entry(sym.address).or_insert_with(|| sym.name.clone());
    }
    for imp in &bin.imports {
        // ELF slots are data addresses that never collide with entries;
        // ELF stubs take `sym@plt` from the stub map below instead.
        if bin.format == BinaryFormat::Elf {
            continue;
        }
        if let Some(addr) = imp.address {
            names.entry(addr).or_insert_with(|| imp.name.clone());
        }
    }
    // PLT/import-thunk stubs: a `jmp [slot]` site that starts a function
    // serves that import. ELF stubs read `sym@plt`; PE thunks carry the
    // bare import name. `or_insert` keeps the export > symbol > import
    // precedence of the loops above.
    for (&site, &i) in &stubs {
        if !entries.contains(&site) {
            continue;
        }
        let Some(imp) = bin.imports.get(i) else {
            continue;
        };
        let name = match bin.format {
            BinaryFormat::Elf => format!("{}@plt", imp.name),
            _ => imp.name.clone(),
        };
        names.entry(site).or_insert(name);
    }

    // Pass C: assign blocks to functions, build CFGs and the callgraph.
    let mut functions: BTreeMap<u64, Function> = BTreeMap::new();
    for e in &entries {
        functions.insert(
            *e,
            Function {
                entry: *e,
                name: names.get(e).cloned(),
                blocks: BTreeMap::new(),
                cfg: DiGraphMap::new(),
                inferred: BTreeSet::new(),
                reasons: reasons.remove(e).unwrap_or_default(),
                decode_arch: None,
                noreturn: false,
            },
        );
    }
    for (start, block) in blocks {
        let Some(o) = owner(start) else {
            continue;
        };
        if let Some(f) = functions.get_mut(&o) {
            f.cfg.add_node(start);
            f.blocks.insert(start, block);
        }
    }
    functions.retain(|_, f| !f.blocks.is_empty());

    // Per-function decode arch: the arch the entry decoded with, when it
    // differs from the project arch (a user seed mode). Persisted per
    // function so snapshot reload re-decodes identical bytes.
    for (entry, f) in functions.iter_mut() {
        let entry_arch = decoded.get(entry).map(|d| d.arch).unwrap_or(arch);
        f.decode_arch = (entry_arch != arch).then_some(entry_arch);
    }

    // Inferred edges: attribute each resolved `(site, target)` to its
    // site/target blocks, recording the edge only when attribution confirms
    // the same function. Anything else (including a target whose block
    // landed elsewhere) rolls back to unresolved: no edge, no xref, and the
    // site keeps its diagnostic.
    let mut block_func: BTreeMap<u64, u64> = BTreeMap::new();
    for (entry, f) in &functions {
        for start in f.blocks.keys() {
            block_func.insert(*start, *entry);
        }
    }
    let mut resolved_sites: BTreeSet<u64> = BTreeSet::new();
    for (site, target) in &jumps.pairs {
        // Blocks partition decoded addresses across functions, so the site
        // sits in exactly one block; the target is a block start by
        // construction (it joined `jump_targets` before Pass B). Two ordered
        // lookups (function entry, then block start) replace the old scan
        // over every function.
        let hit: Option<(u64, u64)> =
            functions
                .range(..=*site)
                .next_back()
                .and_then(|(&entry, f)| {
                    f.blocks
                        .range(..=*site)
                        .next_back()
                        .filter(|(_, b)| *site < b.end())
                        .map(|(&start, _)| (entry, start))
                });
        match (hit, block_func.get(target)) {
            (Some((func, site_block)), Some(target_func)) if func == *target_func => {
                if let Some(f) = functions.get_mut(&func) {
                    f.inferred.insert((site_block, *target));
                    resolved_sites.insert(*site);
                }
            }
            _ => {}
        }
    }

    let mut callgraph = DiGraphMap::<u64, ()>::new();
    for e in functions.keys() {
        callgraph.add_node(*e);
    }
    // Noreturn calls: stub entries serving known-noreturn imports seed
    // the fixpoint; direct callers and tail jumps propagate (see
    // `plan_noreturn`). Flows are the stored walker flows, exactly as
    // edge building reads them below.
    let mut flows: BTreeMap<(u64, u64), Flow> = BTreeMap::new();
    for (entry, f) in &functions {
        for (start, block) in &f.blocks {
            if let Some(ctrl) = block_control(arch, block) {
                flows.insert(
                    (*entry, *start),
                    decoded
                        .get(&ctrl.addr)
                        .map(|d| d.flow)
                        .unwrap_or_else(|| flow_of(arch, ctrl)),
                );
            }
        }
    }
    let mut seeds = BTreeSet::new();
    for (&site, &i) in &stubs {
        if entries.contains(&site)
            && let Some(imp) = bin.imports.get(i)
            && is_noreturn_import(&imp.name)
        {
            seeds.insert(site);
        }
    }
    let plan = plan_noreturn(&functions, &flows, &seeds);
    // Block-end lookup for edge targets.
    let keys: Vec<u64> = functions.keys().copied().collect();
    let mut cfg_edges: Vec<(u64, u64, u64)> = Vec::new();
    // Callgraph edges carry the caller block: pruned blocks (past cuts)
    // must not contribute edges.
    let mut cg_edges: Vec<(u64, u64, u64)> = Vec::new();
    for entry in keys {
        let Some(f) = functions.get(&entry) else {
            continue;
        };
        for (start, block) in &f.blocks {
            let Some(ctrl) = block_control(arch, block) else {
                continue;
            };
            // Stored walker flow, never a fresh flow_of: Thumb instructions
            // inside an IT block decode without a condition suffix, so only
            // the walker's predicated flow keeps the fallthrough edge. On
            // MIPS32 `ctrl` is the branch (see `block_control`), whose
            // stored flow is the branch's own.
            let flow = decoded
                .get(&ctrl.addr)
                .map(|d| d.flow)
                .unwrap_or_else(|| flow_of(arch, ctrl));
            let end = block.end();
            match flow {
                Flow::Branch { target: Some(t) } => {
                    if f.blocks.contains_key(&t) {
                        cfg_edges.push((entry, *start, t));
                    } else if decoded.contains_key(&t)
                        && let Some(o) = owner(t)
                    {
                        cg_edges.push((entry, *start, o));
                    }
                }
                Flow::Branch { target: None } => {}
                Flow::CBranch { target } => {
                    if let Some(t) = target
                        && f.blocks.contains_key(&t)
                    {
                        cfg_edges.push((entry, *start, t));
                    }
                    if f.blocks.contains_key(&end) {
                        cfg_edges.push((entry, *start, end));
                    }
                }
                Flow::Call { target } => {
                    if let Some(t) = target
                        && decoded.contains_key(&t)
                        && let Some(o) = owner(t)
                    {
                        cg_edges.push((entry, *start, o));
                    }
                    // Noreturn calls never reach the next instruction:
                    // the fall-through edge is cut (see `plan_noreturn`).
                    if plan.cuts.contains(&(entry, *start)) {
                        continue;
                    }
                    if f.blocks.contains_key(&end) {
                        cfg_edges.push((entry, *start, end));
                    }
                }
                Flow::Ret => {}
                Flow::Seq => {
                    if f.blocks.contains_key(&end) {
                        cfg_edges.push((entry, *start, end));
                    }
                }
            }
        }
    }
    // Prune blocks reachable only through cut fall-throughs: they hold
    // bytes the walker decoded past noreturn calls (padding or data),
    // never real continuations. Blocks reachable without cuts (inferred
    // targets included) stay.
    let code: BTreeSet<u64> = functions
        .values()
        .flat_map(|f| f.blocks.keys().copied())
        .collect();
    let inf = inferred_map(&functions);
    let no_inf: BTreeMap<u64, Vec<u64>> = BTreeMap::new();
    let mut pruned: Vec<(u64, u64)> = Vec::new();
    for (entry, f) in &functions {
        let fi = inf.get(entry).unwrap_or(&no_inf);
        let (uncut, _) = walk_function(f, &flows, fi, &plan.noreturn, &owner, &code, false);
        let (cut, _) = walk_function(f, &flows, fi, &plan.noreturn, &owner, &code, true);
        pruned.extend(uncut.difference(&cut).map(|b| (*entry, *b)));
    }
    for (entry, start) in &pruned {
        if let Some(f) = functions.get_mut(entry) {
            f.blocks.remove(start);
            f.cfg.remove_node(*start);
        }
    }
    for f in functions.values_mut() {
        f.inferred
            .retain(|(a, b)| f.blocks.contains_key(a) && f.blocks.contains_key(b));
    }
    for (func, a, b) in cfg_edges {
        if let Some(f) = functions.get_mut(&func)
            && f.blocks.contains_key(&a)
            && f.blocks.contains_key(&b)
        {
            f.cfg.add_edge(a, b, ());
        }
    }
    for (a, blk, b) in cg_edges {
        if functions
            .get(&a)
            .is_some_and(|f| f.blocks.contains_key(&blk))
            && functions.contains_key(&b)
        {
            callgraph.add_edge(a, b, ());
        }
    }
    // One record per cut call site that survived pruning (pruned sites
    // are unreachable padding; the surviving cut marks the real edge).
    for (func, block) in &plan.cuts {
        if let Some(site) = functions
            .get(func)
            .and_then(|f| f.blocks.get(block))
            .and_then(|b| b.insns.last())
            .map(|i| i.addr)
        {
            diagnostic_set.insert(Diagnostic {
                addr: site,
                kind: DiagnosticKind::NoreturnCut,
            });
        }
    }
    for (entry, f) in functions.iter_mut() {
        f.noreturn = plan.noreturn.contains(entry);
    }

    // Pass D: xrefs. Code from direct branch/call targets, data from
    // PC-relative accesses and x86-32 absolute immediates/displacements
    // into a segment, string refs where data lands in a recovered string.
    // Inferred edges add one provenance-marked `InferredCode` xref per
    // resolved site (single-slot) or per unique entry target (tables);
    // the single-slot `Data` slot xref above is retained, and table sites
    // add one `Data` xref per scanned slot.
    let mut xrefs: BTreeSet<(u64, XrefKind, u64)> = BTreeSet::new();
    for (&va, d) in &decoded {
        let target = match d.flow {
            Flow::Branch { target } | Flow::CBranch { target } | Flow::Call { target } => target,
            _ => None,
        };
        if let Some(t) = target {
            xrefs.insert((va, XrefKind::Code, t));
        }
        if let Some(m) = d.insn.mem_target
            && space.contains(m)
        {
            xrefs.insert((va, XrefKind::Data, m));
        }
        // ARM literal-pool loads (`ldr rX, [pc, #imm]`) resolve the pool
        // word above; the word's value is the real pointer, so reference
        // it too. Only the word form carries a pointer: the byte/halfword
        // literal loads read narrower values from the same pool shape.
        if matches!(d.arch, Arch::Arm32 | Arch::Thumb)
            && arm_base_mnem(&d.insn.mnem) == "ldr"
            && let Some(slot) = d.insn.mem_target
            && let Some(raw) = space.file_bytes_at(slot, 4)
        {
            let value = u64::from(u32::from_le_bytes([raw[0], raw[1], raw[2], raw[3]]));
            if space.contains(value) {
                xrefs.insert((va, XrefKind::Data, value));
            }
        }
        // Import rows: indirect slot references and direct stub/thunk
        // targets both resolve to the import's slot address.
        if let Some(i) = import_index(&slots, &stubs, target, d.insn.mem_target)
            && let Some(slot) = bin.imports.get(i).and_then(|imp| imp.address)
        {
            xrefs.insert((va, XrefKind::Import, slot));
        }
    }
    // ARM64 `adrp` decodes to its 4K page base; the page offset rides in
    // the next instruction (`add`/`ldr`). Where an adjacent same-block
    // pair resolves, the second instruction references the final address
    // too; the page-base row above is retained as the strict fallback.
    // ARM32 `movw`/`movt` pairs behave the same way (see
    // `resolve_movw_pair`): the low half rides in the first row, the high
    // half in the second. MIPS32 `lui` pairs behave the same way too (see
    // `resolve_mips_pair`): the high half rides in the first row, the low
    // half in the second (`addiu`/`addu`/load/store). RISC-V `auipc`
    // pairs behave the same way too (see `resolve_auipc_pair`): the page
    // rides in `auipc`, the low 12 bits in the next
    // `addi`/`addiw`/`lw`/`ld`/`sw`.
    for f in functions.values() {
        for block in f.blocks.values() {
            for pair in block.insns.windows(2) {
                if let Some(final_addr) = resolve_const_pair(&pair[0], &pair[1])
                    && space.contains(final_addr)
                {
                    xrefs.insert((pair[1].addr, XrefKind::Data, final_addr));
                }
            }
        }
    }
    for (site, target) in &jumps.pairs {
        if resolved_sites.contains(site) {
            xrefs.insert((*site, XrefKind::InferredCode, *target));
        }
    }
    for (site, slot) in &jumps.slots {
        if resolved_sites.contains(site) {
            xrefs.insert((*site, XrefKind::Data, *slot));
        }
    }
    let mut strings: Vec<StringHit> = Vec::new();
    for seg in &space.all {
        for mut h in strings::extract(
            &seg.data,
            strings::DEFAULT_MIN_LEN,
            strings::DEFAULT_MAX_HITS,
            Some(seg.vaddr),
        ) {
            let (section, executable) = locate_hit(&bin.sections, seg, h.vaddr);
            h.section = section;
            h.executable = executable;
            strings.push(h);
        }
    }
    strings.sort_by_key(|h| h.vaddr.unwrap_or(u64::MAX));
    let spans: Vec<(u64, u64)> = strings
        .iter()
        .filter_map(|h| {
            // String-xref recovery spans the byte-exact classic passes
            // only (ASCII plus ASCII-subset UTF-16). Multibyte hits
            // (UTF-8, BMP letters) are listing coverage: their shifted
            // readings of code and ASCII text would otherwise swallow
            // neighboring classic spans and reroute established string
            // refs, so they never participate in xref recovery.
            let len = match h.encoding {
                Encoding::Ascii => h.value.len() as u64,
                Encoding::Utf16Le | Encoding::Utf16Be => h.value.len() as u64 * 2,
                Encoding::Utf8 | Encoding::Utf16LeBmp | Encoding::Base64 => return None,
            };
            h.vaddr.map(|v| (v, v.wrapping_add(len)))
        })
        .collect();
    let span_index = StringSpanIndex::new(spans);
    let data_tos: Vec<(u64, u64)> = xrefs
        .iter()
        .filter(|(_, k, _)| *k == XrefKind::Data)
        .map(|(f, _, t)| (*f, *t))
        .collect();
    for (from, to) in data_tos {
        if let Some(s) = span_index.lookup(to) {
            xrefs.insert((from, XrefKind::String, s));
        }
    }
    let xrefs: Vec<Xref> = xrefs
        .into_iter()
        .map(|(from, kind, to)| Xref { from, to, kind })
        .collect();
    // Inferred rows count jointly against the `Code` budget so they cannot
    // evade the cap by relabeling; hard budgets stay [`Error::Limit`].
    let code_like = xrefs
        .iter()
        .filter(|x| matches!(x.kind, XrefKind::Code | XrefKind::InferredCode))
        .count();
    if code_like > MAX_XREFS_PER_KIND {
        return Err(Error::Limit(format!(
            "more than {MAX_XREFS_PER_KIND} {:?} xrefs",
            XrefKind::Code
        )));
    }
    for kind in [XrefKind::Data, XrefKind::String, XrefKind::Import] {
        if xrefs.iter().filter(|x| x.kind == kind).count() > MAX_XREFS_PER_KIND {
            return Err(Error::Limit(format!(
                "more than {MAX_XREFS_PER_KIND} {kind:?} xrefs"
            )));
        }
    }

    // Resolved sites leave the diagnostics set; failed and skipped sites
    // keep theirs.
    for site in &resolved_sites {
        diagnostic_set.remove(&Diagnostic {
            addr: *site,
            kind: DiagnosticKind::UnresolvedIndirectJump,
        });
    }
    let mut diagnostics = Diagnostics::collect(diagnostic_set.into_iter().collect(), false, 0);
    diagnostics.inferred_truncated = jumps.truncated;
    diagnostics.inferred_omitted = jumps.omitted;

    Ok(Analysis {
        arch,
        functions,
        callgraph,
        xrefs,
        to_index: OnceLock::new(),
        import_stubs: stubs,
        strings,
        diagnostics,
    })
}

/// Analyze a raw byte blob mapped at `base`, for tests and shellcode.
pub fn analyze_raw(bytes: &[u8], base: u64, arch: Arch, entry: Option<u64>) -> Result<Analysis> {
    let bin = load_raw(bytes, RawOptions { base, arch, entry })?;
    analyze(&bin)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn flow_of_maps_lift_ops() {
        let ret = Insn {
            addr: 0x1000,
            size: 1,
            bytes: vec![0xC3],
            mnem: "ret".to_string(),
            ops: Vec::new(),
            branch_target: None,
            mem_target: None,
            table_base: None,
            import: None,
            target_name: None,
            comment: None,
            string: None,
            operands: Vec::new(),
            thumb: false,
        };
        assert_eq!(flow_of(Arch::X86_64, &ret), Flow::Ret);
        let call = Insn {
            addr: 0x1000,
            size: 5,
            bytes: vec![0xE8, 0, 0, 0, 0],
            mnem: "call".to_string(),
            ops: vec!["0x1005".to_string()],
            branch_target: Some(0x1005),
            mem_target: None,
            table_base: None,
            import: None,
            target_name: None,
            comment: None,
            string: None,
            operands: Vec::new(),
            thumb: false,
        };
        assert_eq!(
            flow_of(Arch::X86_64, &call),
            Flow::Call {
                target: Some(0x1005)
            }
        );
    }

    #[test]
    fn pages_truncate_at_max_page() {
        let items: Vec<u64> = (0..10).collect();
        assert_eq!(page_slice(&items, 0, usize::MAX).len(), 10);
        assert!(page_slice(&items, 0, 3) == [0, 1, 2]);
        assert!(page_slice(&items, 20, 5).is_empty());
    }

    #[test]
    fn block_id_is_stable() {
        let b = BasicBlock {
            start: 0x2007,
            insns: Vec::new(),
        };
        assert_eq!(b.id(0x2000), "block@0x2000+0x2007");
    }

    #[test]
    fn noreturn_import_names_are_exact() {
        for name in [
            "exit",
            "_exit",
            "_Exit",
            "abort",
            "quick_exit",
            "longjmp",
            "siglongjmp",
            "pthread_exit",
            "exit_group",
            "__assert_fail",
            "__assert_rtn",
            "__stack_chk_fail",
            "__fortify_fail",
            "_Unwind_Resume",
            "__cxa_throw",
            "__cxa_rethrow",
            "ExitProcess",
            "ExitThread",
            "TerminateProcess",
            "TerminateThread",
            "FatalExit",
            "os_fatal",
            // Mach-O `_` prefix convention.
            "_abort",
            "___stack_chk_fail",
            "_pthread_exit",
        ] {
            assert!(is_noreturn_import(name), "{name:?} is noreturn");
        }
        for name in [
            "foo",
            "myexit",
            "exit2",
            "exiting",
            "Exit",
            "ABORT",
            "abort_handler",
            "pthread_create",
            "",
        ] {
            assert!(!is_noreturn_import(name), "{name:?} returns");
        }
    }

    /// Eager pre-fix oracle: collect every candidate, sort, dedup, filter,
    /// cap. For ARM this is verbatim the old behavior; for x86 it is the
    /// specified sorted-prefix contract (the old code stopped over-budget
    /// inputs in collection order instead of sorting).
    fn oracle_seeds(arch: Arch, space: &AddrSpace, reached: &BTreeSet<u64>) -> Result<Vec<u64>> {
        let mut out: Vec<u64> = Vec::new();
        for seg in &space.exec {
            if arch == Arch::Aarch64 {
                let mut off = 0usize;
                while off + 4 <= seg.data.len() {
                    let raw = seg.data.get(off..off + 4).expect("word in bounds");
                    let w = u32::from_le_bytes(raw.try_into().expect("word converts"));
                    if (w & 0xFFC0_7FFF) == 0xA980_7BFD {
                        out.push(seg.vaddr.wrapping_add(off as u64));
                    }
                    off += 4;
                }
                continue;
            }
            if arch == Arch::Arm32 {
                let mut off = 0usize;
                while off + 4 <= seg.data.len() {
                    let raw = seg.data.get(off..off + 4).expect("word in bounds");
                    let w = u32::from_le_bytes(raw.try_into().expect("word converts"));
                    if is_arm_push_lr(w) {
                        out.push(seg.vaddr.wrapping_add(off as u64));
                    }
                    off += 4;
                }
                continue;
            }
            if arch == Arch::Thumb {
                let mut off = 0usize;
                while off + 2 <= seg.data.len() {
                    let raw = seg.data.get(off..off + 2).expect("halfword in bounds");
                    let hw = u16::from_le_bytes(raw.try_into().expect("halfword converts"));
                    if (hw & 0xFF00) == 0xB500 && (hw & 0x0100) != 0 {
                        out.push(seg.vaddr.wrapping_add(off as u64));
                    } else if off + 4 <= seg.data.len() {
                        let raw = seg.data.get(off..off + 4).expect("word in bounds");
                        let w = u32::from_le_bytes(raw.try_into().expect("word converts"));
                        if is_arm_push_lr(w) {
                            out.push(seg.vaddr.wrapping_add(off as u64));
                        }
                    }
                    off += 2;
                }
                continue;
            }
            if arch == Arch::Riscv32 || arch == Arch::Riscv64 {
                let mut off = 0usize;
                while off + 2 <= seg.data.len() {
                    let raw = seg.data.get(off..off + 2).expect("halfword in bounds");
                    let hw = u16::from_le_bytes(raw.try_into().expect("halfword converts"));
                    if is_riscv_c_addi16sp(hw) {
                        out.push(seg.vaddr.wrapping_add(off as u64));
                    } else if off + 4 <= seg.data.len() {
                        let raw = seg.data.get(off..off + 4).expect("word in bounds");
                        let w = u32::from_le_bytes(raw.try_into().expect("word converts"));
                        if is_riscv_addi_sp(w) {
                            out.push(seg.vaddr.wrapping_add(off as u64));
                        }
                    }
                    off += 2;
                }
                continue;
            }
            if arch == Arch::Mips32 {
                let mut off = 0usize;
                while off + 4 <= seg.data.len() {
                    let raw = seg.data.get(off..off + 4).expect("word in bounds");
                    let w = u32::from_le_bytes(raw.try_into().expect("word converts"));
                    if is_mips_addiu_sp(w) {
                        out.push(seg.vaddr.wrapping_add(off as u64));
                    }
                    off += 4;
                }
                continue;
            }
            for pat in prologue_patterns(arch) {
                for (i, win) in seg.data.windows(pat.len()).enumerate() {
                    if win != *pat {
                        continue;
                    }
                    let mut va = seg.vaddr.wrapping_add(i as u64);
                    if i > 0 && seg.data[i - 1] == 0x55 {
                        va = va.wrapping_sub(1);
                    }
                    out.push(va);
                }
            }
        }
        out.sort_unstable();
        out.dedup();
        let mut seeds: Vec<u64> = Vec::new();
        for va in out {
            if seeds.len() >= MAX_SEEDS {
                break;
            }
            if !reached.contains(&va) && decode_one(arch, space, va)?.is_some() {
                seeds.push(va);
            }
        }
        Ok(seeds)
    }

    fn seed_test_binary(arch: Arch, entry: Option<u64>, segs: Vec<(u64, Vec<u8>)>) -> LoadedBinary {
        LoadedBinary {
            format: crate::loader::BinaryFormat::Raw,
            arch,
            entry,
            segments: segs
                .into_iter()
                .map(|(vaddr, data)| Segment {
                    vaddr,
                    mem_size: data.len() as u64,
                    data,
                    readable: true,
                    writable: false,
                    executable: true,
                })
                .collect(),
            sections: Vec::new(),
            imports: Vec::new(),
            exports: Vec::new(),
            symbols: Vec::new(),
            pdata_funcs: Vec::new(),
            tls_callbacks: Vec::new(),
            init_funcs: Vec::new(),
            func_starts: Vec::new(),
            debug_funcs: Vec::new(),
            relocatable: false,
            arm_hints: Default::default(),
        }
    }

    /// One match (`M`), decoder-rejected match (`U`), or junk (`J`) unit.
    fn seed_words(arch: Arch) -> (&'static [u8], &'static [u8], &'static [u8]) {
        match arch {
            Arch::Aarch64 => (
                &[0xFD, 0x7B, 0x80, 0xA9],
                &[0xFD, 0x7B, 0x80, 0xA9],
                &[0x1F, 0x20, 0x03, 0xD5],
            ),
            Arch::Arm32 => (
                &[0xF0, 0x40, 0x2D, 0xE9],
                &[0xF0, 0x40, 0x2D, 0xF9],
                &[0x1E, 0xFF, 0x2F, 0xE1],
            ),
            Arch::Thumb => (&[0xF0, 0xB5], &[0xF0, 0xB5], &[0x00, 0xBF]),
            // `addi sp, sp, -16`; the reserved `c.addi16sp` zero-immediate
            // form still decodes (no rejected form exists, so U behaves
            // as a second M, like Aarch64); `c.unimp` junk.
            Arch::Riscv32 | Arch::Riscv64 => {
                (&[0x13, 0x01, 0x01, 0xFF], &[0x01, 0x61], &[0x00, 0x00])
            }
            // `addiu sp, sp, -16`; every masked word decodes (no rejected
            // form exists, so U behaves as a second M, like Aarch64);
            // all-set junk.
            Arch::Mips32 => (
                &[0xF0, 0xFF, 0xBD, 0x27],
                &[0xF0, 0xFF, 0xBD, 0x27],
                &[0xFF, 0xFF, 0xFF, 0xFF],
            ),
            // `stwu r1, -16(r1)` big-endian; every masked word decodes (no
            // rejected form exists, so U behaves as a second M, like
            // Aarch64); all-set junk.
            Arch::Ppc32 | Arch::Ppc64 => (
                &[0x94, 0x21, 0xFF, 0xF0],
                &[0x94, 0x21, 0xFF, 0xF0],
                &[0xFF, 0xFF, 0xFF, 0xFF],
            ),
            Arch::X86_64 => (&[0x48, 0x89, 0xE5], &[0x48, 0x89, 0xE5], &[0x90]),
            Arch::X86_32 => (&[0x89, 0xE5], &[0x89, 0xE5], &[0x90]),
        }
    }

    /// Adversarial layout: out-of-order file order, an overlap with
    /// identical bytes (duplicate addresses), a wrapped segment, empty and
    /// short segments, and a zero-based segment.
    fn tricky_segments(arch: Arch) -> Vec<(u64, Vec<u8>)> {
        let (m, u, j) = seed_words(arch);
        let mut hi = Vec::new();
        for w in [m, j, m, u, j, m] {
            hi.extend_from_slice(w);
        }
        hi.push(0x00);
        if arch == Arch::Thumb {
            // 32-bit ARM-form word where the halfword is not a push; kept
            // halfword-aligned so the scan's word branch can hit it.
            hi.push(0x00);
            hi.extend_from_slice(&[0xF0, 0x40, 0x2D, 0xE9]);
        }
        if arch == Arch::X86_64 || arch == Arch::X86_32 {
            // Leading `push rbp`/`push ebp` steps the next match back a byte.
            hi.push(0x55);
            hi.extend_from_slice(m);
        }
        let mut lo = Vec::new();
        lo.extend_from_slice(j);
        lo.extend_from_slice(j);
        lo.extend_from_slice(&hi[..0x18.min(hi.len())]);
        let mut wrap = Vec::new();
        while wrap.len() + m.len() + j.len() <= 16 {
            wrap.extend_from_slice(m);
            wrap.extend_from_slice(j);
        }
        // End on a match so the wrapped-low tail holds a candidate.
        wrap.truncate(16 - m.len());
        wrap.extend_from_slice(m);
        let mut zero = Vec::new();
        for w in [m, j, m] {
            zero.extend_from_slice(w);
        }
        vec![
            (0x5000, hi),
            (0x4FF0, lo),
            (u64::MAX - 8, wrap),
            (0x6000, Vec::new()),
            (0x6100, vec![0x90]),
            (0, zero),
        ]
    }

    #[test]
    fn seed_streams_match_eager_oracle() {
        for arch in [
            Arch::Aarch64,
            Arch::Arm32,
            Arch::Thumb,
            Arch::X86_64,
            Arch::X86_32,
            Arch::Riscv32,
            Arch::Riscv64,
            Arch::Mips32,
        ] {
            let bin = seed_test_binary(arch, None, tricky_segments(arch));
            let space = AddrSpace::new(&bin);
            let reached: BTreeSet<u64> = [0x5000, 0x5001, 0x5002, 0x5003, 0x4FF0, u64::MAX, 1]
                .into_iter()
                .collect();
            let got =
                prologue_seeds(arch, &space, |va| reached.contains(&va)).expect("streaming seeds");
            let want = oracle_seeds(arch, &space, &reached).expect("oracle seeds");
            assert_eq!(got, want, "seed mismatch for {arch:?}");
            assert!(
                got.windows(2).all(|w| w[0] < w[1]),
                "seeds must be sorted and deduped for {arch:?}"
            );
        }
    }

    #[test]
    fn x86_wrap_edge_step_back_sorts_last() {
        // Pattern at the wrap point with a `0x55` step-back lands on
        // `u64::MAX`; it must sort after the high run, not first.
        let vaddr = u64::MAX - 4;
        let data = vec![
            0x48, 0x89, 0xE5, 0x90, 0x55, 0x48, 0x89, 0xE5, 0x48, 0x89, 0xE5,
        ];
        let bin = seed_test_binary(Arch::X86_64, None, vec![(vaddr, data)]);
        let space = AddrSpace::new(&bin);
        let reached = BTreeSet::new();
        let got = prologue_seeds(Arch::X86_64, &space, |va| reached.contains(&va)).expect("seeds");
        // `vaddr + 8` wraps to `3`, which is unmapped (`seg_at` uses plain
        // comparison), so it is offered first and rejected; the stashed
        // `u64::MAX` still sorts after the high run.
        assert_eq!(got, [vaddr, u64::MAX]);
        let want = oracle_seeds(Arch::X86_64, &space, &reached).expect("oracle");
        assert_eq!(got, want);
    }

    /// Drive Pass A plus entry computation over `bytes`, then resolve with
    /// an explicit edge budget. Mirrors [`analyze`] without block building.
    fn run_inferred_cap(
        bytes: &[u8],
        max_edges: usize,
    ) -> (Vec<(u64, u64)>, bool, usize, Vec<u64>) {
        let bin = load_raw(
            bytes,
            RawOptions {
                base: 0x1000,
                arch: Arch::X86_32,
                entry: Some(0x1000),
            },
        )
        .expect("raw loads");
        let space = AddrSpace::new(&bin);
        let mut walk = Walker::new(&space);
        let seeds = authoritative_seeds(&space, &bin, &[], AnalyzeOptions::default()).0;
        walk.run(seeds.clone()).expect("round one walks");
        let seeds2 = prologue_seeds(Arch::X86_32, &space, |va| walk.decoded.contains_key(&va))
            .expect("prologue scans");
        walk.run(seeds2.iter().map(|&a| (a, Arch::X86_32)).collect())
            .expect("round two walks");
        let mut entries: BTreeSet<u64> = BTreeSet::new();
        for s in seeds.iter().map(|(a, _)| a).chain(seeds2.iter()) {
            if walk.decoded.contains_key(s) {
                entries.insert(*s);
            }
        }
        let targets: Vec<u64> = walk.call_targets.iter().copied().collect();
        for t in targets {
            if walk.decoded.contains_key(&t) {
                entries.insert(t);
            }
        }
        let entry_list: Vec<u64> = entries.into_iter().collect();
        let jumps = resolve_indirect_jumps(
            &mut walk,
            Arch::X86_32,
            BinaryFormat::Raw,
            &space,
            &entry_list,
            max_edges,
        )
        .expect("resolution walks");
        (jumps.pairs, jumps.truncated, jumps.omitted, entry_list)
    }

    #[test]
    fn inferred_cap_reports_omissions_without_clipping() {
        // Two Pass-A-visible single-slot sites (x86-32, 27 bytes): the
        // entry calls 0x1010, each site jumps through its own slot at a
        // same-function ret.
        let bytes = vec![
            0xE8, 0x0B, 0x00, 0x00, 0x00, // 0x1000: call 0x1010
            0xFF, 0x25, 0x0B, 0x10, 0x00, 0x00, // 0x1005: jmp [0x100b]
            0x0F, 0x10, 0x00, 0x00, // 0x100b: dd 0x100f
            0xC3, // 0x100f: ret
            0xFF, 0x25, 0x16, 0x10, 0x00, 0x00, // 0x1010: jmp [0x1016]
            0x1A, 0x10, 0x00, 0x00, // 0x1016: dd 0x101a
            0xC3, // 0x101a: ret
        ];
        assert_eq!(bytes.len(), 27);
        // A budget of one resolves the first site and counts the skip
        // explicitly; the skipped site is left for the caller unresolved.
        let (pairs, truncated, omitted, entries) = run_inferred_cap(&bytes, 1);
        assert_eq!(entries, [0x1000, 0x1010]);
        assert_eq!(pairs, [(0x1005, 0x100F)]);
        assert!(truncated);
        assert_eq!(omitted, 1);
        // A full budget resolves both with clean accounting.
        let (pairs, truncated, omitted, _) = run_inferred_cap(&bytes, MAX_INFERRED_EDGES);
        assert_eq!(pairs, [(0x1005, 0x100F), (0x1010, 0x101A)]);
        assert!(!truncated);
        assert_eq!(omitted, 0);
    }

    #[test]
    fn table_cap_counts_unique_edges_against_shared_budget() {
        // One guarded x86-32 table site (base 0x1000): two slots, two
        // unique same-function ret targets, probe slot past the cap
        // window holding nop bytes (unmapped value, exact end).
        let mut bytes = vec![
            0x83, 0xF8, 0x01, // 0x1000: cmp eax,1
            0x73, 0x07, // 0x1003: jae 0x100c
            0xFF, 0x24, 0x85, 0x12, 0x10, 0x00, 0x00, // 0x1005: jmp [eax*4+0x1012]
            0xB8, 0x01, 0x00, 0x00, 0x00, // 0x100c: mov eax,1
            0xC3, // 0x1011: ret
            0x22, 0x10, 0x00, 0x00, // 0x1012: slot 0 -> 0x1022
            0x23, 0x10, 0x00, 0x00, // 0x1016: slot 1 -> 0x1023
        ];
        bytes.extend([0x90; 8]); // 0x101a: probe window (value unmapped)
        bytes.extend([0xC3, 0xC3]); // 0x1022/0x1023: bodies
        assert_eq!(bytes.len(), 36);
        // A budget below the unique-edge cost skips the whole site and
        // counts every edge that would have resolved, never a prefix.
        let (pairs, truncated, omitted, entries) = run_inferred_cap(&bytes, 1);
        assert_eq!(entries, [0x1000]);
        assert!(pairs.is_empty());
        assert!(truncated);
        assert_eq!(omitted, 2);
        // A full budget resolves both edges with clean accounting.
        let (pairs, truncated, omitted, _) = run_inferred_cap(&bytes, MAX_INFERRED_EDGES);
        assert_eq!(pairs, [(0x1005, 0x1022), (0x1005, 0x1023)]);
        assert!(!truncated);
        assert_eq!(omitted, 0);
    }

    #[test]
    fn seed_budget_truncates_accepted_prefix() {
        // 120k raw candidates with the first 12k reached: rejected rows must
        // not consume budget, so seeds are the next 100k accepted addresses.
        for arch in [
            Arch::Aarch64,
            Arch::Arm32,
            Arch::Thumb,
            Arch::X86_64,
            Arch::X86_32,
            Arch::Riscv32,
            Arch::Riscv64,
            Arch::Mips32,
        ] {
            let (m, _, _) = seed_words(arch);
            let base: u64 = 0x1_0000;
            let period = m.len() as u64;
            let raw: usize = 120_000;
            let mut data = Vec::with_capacity(raw * m.len());
            for _ in 0..raw {
                data.extend_from_slice(m);
            }
            let bin = seed_test_binary(arch, None, vec![(base, data)]);
            let space = AddrSpace::new(&bin);
            let reached: BTreeSet<u64> = (0..12_000).map(|i| base + i * period).collect();
            let got =
                prologue_seeds(arch, &space, |va| reached.contains(&va)).expect("streaming seeds");
            let want = oracle_seeds(arch, &space, &reached).expect("oracle seeds");
            assert_eq!(got.len(), MAX_SEEDS, "budget must fill for {arch:?}");
            assert_eq!(got, want, "truncated prefix mismatch for {arch:?}");
            assert_eq!(got[0], base + 12_000 * period);
            assert!(got.windows(2).all(|w| w[0] < w[1]));
        }
    }
}