rustrip 0.1.14

Make stripped Rust binaries readable again: recover slice-string boundaries, demangle symbols, and reconstruct panic source locations from release/stripped ELF, PE, and Mach-O binaries.
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
//! Parsed-binary model: ELF / PE / Mach-O, with `vaddr <-> file offset`
//! translation and size-aware readers.
//!
//! The model is intentionally narrow: it exposes only what analyzers need
//! (`Section`s, `Symbol`s, byte reads by virtual address, target architecture
//! bitness). Anything richer (full disassembly, relocation processing) is
//! deliberately out of scope — `rustrip` reasons about *data*, not control
//! flow, in v0.1.

use anyhow::{anyhow, Context, Result};
use goblin::{elf, mach, pe, Object};

use goblin::mach::constants::cputype::{
    CPU_TYPE_ARM, CPU_TYPE_ARM64, CPU_TYPE_ARM64_32, CPU_TYPE_I386, CPU_TYPE_POWERPC,
    CPU_TYPE_POWERPC64, CPU_TYPE_X86_64,
};

const RANGE_TREE_MARKER: u64 = u64::MAX;
const RANGE_TREE_INDEX: usize = usize::MAX;
/// Cap input before cloning it. Preflight below bounds parser-controlled tables,
/// while 128 MiB keeps the two owned input copies and linear validation work
/// proportionate for a command-line analysis tool.
pub const MAX_INPUT_BYTES: usize = 128 * 1024 * 1024;
/// Maximum entries in any parser-controlled table.
const MAX_TABLE_ENTRIES: usize = 65_536;
/// Bound table families which can contain multiple independently sized tables.
const MAX_AGGREGATE_TABLE_ENTRIES: usize = MAX_TABLE_ENTRIES * 4;
/// Hard ceiling for all owned symbol names, including repeated references to one
/// on-disk string.
const MAX_OWNED_SYMBOL_NAME_BYTES: usize = 16 * 1024 * 1024;
/// Names may consume at most four times the input size in aggregate.
const SYMBOL_NAME_INPUT_MULTIPLIER: usize = 4;

/// The executable format of a parsed binary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinaryFormat {
    /// ELF (Unix/Linux).
    Elf,
    /// PE (Windows).
    Pe,
    /// Mach-O (macOS/iOS).
    MachO,
}

/// A named section from the binary's section table.
#[derive(Debug, Clone)]
pub struct Section {
    /// Section name (e.g. `.rodata`, `.text`).
    pub name: String,
    /// Virtual address where the section is loaded.
    pub vaddr: u64,
    /// Declared size from the section header.
    pub size: u64,
    /// Available file-backed bytes for this section. These may be shorter
    /// than `size` for truncated or zero-filled regions, or longer for PE
    /// sections whose raw data is file-alignment padded beyond virtual size.
    pub data: Vec<u8>,
}

/// A symbol from the binary's symbol table.
#[derive(Debug, Clone)]
pub struct Symbol {
    /// Virtual address of the symbol.
    pub vaddr: u64,
    /// Raw symbol name as stored in the object (usually still mangled).
    pub name: String,
    /// Symbol size (0 if unknown).
    pub size: u64,
}

/// In-memory parsed object representing a single executable format.
///
/// File bytes are kept so that vaddrs can be resolved even if sections were
/// truncated on disk (NOBITS, sparse Mach-O, etc.) — readers return `None`
/// rather than panic when ranges fall outside the loaded segment.
pub struct Binary {
    pub path: Option<String>,
    pub format: BinaryFormat,
    pub arch: String,
    /// `true` when the target pointer ABI is 64-bit, `false` when it is
    /// 32-bit. Analyzers size their pointer reads off this flag.
    pub is_64: bool,
    pub little_endian: bool,
    pub bytes: Vec<u8>,
    // External callers use the read-only accessors below, which keeps this
    // cache synchronized with its source sections. Unit tests retain narrowly
    // scoped crate visibility for malformed-fixture coverage.
    #[cfg(not(test))]
    sections: Vec<Section>,
    #[cfg(test)]
    pub(crate) sections: Vec<Section>,
    pub symbols: Vec<Symbol>,

    /// Augmented interval tree built exclusively from `sections`.
    #[cfg(not(test))]
    sec_by_vaddr: Vec<(u64, u64, usize)>,
    #[cfg(test)]
    pub(crate) sec_by_vaddr: Vec<(u64, u64, usize)>,
    /// Indices into `sections` of sections we believe may host string bytes.
    #[cfg(not(test))]
    string_sections: Vec<usize>,
    #[cfg(test)]
    pub(crate) string_sections: Vec<usize>,
}

impl Binary {
    /// Parse a raw object file (ELF, PE, or single-arch Mach-O).
    ///
    /// The input is cloned once internally so that the parsed object's
    /// `&[u8]` references (via `Elf<'_>`, `PE<'_>`, `Mach<'_>`) stay valid
    /// until we finish copying them out into owned types.
    ///
    /// # Errors
    ///
    /// Returns `Err` when the input exceeds [`MAX_INPUT_BYTES`], goblin cannot
    /// recognize the format, the object is truncated, an ar archive is passed
    /// (we do not dereference archive members in v0.1), or a Mach-O fat archive
    /// is passed (we only support single-arch slices). Any panic raised by
    /// goblin's parser on a malformed object (e.g. Mach-O `LC_MAIN` load commands
    /// that trigger subtract-with-overflow in goblin 0.8.2) is also converted
    /// to `Err`, so a hostile object cannot abort the process.
    pub fn parse(path: Option<&str>, bytes: Vec<u8>) -> Result<Self> {
        validate_input_len(bytes.len())?;
        preflight_object(&bytes)?;
        let parse_buffer = bytes.clone();
        // Preflight bounds every parser-controlled table before goblin sees
        // the object, but goblin 0.8.2 can still panic on load commands its
        // internal walker does not range-check (notably Mach-O LC_MAIN with
        // values that trigger subtract-with-overflow at mach/mod.rs:280). Wrap
        // the call so any residual panic surfaces as `Err` instead of aborting.
        let obj = std::panic::catch_unwind(|| Object::parse(&parse_buffer))
            .map_err(|_| anyhow!("goblin: parser panicked on malformed object"))?
            .context("goblin: failed to parse object")?;
        // The loaders iterate goblin's already-parsed views (sections, symbols,
        // string tables), which can still panic on edge cases goblin's
        // `Object::parse` did not range-check. Guard the dispatch so any
        // residual panic surfaces as `Err` instead of aborting.
        std::panic::catch_unwind(|| match obj {
            Object::Elf(elf) => load_elf(path, &elf, bytes),
            Object::PE(pe) => load_pe(path, &pe, bytes),
            Object::Mach(mach) => load_mach(path, &mach, bytes),
            _ => Err(anyhow!("unsupported object kind (likely archive)")),
        })
        .map_err(|_| anyhow!("goblin: loader panicked on malformed object"))?
    }

    /// Translate `vaddr` to `(section_index, offset_within_section)`. Returns
    /// `None` if `vaddr` falls outside the span of any loaded section. If
    /// ranges overlap, the containing section with the highest start address
    /// (then the smallest span) wins.
    #[must_use]
    pub fn vaddr_to_offset(&self, vaddr: u64) -> Option<(usize, usize)> {
        let read_end = vaddr.checked_add(1)?;
        self.lookup_range(vaddr, read_end, None, false)
    }

    /// Read `len` bytes at `vaddr`. Returns `None` if any byte falls
    /// outside the section bounds or the backing `data` is too short.
    #[must_use]
    pub fn read_at_vaddr(&self, vaddr: u64, len: usize) -> Option<&[u8]> {
        let read_end = vaddr.checked_add(u64::try_from(len).ok()?)?;
        let (section_index, offset) = self.lookup_range(vaddr, read_end, Some(len), false)?;
        let section = self.sections.get(section_index)?;
        let data_end = offset.checked_add(len)?;
        section.data.get(offset..data_end)
    }

    /// Read a pointer-sized value (4 bytes on 32-bit, 8 on 64-bit) at
    /// `vaddr`, respecting the binary's endianness.
    #[must_use]
    pub fn read_ptr(&self, vaddr: u64) -> Option<u64> {
        let sz = if self.is_64 { 8 } else { 4 };
        let bytes = self.read_at_vaddr(vaddr, sz)?;
        Some(if self.little_endian {
            read_le_ptr(bytes, self.is_64)
        } else {
            read_be_ptr(bytes, self.is_64)
        })
    }

    /// Read a u32 (little- or big-endian per `self.little_endian`).
    #[must_use]
    pub fn read_u32(&self, vaddr: u64) -> Option<u32> {
        let bytes = self.read_at_vaddr(vaddr, 4)?;
        Some(if self.little_endian {
            u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
        } else {
            u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
        })
    }

    /// `true` if `vaddr..vaddr+len` lies entirely inside a section
    /// classified as hosting string bytes (read-only data across formats).
    #[must_use]
    pub fn vaddr_in_string_section(&self, vaddr: u64, len: u64) -> bool {
        vaddr
            .checked_add(len)
            .and_then(|end| self.lookup_range(vaddr, end, None, true))
            .is_some()
    }

    /// Indices into `self.sections` of sections classified as hosting
    /// string bytes (`.rodata*`, `.rdata*`, `__cstring`, ...).
    #[must_use]
    pub fn string_section_indices(&self) -> &[usize] {
        &self.string_sections
    }

    /// `true` when the section at `index` is classified as hosting string
    /// bytes.
    #[must_use]
    pub fn is_string_section_index(&self, index: usize) -> bool {
        index < self.sections.len() && self.section_is_string(index)
    }

    /// All sections parsed from the object file (not all are guaranteed
    /// to contain parseable bytes — some are NOBITS or sparse).
    #[must_use]
    pub fn sections(&self) -> &[Section] {
        &self.sections
    }

    /// Test-utility constructor: build a `Binary` from a set of
    /// precomputed sections and (optionally) symbols.
    ///
    /// Used by integration tests to construct minimal-but-representative
    /// blobs without going through goblin's parser. The internal indices
    /// are rebuilt from the provided sections before the function returns.
    /// `force_string_sections` lets a test bypass the name-based
    /// predicate and pin specific sections as string-hosting.
    ///
    /// ⚠️ Public-but-test-oriented. Production callers should use
    /// `Binary::parse`. The signature may change without notice.
    #[doc(hidden)]
    #[must_use]
    pub fn from_test_parts(
        format: BinaryFormat,
        is_64: bool,
        little_endian: bool,
        sections: Vec<Section>,
        symbols: Vec<Symbol>,
        force_string_sections: Vec<usize>,
    ) -> Self {
        let mut bin = Self {
            path: None,
            format,
            arch: "test".into(),
            is_64,
            little_endian,
            bytes: vec![],
            sections,
            symbols,
            sec_by_vaddr: Vec::new(),
            string_sections: Vec::new(),
        };
        bin.build_indices();
        bin.set_forced_string_sections(force_string_sections);
        bin
    }

    fn lookup_range(
        &self,
        vaddr: u64,
        read_end: u64,
        data_len: Option<usize>,
        require_string: bool,
    ) -> Option<(usize, usize)> {
        self.lookup_range_impl(vaddr, read_end, data_len, require_string, None)
    }

    fn lookup_range_impl(
        &self,
        vaddr: u64,
        read_end: u64,
        data_len: Option<usize>,
        require_string: bool,
        mut probes: Option<&mut usize>,
    ) -> Option<(usize, usize)> {
        let tree = range_tree_metadata(&self.sec_by_vaddr)?;
        let mut low = 0usize;
        let mut high = tree.leaf_count;
        while low < high {
            let mid = low + (high - low) / 2;
            if self.sec_by_vaddr[tree.base + mid].0 <= vaddr {
                low = mid + 1;
            } else {
                high = mid;
            }
        }
        search_range_tree(
            self,
            1,
            0,
            tree.base,
            low,
            vaddr,
            read_end,
            data_len,
            require_string,
            &mut probes,
        )
    }

    fn validate_range_candidate(
        &self,
        section_index: usize,
        vaddr: u64,
        read_end: u64,
        data_len: Option<usize>,
        require_string: bool,
    ) -> Option<(usize, u64)> {
        let section = self.sections.get(section_index)?;
        let section_end = section.vaddr.checked_add(section.size)?;
        if vaddr < section.vaddr || vaddr >= section_end || read_end > section_end {
            return None;
        }
        if require_string && !self.section_is_string(section_index) {
            return None;
        }
        let offset = usize::try_from(vaddr - section.vaddr).ok()?;
        if let Some(len) = data_len {
            if offset.checked_add(len)? > section.data.len() {
                return None;
            }
        }
        Some((offset, section.size))
    }

    fn section_is_string(&self, section_index: usize) -> bool {
        self.string_sections.binary_search(&section_index).is_ok()
    }

    fn set_forced_string_sections(&mut self, force_string_sections: Vec<usize>) {
        self.string_sections = force_string_sections
            .into_iter()
            .filter(|&index| index < self.sections.len())
            .collect();
        self.string_sections.sort_unstable();
        self.string_sections.dedup();
    }

    /// Replace sections and rebuild their derived indices for unit tests.
    #[cfg(test)]
    fn replace_sections_for_test(&mut self, sections: Vec<Section>) {
        self.sections = sections;
        self.build_indices();
    }

    /// Expose section bytes for unit tests without exposing cache-driving data.
    #[cfg(test)]
    fn section_data_mut_for_test(&mut self, index: usize) -> Option<&mut [u8]> {
        Some(self.sections.get_mut(index)?.data.as_mut_slice())
    }

    /// Test/benchmark utility returning the interval-tree nodes visited by a
    /// point lookup. Production callers should use [`Self::vaddr_to_offset`].
    #[doc(hidden)]
    #[must_use]
    pub fn lookup_probe_count(&self, vaddr: u64) -> (Option<(usize, usize)>, usize) {
        let mut probes = 0;
        let result = vaddr.checked_add(1).and_then(|read_end| {
            self.lookup_range_impl(vaddr, read_end, None, false, Some(&mut probes))
        });
        (result, probes)
    }
}

// ---------------------------------------------------------------------------
// parsers — each returns an owned `Binary` so the parsed view's borrows on
// the input buffer can be dropped before we hand the buffer back to the
// caller. This is the only end-of-fn ELF<'_>-in-scope-after-bytes-moved risk
// can be eliminated cleanly.
// ---------------------------------------------------------------------------

// Checked arithmetic and malformed-object errors propagate uniformly.
//
// `Object::parse` dispatches directly to format parsers which allocate from
// header-controlled counts. Keep this byte-only preflight before that dispatch.
// Layout references: System V ABI, chapter 4 (ELF),
// https://refspecs.linuxfoundation.org/elf/gabi4+/contents.html ; Microsoft PE
// format, https://learn.microsoft.com/en-us/windows/win32/debug/pe-format ; Apple
// `loader.h`, https://github.com/apple-oss-distributions/xnu/blob/main/EXTERNAL_HEADERS/mach-o/loader.h .

const ELF_MAGIC: &[u8; 4] = b"\x7fELF";
const PE_MAGIC: &[u8; 4] = b"PE\0\0";
const ARCHIVE_MAGIC: &[u8; 8] = b"!<arch>\n";
const MACH_FAT_MAGIC: u32 = 0xcafe_babe;
const MACH_MAGIC_32: u32 = 0xfeed_face;
const MACH_CIGAM_32: u32 = 0xcefa_edfe;
const MACH_MAGIC_64: u32 = 0xfeed_facf;
const MACH_CIGAM_64: u32 = 0xcffa_edfe;

const ELFCLASS32: u8 = 1;
const ELFCLASS64: u8 = 2;
const ELFDATA2LSB: u8 = 1;
const ELFDATA2MSB: u8 = 2;
const ELF_PT_LOAD: u32 = 1;
const ELF_PT_DYNAMIC: u32 = 2;
const ELF_SHT_SYMTAB: u32 = 2;
const ELF_SHT_STRTAB: u32 = 3;
const ELF_SHT_DYNSYM: u32 = 11;
const ELF_DT_NULL: u64 = 0;
const ELF_DT_HASH: u64 = 4;
const ELF_DT_STRTAB: u64 = 5;
const ELF_DT_SYMTAB: u64 = 6;
const ELF_DT_RELA: u64 = 7;
const ELF_DT_RELASZ: u64 = 8;
const ELF_DT_STRSZ: u64 = 10;
const ELF_DT_REL: u64 = 17;
const ELF_DT_RELSZ: u64 = 18;
const ELF_DT_PLTREL: u64 = 20;
const ELF_DT_JMPREL: u64 = 23;
const ELF_DT_PLTRELSZ: u64 = 2;
const ELF_DT_GNU_HASH: u64 = 0x6fff_fef5;

const PE32_MAGIC: u16 = 0x10b;
const PE32_PLUS_MAGIC: u16 = 0x20b;
const COFF_MACHINE_X86: u16 = 0x14c;
const COFF_MACHINE_X86_64: u16 = 0x8664;
const COFF_MACHINE_ARM64: u16 = 0xaa64;
const PE_DIRECTORY_EXPORT: usize = 0;
const PE_DIRECTORY_IMPORT: usize = 1;
const PE_DIRECTORY_CERTIFICATE: usize = 4;
const PE_DATA_DIRECTORY_SIZE: usize = 8;
const PE_SECTION_HEADER_SIZE: usize = 40;
const PE_EXPORT_DIRECTORY_SIZE: usize = 40;
const PE_IMPORT_DIRECTORY_SIZE: usize = 20;
const PE_COFF_SYMBOL_SIZE: usize = 18;
const PE_COFF_STRING_LENGTH_SIZE: usize = 4;
const PE_RELOCATION_SIZE: usize = 10;
const PE_FILE_ALIGNMENT_OFFSET: usize = 36;
const PE_NUMBER_OF_RVAS_OFFSET_32: usize = 92;
const PE_NUMBER_OF_RVAS_OFFSET_64: usize = 108;
const PE_DATA_DIRECTORIES_OFFSET_32: usize = 96;
const PE_DATA_DIRECTORIES_OFFSET_64: usize = 112;
const PE_MAX_DATA_DIRECTORIES: usize = 16;
const MAX_SECTION_NAME_BYTES: usize = 4 * 1024;
const MAX_OWNED_SECTION_NAME_BYTES: usize = 16 * 1024 * 1024;

const MACH_HEADER_SIZE_32: usize = 28;
const MACH_HEADER_SIZE_64: usize = 32;
const MACH_LOAD_COMMAND_SIZE: usize = 8;
const MACH_LC_SEGMENT: u32 = 0x1;
const MACH_LC_SYMTAB: u32 = 0x2;
const MACH_LC_SEGMENT_64: u32 = 0x19;
const MACH_SEGMENT_COMMAND_SIZE_32: usize = 56;
const MACH_SEGMENT_COMMAND_SIZE_64: usize = 72;
const MACH_SECTION_SIZE_32: usize = 68;
const MACH_SECTION_SIZE_64: usize = 80;
const MACH_SYMTAB_COMMAND_SIZE: usize = 24;

fn preflight_object(bytes: &[u8]) -> Result<()> {
    if bytes.starts_with(ELF_MAGIC) {
        return preflight_elf(bytes);
    }
    if bytes.starts_with(b"MZ") {
        return preflight_pe(bytes);
    }
    if bytes.starts_with(ARCHIVE_MAGIC) {
        return Err(anyhow!("unsupported object kind (archive)"));
    }
    // Goblin 0.8.2 recognizes only these raw COFF machine words in its object
    // peek path. rustrip does not support COFF, so reject before that parser
    // can allocate its section table.
    if matches!(
        preflight_u16(bytes, 0, true, "object magic").ok(),
        Some(COFF_MACHINE_X86 | COFF_MACHINE_X86_64 | COFF_MACHINE_ARM64)
    ) {
        return Err(anyhow!("unsupported object kind (COFF)"));
    }

    let magic = preflight_u32(bytes, 0, false, "object magic").ok();
    match magic {
        Some(MACH_FAT_MAGIC) => Err(anyhow!("Mach-O fat archives are not supported")),
        Some(MACH_MAGIC_32 | MACH_CIGAM_32 | MACH_MAGIC_64 | MACH_CIGAM_64) => {
            preflight_mach(bytes)
        }
        _ => Ok(()),
    }
}

fn preflight_bytes<'a>(
    bytes: &'a [u8],
    offset: usize,
    len: usize,
    context: &str,
) -> Result<&'a [u8]> {
    let end = offset
        .checked_add(len)
        .ok_or_else(|| anyhow!("{context}: byte range overflow"))?;
    bytes
        .get(offset..end)
        .ok_or_else(|| anyhow!("{context}: truncated input"))
}

fn preflight_u16(bytes: &[u8], offset: usize, little_endian: bool, context: &str) -> Result<u16> {
    let mut raw = [0u8; 2];
    raw.copy_from_slice(preflight_bytes(bytes, offset, 2, context)?);
    Ok(if little_endian {
        u16::from_le_bytes(raw)
    } else {
        u16::from_be_bytes(raw)
    })
}

fn preflight_u32(bytes: &[u8], offset: usize, little_endian: bool, context: &str) -> Result<u32> {
    let mut raw = [0u8; 4];
    raw.copy_from_slice(preflight_bytes(bytes, offset, 4, context)?);
    Ok(if little_endian {
        u32::from_le_bytes(raw)
    } else {
        u32::from_be_bytes(raw)
    })
}

fn preflight_u64(bytes: &[u8], offset: usize, little_endian: bool, context: &str) -> Result<u64> {
    let mut raw = [0u8; 8];
    raw.copy_from_slice(preflight_bytes(bytes, offset, 8, context)?);
    Ok(if little_endian {
        u64::from_le_bytes(raw)
    } else {
        u64::from_be_bytes(raw)
    })
}

fn preflight_usize(value: u64, context: &str) -> Result<usize> {
    usize::try_from(value).map_err(|_| anyhow!("{context}: value does not fit this host"))
}

fn preflight_table_end(
    offset: usize,
    count: usize,
    entry_size: usize,
    input_len: usize,
    context: &str,
) -> Result<usize> {
    let bytes = count
        .checked_mul(entry_size)
        .ok_or_else(|| anyhow!("{context}: table byte count overflow"))?;
    let end = offset
        .checked_add(bytes)
        .ok_or_else(|| anyhow!("{context}: table range overflow"))?;
    if end > input_len {
        return Err(anyhow!("{context}: table exceeds input"));
    }
    Ok(end)
}

fn preflight_count(count: usize, context: &str) -> Result<()> {
    if count > MAX_TABLE_ENTRIES {
        return Err(anyhow!(
            "{context}: count {count} exceeds limit {MAX_TABLE_ENTRIES}"
        ));
    }
    Ok(())
}

struct PreflightBudget {
    entries: usize,
}

impl PreflightBudget {
    fn consume(&mut self, count: usize, context: &str) -> Result<()> {
        preflight_count(count, context)?;
        self.entries = self
            .entries
            .checked_add(count)
            .ok_or_else(|| anyhow!("{context}: aggregate count overflow"))?;
        if self.entries > MAX_AGGREGATE_TABLE_ENTRIES {
            return Err(anyhow!(
                "{context}: aggregate count exceeds limit {MAX_AGGREGATE_TABLE_ENTRIES}"
            ));
        }
        Ok(())
    }
}

fn preflight_string_table(
    bytes: &[u8],
    offset: usize,
    size: usize,
    budget: &mut PreflightBudget,
    context: &str,
) -> Result<()> {
    let table = preflight_bytes(bytes, offset, size, context)?;
    let mut entries = 0usize;
    for &byte in table {
        if byte == 0 {
            entries = entries
                .checked_add(1)
                .ok_or_else(|| anyhow!("{context}: string entry count overflow"))?;
        }
    }
    if table.last().is_some_and(|&byte| byte != 0) {
        entries = entries
            .checked_add(1)
            .ok_or_else(|| anyhow!("{context}: string entry count overflow"))?;
    }
    budget.consume(entries, context)
}

#[derive(Clone, Copy)]
struct ElfPreflightLayout {
    is_64: bool,
    little_endian: bool,
    machine: u16,
    phoff: usize,
    phnum: usize,
    shoff: usize,
    shnum: usize,
    phent_size: usize,
    shent_size: usize,
}

// Keep the header/count validation together so every parser-controlled table
// is bounded before Goblin sees the object.
#[allow(clippy::too_many_lines)]
fn preflight_elf(bytes: &[u8]) -> Result<()> {
    preflight_bytes(bytes, 0, 16, "ELF identification")?;
    let (is_64, header_size, phent_size, shent_size) = match bytes[4] {
        ELFCLASS32 => (false, 52usize, 32usize, 40usize),
        ELFCLASS64 => (true, 64usize, 56usize, 64usize),
        class => return Err(anyhow!("ELF: unsupported class {class}")),
    };
    let little_endian = match bytes[5] {
        ELFDATA2LSB => true,
        ELFDATA2MSB => false,
        encoding => return Err(anyhow!("ELF: unsupported data encoding {encoding}")),
    };
    preflight_bytes(bytes, 0, header_size, "ELF header")?;

    // These field positions are the Elf32_Ehdr/Elf64_Ehdr layouts in System V
    // ABI chapter 4, "ELF Header". Goblin 0.8.2 parses tables using their
    // class-defined entry sizes, rather than e_*entsize.
    let machine = preflight_u16(bytes, 18, little_endian, "ELF e_machine")?;
    let (phoff, shoff, ehsize, raw_program_count, raw_section_count) = if is_64 {
        (
            preflight_usize(
                preflight_u64(bytes, 32, little_endian, "ELF e_phoff")?,
                "ELF e_phoff",
            )?,
            preflight_usize(
                preflight_u64(bytes, 40, little_endian, "ELF e_shoff")?,
                "ELF e_shoff",
            )?,
            preflight_u16(bytes, 52, little_endian, "ELF e_ehsize")?,
            preflight_u16(bytes, 56, little_endian, "ELF e_phnum")?,
            preflight_u16(bytes, 60, little_endian, "ELF e_shnum")?,
        )
    } else {
        (
            preflight_usize(
                u64::from(preflight_u32(bytes, 28, little_endian, "ELF e_phoff")?),
                "ELF e_phoff",
            )?,
            preflight_usize(
                u64::from(preflight_u32(bytes, 32, little_endian, "ELF e_shoff")?),
                "ELF e_shoff",
            )?,
            preflight_u16(bytes, 40, little_endian, "ELF e_ehsize")?,
            preflight_u16(bytes, 44, little_endian, "ELF e_phnum")?,
            preflight_u16(bytes, 48, little_endian, "ELF e_shnum")?,
        )
    };
    if usize::from(ehsize) < header_size {
        return Err(anyhow!("ELF: e_ehsize is smaller than the class header"));
    }

    let mut phnum = usize::from(raw_program_count);
    let mut shnum = usize::from(raw_section_count);
    if phnum != 0 && phoff == 0 {
        return Err(anyhow!("ELF: non-empty program table has zero offset"));
    }
    if shnum != 0 && shoff == 0 {
        return Err(anyhow!("ELF: non-empty section table has zero offset"));
    }

    // Extended ELF counts live in section header zero. Accept them only after
    // its fixed class-sized record is itself range checked.
    if raw_program_count == u16::MAX || (raw_section_count == 0 && shoff != 0) {
        if shoff == 0 {
            return Err(anyhow!("ELF: extended counts require section header zero"));
        }
        preflight_table_end(shoff, 1, shent_size, bytes.len(), "ELF section header zero")?;
        if raw_program_count == u16::MAX {
            let sh_info_offset = shoff + if is_64 { 44 } else { 28 };
            phnum = preflight_usize(
                u64::from(preflight_u32(
                    bytes,
                    sh_info_offset,
                    little_endian,
                    "ELF extended e_phnum",
                )?),
                "ELF extended e_phnum",
            )?;
        }
        if raw_section_count == 0 {
            let sh_size_offset = shoff + if is_64 { 32 } else { 20 };
            shnum = preflight_usize(
                if is_64 {
                    preflight_u64(bytes, sh_size_offset, little_endian, "ELF extended e_shnum")?
                } else {
                    u64::from(preflight_u32(
                        bytes,
                        sh_size_offset,
                        little_endian,
                        "ELF extended e_shnum",
                    )?)
                },
                "ELF extended e_shnum",
            )?;
            if shnum == 0 {
                return Err(anyhow!("ELF: extended section count is zero"));
            }
        }
    }

    let layout = ElfPreflightLayout {
        is_64,
        little_endian,
        machine,
        phoff,
        phnum,
        shoff,
        shnum,
        phent_size,
        shent_size,
    };
    let mut budget = PreflightBudget { entries: 0 };
    budget.consume(layout.phnum, "ELF program headers")?;
    budget.consume(layout.shnum, "ELF section headers")?;
    preflight_table_end(
        layout.phoff,
        layout.phnum,
        layout.phent_size,
        bytes.len(),
        "ELF program headers",
    )?;
    if layout.shnum != 0 {
        preflight_table_end(
            layout.shoff,
            layout.shnum,
            layout.shent_size,
            bytes.len(),
            "ELF section headers",
        )?;
    }

    preflight_elf_section_tables(bytes, layout, &mut budget)?;
    preflight_elf_dynamic(bytes, layout, &mut budget)
}

fn preflight_elf_section_tables(
    bytes: &[u8],
    layout: ElfPreflightLayout,
    budget: &mut PreflightBudget,
) -> Result<()> {
    for index in 0..layout.shnum {
        let offset = layout
            .shoff
            .checked_add(
                index
                    .checked_mul(layout.shent_size)
                    .ok_or_else(|| anyhow!("ELF section header offset overflow"))?,
            )
            .ok_or_else(|| anyhow!("ELF section header offset overflow"))?;
        let section_type = preflight_u32(bytes, offset + 4, layout.little_endian, "ELF sh_type")?;
        let (section_offset, section_size, entry_size) = if layout.is_64 {
            (
                preflight_usize(
                    preflight_u64(bytes, offset + 24, layout.little_endian, "ELF sh_offset")?,
                    "ELF sh_offset",
                )?,
                preflight_usize(
                    preflight_u64(bytes, offset + 32, layout.little_endian, "ELF sh_size")?,
                    "ELF sh_size",
                )?,
                preflight_usize(
                    preflight_u64(bytes, offset + 56, layout.little_endian, "ELF sh_entsize")?,
                    "ELF sh_entsize",
                )?,
            )
        } else {
            (
                preflight_usize(
                    u64::from(preflight_u32(
                        bytes,
                        offset + 16,
                        layout.little_endian,
                        "ELF sh_offset",
                    )?),
                    "ELF sh_offset",
                )?,
                preflight_usize(
                    u64::from(preflight_u32(
                        bytes,
                        offset + 20,
                        layout.little_endian,
                        "ELF sh_size",
                    )?),
                    "ELF sh_size",
                )?,
                preflight_usize(
                    u64::from(preflight_u32(
                        bytes,
                        offset + 36,
                        layout.little_endian,
                        "ELF sh_entsize",
                    )?),
                    "ELF sh_entsize",
                )?,
            )
        };
        match section_type {
            ELF_SHT_STRTAB => preflight_string_table(
                bytes,
                section_offset,
                section_size,
                budget,
                "ELF string table",
            )?,
            ELF_SHT_SYMTAB | ELF_SHT_DYNSYM if entry_size != 0 => {
                let count = section_size / entry_size;
                budget.consume(count, "ELF symbol table")?;
                preflight_table_end(
                    section_offset,
                    count,
                    if layout.is_64 { 24 } else { 16 },
                    bytes.len(),
                    "ELF symbol table",
                )?;
            }
            _ => {}
        }
    }
    Ok(())
}

const fn elf_program_header_field_offset(
    layout: ElfPreflightLayout,
    field: usize,
) -> Option<usize> {
    if layout.is_64 {
        match field {
            0 => Some(0),
            1 => Some(8),
            2 => Some(16),
            3 => Some(32),
            4 => Some(40),
            _ => None,
        }
    } else {
        match field {
            0 => Some(0),
            1 => Some(4),
            2 => Some(8),
            3 => Some(16),
            4 => Some(20),
            _ => None,
        }
    }
}

fn preflight_elf_program_header_value(
    bytes: &[u8],
    layout: ElfPreflightLayout,
    index: usize,
    field: usize,
    context: &str,
) -> Result<u64> {
    let field_offset = elf_program_header_field_offset(layout, field)
        .ok_or_else(|| anyhow!("{context}: unsupported program header field"))?;
    let offset = layout
        .phoff
        .checked_add(
            index
                .checked_mul(layout.phent_size)
                .ok_or_else(|| anyhow!("{context}: program header offset overflow"))?,
        )
        .and_then(|offset| offset.checked_add(field_offset))
        .ok_or_else(|| anyhow!("{context}: program header offset overflow"))?;
    if field == 0 {
        return Ok(u64::from(preflight_u32(
            bytes,
            offset,
            layout.little_endian,
            context,
        )?));
    }
    if layout.is_64 {
        preflight_u64(bytes, offset, layout.little_endian, context)
    } else {
        Ok(u64::from(preflight_u32(
            bytes,
            offset,
            layout.little_endian,
            context,
        )?))
    }
}

fn preflight_elf_vaddr_to_offset(
    bytes: &[u8],
    layout: ElfPreflightLayout,
    vaddr: u64,
) -> Option<usize> {
    for index in 0..layout.phnum {
        let kind =
            preflight_elf_program_header_value(bytes, layout, index, 0, "ELF p_type").ok()?;
        if kind != u64::from(ELF_PT_LOAD) {
            continue;
        }
        let segment_vaddr =
            preflight_elf_program_header_value(bytes, layout, index, 2, "ELF p_vaddr").ok()?;
        let memory_size =
            preflight_elf_program_header_value(bytes, layout, index, 4, "ELF p_memsz").ok()?;
        let delta = vaddr.checked_sub(segment_vaddr)?;
        if delta < memory_size {
            let file_offset =
                preflight_elf_program_header_value(bytes, layout, index, 1, "ELF p_offset").ok()?;
            return preflight_usize(file_offset.checked_add(delta)?, "ELF mapped offset").ok();
        }
    }
    None
}

fn preflight_elf_dynamic(
    bytes: &[u8],
    layout: ElfPreflightLayout,
    budget: &mut PreflightBudget,
) -> Result<()> {
    for index in 0..layout.phnum {
        if preflight_elf_program_header_value(bytes, layout, index, 0, "ELF p_type")?
            != u64::from(ELF_PT_DYNAMIC)
        {
            continue;
        }
        let offset = preflight_usize(
            preflight_elf_program_header_value(bytes, layout, index, 1, "ELF PT_DYNAMIC offset")?,
            "ELF PT_DYNAMIC offset",
        )?;
        let size = preflight_usize(
            preflight_elf_program_header_value(bytes, layout, index, 3, "ELF PT_DYNAMIC size")?,
            "ELF PT_DYNAMIC size",
        )?;
        let entry_size = if layout.is_64 { 16 } else { 8 };
        let count = size / entry_size;
        budget.consume(count, "ELF dynamic table")?;
        preflight_table_end(offset, count, entry_size, bytes.len(), "ELF dynamic table")?;
        return preflight_elf_dynamic_entries(bytes, layout, offset, count, budget);
    }
    Ok(())
}

// Dynamic tags cross-reference multiple untrusted tables; keeping these checks
// in one routine prevents a partially validated tag set from reaching Goblin.
#[allow(clippy::too_many_lines)]
fn preflight_elf_dynamic_entries(
    bytes: &[u8],
    layout: ElfPreflightLayout,
    offset: usize,
    count: usize,
    budget: &mut PreflightBudget,
) -> Result<()> {
    let entry_size = if layout.is_64 { 16 } else { 8 };
    let mut strtab = None;
    let mut strsz = 0usize;
    let mut symtab = None;
    let mut hash = None;
    let mut gnu_hash = None;
    let mut rela = None;
    let mut relocation_with_addend_size_bytes = 0usize;
    let mut rel = None;
    let mut relocation_without_addend_size_bytes = 0usize;
    let mut jmprel = None;
    let mut pltrelsz = 0usize;
    let mut pltrel = 0u64;

    for index in 0..count {
        let entry_offset = offset
            .checked_add(
                index
                    .checked_mul(entry_size)
                    .ok_or_else(|| anyhow!("ELF dynamic offset overflow"))?,
            )
            .ok_or_else(|| anyhow!("ELF dynamic offset overflow"))?;
        let tag = if layout.is_64 {
            preflight_u64(bytes, entry_offset, layout.little_endian, "ELF dynamic tag")?
        } else {
            u64::from(preflight_u32(
                bytes,
                entry_offset,
                layout.little_endian,
                "ELF dynamic tag",
            )?)
        };
        let value_offset = entry_offset + if layout.is_64 { 8 } else { 4 };
        let value = if layout.is_64 {
            preflight_u64(
                bytes,
                value_offset,
                layout.little_endian,
                "ELF dynamic value",
            )?
        } else {
            u64::from(preflight_u32(
                bytes,
                value_offset,
                layout.little_endian,
                "ELF dynamic value",
            )?)
        };
        match tag {
            ELF_DT_NULL => break,
            ELF_DT_STRTAB => strtab = Some(value),
            ELF_DT_STRSZ => strsz = preflight_usize(value, "ELF DT_STRSZ")?,
            ELF_DT_SYMTAB => symtab = Some(value),
            ELF_DT_HASH => hash = Some(value),
            ELF_DT_GNU_HASH => gnu_hash = Some(value),
            ELF_DT_RELA => rela = Some(value),
            ELF_DT_RELASZ => {
                relocation_with_addend_size_bytes = preflight_usize(value, "ELF DT_RELASZ")?;
            }
            ELF_DT_REL => rel = Some(value),
            ELF_DT_RELSZ => {
                relocation_without_addend_size_bytes = preflight_usize(value, "ELF DT_RELSZ")?;
            }
            ELF_DT_JMPREL => jmprel = Some(value),
            ELF_DT_PLTRELSZ => pltrelsz = preflight_usize(value, "ELF DT_PLTRELSZ")?,
            ELF_DT_PLTREL => pltrel = value,
            _ => {}
        }
    }

    let strtab_offset = strtab
        .and_then(|vaddr| preflight_elf_vaddr_to_offset(bytes, layout, vaddr))
        .unwrap_or(0);
    preflight_string_table(
        bytes,
        strtab_offset,
        strsz,
        budget,
        "ELF dynamic string table",
    )?;

    let mut max_symbol_count = if let Some(vaddr) = gnu_hash {
        preflight_elf_gnu_hash(
            bytes,
            layout,
            preflight_elf_vaddr_to_offset(bytes, layout, vaddr),
            budget,
        )?
    } else if let Some(vaddr) = hash {
        preflight_elf_hash(
            bytes,
            layout,
            preflight_elf_vaddr_to_offset(bytes, layout, vaddr),
            budget,
        )?
    } else {
        0
    };
    max_symbol_count = max_symbol_count.max(preflight_elf_relocations(
        bytes,
        layout,
        rela.and_then(|vaddr| preflight_elf_vaddr_to_offset(bytes, layout, vaddr)),
        relocation_with_addend_size_bytes,
        true,
        budget,
    )?);
    max_symbol_count = max_symbol_count.max(preflight_elf_relocations(
        bytes,
        layout,
        rel.and_then(|vaddr| preflight_elf_vaddr_to_offset(bytes, layout, vaddr)),
        relocation_without_addend_size_bytes,
        false,
        budget,
    )?);
    max_symbol_count = max_symbol_count.max(preflight_elf_relocations(
        bytes,
        layout,
        jmprel.and_then(|vaddr| preflight_elf_vaddr_to_offset(bytes, layout, vaddr)),
        pltrelsz,
        pltrel == ELF_DT_RELA,
        budget,
    )?);
    budget.consume(max_symbol_count, "ELF dynamic symbols")?;
    let symtab_offset = symtab
        .and_then(|vaddr| preflight_elf_vaddr_to_offset(bytes, layout, vaddr))
        .unwrap_or(0);
    preflight_table_end(
        symtab_offset,
        max_symbol_count,
        if layout.is_64 { 24 } else { 16 },
        bytes.len(),
        "ELF dynamic symbols",
    )?;
    Ok(())
}

fn preflight_elf_hash(
    bytes: &[u8],
    layout: ElfPreflightLayout,
    offset: Option<usize>,
    budget: &mut PreflightBudget,
) -> Result<usize> {
    let Some(offset) = offset else {
        return Ok(0);
    };
    preflight_bytes(bytes, offset, 8, "ELF DT_HASH header")?;
    let count = if layout.is_64 && (layout.machine == 22 || layout.machine == 0x9026) {
        preflight_usize(
            preflight_u64(
                bytes,
                offset + 4,
                layout.little_endian,
                "ELF DT_HASH nchain",
            )?,
            "ELF DT_HASH nchain",
        )?
    } else {
        preflight_usize(
            u64::from(preflight_u32(
                bytes,
                offset + 4,
                layout.little_endian,
                "ELF DT_HASH nchain",
            )?),
            "ELF DT_HASH nchain",
        )?
    };
    budget.consume(count, "ELF DT_HASH symbols")?;
    Ok(count)
}

// GNU hash validation depends on all preceding variable-sized regions.
#[allow(clippy::too_many_lines)]
fn preflight_elf_gnu_hash(
    bytes: &[u8],
    layout: ElfPreflightLayout,
    offset: Option<usize>,
    budget: &mut PreflightBudget,
) -> Result<usize> {
    let Some(offset) = offset else {
        return Ok(0);
    };
    preflight_bytes(bytes, offset, 16, "ELF DT_GNU_HASH header")?;
    let buckets = preflight_usize(
        u64::from(preflight_u32(
            bytes,
            offset,
            layout.little_endian,
            "ELF DT_GNU_HASH buckets",
        )?),
        "ELF DT_GNU_HASH buckets",
    )?;
    let first_symbol = preflight_usize(
        u64::from(preflight_u32(
            bytes,
            offset + 4,
            layout.little_endian,
            "ELF DT_GNU_HASH first symbol",
        )?),
        "ELF DT_GNU_HASH first symbol",
    )?;
    let bloom = preflight_usize(
        u64::from(preflight_u32(
            bytes,
            offset + 8,
            layout.little_endian,
            "ELF DT_GNU_HASH bloom size",
        )?),
        "ELF DT_GNU_HASH bloom size",
    )?;
    if buckets == 0 || first_symbol == 0 || bloom == 0 {
        return Err(anyhow!("ELF DT_GNU_HASH has a zero required field"));
    }
    budget.consume(buckets, "ELF DT_GNU_HASH buckets")?;
    budget.consume(bloom, "ELF DT_GNU_HASH bloom")?;
    let bloom_bytes = bloom
        .checked_mul(if layout.is_64 { 8 } else { 4 })
        .ok_or_else(|| anyhow!("ELF DT_GNU_HASH bloom byte count overflow"))?;
    let buckets_offset = offset
        .checked_add(16)
        .and_then(|value| value.checked_add(bloom_bytes))
        .ok_or_else(|| anyhow!("ELF DT_GNU_HASH bucket offset overflow"))?;
    preflight_table_end(
        buckets_offset,
        buckets,
        4,
        bytes.len(),
        "ELF DT_GNU_HASH buckets",
    )?;

    let mut max_symbol = 0usize;
    for index in 0..buckets {
        max_symbol = max_symbol.max(preflight_usize(
            u64::from(preflight_u32(
                bytes,
                buckets_offset + index * 4,
                layout.little_endian,
                "ELF DT_GNU_HASH bucket",
            )?),
            "ELF DT_GNU_HASH bucket",
        )?);
    }
    if max_symbol < first_symbol {
        return Ok(0);
    }
    let mut chain_index = max_symbol
        .checked_sub(first_symbol)
        .ok_or_else(|| anyhow!("ELF DT_GNU_HASH chain underflow"))?;
    loop {
        let symbol_count = max_symbol
            .checked_add(1)
            .ok_or_else(|| anyhow!("ELF DT_GNU_HASH symbol count overflow"))?;
        preflight_count(symbol_count, "ELF DT_GNU_HASH symbols")?;
        let chain_offset = buckets_offset
            .checked_add(
                buckets
                    .checked_mul(4)
                    .and_then(|bytes| {
                        chain_index
                            .checked_mul(4)
                            .and_then(|chain| bytes.checked_add(chain))
                    })
                    .ok_or_else(|| anyhow!("ELF DT_GNU_HASH chain offset overflow"))?,
            )
            .ok_or_else(|| anyhow!("ELF DT_GNU_HASH chain offset overflow"))?;
        let hash = preflight_u32(
            bytes,
            chain_offset,
            layout.little_endian,
            "ELF DT_GNU_HASH chain",
        )?;
        if hash & 1 != 0 {
            return Ok(symbol_count);
        }
        chain_index = chain_index
            .checked_add(1)
            .ok_or_else(|| anyhow!("ELF DT_GNU_HASH chain index overflow"))?;
        max_symbol = max_symbol
            .checked_add(1)
            .ok_or_else(|| anyhow!("ELF DT_GNU_HASH symbol count overflow"))?;
    }
}

fn preflight_elf_relocations(
    bytes: &[u8],
    layout: ElfPreflightLayout,
    offset: Option<usize>,
    size: usize,
    has_addend: bool,
    budget: &mut PreflightBudget,
) -> Result<usize> {
    if size == 0 {
        return Ok(0);
    }
    let entry_size = match (layout.is_64, has_addend) {
        (false, false) => 8,
        (false, true) => 12,
        (true, false) => 16,
        (true, true) => 24,
    };
    let count = size / entry_size;
    budget.consume(count, "ELF dynamic relocations")?;
    let offset = offset.unwrap_or(0);
    preflight_table_end(
        offset,
        count,
        entry_size,
        bytes.len(),
        "ELF dynamic relocations",
    )?;
    let mut max_symbol_count = 0usize;
    for index in 0..count {
        let entry_offset = offset + index * entry_size;
        let info_offset = entry_offset + if layout.is_64 { 8 } else { 4 };
        let symbol = if layout.is_64 {
            preflight_usize(
                preflight_u64(
                    bytes,
                    info_offset,
                    layout.little_endian,
                    "ELF relocation info",
                )? >> 32,
                "ELF relocation symbol",
            )?
        } else {
            preflight_usize(
                u64::from(
                    preflight_u32(
                        bytes,
                        info_offset,
                        layout.little_endian,
                        "ELF relocation info",
                    )? >> 8,
                ),
                "ELF relocation symbol",
            )?
        };
        max_symbol_count = max_symbol_count.max(
            symbol
                .checked_add(1)
                .ok_or_else(|| anyhow!("ELF relocation symbol count overflow"))?,
        );
    }
    preflight_count(max_symbol_count, "ELF relocation symbols")?;
    Ok(max_symbol_count)
}

#[derive(Clone, Copy)]
struct PeSection {
    virtual_address: u32,
    virtual_size: u32,
    raw_offset: u32,
    raw_size: u32,
}

fn preflight_pe(bytes: &[u8]) -> Result<()> {
    // e_lfanew at 0x3c, IMAGE_FILE_HEADER, and PE32/PE32+ optional-header
    // offsets are specified in Microsoft PE/COFF, "File Headers" and
    // "Optional Header". Goblin 0.8.2 uses them before any caller can limit
    // its vectors or directory walks.
    preflight_bytes(bytes, 0, 64, "PE DOS header")?;
    let pe_offset = preflight_usize(
        u64::from(preflight_u32(bytes, 0x3c, true, "PE e_lfanew")?),
        "PE e_lfanew",
    )?;
    if preflight_bytes(bytes, pe_offset, PE_MAGIC.len(), "PE signature")? != PE_MAGIC {
        return Err(anyhow!("PE: missing PE\\0\\0 signature"));
    }
    let coff_offset = pe_offset
        .checked_add(PE_MAGIC.len())
        .ok_or_else(|| anyhow!("PE: COFF header offset overflow"))?;
    preflight_bytes(bytes, coff_offset, 20, "PE COFF header")?;
    let section_count = usize::from(preflight_u16(
        bytes,
        coff_offset + 2,
        true,
        "PE NumberOfSections",
    )?);
    let symbol_table_offset = preflight_usize(
        u64::from(preflight_u32(
            bytes,
            coff_offset + 8,
            true,
            "PE PointerToSymbolTable",
        )?),
        "PE PointerToSymbolTable",
    )?;
    let symbol_count = preflight_usize(
        u64::from(preflight_u32(
            bytes,
            coff_offset + 12,
            true,
            "PE NumberOfSymbols",
        )?),
        "PE NumberOfSymbols",
    )?;
    let optional_size = usize::from(preflight_u16(
        bytes,
        coff_offset + 16,
        true,
        "PE SizeOfOptionalHeader",
    )?);

    let mut budget = PreflightBudget { entries: 0 };
    budget.consume(section_count, "PE section table")?;
    budget.consume(symbol_count, "PE COFF symbol table")?;
    let coff_string_offset = if symbol_table_offset == 0 {
        None
    } else {
        Some(preflight_table_end(
            symbol_table_offset,
            symbol_count,
            PE_COFF_SYMBOL_SIZE,
            bytes.len(),
            "PE COFF symbol table",
        )?)
    };

    let optional_offset = coff_offset
        .checked_add(20)
        .ok_or_else(|| anyhow!("PE optional header offset overflow"))?;
    preflight_bytes(bytes, optional_offset, optional_size, "PE optional header")?;
    let section_offset = optional_offset
        .checked_add(optional_size)
        .ok_or_else(|| anyhow!("PE section table offset overflow"))?;
    preflight_table_end(
        section_offset,
        section_count,
        PE_SECTION_HEADER_SIZE,
        bytes.len(),
        "PE section table",
    )?;
    let sections = preflight_pe_sections(
        bytes,
        section_offset,
        section_count,
        coff_string_offset,
        &mut budget,
    )?;

    if optional_size == 0 {
        return Ok(());
    }
    preflight_pe_optional(
        bytes,
        optional_offset,
        optional_size,
        &sections,
        &mut budget,
    )
}

fn preflight_pe_sections(
    bytes: &[u8],
    section_offset: usize,
    section_count: usize,
    coff_string_offset: Option<usize>,
    budget: &mut PreflightBudget,
) -> Result<Vec<PeSection>> {
    let coff_string = coff_string_offset
        .map(|offset| preflight_pe_coff_string_table(bytes, offset, budget))
        .transpose()?;
    let mut owned_name_bytes = 0usize;
    let mut sections = Vec::with_capacity(section_count);
    for index in 0..section_count {
        let offset = section_offset
            .checked_add(
                index
                    .checked_mul(PE_SECTION_HEADER_SIZE)
                    .ok_or_else(|| anyhow!("PE section header offset overflow"))?,
            )
            .ok_or_else(|| anyhow!("PE section header offset overflow"))?;
        let name = preflight_bytes(bytes, offset, 8, "PE section name")?;
        if name.first() == Some(&b'/') {
            // `/nnn` indirect names point into the COFF string table. Goblin
            // 0.8.2 tolerates a missing string table (the name resolves to
            // nothing), so stay parseable here too: only bound the referenced
            // bytes when a table actually exists.
            if let Some((strings, string_data_offset, string_data_end)) = coff_string {
                let name_offset = preflight_pe_section_name_offset(name)?;
                if name_offset >= strings {
                    return Err(anyhow!(
                        "PE indirect section name offset exceeds string table"
                    ));
                }
                let start = string_data_offset
                    .checked_add(name_offset)
                    .ok_or_else(|| anyhow!("PE indirect section name offset overflow"))?;
                let name_bytes = bytes
                    .get(start..string_data_end)
                    .ok_or_else(|| anyhow!("PE indirect section name is outside string table"))?;
                let length = name_bytes
                    .iter()
                    .position(|&byte| byte == 0)
                    .unwrap_or(name_bytes.len());
                if length > MAX_SECTION_NAME_BYTES {
                    return Err(anyhow!(
                        "PE indirect section name exceeds {MAX_SECTION_NAME_BYTES} bytes"
                    ));
                }
                owned_name_bytes = owned_name_bytes
                    .checked_add(length)
                    .ok_or_else(|| anyhow!("PE aggregate section-name bytes overflow"))?;
                if owned_name_bytes > MAX_OWNED_SECTION_NAME_BYTES {
                    return Err(anyhow!(
                        "PE aggregate owned section-name bytes exceed {MAX_OWNED_SECTION_NAME_BYTES}"
                    ));
                }
            }
        }
        let relocation_count = usize::from(preflight_u16(
            bytes,
            offset + 32,
            true,
            "PE NumberOfRelocations",
        )?);
        budget.consume(relocation_count, "PE section relocations")?;
        let relocation_offset = preflight_usize(
            u64::from(preflight_u32(
                bytes,
                offset + 24,
                true,
                "PE PointerToRelocations",
            )?),
            "PE PointerToRelocations",
        )?;
        if relocation_count != 0 {
            preflight_table_end(
                relocation_offset,
                relocation_count,
                PE_RELOCATION_SIZE,
                bytes.len(),
                "PE section relocations",
            )?;
        }
        sections.push(PeSection {
            virtual_size: preflight_u32(bytes, offset + 8, true, "PE VirtualSize")?,
            virtual_address: preflight_u32(bytes, offset + 12, true, "PE VirtualAddress")?,
            raw_size: preflight_u32(bytes, offset + 16, true, "PE SizeOfRawData")?,
            raw_offset: preflight_u32(bytes, offset + 20, true, "PE PointerToRawData")?,
        });
    }
    Ok(sections)
}

fn preflight_pe_coff_string_table(
    bytes: &[u8],
    offset: usize,
    budget: &mut PreflightBudget,
) -> Result<(usize, usize, usize)> {
    let declared_size = preflight_usize(
        u64::from(preflight_u32(
            bytes,
            offset,
            true,
            "PE COFF string table length",
        )?),
        "PE COFF string table length",
    )?;
    if declared_size < PE_COFF_STRING_LENGTH_SIZE {
        return Err(anyhow!("PE COFF string table length is too small"));
    }
    let end = offset
        .checked_add(declared_size)
        .ok_or_else(|| anyhow!("PE COFF string table range overflow"))?;
    preflight_bytes(bytes, offset, declared_size, "PE COFF string table")?;
    preflight_string_table(
        bytes,
        offset + PE_COFF_STRING_LENGTH_SIZE,
        declared_size - PE_COFF_STRING_LENGTH_SIZE,
        budget,
        "PE COFF string table",
    )?;
    Ok((declared_size, offset, end))
}

fn preflight_pe_section_name_offset(name: &[u8]) -> Result<usize> {
    let rest = name
        .get(1..)
        .ok_or_else(|| anyhow!("PE malformed indirect section name"))?;
    if rest.first() == Some(&b'/') {
        let mut value = 0usize;
        for &byte in &rest[1..] {
            let digit = match byte {
                b'A'..=b'Z' => usize::from(byte - b'A'),
                b'a'..=b'z' => usize::from(byte - b'a') + 26,
                b'0'..=b'9' => usize::from(byte - b'0') + 52,
                b'+' => 62,
                b'/' => 63,
                0 => break,
                _ => return Err(anyhow!("PE malformed base64 section-name offset")),
            };
            value = value
                .checked_mul(64)
                .and_then(|value| value.checked_add(digit))
                .ok_or_else(|| anyhow!("PE base64 section-name offset overflow"))?;
        }
        Ok(value)
    } else {
        let length = rest
            .iter()
            .position(|&byte| byte == 0)
            .unwrap_or(rest.len());
        let text = std::str::from_utf8(&rest[..length])
            .context("PE indirect section name is not UTF-8")?;
        text.parse::<usize>()
            .context("PE malformed decimal section-name offset")
    }
}

fn preflight_pe_optional(
    bytes: &[u8],
    optional_offset: usize,
    optional_size: usize,
    sections: &[PeSection],
    budget: &mut PreflightBudget,
) -> Result<()> {
    let magic = preflight_u16(bytes, optional_offset, true, "PE optional-header magic")?;
    let (minimum_size, number_rvas_offset, directories_offset, pointer_size) = match magic {
        PE32_MAGIC => (
            PE_DATA_DIRECTORIES_OFFSET_32,
            PE_NUMBER_OF_RVAS_OFFSET_32,
            PE_DATA_DIRECTORIES_OFFSET_32,
            4usize,
        ),
        PE32_PLUS_MAGIC => (
            PE_DATA_DIRECTORIES_OFFSET_64,
            PE_NUMBER_OF_RVAS_OFFSET_64,
            PE_DATA_DIRECTORIES_OFFSET_64,
            8usize,
        ),
        other => return Err(anyhow!("PE: unsupported optional-header magic {other:#x}")),
    };
    if optional_size < minimum_size {
        return Err(anyhow!(
            "PE optional header is shorter than its fixed fields"
        ));
    }
    let file_alignment = preflight_u32(
        bytes,
        optional_offset + PE_FILE_ALIGNMENT_OFFSET,
        true,
        "PE FileAlignment",
    )?;
    let directory_count = preflight_usize(
        u64::from(preflight_u32(
            bytes,
            optional_offset + number_rvas_offset,
            true,
            "PE NumberOfRvaAndSizes",
        )?),
        "PE NumberOfRvaAndSizes",
    )?;
    if directory_count > PE_MAX_DATA_DIRECTORIES {
        return Err(anyhow!(
            "PE NumberOfRvaAndSizes {directory_count} exceeds limit {PE_MAX_DATA_DIRECTORIES}"
        ));
    }
    let directory_bytes = directory_count
        .checked_mul(PE_DATA_DIRECTORY_SIZE)
        .ok_or_else(|| anyhow!("PE data-directory byte count overflow"))?;
    if optional_size < directories_offset + directory_bytes {
        return Err(anyhow!("PE data directories exceed SizeOfOptionalHeader"));
    }
    preflight_bytes(
        bytes,
        optional_offset + directories_offset,
        directory_bytes,
        "PE data directories",
    )?;

    let directory = |index: usize| -> Result<Option<(u32, u32)>> {
        if index >= directory_count {
            return Ok(None);
        }
        let offset = optional_offset + directories_offset + index * PE_DATA_DIRECTORY_SIZE;
        let rva = preflight_u32(bytes, offset, true, "PE data-directory RVA")?;
        let size = preflight_u32(bytes, offset + 4, true, "PE data-directory size")?;
        Ok((rva != 0 || size != 0).then_some((rva, size)))
    };

    if let Some((rva, _size)) = directory(PE_DIRECTORY_EXPORT)? {
        if let Some(offset) = preflight_pe_rva_to_offset(rva, sections, file_alignment) {
            preflight_pe_export(bytes, offset, sections, file_alignment, budget)?;
        }
    }
    if let Some((rva, _size)) = directory(PE_DIRECTORY_IMPORT)? {
        let offset = preflight_pe_rva_to_offset(rva, sections, file_alignment)
            .ok_or_else(|| anyhow!("PE import directory cannot be mapped"))?;
        preflight_pe_imports(
            bytes,
            offset,
            sections,
            file_alignment,
            pointer_size,
            budget,
        )?;
    }
    if let Some((offset, size)) = directory(PE_DIRECTORY_CERTIFICATE)? {
        preflight_pe_certificates(
            bytes,
            preflight_usize(u64::from(offset), "PE certificate offset")?,
            preflight_usize(u64::from(size), "PE certificate size")?,
            budget,
        )?;
    }
    Ok(())
}

fn preflight_pe_rva_to_offset(
    rva: u32,
    sections: &[PeSection],
    file_alignment: u32,
) -> Option<usize> {
    if file_alignment == 0 || !file_alignment.is_power_of_two() {
        return None;
    }
    let alignment = usize::try_from(file_alignment).ok()?;
    for section in sections {
        let raw_offset = usize::try_from(section.raw_offset).ok()?;
        let raw_size = usize::try_from(section.raw_size).ok()?;
        let virtual_size = usize::try_from(section.virtual_size).ok()?;
        // 0xfff = 4096-1: conservative 4 KiB page-floor rounding for the
        // raw/virtual read window. PE FileAlignment may be as small as 512
        // (Microsoft PE/COFF §"Optional Header (Image Only)"), so rounding up
        // to 4 KiB is a safe over-approximation for RVA-containment checks.
        let rounded_raw = raw_size.checked_add(0xfff)? & !0xfff;
        let raw_end = raw_offset.checked_add(raw_size)?;
        let aligned_end =
            raw_end.checked_add(alignment.checked_sub(1)?)? & !alignment.checked_sub(1)?;
        // 0x1ff = 512-1: the mandatory PE FileAlignment floor. Per Microsoft
        // PE/COFF, FileAlignment ∈ {512, 1024, ..., 65536}; masking raw_offset
        // to a 512-byte boundary aligns the file start of the section's raw
        // data with the smallest permitted alignment.
        let aligned_start = raw_offset & !0x1ff;
        let mut read_size = aligned_end.checked_sub(aligned_start)?.min(rounded_raw);
        if virtual_size != 0 {
            let rounded_virtual = virtual_size.checked_add(0xfff)? & !0xfff;
            read_size = read_size.min(rounded_virtual);
        }
        let start = usize::try_from(section.virtual_address).ok()?;
        let end = start.checked_add(read_size)?;
        let rva = usize::try_from(rva).ok()?;
        if (start..end).contains(&rva) {
            return rva.checked_sub(start)?.checked_add(aligned_start);
        }
    }
    None
}

fn preflight_pe_export(
    bytes: &[u8],
    offset: usize,
    sections: &[PeSection],
    file_alignment: u32,
    budget: &mut PreflightBudget,
) -> Result<()> {
    // IMAGE_EXPORT_DIRECTORY NumberOfFunctions and NumberOfNames are at byte
    // offsets 20 and 24; Goblin reserves all three export arrays from them.
    preflight_bytes(
        bytes,
        offset,
        PE_EXPORT_DIRECTORY_SIZE,
        "PE export directory",
    )?;
    let address_count = preflight_usize(
        u64::from(preflight_u32(
            bytes,
            offset + 20,
            true,
            "PE export NumberOfFunctions",
        )?),
        "PE export NumberOfFunctions",
    )?;
    let name_count = preflight_usize(
        u64::from(preflight_u32(
            bytes,
            offset + 24,
            true,
            "PE export NumberOfNames",
        )?),
        "PE export NumberOfNames",
    )?;
    budget.consume(address_count, "PE export address table")?;
    budget.consume(name_count, "PE export name pointers")?;
    budget.consume(name_count, "PE export ordinals")?;
    let address_rva = preflight_u32(bytes, offset + 28, true, "PE export AddressOfFunctions")?;
    let names_rva = preflight_u32(bytes, offset + 32, true, "PE export AddressOfNames")?;
    let ordinals_rva = preflight_u32(bytes, offset + 36, true, "PE export AddressOfNameOrdinals")?;
    if let Some(table_offset) = preflight_pe_rva_to_offset(address_rva, sections, file_alignment) {
        preflight_table_end(
            table_offset,
            address_count,
            4,
            bytes.len(),
            "PE export address table",
        )?;
    }
    if let Some(table_offset) = preflight_pe_rva_to_offset(names_rva, sections, file_alignment) {
        preflight_table_end(
            table_offset,
            name_count,
            4,
            bytes.len(),
            "PE export name-pointer table",
        )?;
    }
    if let Some(table_offset) = preflight_pe_rva_to_offset(ordinals_rva, sections, file_alignment) {
        preflight_table_end(
            table_offset,
            name_count,
            2,
            bytes.len(),
            "PE export ordinal table",
        )?;
    }
    Ok(())
}

fn preflight_pe_imports(
    bytes: &[u8],
    mut offset: usize,
    sections: &[PeSection],
    file_alignment: u32,
    pointer_size: usize,
    budget: &mut PreflightBudget,
) -> Result<()> {
    for _ in 0..MAX_TABLE_ENTRIES {
        let descriptor = preflight_bytes(
            bytes,
            offset,
            PE_IMPORT_DIRECTORY_SIZE,
            "PE import descriptor",
        )?;
        let lookup_rva = preflight_u32(bytes, offset, true, "PE import lookup RVA")?;
        let name_rva = preflight_u32(bytes, offset + 12, true, "PE import name RVA")?;
        let address_rva = preflight_u32(bytes, offset + 16, true, "PE import address RVA")?;
        if descriptor.iter().all(|&byte| byte == 0) {
            return Ok(());
        }
        budget.consume(1, "PE import descriptors")?;
        let name_offset = preflight_pe_rva_to_offset(name_rva, sections, file_alignment)
            .ok_or_else(|| anyhow!("PE import name cannot be mapped"))?;
        preflight_c_string(bytes, name_offset, "PE import name")?;
        let lookup_offset = preflight_pe_rva_to_offset(lookup_rva, sections, file_alignment)
            .or_else(|| preflight_pe_rva_to_offset(address_rva, sections, file_alignment))
            .ok_or_else(|| anyhow!("PE import lookup table cannot be mapped"))?;
        preflight_pe_import_lookup_table(bytes, lookup_offset, pointer_size, budget)?;
        let address_offset = preflight_pe_rva_to_offset(address_rva, sections, file_alignment)
            .ok_or_else(|| anyhow!("PE import address table cannot be mapped"))?;
        preflight_pe_import_address_table(bytes, address_offset, pointer_size, budget)?;
        offset = offset
            .checked_add(PE_IMPORT_DIRECTORY_SIZE)
            .ok_or_else(|| anyhow!("PE import descriptor offset overflow"))?;
    }
    Err(anyhow!(
        "PE import descriptor count exceeds limit {MAX_TABLE_ENTRIES}"
    ))
}

fn preflight_pe_import_lookup_table(
    bytes: &[u8],
    mut offset: usize,
    pointer_size: usize,
    budget: &mut PreflightBudget,
) -> Result<()> {
    for _ in 0..MAX_TABLE_ENTRIES {
        let value = match pointer_size {
            4 => u64::from(preflight_u32(
                bytes,
                offset,
                true,
                "PE import lookup entry",
            )?),
            8 => preflight_u64(bytes, offset, true, "PE import lookup entry")?,
            _ => return Err(anyhow!("PE import lookup pointer size is invalid")),
        };
        if value == 0 {
            return Ok(());
        }
        budget.consume(1, "PE import lookup table")?;
        offset = offset
            .checked_add(pointer_size)
            .ok_or_else(|| anyhow!("PE import lookup offset overflow"))?;
    }
    Err(anyhow!(
        "PE import lookup count exceeds limit {MAX_TABLE_ENTRIES}"
    ))
}

fn preflight_pe_import_address_table(
    bytes: &[u8],
    mut offset: usize,
    pointer_size: usize,
    budget: &mut PreflightBudget,
) -> Result<()> {
    for _ in 0..MAX_TABLE_ENTRIES {
        let value = match pointer_size {
            4 => u64::from(preflight_u32(
                bytes,
                offset,
                true,
                "PE import address entry",
            )?),
            8 => preflight_u64(bytes, offset, true, "PE import address entry")?,
            _ => return Err(anyhow!("PE import address pointer size is invalid")),
        };
        if value == 0 {
            return Ok(());
        }
        budget.consume(1, "PE import address table")?;
        offset = offset
            .checked_add(pointer_size)
            .ok_or_else(|| anyhow!("PE import address offset overflow"))?;
    }
    Err(anyhow!(
        "PE import address count exceeds limit {MAX_TABLE_ENTRIES}"
    ))
}

fn preflight_pe_certificates(
    bytes: &[u8],
    offset: usize,
    size: usize,
    budget: &mut PreflightBudget,
) -> Result<()> {
    let end = offset
        .checked_add(size)
        .ok_or_else(|| anyhow!("PE certificate table range overflow"))?;
    preflight_bytes(bytes, offset, size, "PE certificate table")?;
    let mut current = offset;
    while current < end {
        budget.consume(1, "PE certificates")?;
        let length = preflight_usize(
            u64::from(preflight_u32(
                bytes,
                current,
                true,
                "PE certificate length",
            )?),
            "PE certificate length",
        )?;
        if length < 8 {
            return Err(anyhow!("PE certificate length is smaller than its header"));
        }
        let next = current
            .checked_add(length)
            .and_then(|value| value.checked_add(7))
            .map(|value| value & !7)
            .ok_or_else(|| anyhow!("PE certificate offset overflow"))?;
        if next <= current || next > end {
            return Err(anyhow!("PE certificate table has an invalid entry range"));
        }
        current = next;
    }
    Ok(())
}

fn preflight_c_string(bytes: &[u8], offset: usize, context: &str) -> Result<()> {
    let tail = bytes
        .get(offset..)
        .ok_or_else(|| anyhow!("{context}: offset exceeds input"))?;
    let length = tail
        .iter()
        .position(|&byte| byte == 0)
        .unwrap_or(tail.len());
    if length == tail.len() {
        return Err(anyhow!("{context}: missing NUL terminator"));
    }
    Ok(())
}

fn preflight_mach(bytes: &[u8]) -> Result<()> {
    // `mach_header{,_64}`, `load_command`, `segment_command{,_64}`, and
    // `symtab_command` layouts are from Apple XNU's `mach-o/loader.h`.
    let magic = preflight_u32(bytes, 0, false, "Mach-O magic")?;
    let (is_64, little_endian, header_size) = match magic {
        MACH_MAGIC_32 => (false, false, MACH_HEADER_SIZE_32),
        MACH_CIGAM_32 => (false, true, MACH_HEADER_SIZE_32),
        MACH_MAGIC_64 => (true, false, MACH_HEADER_SIZE_64),
        MACH_CIGAM_64 => (true, true, MACH_HEADER_SIZE_64),
        _ => return Err(anyhow!("Mach-O: unsupported magic {magic:#x}")),
    };
    preflight_bytes(bytes, 0, header_size, "Mach-O header")?;
    let ncmds = preflight_usize(
        u64::from(preflight_u32(bytes, 16, little_endian, "Mach-O ncmds")?),
        "Mach-O ncmds",
    )?;
    let sizeofcmds = preflight_usize(
        u64::from(preflight_u32(
            bytes,
            20,
            little_endian,
            "Mach-O sizeofcmds",
        )?),
        "Mach-O sizeofcmds",
    )?;
    let mut budget = PreflightBudget { entries: 0 };
    budget.consume(ncmds, "Mach-O load commands")?;
    if ncmds > sizeofcmds / MACH_LOAD_COMMAND_SIZE {
        return Err(anyhow!("Mach-O: ncmds cannot fit in sizeofcmds"));
    }
    let commands_end = header_size
        .checked_add(sizeofcmds)
        .ok_or_else(|| anyhow!("Mach-O load-command range overflow"))?;
    if commands_end > bytes.len() {
        return Err(anyhow!("Mach-O load commands exceed input"));
    }

    let mut offset = header_size;
    for _ in 0..ncmds {
        let command = preflight_u32(bytes, offset, little_endian, "Mach-O load command")?;
        let command_size = preflight_usize(
            u64::from(preflight_u32(
                bytes,
                offset + 4,
                little_endian,
                "Mach-O load command size",
            )?),
            "Mach-O load command size",
        )?;
        if command_size < MACH_LOAD_COMMAND_SIZE || command_size % if is_64 { 8 } else { 4 } != 0 {
            return Err(anyhow!("Mach-O load command has an invalid cmdsize"));
        }
        let command_cursor_end = offset
            .checked_add(command_size)
            .ok_or_else(|| anyhow!("Mach-O load-command range overflow"))?;
        if command_cursor_end > commands_end {
            return Err(anyhow!("Mach-O load command exceeds sizeofcmds"));
        }
        match command {
            MACH_LC_SEGMENT => preflight_mach_segment(
                bytes,
                offset,
                command_size,
                little_endian,
                false,
                &mut budget,
            )?,
            MACH_LC_SEGMENT_64 => preflight_mach_segment(
                bytes,
                offset,
                command_size,
                little_endian,
                true,
                &mut budget,
            )?,
            MACH_LC_SYMTAB => preflight_mach_symtab(
                bytes,
                offset,
                command_size,
                little_endian,
                is_64,
                &mut budget,
            )?,
            _ => {}
        }
        offset = command_cursor_end;
    }
    Ok(())
}

fn preflight_mach_segment(
    bytes: &[u8],
    offset: usize,
    command_size: usize,
    little_endian: bool,
    is_64: bool,
    budget: &mut PreflightBudget,
) -> Result<()> {
    let (header_size, section_size, nsects_offset) = if is_64 {
        (MACH_SEGMENT_COMMAND_SIZE_64, MACH_SECTION_SIZE_64, 64)
    } else {
        (MACH_SEGMENT_COMMAND_SIZE_32, MACH_SECTION_SIZE_32, 48)
    };
    if command_size < header_size {
        return Err(anyhow!("Mach-O segment command is too short"));
    }
    let nsects = preflight_usize(
        u64::from(preflight_u32(
            bytes,
            offset + nsects_offset,
            little_endian,
            "Mach-O segment nsects",
        )?),
        "Mach-O segment nsects",
    )?;
    budget.consume(nsects, "Mach-O segment sections")?;
    let required = header_size
        .checked_add(
            nsects
                .checked_mul(section_size)
                .ok_or_else(|| anyhow!("Mach-O segment section bytes overflow"))?,
        )
        .ok_or_else(|| anyhow!("Mach-O segment command size overflow"))?;
    if required > command_size {
        return Err(anyhow!("Mach-O segment sections exceed cmdsize"));
    }
    Ok(())
}

fn preflight_mach_symtab(
    bytes: &[u8],
    offset: usize,
    command_size: usize,
    little_endian: bool,
    is_64: bool,
    budget: &mut PreflightBudget,
) -> Result<()> {
    if command_size < MACH_SYMTAB_COMMAND_SIZE {
        return Err(anyhow!("Mach-O symtab command is too short"));
    }
    let symbol_offset = preflight_usize(
        u64::from(preflight_u32(
            bytes,
            offset + 8,
            little_endian,
            "Mach-O symoff",
        )?),
        "Mach-O symoff",
    )?;
    let symbol_count = preflight_usize(
        u64::from(preflight_u32(
            bytes,
            offset + 12,
            little_endian,
            "Mach-O nsyms",
        )?),
        "Mach-O nsyms",
    )?;
    let string_offset = preflight_usize(
        u64::from(preflight_u32(
            bytes,
            offset + 16,
            little_endian,
            "Mach-O stroff",
        )?),
        "Mach-O stroff",
    )?;
    let string_size = preflight_usize(
        u64::from(preflight_u32(
            bytes,
            offset + 20,
            little_endian,
            "Mach-O strsize",
        )?),
        "Mach-O strsize",
    )?;
    budget.consume(symbol_count, "Mach-O nlist symbols")?;
    preflight_table_end(
        symbol_offset,
        symbol_count,
        if is_64 { 16 } else { 12 },
        bytes.len(),
        "Mach-O nlist symbols",
    )?;
    preflight_string_table(
        bytes,
        string_offset,
        string_size,
        budget,
        "Mach-O string table",
    )
}

fn extract_section_data_budgeted(
    off: usize,
    size: usize,
    bytes: &[u8],
    copied: &mut usize,
    context: &str,
) -> Result<Vec<u8>> {
    let data_len = if size == 0 || off >= bytes.len() {
        0
    } else if let Some(end) = off.checked_add(size) {
        end.min(bytes.len()) - off
    } else {
        return Err(anyhow!("{context}: section file range overflow"));
    };
    let total = copied
        .checked_add(data_len)
        .ok_or_else(|| anyhow!("{context}: cumulative copied data size overflow"))?;
    if total > bytes.len() {
        return Err(anyhow!(
            "{context}: cumulative copied data exceeds input size"
        ));
    }
    *copied = total;
    let end = off
        .checked_add(data_len)
        .ok_or_else(|| anyhow!("{context}: section file range overflow"))?;
    Ok(bytes.get(off..end).unwrap_or_default().to_vec())
}

#[allow(clippy::too_many_lines)]
fn load_elf(path: Option<&str>, elf: &elf::Elf<'_>, bytes: Vec<u8>) -> Result<Binary> {
    let is_64 = elf.is_64;
    let little_endian = elf.little_endian;
    let arch = arch_name_elf(elf.header.e_machine);
    let is_relocatable = elf.header.e_type == elf::header::ET_REL;
    let mut symbol_budget = SymbolBudget::new(bytes.len());
    let mut copied = 0usize;
    let mut section_vaddrs = vec![None; elf.section_headers.len()];
    let mut next_relocatable_vaddr = 0u64;
    let mut sections: Vec<Section> = Vec::new();
    if elf.section_headers.is_empty() {
        for (index, ph) in elf.program_headers.iter().enumerate() {
            if ph.p_type != elf::program_header::PT_LOAD
                || ph.p_flags & elf::program_header::PF_R == 0
            {
                continue;
            }
            ph.p_vaddr
                .checked_add(ph.p_memsz)
                .ok_or_else(|| anyhow!("ELF: PT_LOAD virtual range overflow"))?;
            ph.p_offset
                .checked_add(ph.p_filesz)
                .ok_or_else(|| anyhow!("ELF: PT_LOAD file range overflow"))?;
            if ph.p_filesz > ph.p_memsz {
                return Err(anyhow!("ELF: PT_LOAD file size exceeds memory size"));
            }
            let off = usize::try_from(ph.p_offset)
                .context("ELF: PT_LOAD file offset exceeds usize on this host")?;
            let size = usize::try_from(ph.p_filesz)
                .context("ELF: PT_LOAD file size exceeds usize on this host")?;
            let data =
                extract_section_data_budgeted(off, size, &bytes, &mut copied, "ELF PT_LOAD")?;
            let kind = if ph.p_flags & elf::program_header::PF_W != 0 {
                ".data.rel.ro"
            } else if ph.p_flags & elf::program_header::PF_X != 0 {
                ".text"
            } else {
                ".rodata"
            };
            sections.push(Section {
                name: format!("{kind}.pt_load.{index}"),
                vaddr: ph.p_vaddr,
                size: ph.p_memsz,
                data,
            });
        }
    } else {
        for (index, sc) in elf.section_headers.iter().enumerate() {
            if sc.sh_flags & u64::from(elf::section_header::SHF_ALLOC) == 0 {
                continue;
            }
            let vaddr = if is_relocatable {
                next_relocatable_vaddr = checked_align_up(
                    next_relocatable_vaddr,
                    sc.sh_addralign.max(1),
                    "ELF relocatable section alignment",
                )?;
                let vaddr = next_relocatable_vaddr;
                next_relocatable_vaddr = vaddr
                    .checked_add(sc.sh_size)
                    .ok_or_else(|| anyhow!("ELF: relocatable section range overflow"))?;
                vaddr
            } else {
                sc.sh_addr
            };
            vaddr
                .checked_add(sc.sh_size)
                .ok_or_else(|| anyhow!("ELF: section virtual range overflow"))?;
            section_vaddrs[index] = Some(vaddr);
            let data = if sc.sh_type == elf::section_header::SHT_NOBITS {
                Vec::new()
            } else {
                sc.sh_offset
                    .checked_add(sc.sh_size)
                    .ok_or_else(|| anyhow!("ELF: section file range overflow"))?;
                let off = usize::try_from(sc.sh_offset)
                    .context("ELF: section file offset exceeds usize on this host")?;
                let size = usize::try_from(sc.sh_size)
                    .context("ELF: section size exceeds usize on this host")?;
                extract_section_data_budgeted(off, size, &bytes, &mut copied, "ELF sections")?
            };
            sections.push(Section {
                name: elf.shdr_strtab.get_at(sc.sh_name).unwrap_or("").to_string(),
                vaddr,
                size: sc.sh_size,
                data,
            });
        }
    }

    let mut symbols: Vec<Symbol> = Vec::new();
    for sym in &elf.syms {
        append_elf_symbol(
            &mut symbols,
            sym,
            elf.strtab.get_at(sym.st_name),
            is_relocatable,
            &section_vaddrs,
            &mut symbol_budget,
        )?;
    }
    for sym in &elf.dynsyms {
        append_elf_symbol(
            &mut symbols,
            sym,
            elf.dynstrtab.get_at(sym.st_name),
            is_relocatable,
            &section_vaddrs,
            &mut symbol_budget,
        )?;
    }

    let mut bin = Binary {
        path: path.map(String::from),
        format: BinaryFormat::Elf,
        arch,
        is_64,
        little_endian,
        bytes,
        sections,
        symbols,
        sec_by_vaddr: Vec::new(),
        string_sections: Vec::new(),
    };
    bin.build_indices();
    Ok(bin)
}

fn load_pe(path: Option<&str>, pe: &pe::PE<'_>, bytes: Vec<u8>) -> Result<Binary> {
    let is_64 = pe.is_64;
    let arch = arch_name_pe(pe.header.coff_header.machine);
    let base = pe_image_base(pe.header.optional_header.as_ref());
    let mut copied = 0usize;

    let mut sections: Vec<Section> = Vec::new();
    for sc in &pe.sections {
        let name = sc.name().unwrap_or("").to_string();
        let off = usize::try_from(sc.pointer_to_raw_data)
            .context("PE: section raw pointer exceeds usize on this host")?;
        let sz = usize::try_from(sc.size_of_raw_data)
            .context("PE: section raw size exceeds usize on this host")?;
        let data = extract_section_data_budgeted(off, sz, &bytes, &mut copied, "PE sections")?;
        let vaddr = checked_vaddr_add(base, u64::from(sc.virtual_address), "PE section RVA")?;
        vaddr
            .checked_add(u64::from(sc.virtual_size))
            .ok_or_else(|| anyhow!("PE: section virtual range overflow"))?;
        sections.push(Section {
            name,
            vaddr,
            size: u64::from(sc.virtual_size),
            data,
        });
    }

    let mut symbols: Vec<Symbol> = Vec::new();
    let mut symbol_budget = SymbolBudget::new(bytes.len());
    for exp in &pe.exports {
        append_pe_export(&mut symbols, exp, base, &mut symbol_budget)?;
    }

    let mut bin = Binary {
        path: path.map(String::from),
        format: BinaryFormat::Pe,
        arch,
        is_64,
        little_endian: true,
        bytes,
        sections,
        symbols,
        sec_by_vaddr: Vec::new(),
        string_sections: Vec::new(),
    };
    bin.build_indices();
    Ok(bin)
}

#[allow(clippy::too_many_lines)]
fn load_mach(path: Option<&str>, mach: &mach::Mach<'_>, bytes: Vec<u8>) -> Result<Binary> {
    let mach_bin = match mach {
        mach::Mach::Binary(b) => b,
        mach::Mach::Fat(_) => return Err(anyhow!("Mach-O fat archives are not supported")),
    };
    let is_64 = mach_pointer_is_64(mach_bin.is_64, mach_bin.header.cputype());
    let little_endian = mach_bin.little_endian;
    let arch = arch_name_mach(mach_bin.header.cputype(), mach_bin.header.cpusubtype());
    let mut copied = 0usize;
    let mut sections: Vec<Section> = Vec::new();
    for segment in &mach_bin.segments {
        segment
            .vmaddr
            .checked_add(segment.vmsize)
            .ok_or_else(|| anyhow!("Mach-O: segment virtual range overflow"))?;
        segment
            .fileoff
            .checked_add(segment.filesize)
            .ok_or_else(|| anyhow!("Mach-O: segment file range overflow"))?;
        for entry in segment {
            let (sc, data) = entry.context("mach-o section parse")?;
            sc.addr
                .checked_add(sc.size)
                .ok_or_else(|| anyhow!("Mach-O: section virtual range overflow"))?;
            u64::from(sc.offset)
                .checked_add(sc.size)
                .ok_or_else(|| anyhow!("Mach-O: section file range overflow"))?;
            let total = copied
                .checked_add(data.len())
                .ok_or_else(|| anyhow!("Mach-O: cumulative copied data size overflow"))?;
            if total > bytes.len() {
                return Err(anyhow!("Mach-O: cumulative copied data exceeds input size"));
            }
            copied = total;
            let sectname = sc.name().unwrap_or("").to_string();
            let segname = sc.segname().unwrap_or("").to_string();
            let name = if segname.is_empty() {
                sectname
            } else {
                format!("{segname}.{sectname}")
            };
            sections.push(Section {
                name,
                vaddr: sc.addr,
                size: sc.size,
                data: data.to_vec(),
            });
        }
    }

    // Keep normal nlist symbols only; do not invoke `mach_bin.exports()`:
    // Goblin 0.8.2's export-trie walker recursively follows untrusted offsets
    // without cycle detection.
    let mut symbols = Vec::new();
    let mut symbol_budget = SymbolBudget::new(bytes.len());
    for entry in mach_bin.symbols() {
        let (name, symbol) = entry.context("mach-o symbol parse")?;
        if name.is_empty() || symbol.is_stab() {
            continue;
        }
        if symbol.get_type() != mach::symbols::N_SECT && symbol.get_type() != mach::symbols::N_ABS {
            continue;
        }
        if symbol.get_type() == mach::symbols::N_SECT
            && (symbol.n_sect == 0 || symbol.n_sect > sections.len())
        {
            return Err(anyhow!("Mach-O: symbol references invalid section"));
        }
        append_mach_symbol(&mut symbols, name, &symbol, &mut symbol_budget)?;
    }

    let mut bin = Binary {
        path: path.map(String::from),
        format: BinaryFormat::MachO,
        arch,
        is_64,
        little_endian,
        bytes,
        sections,
        symbols,
        sec_by_vaddr: Vec::new(),
        string_sections: Vec::new(),
    };
    bin.build_indices();
    Ok(bin)
}

impl Binary {
    fn build_indices(&mut self) {
        self.sec_by_vaddr.clear();
        self.string_sections.clear();
        let mut ranges = Vec::with_capacity(self.sections.len());
        for (index, section) in self.sections.iter().enumerate() {
            if section.size == 0 {
                continue;
            }
            if let Some(end) = section.vaddr.checked_add(section.size) {
                ranges.push((section.vaddr, end, index));
            }
        }
        ranges.sort_by(|left, right| {
            left.0
                .cmp(&right.0)
                .then_with(|| (right.1 - right.0).cmp(&(left.1 - left.0)))
                .then_with(|| right.2.cmp(&left.2))
        });
        if !ranges.is_empty() {
            if let Some((base, tree_len)) = ranges
                .len()
                .checked_next_power_of_two()
                .and_then(|base| base.checked_mul(2).map(|tree_len| (base, tree_len)))
            {
                self.sec_by_vaddr = vec![(0, 0, RANGE_TREE_INDEX); tree_len];
                self.sec_by_vaddr[0] = (
                    RANGE_TREE_MARKER,
                    u64::try_from(ranges.len()).unwrap_or(u64::MAX),
                    RANGE_TREE_INDEX,
                );
                for (offset, range) in ranges.into_iter().enumerate() {
                    self.sec_by_vaddr[base + offset] = range;
                }
                for node in (1..base).rev() {
                    self.sec_by_vaddr[node].1 = self.sec_by_vaddr[node * 2]
                        .1
                        .max(self.sec_by_vaddr[node * 2 + 1].1);
                }
            }
        }

        for (index, section) in self.sections.iter().enumerate() {
            if is_string_section_name(&section.name) {
                self.string_sections.push(index);
            }
        }
        self.string_sections.sort_unstable();
        self.string_sections.dedup();
    }
}

#[derive(Clone, Copy)]
struct RangeTreeMetadata {
    base: usize,
    leaf_count: usize,
}

fn range_tree_metadata(index: &[(u64, u64, usize)]) -> Option<RangeTreeMetadata> {
    let &(marker, leaf_count, marker_index) = index.first()?;
    if marker != RANGE_TREE_MARKER || marker_index != RANGE_TREE_INDEX {
        return None;
    }
    let leaf_count = usize::try_from(leaf_count).ok()?;
    let base = leaf_count.checked_next_power_of_two()?;
    let tree_len = base.checked_mul(2)?;
    (leaf_count != 0 && base.is_power_of_two() && leaf_count <= base && index.len() == tree_len)
        .then_some(RangeTreeMetadata { base, leaf_count })
}

#[allow(clippy::too_many_arguments)]
fn search_range_tree(
    binary: &Binary,
    node: usize,
    left: usize,
    right: usize,
    query_right: usize,
    vaddr: u64,
    read_end: u64,
    data_len: Option<usize>,
    require_string: bool,
    probes: &mut Option<&mut usize>,
) -> Option<(usize, usize)> {
    if let Some(count) = probes.as_deref_mut() {
        *count += 1;
    }
    let entry = *binary.sec_by_vaddr.get(node)?;
    if left >= query_right || entry.1 < read_end {
        return None;
    }
    if right - left == 1 {
        return binary
            .validate_range_candidate(entry.2, vaddr, read_end, data_len, require_string)
            .map(|(offset, _)| (entry.2, offset));
    }
    let mid = left + (right - left) / 2;
    search_range_tree(
        binary,
        node * 2 + 1,
        mid,
        right,
        query_right,
        vaddr,
        read_end,
        data_len,
        require_string,
        probes,
    )
    .or_else(|| {
        search_range_tree(
            binary,
            node * 2,
            left,
            mid,
            query_right,
            vaddr,
            read_end,
            data_len,
            require_string,
            probes,
        )
    })
}

fn read_le_ptr(bytes: &[u8], is_64: bool) -> u64 {
    if is_64 {
        let mut a = [0u8; 8];
        a.copy_from_slice(&bytes[..8]);
        u64::from_le_bytes(a)
    } else {
        let mut a = [0u8; 4];
        a.copy_from_slice(&bytes[..4]);
        u64::from(u32::from_le_bytes(a))
    }
}

fn read_be_ptr(bytes: &[u8], is_64: bool) -> u64 {
    if is_64 {
        let mut a = [0u8; 8];
        a.copy_from_slice(&bytes[..8]);
        u64::from_be_bytes(a)
    } else {
        let mut a = [0u8; 4];
        a.copy_from_slice(&bytes[..4]);
        u64::from(u32::from_be_bytes(a))
    }
}

fn is_string_section_name(name: &str) -> bool {
    if name == ".rodata" || name == ".rodata1" || name.starts_with(".rodata.") {
        return true;
    }
    if name == ".data.rel.ro" || name.starts_with(".data.rel.ro.") {
        return true;
    }
    if name == ".rdata" || name.starts_with(".rdata.") {
        return true;
    }
    let mach_section = name.rsplit_once('.').map_or(name, |(_, section)| section);
    if mach_section == "__cstring" || mach_section.starts_with("__cstring,") {
        return true;
    }
    if mach_section == "__const" || mach_section.starts_with("__const,") {
        return true;
    }
    false
}

fn arch_name_elf(machine: u16) -> String {
    use goblin::elf::header::{EM_386, EM_AARCH64, EM_ARM, EM_MIPS, EM_PPC64, EM_RISCV, EM_X86_64};
    match machine {
        EM_X86_64 => "x86_64".into(),
        EM_386 => "x86".into(),
        EM_AARCH64 => "aarch64".into(),
        EM_ARM => "arm".into(),
        EM_RISCV => "riscv".into(),
        EM_PPC64 => "ppc64".into(),
        EM_MIPS => "mips".into(),
        _ => format!("elf:{machine}"),
    }
}

fn arch_name_pe(machine: u16) -> String {
    use goblin::pe::header::{
        COFF_MACHINE_ARM, COFF_MACHINE_ARM64, COFF_MACHINE_X86, COFF_MACHINE_X86_64,
    };
    match machine {
        COFF_MACHINE_X86_64 => "x86_64".into(),
        COFF_MACHINE_X86 => "x86".into(),
        COFF_MACHINE_ARM64 => "aarch64".into(),
        COFF_MACHINE_ARM => "arm".into(),
        _ => format!("pe:{machine}"),
    }
}

fn arch_name_mach(cpu_type: u32, cpu_subtype: u32) -> String {
    if let Some(name) =
        goblin::mach::constants::cputype::get_arch_name_from_types(cpu_type, cpu_subtype)
    {
        return name.to_string();
    }
    match cpu_type {
        CPU_TYPE_X86_64 => "x86_64".into(),
        CPU_TYPE_I386 => "x86".into(),
        CPU_TYPE_ARM64 => "aarch64".into(),
        CPU_TYPE_ARM64_32 => "arm64_32".into(),
        CPU_TYPE_ARM => "arm".into(),
        CPU_TYPE_POWERPC64 => "ppc64".into(),
        CPU_TYPE_POWERPC => "ppc".into(),
        _ => format!("macho:{cpu_type}:{cpu_subtype}"),
    }
}

fn checked_align_up(value: u64, alignment: u64, context: &str) -> Result<u64> {
    let remainder = value % alignment;
    if remainder == 0 {
        Ok(value)
    } else {
        value
            .checked_add(alignment - remainder)
            .ok_or_else(|| anyhow!("{context}: address overflow"))
    }
}

fn checked_vaddr_add(base: u64, offset: u64, context: &str) -> Result<u64> {
    base.checked_add(offset)
        .ok_or_else(|| anyhow!("{context}: address overflow"))
}

fn validate_input_len(input_len: usize) -> Result<()> {
    if input_len > MAX_INPUT_BYTES {
        return Err(anyhow!(
            "input size {input_len} exceeds maximum {MAX_INPUT_BYTES} bytes"
        ));
    }
    Ok(())
}

fn pe_image_base(optional_header: Option<&pe::optional_header::OptionalHeader>) -> u64 {
    optional_header.map_or(0, |header| header.windows_fields.image_base)
}

const fn mach_pointer_is_64(container_is_64: bool, cpu_type: u32) -> bool {
    container_is_64 && cpu_type != CPU_TYPE_ARM64_32
}

struct SymbolBudget {
    remaining_symbols: usize,
    remaining_name_bytes: usize,
}

impl SymbolBudget {
    fn new(input_len: usize) -> Self {
        Self {
            remaining_symbols: MAX_TABLE_ENTRIES,
            remaining_name_bytes: MAX_OWNED_SYMBOL_NAME_BYTES
                .min(input_len.saturating_mul(SYMBOL_NAME_INPUT_MULTIPLIER)),
        }
    }

    fn consume_name(&mut self, bytes: usize, format: &str) -> Result<()> {
        self.remaining_symbols = self.remaining_symbols.checked_sub(1).ok_or_else(|| {
            anyhow!("{format}: owned symbol count exceeds limit {MAX_TABLE_ENTRIES}")
        })?;
        self.remaining_name_bytes =
            self.remaining_name_bytes
                .checked_sub(bytes)
                .ok_or_else(|| {
                    anyhow!(
                    "{format}: aggregate owned symbol-name bytes exceed configured/input-size budget"
                )
                })?;
        Ok(())
    }
}

fn append_elf_symbol(
    symbols: &mut Vec<Symbol>,
    symbol: elf::Sym,
    raw_name: Option<&str>,
    is_relocatable: bool,
    section_vaddrs: &[Option<u64>],
    budget: &mut SymbolBudget,
) -> Result<()> {
    let Ok(section_index) = u32::try_from(symbol.st_shndx) else {
        return Ok(());
    };
    if section_index == elf::section_header::SHN_UNDEF || symbol.st_type() == elf::sym::STT_TLS {
        return Ok(());
    }
    let Some(raw_name) = raw_name.filter(|name| !name.is_empty()) else {
        return Ok(());
    };
    let vaddr = if section_index == elf::section_header::SHN_ABS {
        symbol.st_value
    } else if section_index >= elf::section_header::SHN_LORESERVE {
        return Ok(());
    } else if is_relocatable {
        let Some(base) = section_vaddrs.get(symbol.st_shndx).copied().flatten() else {
            return Ok(());
        };
        checked_vaddr_add(base, symbol.st_value, "ELF relocatable symbol")?
    } else {
        symbol.st_value
    };
    budget.consume_name(raw_name.len(), "ELF")?;
    symbols.push(Symbol {
        vaddr,
        name: raw_name.to_string(),
        size: symbol.st_size,
    });
    Ok(())
}

fn append_pe_export(
    symbols: &mut Vec<Symbol>,
    export: &pe::export::Export<'_>,
    base: u64,
    budget: &mut SymbolBudget,
) -> Result<()> {
    if export.reexport.is_some() {
        return Ok(());
    }
    let Some(raw_name) = export.name.filter(|name| !name.is_empty()) else {
        return Ok(());
    };
    let rva = u64::try_from(export.rva).context("PE: export RVA exceeds u64")?;
    budget.consume_name(raw_name.len(), "PE")?;
    symbols.push(Symbol {
        vaddr: checked_vaddr_add(base, rva, "PE export RVA")?,
        name: raw_name.to_string(),
        size: 0,
    });
    Ok(())
}

fn append_mach_symbol(
    symbols: &mut Vec<Symbol>,
    raw_name: &str,
    symbol: &mach::symbols::Nlist,
    budget: &mut SymbolBudget,
) -> Result<()> {
    budget.consume_name(raw_name.len(), "Mach-O")?;
    symbols.push(Symbol {
        vaddr: symbol.n_value,
        name: raw_name.to_string(),
        size: 0,
    });
    Ok(())
}

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

    fn fake_binary_empty() -> Binary {
        Binary::from_test_parts(
            BinaryFormat::Elf,
            true,
            true,
            vec![Section {
                name: ".rodata".into(),
                vaddr: 0x2000,
                size: 0x1000,
                data: vec![0; 0x1000],
            }],
            vec![],
            vec![0],
        )
    }

    /// Direct unit tests for `arch_name_elf` covering every documented ELF
    /// architecture. cargo-mutants otherwise flags each individual match
    /// arm as uncaught because the only path we exercised was `x86_64`;
    /// these tests catch any future removal.
    #[test]
    fn arch_name_elf_x86_64() {
        assert_eq!(arch_name_elf(goblin::elf::header::EM_X86_64), "x86_64");
    }

    #[test]
    fn arch_name_elf_x86() {
        assert_eq!(arch_name_elf(goblin::elf::header::EM_386), "x86");
    }

    #[test]
    fn arch_name_elf_aarch64() {
        assert_eq!(arch_name_elf(goblin::elf::header::EM_AARCH64), "aarch64");
    }

    #[test]
    fn arch_name_elf_arm() {
        assert_eq!(arch_name_elf(goblin::elf::header::EM_ARM), "arm");
    }

    #[test]
    fn arch_name_elf_riscv() {
        assert_eq!(arch_name_elf(goblin::elf::header::EM_RISCV), "riscv");
    }

    #[test]
    fn arch_name_elf_ppc64() {
        assert_eq!(arch_name_elf(goblin::elf::header::EM_PPC64), "ppc64");
    }

    #[test]
    fn arch_name_elf_mips() {
        assert_eq!(arch_name_elf(goblin::elf::header::EM_MIPS), "mips");
    }

    #[test]
    fn arch_name_elf_unknown_emits_default() {
        assert_eq!(arch_name_elf(0xFFFF), "elf:65535");
    }

    #[test]
    fn arch_name_pe_x86_64() {
        assert_eq!(
            arch_name_pe(goblin::pe::header::COFF_MACHINE_X86_64),
            "x86_64"
        );
    }

    #[test]
    fn arch_name_pe_x86() {
        assert_eq!(arch_name_pe(goblin::pe::header::COFF_MACHINE_X86), "x86");
    }

    #[test]
    fn arch_name_pe_aarch64() {
        assert_eq!(
            arch_name_pe(goblin::pe::header::COFF_MACHINE_ARM64),
            "aarch64"
        );
    }

    #[test]
    fn arch_name_pe_arm() {
        assert_eq!(arch_name_pe(goblin::pe::header::COFF_MACHINE_ARM), "arm");
    }

    #[test]
    fn arch_name_pe_unknown_emits_default() {
        assert_eq!(arch_name_pe(0xBEEF), "pe:48879");
    }

    #[test]
    fn is_string_section_name_full_matrix_positive() {
        let positives = [
            ".rodata",
            ".rodata1",
            ".rodata.1",
            ".rodata.foo.bar",
            ".data.rel.ro",
            ".data.rel.ro.local",
            ".rdata",
            ".rdata.0",
            "__cstring",
            "__cstring,FOO",
            "__const",
            "__const,FUNC",
            "__TEXT.__cstring",
            "__DATA_CONST.__const",
        ];
        for n in positives {
            assert!(
                super::is_string_section_name(n),
                "{n} should be classified as string-hosting",
            );
        }
    }

    #[test]
    fn vaddr_lookup_in_range() {
        let b = fake_binary_empty();
        // nosemgrep: rustrip-no-unwrapping-trust-bytes (test code)
        let r = b.vaddr_to_offset(0x2000 + 5).unwrap();
        assert_eq!(r, (0, 5));
        assert!(b.vaddr_to_offset(0x3000).is_none());
        assert!(b.vaddr_to_offset(0x1FFF).is_none());
    }

    #[test]
    fn read_ptr_endianness_le() {
        let mut b = fake_binary_empty();
        // 0x1122_3344_5566_7788 little-endian
        b.section_data_mut_for_test(0).expect("fixture section")[..8]
            .copy_from_slice(&[0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11]);
        // nosemgrep: rustrip-no-unwrapping-trust-bytes (test code)
        assert_eq!(b.read_ptr(0x2000).unwrap(), 0x1122_3344_5566_7788);
    }

    #[test]
    fn string_section_recognized() {
        let b = fake_binary_empty();
        assert!(b.vaddr_in_string_section(0x2000, 1));
        assert!(b.vaddr_in_string_section(0x2800, 0x800));
        assert!(!b.vaddr_in_string_section(0x3000, 1));
    }

    #[test]
    fn read_be_ptr_64bit() {
        let bytes = [0x11u8, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88];
        assert_eq!(read_be_ptr(&bytes, true), 0x1122_3344_5566_7788);
    }

    #[test]
    fn read_be_ptr_32bit() {
        let bytes = [0x11u8, 0x22, 0x33, 0x44];
        assert_eq!(read_be_ptr(&bytes, false), 0x1122_3344);
    }

    #[test]
    fn read_ptr_endianness_be() {
        let mut b = fake_binary_empty();
        b.little_endian = false;
        b.section_data_mut_for_test(0).expect("fixture section")[..8]
            .copy_from_slice(&[0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]);
        // nosemgrep: rustrip-no-unwrapping-trust-bytes (test code)
        assert_eq!(b.read_ptr(0x2000).unwrap(), 0x1122_3344_5566_7788);
    }

    #[test]
    fn is_string_section_name_rejects_non_string_sections() {
        assert!(!is_string_section_name(".text"));
        assert!(!is_string_section_name(".data"));
        assert!(!is_string_section_name(".bss"));
        assert!(!is_string_section_name(".got"));
        assert!(!is_string_section_name(".dynsym"));
    }

    #[test]
    fn string_section_indices_correct_with_multiple_sections() {
        let mut bin =
            Binary::from_test_parts(BinaryFormat::Elf, true, true, vec![], vec![], vec![]);
        bin.replace_sections_for_test(vec![
            Section {
                name: ".text".into(),
                vaddr: 0x1000,
                size: 0x100,
                data: vec![0; 0x100],
            },
            Section {
                name: ".rodata".into(),
                vaddr: 0x2000,
                size: 0x100,
                data: vec![0; 0x100],
            },
            Section {
                name: ".data".into(),
                vaddr: 0x3000,
                size: 0x100,
                data: vec![0; 0x100],
            },
            Section {
                name: ".rdata".into(),
                vaddr: 0x4000,
                size: 0x100,
                data: vec![0; 0x100],
            },
        ]);
        let indices = bin.string_section_indices();
        assert!(indices.contains(&1), ".rodata must be in string_sections");
        assert!(indices.contains(&3), ".rdata must be in string_sections");
        assert!(
            !indices.contains(&0),
            ".text must NOT be in string_sections"
        );
    }

    #[test]
    fn string_section_indices_empty_when_no_string_sections() {
        let bin = Binary::from_test_parts(
            BinaryFormat::Elf,
            true,
            true,
            vec![
                Section {
                    name: ".text".into(),
                    vaddr: 0x1000,
                    size: 0x100,
                    data: vec![0; 0x100],
                },
                Section {
                    name: ".data".into(),
                    vaddr: 0x2000,
                    size: 0x100,
                    data: vec![0; 0x100],
                },
            ],
            vec![],
            vec![],
        );
        assert!(bin.string_section_indices().is_empty());
    }

    fn minimal_elf64() -> Vec<u8> {
        let mut e = vec![0u8; 64];
        e[0..4].copy_from_slice(b"\x7fELF");
        e[4] = 2;
        e[5] = 1;
        e[6] = 1;
        e[16..18].copy_from_slice(&2u16.to_le_bytes());
        e[18..20].copy_from_slice(&62u16.to_le_bytes());
        e[20..24].copy_from_slice(&1u32.to_le_bytes());
        e[52..54].copy_from_slice(&64u16.to_le_bytes());
        e[58..60].copy_from_slice(&64u16.to_le_bytes());
        e
    }

    fn minimal_elf32() -> Vec<u8> {
        let mut e = vec![0u8; 52];
        e[0..4].copy_from_slice(b"\x7fELF");
        e[4] = ELFCLASS32;
        e[5] = ELFDATA2LSB;
        e[6] = 1;
        e[16..18].copy_from_slice(&2u16.to_le_bytes());
        e[18..20].copy_from_slice(&elf::header::EM_386.to_le_bytes());
        e[20..24].copy_from_slice(&1u32.to_le_bytes());
        e[40..42].copy_from_slice(&52u16.to_le_bytes());
        e[46..48].copy_from_slice(&40u16.to_le_bytes());
        e
    }

    fn minimal_pe(is_64: bool) -> Vec<u8> {
        const PE_OFFSET: usize = 0x80;
        const COFF_OFFSET: usize = PE_OFFSET + 4;
        const OPTIONAL_OFFSET: usize = COFF_OFFSET + 20;
        let optional_size = if is_64 { 240usize } else { 224usize };
        let section_offset = OPTIONAL_OFFSET + optional_size;
        let raw_offset = 0x200usize;
        let mut pe = vec![0u8; raw_offset + 0x200];
        pe[0..2].copy_from_slice(b"MZ");
        pe[0x3c..0x40].copy_from_slice(
            &u32::try_from(PE_OFFSET)
                .expect("PE offset fits u32")
                .to_le_bytes(),
        );
        pe[PE_OFFSET..PE_OFFSET + 4].copy_from_slice(PE_MAGIC);
        pe[COFF_OFFSET..COFF_OFFSET + 2].copy_from_slice(
            &(if is_64 {
                COFF_MACHINE_X86_64
            } else {
                COFF_MACHINE_X86
            })
            .to_le_bytes(),
        );
        pe[COFF_OFFSET + 2..COFF_OFFSET + 4].copy_from_slice(&1u16.to_le_bytes());
        pe[COFF_OFFSET + 16..COFF_OFFSET + 18].copy_from_slice(
            &u16::try_from(optional_size)
                .expect("PE optional header size fits u16")
                .to_le_bytes(),
        );
        pe[OPTIONAL_OFFSET..OPTIONAL_OFFSET + 2]
            .copy_from_slice(&(if is_64 { PE32_PLUS_MAGIC } else { PE32_MAGIC }).to_le_bytes());
        pe[OPTIONAL_OFFSET + 4..OPTIONAL_OFFSET + 8].copy_from_slice(&1u32.to_le_bytes());
        if is_64 {
            pe[OPTIONAL_OFFSET + 24..OPTIONAL_OFFSET + 32]
                .copy_from_slice(&0x0000_0001_4000_0000u64.to_le_bytes());
            pe[OPTIONAL_OFFSET + PE_NUMBER_OF_RVAS_OFFSET_64
                ..OPTIONAL_OFFSET + PE_NUMBER_OF_RVAS_OFFSET_64 + 4]
                .copy_from_slice(&16u32.to_le_bytes());
        } else {
            pe[OPTIONAL_OFFSET + 28..OPTIONAL_OFFSET + 32]
                .copy_from_slice(&0x0040_0000u32.to_le_bytes());
            pe[OPTIONAL_OFFSET + PE_NUMBER_OF_RVAS_OFFSET_32
                ..OPTIONAL_OFFSET + PE_NUMBER_OF_RVAS_OFFSET_32 + 4]
                .copy_from_slice(&16u32.to_le_bytes());
        }
        pe[OPTIONAL_OFFSET + 32..OPTIONAL_OFFSET + 36].copy_from_slice(&0x1000u32.to_le_bytes());
        pe[OPTIONAL_OFFSET + PE_FILE_ALIGNMENT_OFFSET
            ..OPTIONAL_OFFSET + PE_FILE_ALIGNMENT_OFFSET + 4]
            .copy_from_slice(&0x200u32.to_le_bytes());
        pe[OPTIONAL_OFFSET + 56..OPTIONAL_OFFSET + 60].copy_from_slice(&0x2000u32.to_le_bytes());
        pe[OPTIONAL_OFFSET + 60..OPTIONAL_OFFSET + 64].copy_from_slice(&0x200u32.to_le_bytes());

        pe[section_offset..section_offset + 6].copy_from_slice(b".rdata");
        pe[section_offset + 8..section_offset + 12].copy_from_slice(&5u32.to_le_bytes());
        pe[section_offset + 12..section_offset + 16].copy_from_slice(&0x1000u32.to_le_bytes());
        pe[section_offset + 16..section_offset + 20].copy_from_slice(&0x200u32.to_le_bytes());
        pe[section_offset + 20..section_offset + 24].copy_from_slice(
            &u32::try_from(raw_offset)
                .expect("PE raw offset fits u32")
                .to_le_bytes(),
        );
        pe[section_offset + 36..section_offset + 40].copy_from_slice(&0x4000_0040u32.to_le_bytes());
        pe[raw_offset..raw_offset + 5].copy_from_slice(b"hello");
        pe
    }

    fn minimal_macho32() -> Vec<u8> {
        let mut m = vec![0u8; 32];
        m[0..4].copy_from_slice(&MACH_MAGIC_32.to_le_bytes());
        m[4..8].copy_from_slice(&CPU_TYPE_I386.to_le_bytes());
        m[8..12].copy_from_slice(&3u32.to_le_bytes());
        m[12..16].copy_from_slice(&1u32.to_le_bytes());
        m
    }

    #[test]
    fn pe_indirect_section_name_without_coff_string_table_is_tolerated() {
        // Regression: goblin 0.8.2 renders a `/nnn` name with no string table
        // as empty instead of failing, so the preflight must not reject the
        // whole object. Real-world trigger: images with long section names
        // (e.g. `.llvm_prf_names`) and no COFF symbol table.
        let mut pe = minimal_pe(true);
        let section_offset = 0x80 + 4 + 20 + 240;
        pe[section_offset..section_offset + 8].copy_from_slice(b"/4\0\0\0\0\0\0");
        let bin = Binary::parse(None, pe).expect("PE with unresolved indirect name must parse");
        assert_eq!(bin.sections().len(), 1);
        assert_eq!(bin.sections()[0].name, "");
    }

    #[test]
    fn pe_indirect_section_name_offset_beyond_string_table_is_rejected() {
        let mut pe = vec![0u8; 0x400];
        pe[0..2].copy_from_slice(b"MZ");
        pe[0x3c..0x40].copy_from_slice(&64u32.to_le_bytes());
        pe[64..68].copy_from_slice(PE_MAGIC);
        let coff = 68usize;
        pe[coff..coff + 2].copy_from_slice(&COFF_MACHINE_X86_64.to_le_bytes());
        pe[coff + 2..coff + 4].copy_from_slice(&1u16.to_le_bytes());
        pe[coff + 8..coff + 12].copy_from_slice(&0x100u32.to_le_bytes()); // symbol table
        pe[coff + 16..coff + 18].copy_from_slice(&240u16.to_le_bytes());
        let optional = coff + 20;
        pe[optional..optional + 2].copy_from_slice(&PE32_PLUS_MAGIC.to_le_bytes());
        pe[optional + 92..optional + 96].copy_from_slice(&0u32.to_le_bytes());
        let section_offset = optional + 240;
        pe[section_offset..section_offset + 2].copy_from_slice(b"/9");
        // COFF string table with declared size 4 (just the length field).
        pe[0x100..0x104].copy_from_slice(&4u32.to_le_bytes());
        let error = preflight_pe(&pe).expect_err("name offset past string table must fail");
        assert!(error.to_string().contains("exceeds string table"));
    }

    #[test]
    fn parse_minimal_elf_succeeds() {
        let elf = minimal_elf64();
        let bin = Binary::parse(Some("test.elf"), elf).expect("minimal ELF must parse");
        assert_eq!(bin.format, BinaryFormat::Elf);
        assert!(bin.is_64);
        assert!(bin.little_endian);
        assert_eq!(bin.arch, "x86_64");
    }

    #[test]
    fn safe_popular_format_corpus_parses_and_renders_without_executing_samples() {
        use crate::analyzers::{
            panics::PanicsAnalyzer, strings::StringsAnalyzer, symbols::SymbolsAnalyzer, Registry,
        };
        use crate::output::{
            binja::Binja, ghidra::Ghidra, json::Json, table::Table, OutputBackend,
        };

        let cases = [
            (
                "elf32-i386",
                BinaryFormat::Elf,
                false,
                "x86",
                minimal_elf32(),
            ),
            (
                "elf64-x86_64",
                BinaryFormat::Elf,
                true,
                "x86_64",
                minimal_elf64(),
            ),
            (
                "pe32-i386",
                BinaryFormat::Pe,
                false,
                "x86",
                minimal_pe(false),
            ),
            (
                "pe64-x86_64",
                BinaryFormat::Pe,
                true,
                "x86_64",
                minimal_pe(true),
            ),
            (
                "macho32-i386",
                BinaryFormat::MachO,
                false,
                "i386",
                minimal_macho32(),
            ),
            (
                "macho64-x86_64",
                BinaryFormat::MachO,
                true,
                "x86_64",
                minimal_macho64(),
            ),
        ];

        for (name, format, is_64, arch, bytes) in cases {
            let bin = Binary::parse(Some(name), bytes).unwrap_or_else(|error| {
                panic!("safe synthetic corpus case {name} must parse without execution: {error}")
            });
            assert_eq!(bin.format, format, "{name} format");
            assert_eq!(bin.is_64, is_64, "{name} pointer width");
            assert_eq!(bin.arch, arch, "{name} arch");

            // This corpus deliberately validates parser + analyzer + renderer
            // stability for popular container formats. Some minimal objects do
            // not contain Rust slice/panic/symbol layouts, so empty annotations
            // are a valid outcome; semantic analyzer recovery is covered by the
            // dedicated synthetic tests with controlled section contents.
            let annotations = Registry::new()
                .with(Box::new(StringsAnalyzer::new()))
                .with(Box::new(SymbolsAnalyzer::new()))
                .with(Box::new(PanicsAnalyzer::new()))
                .run(&bin);
            for (backend_name, backend) in [
                ("json", Box::new(Json) as Box<dyn OutputBackend>),
                ("table", Box::new(Table) as Box<dyn OutputBackend>),
                ("ghidra", Box::new(Ghidra) as Box<dyn OutputBackend>),
                ("binja", Box::new(Binja) as Box<dyn OutputBackend>),
            ] {
                let mut output = Vec::new();
                backend
                    .render(&annotations, &mut output)
                    .unwrap_or_else(|error| panic!("{name} {backend_name} render failed: {error}"));
                assert!(!output.is_empty(), "{name} {backend_name} output is empty");
            }
        }
    }

    /// Build a minimal ELF64 with one .rodata section containing "hello".
    fn elf64_with_rodata() -> Vec<u8> {
        let mut buf = vec![0u8; 64]; // ELF header
        buf[0..4].copy_from_slice(b"\x7fELF");
        buf[4] = 2;
        buf[5] = 1;
        buf[6] = 1;
        buf[16..18].copy_from_slice(&2u16.to_le_bytes());
        buf[18..20].copy_from_slice(&62u16.to_le_bytes());
        buf[20..24].copy_from_slice(&1u32.to_le_bytes());
        buf[40..48].copy_from_slice(&64u64.to_le_bytes()); // e_shoff
        buf[52..54].copy_from_slice(&64u16.to_le_bytes()); // e_ehsize
        buf[58..60].copy_from_slice(&64u16.to_le_bytes()); // e_shentsize
        buf[60..62].copy_from_slice(&2u16.to_le_bytes()); // e_shnum = 2
                                                          // Section header 0: null
        buf.extend_from_slice(&[0u8; 64]);
        // Section header 1: .rodata with 5 bytes at offset 192
        let data_off = 192u64;
        let sh1 = 64 + 64; // offset of section header 1
        buf.extend_from_slice(&[0u8; 64]);
        buf[sh1 + 4..sh1 + 8].copy_from_slice(&1u32.to_le_bytes()); // SHT_PROGBITS
        buf[sh1 + 8..sh1 + 16].copy_from_slice(&2u64.to_le_bytes()); // SHF_ALLOC
        buf[sh1 + 16..sh1 + 24].copy_from_slice(&0x1000u64.to_le_bytes()); // addr
        buf[sh1 + 24..sh1 + 32].copy_from_slice(&data_off.to_le_bytes()); // offset
        buf[sh1 + 32..sh1 + 40].copy_from_slice(&5u64.to_le_bytes()); // size = 5
                                                                      // Section data
        buf.extend_from_slice(b"hello");
        buf
    }

    #[test]
    fn parse_elf_section_data_not_empty() {
        let elf = elf64_with_rodata();
        let bin = Binary::parse(Some("test.elf"), elf).expect("parse");
        let has_data = bin.sections().iter().any(|s| !s.data.is_empty());
        assert!(
            has_data,
            "at least one section must have non-empty data (kills sz==0 → != mutation)"
        );
    }

    #[test]
    fn parse_elf_truncated_section_clamps_data() {
        // Build an ELF where .rodata claims 100 bytes but only 5 exist.
        let mut elf = elf64_with_rodata();
        // Modify sh_size of section 1 to 100 (was 5)
        let sh1_size_off = 64 + 64 + 32; // header + null section + offset to sh_size
        elf[sh1_size_off..sh1_size_off + 8].copy_from_slice(&100u64.to_le_bytes());
        // File is only 197 bytes, section data starts at 192, so only 5 bytes available
        let bin = Binary::parse(Some("truncated.elf"), elf).expect("parse");
        let rodata = bin.sections().iter().find(|s| s.size == 100);
        assert!(rodata.is_some(), "section with size=100 must exist");
        // nosemgrep: rustrip-no-unwrapping-trust-bytes (test code)
        let rodata = rodata.unwrap();
        // Data must be clamped to available bytes (5), not 100
        assert_eq!(
            rodata.data.len(),
            5,
            "truncated section data must be clamped to available bytes"
        );
    }

    #[allow(clippy::too_many_arguments)]
    fn put_elf64_program_header(
        bytes: &mut [u8],
        offset: usize,
        kind: u32,
        flags: u32,
        file_offset: u64,
        vaddr: u64,
        file_size: u64,
        memory_size: u64,
    ) {
        bytes[offset..offset + 4].copy_from_slice(&kind.to_le_bytes());
        bytes[offset + 4..offset + 8].copy_from_slice(&flags.to_le_bytes());
        bytes[offset + 8..offset + 16].copy_from_slice(&file_offset.to_le_bytes());
        bytes[offset + 16..offset + 24].copy_from_slice(&vaddr.to_le_bytes());
        bytes[offset + 24..offset + 32].copy_from_slice(&vaddr.to_le_bytes());
        bytes[offset + 32..offset + 40].copy_from_slice(&file_size.to_le_bytes());
        bytes[offset + 40..offset + 48].copy_from_slice(&memory_size.to_le_bytes());
        bytes[offset + 48..offset + 56].copy_from_slice(&0x1000u64.to_le_bytes());
    }

    #[allow(clippy::too_many_arguments)]
    fn put_elf64_section_header(
        bytes: &mut [u8],
        index: usize,
        name: u32,
        kind: u32,
        flags: u64,
        address: u64,
        file_offset: u64,
        size: u64,
        link: u32,
        alignment: u64,
        entry_size: u64,
    ) {
        let offset = 64 + index * 64;
        bytes[offset..offset + 4].copy_from_slice(&name.to_le_bytes());
        bytes[offset + 4..offset + 8].copy_from_slice(&kind.to_le_bytes());
        bytes[offset + 8..offset + 16].copy_from_slice(&flags.to_le_bytes());
        bytes[offset + 16..offset + 24].copy_from_slice(&address.to_le_bytes());
        bytes[offset + 24..offset + 32].copy_from_slice(&file_offset.to_le_bytes());
        bytes[offset + 32..offset + 40].copy_from_slice(&size.to_le_bytes());
        bytes[offset + 40..offset + 44].copy_from_slice(&link.to_le_bytes());
        bytes[offset + 48..offset + 56].copy_from_slice(&alignment.to_le_bytes());
        bytes[offset + 56..offset + 64].copy_from_slice(&entry_size.to_le_bytes());
    }

    fn elf64_without_sections_with_dynsym() -> Vec<u8> {
        const DYNAMIC_OFFSET: usize = 0x200;
        const DYNSTR_OFFSET: usize = 0x300;
        const DYNSYM_OFFSET: usize = 0x400;
        const HASH_OFFSET: usize = 0x500;
        const LOAD_VADDR: u64 = 0x1000;

        let name = b"\0_ZN7mycrate3fooE\0";
        let mut bytes = vec![0u8; HASH_OFFSET + 8];
        bytes[0..4].copy_from_slice(b"\x7fELF");
        bytes[4] = 2;
        bytes[5] = 1;
        bytes[6] = 1;
        bytes[16..18].copy_from_slice(&3u16.to_le_bytes());
        bytes[18..20].copy_from_slice(&62u16.to_le_bytes());
        bytes[20..24].copy_from_slice(&1u32.to_le_bytes());
        bytes[32..40].copy_from_slice(&64u64.to_le_bytes());
        bytes[52..54].copy_from_slice(&64u16.to_le_bytes());
        bytes[54..56].copy_from_slice(&56u16.to_le_bytes());
        bytes[56..58].copy_from_slice(&2u16.to_le_bytes());
        bytes[58..60].copy_from_slice(&64u16.to_le_bytes());

        let file_size = u64::try_from(bytes.len()).expect("fixture length fits u64");
        put_elf64_program_header(&mut bytes, 64, 1, 4, 0, LOAD_VADDR, file_size, file_size);
        put_elf64_program_header(
            &mut bytes,
            120,
            2,
            4,
            u64::try_from(DYNAMIC_OFFSET).expect("offset fits u64"),
            LOAD_VADDR + u64::try_from(DYNAMIC_OFFSET).expect("offset fits u64"),
            96,
            96,
        );

        let dynamic = [
            (
                5u64,
                LOAD_VADDR + u64::try_from(DYNSTR_OFFSET).expect("offset fits u64"),
            ),
            (10, u64::try_from(name.len()).expect("name length fits u64")),
            (
                6,
                LOAD_VADDR + u64::try_from(DYNSYM_OFFSET).expect("offset fits u64"),
            ),
            (11, 24),
            (
                4,
                LOAD_VADDR + u64::try_from(HASH_OFFSET).expect("offset fits u64"),
            ),
            (0, 0),
        ];
        for (index, (tag, value)) in dynamic.into_iter().enumerate() {
            let offset = DYNAMIC_OFFSET + index * 16;
            bytes[offset..offset + 8].copy_from_slice(&tag.to_le_bytes());
            bytes[offset + 8..offset + 16].copy_from_slice(&value.to_le_bytes());
        }
        bytes[DYNSTR_OFFSET..DYNSTR_OFFSET + name.len()].copy_from_slice(name);
        let symbol = DYNSYM_OFFSET + 24;
        bytes[symbol..symbol + 4].copy_from_slice(&1u32.to_le_bytes());
        bytes[symbol + 4] = 0x12;
        bytes[symbol + 6..symbol + 8].copy_from_slice(&1u16.to_le_bytes());
        bytes[symbol + 8..symbol + 16].copy_from_slice(&0x1400u64.to_le_bytes());
        bytes[symbol + 16..symbol + 24].copy_from_slice(&4u64.to_le_bytes());
        bytes[HASH_OFFSET..HASH_OFFSET + 4].copy_from_slice(&1u32.to_le_bytes());
        bytes[HASH_OFFSET + 4..HASH_OFFSET + 8].copy_from_slice(&2u32.to_le_bytes());
        bytes
    }

    fn elf64_relocatable_with_zero_symbol() -> Vec<u8> {
        const TEXT_OFFSET: usize = 0x200;
        const STRTAB_OFFSET: usize = 0x204;
        const SYMTAB_OFFSET: usize = 0x220;
        const SHSTRTAB_OFFSET: usize = 0x250;

        let strtab = b"\0_ZN7mycrate3fooE\0";
        let shstrtab = b"\0.text\0.strtab\0.symtab\0.shstrtab\0";
        let mut bytes = vec![0u8; SHSTRTAB_OFFSET + shstrtab.len()];
        bytes[0..4].copy_from_slice(b"\x7fELF");
        bytes[4] = 2;
        bytes[5] = 1;
        bytes[6] = 1;
        bytes[16..18].copy_from_slice(&1u16.to_le_bytes());
        bytes[18..20].copy_from_slice(&62u16.to_le_bytes());
        bytes[20..24].copy_from_slice(&1u32.to_le_bytes());
        bytes[40..48].copy_from_slice(&64u64.to_le_bytes());
        bytes[52..54].copy_from_slice(&64u16.to_le_bytes());
        bytes[58..60].copy_from_slice(&64u16.to_le_bytes());
        bytes[60..62].copy_from_slice(&5u16.to_le_bytes());
        bytes[62..64].copy_from_slice(&4u16.to_le_bytes());

        put_elf64_section_header(
            &mut bytes,
            1,
            1,
            1,
            2,
            0,
            u64::try_from(TEXT_OFFSET).expect("offset fits u64"),
            4,
            0,
            16,
            0,
        );
        put_elf64_section_header(
            &mut bytes,
            2,
            7,
            3,
            0,
            0,
            u64::try_from(STRTAB_OFFSET).expect("offset fits u64"),
            u64::try_from(strtab.len()).expect("length fits u64"),
            0,
            1,
            0,
        );
        put_elf64_section_header(
            &mut bytes,
            3,
            15,
            2,
            0,
            0,
            u64::try_from(SYMTAB_OFFSET).expect("offset fits u64"),
            48,
            2,
            8,
            24,
        );
        put_elf64_section_header(
            &mut bytes,
            4,
            23,
            3,
            0,
            0,
            u64::try_from(SHSTRTAB_OFFSET).expect("offset fits u64"),
            u64::try_from(shstrtab.len()).expect("length fits u64"),
            0,
            1,
            0,
        );

        bytes[TEXT_OFFSET..TEXT_OFFSET + 4].copy_from_slice(&[0x90, 0x90, 0x90, 0x90]);
        bytes[STRTAB_OFFSET..STRTAB_OFFSET + strtab.len()].copy_from_slice(strtab);
        let symbol = SYMTAB_OFFSET + 24;
        bytes[symbol..symbol + 4].copy_from_slice(&1u32.to_le_bytes());
        bytes[symbol + 4] = 0x12;
        bytes[symbol + 6..symbol + 8].copy_from_slice(&1u16.to_le_bytes());
        bytes[symbol + 16..symbol + 24].copy_from_slice(&4u64.to_le_bytes());
        bytes[SHSTRTAB_OFFSET..SHSTRTAB_OFFSET + shstrtab.len()].copy_from_slice(shstrtab);
        bytes
    }

    fn macho64_with_cstring_and_symbol() -> Vec<u8> {
        const SECTION_DATA: usize = 0xd0;
        const SYMBOL_OFFSET: usize = 0xd8;
        const STRING_OFFSET: usize = 0xe8;
        let symbol_name = b"\0_ZN7mycrate3fooE\0";
        let mut bytes = vec![0u8; STRING_OFFSET + symbol_name.len()];
        let file_size = u64::try_from(bytes.len()).expect("fixture length fits u64");

        bytes[0..4].copy_from_slice(&0xfeed_facf_u32.to_le_bytes());
        bytes[4..8].copy_from_slice(&0x0100_0007_u32.to_le_bytes());
        bytes[8..12].copy_from_slice(&3u32.to_le_bytes());
        bytes[12..16].copy_from_slice(&1u32.to_le_bytes());
        bytes[16..20].copy_from_slice(&2u32.to_le_bytes());
        bytes[20..24].copy_from_slice(&176u32.to_le_bytes());

        let segment = 32usize;
        bytes[segment..segment + 4].copy_from_slice(&0x19u32.to_le_bytes());
        bytes[segment + 4..segment + 8].copy_from_slice(&152u32.to_le_bytes());
        bytes[segment + 8..segment + 14].copy_from_slice(b"__TEXT");
        bytes[segment + 24..segment + 32].copy_from_slice(&0x1000u64.to_le_bytes());
        bytes[segment + 32..segment + 40].copy_from_slice(&5u64.to_le_bytes());
        bytes[segment + 48..segment + 56].copy_from_slice(&file_size.to_le_bytes());
        bytes[segment + 56..segment + 60].copy_from_slice(&7u32.to_le_bytes());
        bytes[segment + 60..segment + 64].copy_from_slice(&5u32.to_le_bytes());
        bytes[segment + 64..segment + 68].copy_from_slice(&1u32.to_le_bytes());

        let section = segment + 72;
        bytes[section..section + 10].copy_from_slice(b"__cstring\0");
        bytes[section + 16..section + 22].copy_from_slice(b"__TEXT");
        bytes[section + 32..section + 40].copy_from_slice(&0x1000u64.to_le_bytes());
        bytes[section + 40..section + 48].copy_from_slice(&5u64.to_le_bytes());
        bytes[section + 48..section + 52].copy_from_slice(
            &u32::try_from(SECTION_DATA)
                .expect("offset fits u32")
                .to_le_bytes(),
        );
        bytes[section + 64..section + 68].copy_from_slice(&2u32.to_le_bytes());

        let symtab = segment + 152;
        bytes[symtab..symtab + 4].copy_from_slice(&2u32.to_le_bytes());
        bytes[symtab + 4..symtab + 8].copy_from_slice(&24u32.to_le_bytes());
        bytes[symtab + 8..symtab + 12].copy_from_slice(
            &u32::try_from(SYMBOL_OFFSET)
                .expect("offset fits u32")
                .to_le_bytes(),
        );
        bytes[symtab + 12..symtab + 16].copy_from_slice(&1u32.to_le_bytes());
        bytes[symtab + 16..symtab + 20].copy_from_slice(
            &u32::try_from(STRING_OFFSET)
                .expect("offset fits u32")
                .to_le_bytes(),
        );
        bytes[symtab + 20..symtab + 24].copy_from_slice(
            &u32::try_from(symbol_name.len())
                .expect("length fits u32")
                .to_le_bytes(),
        );

        bytes[SECTION_DATA..SECTION_DATA + 5].copy_from_slice(b"hello");
        bytes[SYMBOL_OFFSET..SYMBOL_OFFSET + 4].copy_from_slice(&1u32.to_le_bytes());
        bytes[SYMBOL_OFFSET + 4] = 0x0f;
        bytes[SYMBOL_OFFSET + 5] = 1;
        bytes[SYMBOL_OFFSET + 8..SYMBOL_OFFSET + 16].copy_from_slice(&0x1000u64.to_le_bytes());
        bytes[STRING_OFFSET..STRING_OFFSET + symbol_name.len()].copy_from_slice(symbol_name);
        bytes
    }

    #[test]
    fn elf_sectionless_pt_load_and_dynstr_symbols_are_analyzable() {
        let bin = Binary::parse(None, elf64_without_sections_with_dynsym()).expect("parse ELF");
        assert_eq!(bin.sections().len(), 1);
        assert_eq!(bin.sections()[0].name, ".rodata.pt_load.0");
        assert!(!bin.string_section_indices().is_empty());
        assert!(bin
            .symbols
            .iter()
            .any(|symbol| symbol.name == "_ZN7mycrate3fooE" && symbol.vaddr == 0x1400));
    }

    #[test]
    fn elf_relocatable_keeps_defined_zero_symbol_at_section_address() {
        let bin = Binary::parse(None, elf64_relocatable_with_zero_symbol()).expect("parse ELF");
        assert_eq!(bin.sections().len(), 1);
        assert_eq!(bin.sections()[0].name, ".text");
        let symbol = bin
            .symbols
            .iter()
            .find(|symbol| symbol.name == "_ZN7mycrate3fooE")
            .expect("defined symbol");
        assert_eq!(symbol.vaddr, bin.sections()[0].vaddr);
    }

    #[test]
    fn elf_nobits_does_not_copy_file_bytes() {
        let mut bytes = elf64_with_rodata();
        let section = 64 + 64;
        bytes[section + 4..section + 8]
            .copy_from_slice(&elf::section_header::SHT_NOBITS.to_le_bytes());
        let bin = Binary::parse(None, bytes).expect("parse NOBITS ELF");
        assert_eq!(bin.sections().len(), 1);
        assert!(bin.sections()[0].data.is_empty());
    }

    #[test]
    fn elf_non_allocated_sections_are_not_indexed() {
        let mut bytes = elf64_with_rodata();
        let section = 64 + 64;
        bytes[section + 8..section + 16].copy_from_slice(&0u64.to_le_bytes());
        let bin = Binary::parse(None, bytes).expect("parse ELF");
        assert!(bin.sections().is_empty());
        assert!(bin.vaddr_to_offset(0x1000).is_none());
    }

    #[test]
    fn elf_overlapping_sections_cannot_amplify_copies_past_input_size() {
        let mut bytes = vec![0u8; 64 + 3 * 64];
        bytes[0..4].copy_from_slice(b"\x7fELF");
        bytes[4] = 2;
        bytes[5] = 1;
        bytes[6] = 1;
        bytes[16..18].copy_from_slice(&2u16.to_le_bytes());
        bytes[18..20].copy_from_slice(&62u16.to_le_bytes());
        bytes[20..24].copy_from_slice(&1u32.to_le_bytes());
        bytes[40..48].copy_from_slice(&64u64.to_le_bytes());
        bytes[52..54].copy_from_slice(&64u16.to_le_bytes());
        bytes[58..60].copy_from_slice(&64u16.to_le_bytes());
        bytes[60..62].copy_from_slice(&3u16.to_le_bytes());
        let size = u64::try_from(bytes.len()).expect("fixture length fits u64");
        put_elf64_section_header(&mut bytes, 1, 0, 1, 2, 0x1000, 0, size, 0, 1, 0);
        put_elf64_section_header(&mut bytes, 2, 0, 1, 2, 0x2000, 0, size, 0, 1, 0);
        let error = Binary::parse(None, bytes)
            .err()
            .expect("copy amplification must fail");
        assert!(error.to_string().contains("exceeds input size"));
    }

    #[test]
    fn macho_uses_loader_names_symbols_architecture_and_endianness() {
        let bin = Binary::parse(None, macho64_with_cstring_and_symbol()).expect("parse Mach-O");
        assert_eq!(bin.format, BinaryFormat::MachO);
        assert_eq!(bin.arch, "x86_64");
        assert!(bin.little_endian);
        assert_eq!(bin.sections()[0].name, "__TEXT.__cstring");
        assert_eq!(bin.string_section_indices(), &[0]);
        assert!(bin
            .symbols
            .iter()
            .any(|symbol| symbol.name == "_ZN7mycrate3fooE" && symbol.vaddr == 0x1000));
    }

    #[test]
    fn macho_big_endian_metadata_is_not_hardcoded() {
        let mut bytes = vec![0u8; 32];
        bytes[0..4].copy_from_slice(&0xfeed_face_u32.to_be_bytes());
        bytes[4..8].copy_from_slice(&7u32.to_be_bytes());
        bytes[8..12].copy_from_slice(&3u32.to_be_bytes());
        bytes[12..16].copy_from_slice(&1u32.to_be_bytes());
        let bin = Binary::parse(None, bytes).expect("parse big-endian Mach-O");
        assert_eq!(bin.arch, "i386");
        assert!(!bin.little_endian);
        assert!(!bin.is_64);
    }

    #[test]
    fn checked_base_plus_rva_rejects_overflow() {
        assert!(checked_vaddr_add(u64::MAX, 1, "test").is_err());
        assert_eq!(checked_vaddr_add(0x1000, 0x20, "test").unwrap(), 0x1020);
    }

    #[test]
    fn input_limit_rejects_length_without_allocating_input() {
        let error = validate_input_len(MAX_INPUT_BYTES + 1).expect_err("oversized input");
        assert!(error.to_string().contains("exceeds maximum"));
        assert!(validate_input_len(MAX_INPUT_BYTES).is_ok());
    }

    #[test]
    fn pe_image_base_uses_u64_optional_header_field() {
        let mut optional_header = pe::optional_header::OptionalHeader {
            standard_fields: pe::optional_header::StandardFields {
                magic: pe::optional_header::MAGIC_64,
                ..pe::optional_header::StandardFields::default()
            },
            windows_fields: pe::optional_header::WindowsFields::default(),
            data_directories: pe::data_directories::DataDirectories::default(),
        };
        optional_header.windows_fields.image_base = 0x1_0000_0000;
        assert_eq!(pe_image_base(Some(&optional_header)), 0x1_0000_0000);
        assert_eq!(pe_image_base(None), 0);
    }

    #[test]
    fn arm64_32_uses_32_bit_pointers_with_a_64_bit_mach_header() {
        assert!(!mach_pointer_is_64(true, CPU_TYPE_ARM64_32));
        assert!(mach_pointer_is_64(true, CPU_TYPE_ARM64));
        assert!(!mach_pointer_is_64(false, CPU_TYPE_ARM64));

        let bin = Binary::from_test_parts(
            BinaryFormat::MachO,
            mach_pointer_is_64(true, CPU_TYPE_ARM64_32),
            true,
            vec![Section {
                name: "__TEXT.__cstring".into(),
                vaddr: 0x1000,
                size: 8,
                data: vec![0x78, 0x56, 0x34, 0x12, 0, 0, 0, 0],
            }],
            vec![],
            vec![],
        );
        assert_eq!(bin.read_ptr(0x1000), Some(0x1234_5678));

        let mut macho = minimal_macho64();
        macho[4..8].copy_from_slice(&CPU_TYPE_ARM64_32.to_le_bytes());
        let parsed = Binary::parse(None, macho).expect("parse arm64_32 Mach-O");
        assert_eq!(parsed.arch, "arm64_32");
        assert!(!parsed.is_64);
    }

    #[test]
    fn replacing_test_sections_rebuilds_range_and_string_indices() {
        let mut bin = Binary::from_test_parts(
            BinaryFormat::Elf,
            true,
            true,
            vec![Section {
                name: ".rodata".into(),
                vaddr: 0x1000,
                size: 0x100,
                data: vec![0xAA; 0x100],
            }],
            vec![],
            vec![0],
        );
        bin.replace_sections_for_test(vec![
            Section {
                name: ".text".into(),
                vaddr: 0x2000,
                size: 0x100,
                data: vec![0xAA; 0x100],
            },
            Section {
                name: ".rodata.inner".into(),
                vaddr: 0x2050,
                size: 0x10,
                data: vec![0xBB; 0x10],
            },
        ]);
        assert_eq!(bin.vaddr_to_offset(0x1000), None);
        assert_eq!(bin.read_at_vaddr(0x2000, 1), Some(&[0xAA][..]));
        assert!(!bin.vaddr_in_string_section(0x2000, 1));
        assert_eq!(bin.vaddr_to_offset(0x2050), Some((1, 0)));
        assert_eq!(bin.read_at_vaddr(0x2050, 1), Some(&[0xBB][..]));
        assert!(bin.vaddr_in_string_section(0x2050, 1));
        assert_eq!(bin.string_section_indices(), &[1]);
    }

    #[test]
    fn symbol_budget_rejects_repeated_names_across_formats() {
        let mut budget = SymbolBudget::new(4);
        let mut symbols = Vec::new();
        let elf_symbol = elf::Sym {
            st_shndx: usize::try_from(elf::section_header::SHN_ABS).expect("section index"),
            ..elf::Sym::default()
        };
        append_elf_symbol(
            &mut symbols,
            elf_symbol,
            Some("repeat"),
            false,
            &[],
            &mut budget,
        )
        .expect("ELF symbol fits shared budget");

        let export = pe::export::Export {
            name: Some("repeat"),
            rva: 0x2000,
            ..pe::export::Export::default()
        };
        append_pe_export(&mut symbols, &export, 0, &mut budget)
            .expect("PE symbol fits shared budget");

        let mach_symbol = mach::symbols::Nlist {
            n_strx: 0,
            n_type: 0,
            n_sect: 0,
            n_desc: 0,
            n_value: 0x3000,
        };
        let error = append_mach_symbol(&mut symbols, "repeat", &mach_symbol, &mut budget)
            .expect_err("repeated Mach-O name must exceed shared budget");
        assert!(error.to_string().contains("Mach-O"));
        assert_eq!(symbols.len(), 2);
    }

    #[test]
    fn elf_tls_symbols_are_not_reported_as_virtual_addresses() {
        let symbol = elf::Sym {
            st_name: 1,
            st_info: elf::sym::STT_TLS,
            st_shndx: 1,
            st_value: 0x1234,
            ..elf::Sym::default()
        };
        let mut symbols = Vec::new();
        let mut budget = SymbolBudget::new(64);
        append_elf_symbol(
            &mut symbols,
            symbol,
            Some("tls_value"),
            false,
            &[None, Some(0)],
            &mut budget,
        )
        .expect("skip TLS symbol");
        assert!(symbols.is_empty());
    }

    #[test]
    fn pe_forwarded_exports_are_skipped() {
        let export = pe::export::Export {
            name: Some("forwarded"),
            rva: 0x2000,
            reexport: Some(pe::export::Reexport::DLLName {
                export: "target",
                lib: "other.dll",
            }),
            ..pe::export::Export::default()
        };
        let mut symbols = Vec::new();
        let mut budget = SymbolBudget::new(64);
        append_pe_export(&mut symbols, &export, 0x1400_0000, &mut budget).expect("skip forwarder");
        assert!(symbols.is_empty());
    }

    #[test]
    fn preflight_rejects_extended_elf_program_header_count() {
        let mut bytes = vec![0u8; 128];
        bytes[0..4].copy_from_slice(ELF_MAGIC);
        bytes[4] = ELFCLASS64;
        bytes[5] = ELFDATA2LSB;
        bytes[6] = 1;
        bytes[32..40].copy_from_slice(&128u64.to_le_bytes());
        bytes[40..48].copy_from_slice(&64u64.to_le_bytes());
        bytes[52..54].copy_from_slice(&64u16.to_le_bytes());
        bytes[56..58].copy_from_slice(&u16::MAX.to_le_bytes());
        bytes[58..60].copy_from_slice(&56u16.to_le_bytes());
        bytes[60..62].copy_from_slice(&1u16.to_le_bytes());
        bytes[64 + 44..64 + 48].copy_from_slice(
            &u32::try_from(MAX_TABLE_ENTRIES + 1)
                .expect("count")
                .to_le_bytes(),
        );

        let error = preflight_elf(&bytes).expect_err("extended ELF count must be capped");
        assert!(error.to_string().contains("ELF program headers"));
    }

    #[test]
    fn preflight_rejects_pe_coff_and_export_amplification_counts() {
        let mut pe = vec![0u8; 128];
        pe[0..2].copy_from_slice(b"MZ");
        pe[0x3c..0x40].copy_from_slice(&64u32.to_le_bytes());
        pe[64..68].copy_from_slice(PE_MAGIC);
        pe[68 + 12..68 + 16].copy_from_slice(
            &u32::try_from(MAX_TABLE_ENTRIES + 1)
                .expect("count")
                .to_le_bytes(),
        );
        let error = preflight_pe(&pe).expect_err("PE COFF count must be capped");
        assert!(error.to_string().contains("PE COFF symbol table"));

        let mut export = vec![0u8; PE_EXPORT_DIRECTORY_SIZE];
        export[24..28].copy_from_slice(
            &u32::try_from(MAX_TABLE_ENTRIES + 1)
                .expect("count")
                .to_le_bytes(),
        );
        let error =
            preflight_pe_export(&export, 0, &[], 0x200, &mut PreflightBudget { entries: 0 })
                .expect_err("PE export name count must be capped");
        assert!(error.to_string().contains("PE export name pointers"));
    }

    #[test]
    fn preflight_rejects_macho_load_command_count() {
        let mut bytes = minimal_macho64();
        bytes[16..20].copy_from_slice(
            &u32::try_from(MAX_TABLE_ENTRIES + 1)
                .expect("count")
                .to_le_bytes(),
        );
        let error = preflight_mach(&bytes).expect_err("Mach-O ncmds must be capped");
        assert!(error.to_string().contains("Mach-O load commands"));
    }

    #[test]
    fn lookup_range_impl_progresses_across_overlapping_boundaries() {
        let bin = Binary::from_test_parts(
            BinaryFormat::Elf,
            true,
            true,
            vec![
                Section {
                    name: ".rodata.outer".into(),
                    vaddr: 0x1000,
                    size: 0x100,
                    data: vec![0xAA; 0x100],
                },
                Section {
                    name: ".rodata.inner".into(),
                    vaddr: 0x1080,
                    size: 0x20,
                    data: vec![0xBB; 0x20],
                },
                Section {
                    name: ".rodata.tail".into(),
                    vaddr: 0x1090,
                    size: 0x70,
                    data: vec![0xCC; 0x70],
                },
            ],
            vec![],
            vec![0, 1, 2],
        );

        let mut probes = 0;
        assert_eq!(
            bin.lookup_range_impl(0x1090, 0x1091, Some(1), true, Some(&mut probes)),
            Some((2, 0)),
            "later-start section must win at an overlapping start boundary"
        );
        assert!(
            probes > 0 && probes <= 7,
            "unexpected probe count: {probes}"
        );

        assert_eq!(
            bin.lookup_range_impl(0x1080, 0x10a0, Some(0x20), true, None),
            Some((1, 0)),
            "exactly ending at the inner section boundary must stay in the inner section"
        );
        assert_eq!(
            bin.lookup_range_impl(0x1080, 0x10a1, Some(0x21), true, None),
            Some((0, 0x80)),
            "a read that crosses the inner boundary must continue to a containing candidate"
        );
    }

    #[test]
    fn validate_range_candidate_rejects_each_or_condition() {
        let bin = Binary::from_test_parts(
            BinaryFormat::Elf,
            true,
            true,
            vec![Section {
                name: ".rodata".into(),
                vaddr: 0x2000,
                size: 4,
                data: vec![1, 2, 3, 4],
            }],
            vec![],
            vec![0],
        );

        assert_eq!(
            bin.validate_range_candidate(0, 0x2000, 0x2004, Some(4), true),
            Some((0, 4))
        );
        assert!(bin
            .validate_range_candidate(0, 0x1fff, 0x2000, None, false)
            .is_none());
        assert!(bin
            .validate_range_candidate(0, 0x2004, 0x2005, None, false)
            .is_none());
        assert!(bin
            .validate_range_candidate(0, 0x2003, 0x2005, None, false)
            .is_none());
        assert!(bin
            .validate_range_candidate(0, 0x2000, 0x2001, Some(5), false)
            .is_none());

        let non_string = Binary::from_test_parts(
            BinaryFormat::Elf,
            true,
            true,
            vec![Section {
                name: ".text".into(),
                vaddr: 0x3000,
                size: 1,
                data: vec![0],
            }],
            vec![],
            vec![],
        );
        assert!(non_string
            .validate_range_candidate(0, 0x3000, 0x3001, None, true)
            .is_none());
    }

    #[test]
    fn preflight_object_dispatches_pe_mach_and_fat_before_goblin() {
        let mut pe = vec![0u8; 88];
        pe[0..2].copy_from_slice(b"MZ");
        pe[0x3c..0x40].copy_from_slice(&64u32.to_le_bytes());
        pe[64..68].copy_from_slice(PE_MAGIC);
        assert!(preflight_object(&pe).is_ok());

        assert!(preflight_object(&minimal_macho64()).is_ok());

        let mut fat = vec![0u8; 8];
        fat[0..4].copy_from_slice(&MACH_FAT_MAGIC.to_be_bytes());
        let error = preflight_object(&fat).expect_err("fat Mach-O must be rejected in preflight");
        assert!(error.to_string().contains("fat archives"));
    }

    #[test]
    fn preflight_count_and_budget_exact_boundaries_are_inclusive() {
        assert!(preflight_count(MAX_TABLE_ENTRIES, "exact count").is_ok());
        let error = preflight_count(MAX_TABLE_ENTRIES + 1, "too many")
            .expect_err("count over the per-table cap must fail");
        assert!(error.to_string().contains("too many"));

        let mut budget = PreflightBudget { entries: 0 };
        for _ in 0..4 {
            budget
                .consume(MAX_TABLE_ENTRIES, "aggregate exact")
                .expect("aggregate cap is inclusive");
        }
        assert_eq!(budget.entries, MAX_AGGREGATE_TABLE_ENTRIES);
        let error = budget
            .consume(1, "aggregate overflow")
            .expect_err("one entry past aggregate cap must fail");
        assert!(error.to_string().contains("aggregate overflow"));
    }

    #[test]
    fn preflight_string_table_counts_first_and_last_nul_boundaries() {
        let mut budget = PreflightBudget { entries: 0 };
        preflight_string_table(b"\0alpha\0", 0, 7, &mut budget, "nul bounded")
            .expect("bounded strings fit");
        assert_eq!(budget.entries, 2, "first and last NUL are both entries");

        let mut unterminated = PreflightBudget { entries: 0 };
        preflight_string_table(b"alpha", 0, 5, &mut unterminated, "unterminated")
            .expect("unterminated final string is counted");
        assert_eq!(unterminated.entries, 1);

        let mut empty = PreflightBudget { entries: 0 };
        preflight_string_table(b"", 0, 0, &mut empty, "empty").expect("empty table fits");
        assert_eq!(empty.entries, 0);
    }

    #[test]
    fn preflight_pe_optional_and_mach_boundaries_are_enforced() {
        let mut pe_optional = vec![
            0u8;
            PE_DATA_DIRECTORIES_OFFSET_32
                + PE_MAX_DATA_DIRECTORIES * PE_DATA_DIRECTORY_SIZE
        ];
        pe_optional[0..2].copy_from_slice(&PE32_MAGIC.to_le_bytes());
        pe_optional[PE_FILE_ALIGNMENT_OFFSET..PE_FILE_ALIGNMENT_OFFSET + 4]
            .copy_from_slice(&0x200u32.to_le_bytes());
        pe_optional[PE_NUMBER_OF_RVAS_OFFSET_32..PE_NUMBER_OF_RVAS_OFFSET_32 + 4].copy_from_slice(
            &u32::try_from(PE_MAX_DATA_DIRECTORIES)
                .expect("PE data directory cap fits u32")
                .to_le_bytes(),
        );
        assert!(preflight_pe_optional(
            &pe_optional,
            0,
            pe_optional.len(),
            &[],
            &mut PreflightBudget { entries: 0 },
        )
        .is_ok());

        pe_optional[PE_NUMBER_OF_RVAS_OFFSET_32..PE_NUMBER_OF_RVAS_OFFSET_32 + 4].copy_from_slice(
            &u32::try_from(PE_MAX_DATA_DIRECTORIES + 1)
                .expect("PE data directory cap plus one fits u32")
                .to_le_bytes(),
        );
        let error = preflight_pe_optional(
            &pe_optional,
            0,
            pe_optional.len(),
            &[],
            &mut PreflightBudget { entries: 0 },
        )
        .expect_err("directory count over PE cap must fail");
        assert!(error.to_string().contains("NumberOfRvaAndSizes"));

        let mut macho = minimal_macho64();
        macho.resize(40, 0);
        macho[16..20].copy_from_slice(&1u32.to_le_bytes());
        macho[20..24].copy_from_slice(&8u32.to_le_bytes());
        macho[32..36].copy_from_slice(&MACH_LC_SEGMENT_64.to_le_bytes());
        macho[36..40].copy_from_slice(&8u32.to_le_bytes());
        let error = preflight_mach(&macho).expect_err("segment command smaller than header fails");
        assert!(error.to_string().contains("segment command is too short"));
    }

    fn minimal_macho64() -> Vec<u8> {
        let mut m = vec![0u8; 32];
        m[0..4].copy_from_slice(&0xfeed_facf_u32.to_le_bytes());
        m[4..8].copy_from_slice(&0x0100_0007_u32.to_le_bytes());
        m[8..12].copy_from_slice(&3u32.to_le_bytes());
        m[12..16].copy_from_slice(&1u32.to_le_bytes());
        m
    }

    #[test]
    fn parse_minimal_macho_succeeds() {
        let macho = minimal_macho64();
        let bin = Binary::parse(Some("test.macho"), macho).expect("minimal Mach-O must parse");
        assert_eq!(bin.format, BinaryFormat::MachO);
        assert!(bin.is_64);
    }

    /// Regression: a malformed Mach-O 64 whose `LC_MAIN` load command triggers
    /// subtract-with-overflow inside goblin 0.8.2's load-command walker
    /// (mach/mod.rs:280) must surface as `Err` via the `catch_unwind` guard in
    /// [`Binary::parse`] instead of aborting the process. Without that guard
    /// this test panics rather than failing an assertion.
    #[test]
    fn macho_lc_main_underflow_returns_err_not_panic() {
        let mut macho = vec![0u8; 128];
        macho[0..4].copy_from_slice(&0xfeed_facf_u32.to_le_bytes());
        macho[4..8].copy_from_slice(&0x0100_0007_u32.to_le_bytes());
        macho[8..12].copy_from_slice(&3u32.to_le_bytes());
        macho[12..16].copy_from_slice(&2u32.to_le_bytes());
        macho[16..20].copy_from_slice(&2u32.to_le_bytes());
        macho[20..24].copy_from_slice(&96u32.to_le_bytes());

        let segment = 32usize;
        macho[segment..segment + 4].copy_from_slice(&MACH_LC_SEGMENT_64.to_le_bytes());
        macho[segment + 4..segment + 8].copy_from_slice(&72u32.to_le_bytes());
        macho[segment + 8..segment + 14].copy_from_slice(b"__TEXT");
        macho[segment + 32..segment + 40].copy_from_slice(&1u64.to_le_bytes());
        macho[segment + 40..segment + 48].copy_from_slice(&1u64.to_le_bytes());

        let main = segment + 72;
        macho[main..main + 4].copy_from_slice(&0x8000_0028u32.to_le_bytes());
        macho[main + 4..main + 8].copy_from_slice(&24u32.to_le_bytes());

        // Preflight deliberately accepts this: it range-checks only segment and
        // symtab commands, so the panic-triggering LC_MAIN still reaches goblin.
        assert!(preflight_mach(&macho).is_ok());
        // The catch_unwind guard must convert goblin's panic into an `Err`.
        assert!(
            Binary::parse(None, macho).is_err(),
            "LC_MAIN underflow must return Err, not panic"
        );
    }

    #[test]
    fn vaddr_to_offset_finds_correct_section() {
        let bin = Binary::from_test_parts(
            BinaryFormat::Elf,
            true,
            true,
            vec![
                Section {
                    name: ".text".into(),
                    vaddr: 0x1000,
                    size: 0x100,
                    data: vec![0xAA; 0x100],
                },
                Section {
                    name: ".rodata".into(),
                    vaddr: 0x2000,
                    size: 0x100,
                    data: vec![0xBB; 0x100],
                },
            ],
            vec![],
            vec![],
        );
        // nosemgrep: rustrip-no-unwrapping-trust-bytes (test code)
        let (sec_i, off) = bin.vaddr_to_offset(0x2005).unwrap();
        assert_eq!(sec_i, 1);
        assert_eq!(off, 5);
        assert_eq!(bin.read_at_vaddr(0x2005, 1).unwrap()[0], 0xBB);
    }

    #[test]
    fn parse_rejects_empty_input() {
        assert!(Binary::parse(Some("empty"), vec![]).is_err());
    }

    #[test]
    fn parse_rejects_garbage() {
        assert!(Binary::parse(Some("garbage"), vec![0x42; 128]).is_err());
    }

    #[test]
    fn budgeted_extract_accepts_exact_cumulative_input_size() {
        let bytes = b"0123456789".to_vec();
        let mut copied = 5usize;
        let data = extract_section_data_budgeted(5, 5, &bytes, &mut copied, "test")
            .expect("exact cumulative copy budget fits");
        assert_eq!(data, b"56789");
        assert_eq!(copied, bytes.len());
    }

    #[test]
    fn budgeted_extract_rejects_cumulative_amplification() {
        let bytes = b"0123456789".to_vec();
        let mut copied = 6usize;
        let error = extract_section_data_budgeted(5, 5, &bytes, &mut copied, "test")
            .expect_err("copy amplification must fail");
        assert!(error
            .to_string()
            .contains("cumulative copied data exceeds input size"));
        assert_eq!(copied, 6, "failed copy must not advance budget");
    }

    #[test]
    fn budgeted_extract_truncates_at_file_end_and_counts_actual_bytes() {
        let bytes = b"0123456789".to_vec();
        let mut copied = 0usize;
        let data = extract_section_data_budgeted(8, 10, &bytes, &mut copied, "test")
            .expect("truncated section copy is allowed");
        assert_eq!(data, b"89");
        assert_eq!(copied, 2);
    }

    #[test]
    fn budgeted_extract_rejects_offset_size_overflow() {
        let bytes = b"0123456789".to_vec();
        let mut copied = 0usize;
        let error = extract_section_data_budgeted(5, usize::MAX, &bytes, &mut copied, "test")
            .expect_err("overflowing section range must fail");
        assert!(error.to_string().contains("section file range overflow"));
        assert_eq!(copied, 0);
    }

    #[test]
    fn budgeted_extract_zero_size_or_offset_past_end_counts_no_bytes() {
        let bytes = b"0123456789".to_vec();
        let mut copied = 3usize;
        assert!(
            extract_section_data_budgeted(0, 0, &bytes, &mut copied, "test")
                .expect("zero size copy succeeds")
                .is_empty()
        );
        assert!(
            extract_section_data_budgeted(20, 5, &bytes, &mut copied, "test")
                .expect("offset past end copy succeeds")
                .is_empty()
        );
        assert_eq!(copied, 3);
    }
}