llvm-native-core 0.1.10

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
//! Deep ELF utilities for X86 platforms.
//!
//! Clean-room reconstruction of the ELF object file format as specified in
//! the System V gABI, AMD64 ELF supplement (Processor Supplement v1.0),
//! and the published ELF-64 Object File Format specification.
//!
//! ## Capabilities
//!
//! - Full ELF file parsing and writing (ELF32/ELF64)
//! - Program header validation with all GNU extension types
//! - Section header handling with all flag combinations
//! - Symbol table (symtab/dynsym) with full st_info/st_other/st_shndx
//! - Relocation tables (R_X86_64_* and R_386_* full catalog)
//! - Dynamic entries (all DT_*)
//! - Version definitions and requirements
//! - Note sections (GNU build ID, ABI tag, gold version)
//! - Hash tables (SysV and GNU hash)
//! - Compressed sections and COMDAT groups
//! - ELF validation with comprehensive diagnostics

use std::collections::{BTreeMap, HashMap, HashSet};
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::path::Path;

// ─── Constants ────────────────────────────────────────────────────────────

/// ELF magic bytes: 0x7f 'E' 'L' 'F'
pub const ELF_MAGIC_BYTES: [u8; 4] = [0x7f, b'E', b'L', b'F'];

/// Size of the ELF identification buffer.
pub const EI_NIDENT: usize = 16;

/// ELF identification field indices.
pub const EI_MAG0: usize = 0;
pub const EI_MAG1: usize = 1;
pub const EI_MAG2: usize = 2;
pub const EI_MAG3: usize = 3;
pub const EI_CLASS: usize = 4;
pub const EI_DATA: usize = 5;
pub const EI_VERSION: usize = 6;
pub const EI_OSABI: usize = 7;
pub const EI_ABIVERSION: usize = 8;
pub const EI_PAD: usize = 9;

// ELF classes
pub const ELFCLASS32: u8 = 1;
pub const ELFCLASS64: u8 = 2;

// ELF endianness
pub const ELFDATA2LSB: u8 = 1;
pub const ELFDATA2MSB: u8 = 2;

// ELF versions
pub const EV_CURRENT: u32 = 1;

// Object file types
pub const ET_NONE: u16 = 0;
pub const ET_REL: u16 = 1;
pub const ET_EXEC: u16 = 2;
pub const ET_DYN: u16 = 3;
pub const ET_CORE: u16 = 4;

// ─── Machine Constants ────────────────────────────────────────────────────

pub const EM_386: u16 = 3;
pub const EM_X86_64: u16 = 62;

// ─── OS/ABI Constants ─────────────────────────────────────────────────────

pub const ELFOSABI_NONE: u8 = 0;
pub const ELFOSABI_SYSV: u8 = 0;
pub const ELFOSABI_HPUX: u8 = 1;
pub const ELFOSABI_NETBSD: u8 = 2;
pub const ELFOSABI_LINUX: u8 = 3;
pub const ELFOSABI_GNU: u8 = 3;
pub const ELFOSABI_SOLARIS: u8 = 6;
pub const ELFOSABI_AIX: u8 = 7;
pub const ELFOSABI_FREEBSD: u8 = 9;
pub const ELFOSABI_OPENBSD: u8 = 12;
pub const ELFOSABI_STANDALONE: u8 = 255;

// ─── Program Header Types ─────────────────────────────────────────────────

pub const PT_NULL: u32 = 0;
pub const PT_LOAD: u32 = 1;
pub const PT_DYNAMIC: u32 = 2;
pub const PT_INTERP: u32 = 3;
pub const PT_NOTE: u32 = 4;
pub const PT_SHLIB: u32 = 5;
pub const PT_PHDR: u32 = 6;
pub const PT_TLS: u32 = 7;
pub const PT_LOOS: u32 = 0x60000000;
pub const PT_HIOS: u32 = 0x6FFFFFFF;
pub const PT_LOPROC: u32 = 0x70000000;
pub const PT_HIPROC: u32 = 0x7FFFFFFF;

// GNU extensions
pub const PT_GNU_EH_FRAME: u32 = 0x6474e550;
pub const PT_GNU_STACK: u32 = 0x6474e551;
pub const PT_GNU_RELRO: u32 = 0x6474e552;
pub const PT_GNU_PROPERTY: u32 = 0x6474e553;

// ─── Program Header Flags ─────────────────────────────────────────────────

pub const PF_X: u32 = 1;
pub const PF_W: u32 = 2;
pub const PF_R: u32 = 4;
pub const PF_MASKOS: u32 = 0x0ff00000;
pub const PF_MASKPROC: u32 = 0xf0000000;

// ─── Section Header Types ─────────────────────────────────────────────────

pub const SHT_NULL: u32 = 0;
pub const SHT_PROGBITS: u32 = 1;
pub const SHT_SYMTAB: u32 = 2;
pub const SHT_STRTAB: u32 = 3;
pub const SHT_RELA: u32 = 4;
pub const SHT_HASH: u32 = 5;
pub const SHT_DYNAMIC: u32 = 6;
pub const SHT_NOTE: u32 = 7;
pub const SHT_NOBITS: u32 = 8;
pub const SHT_REL: u32 = 9;
pub const SHT_SHLIB: u32 = 10;
pub const SHT_DYNSYM: u32 = 11;
pub const SHT_INIT_ARRAY: u32 = 14;
pub const SHT_FINI_ARRAY: u32 = 15;
pub const SHT_PREINIT_ARRAY: u32 = 16;
pub const SHT_GROUP: u32 = 17;
pub const SHT_SYMTAB_SHNDX: u32 = 18;
pub const SHT_LOOS: u32 = 0x60000000;

// GNU section extensions
pub const SHT_GNU_ATTRIBUTES: u32 = 0x6ffffff5;
pub const SHT_GNU_HASH: u32 = 0x6ffffff6;
pub const SHT_GNU_LIBLIST: u32 = 0x6ffffff7;
pub const SHT_GNU_VERDEF: u32 = 0x6ffffffd;
pub const SHT_GNU_VERNEED: u32 = 0x6ffffffe;
pub const SHT_GNU_VERSYM: u32 = 0x6fffffff;

// ─── Section Header Flags ─────────────────────────────────────────────────

pub const SHF_WRITE: u64 = 0x1;
pub const SHF_ALLOC: u64 = 0x2;
pub const SHF_EXECINSTR: u64 = 0x4;
pub const SHF_MERGE: u64 = 0x10;
pub const SHF_STRINGS: u64 = 0x20;
pub const SHF_INFO_LINK: u64 = 0x40;
pub const SHF_LINK_ORDER: u64 = 0x80;
pub const SHF_OS_NONCONFORMING: u64 = 0x100;
pub const SHF_GROUP: u64 = 0x200;
pub const SHF_TLS: u64 = 0x400;
pub const SHF_COMPRESSED: u64 = 0x800;
pub const SHF_MASKOS: u64 = 0x0ff00000;
pub const SHF_MASKPROC: u64 = 0xf0000000;
pub const SHF_EXCLUDE: u64 = 0x80000000;

/// All recognized section flag names for flag combination parsing.
pub const ALL_SHFLAGS: &[(u64, &str)] = &[
    (SHF_WRITE, "W"),
    (SHF_ALLOC, "A"),
    (SHF_EXECINSTR, "X"),
    (SHF_MERGE, "M"),
    (SHF_STRINGS, "S"),
    (SHF_INFO_LINK, "I"),
    (SHF_LINK_ORDER, "L"),
    (SHF_OS_NONCONFORMING, "O"),
    (SHF_GROUP, "G"),
    (SHF_TLS, "T"),
    (SHF_COMPRESSED, "C"),
    (SHF_EXCLUDE, "E"),
];

// ─── Symbol Table Constants ───────────────────────────────────────────────

pub const STN_UNDEF: u16 = 0;

// Symbol bindings
pub const STB_LOCAL: u8 = 0;
pub const STB_GLOBAL: u8 = 1;
pub const STB_WEAK: u8 = 2;
pub const STB_GNU_UNIQUE: u8 = 10;
pub const STB_LOOS: u8 = 10;
pub const STB_HIOS: u8 = 12;
pub const STB_LOPROC: u8 = 13;
pub const STB_HIPROC: u8 = 15;

// Symbol types
pub const STT_NOTYPE: u8 = 0;
pub const STT_OBJECT: u8 = 1;
pub const STT_FUNC: u8 = 2;
pub const STT_SECTION: u8 = 3;
pub const STT_FILE: u8 = 4;
pub const STT_COMMON: u8 = 5;
pub const STT_TLS: u8 = 6;
pub const STT_GNU_IFUNC: u8 = 10;
pub const STT_LOOS: u8 = 10;
pub const STT_HIOS: u8 = 12;
pub const STT_LOPROC: u8 = 13;
pub const STT_HIPROC: u8 = 15;

// Symbol visibilities
pub const STV_DEFAULT: u8 = 0;
pub const STV_INTERNAL: u8 = 1;
pub const STV_HIDDEN: u8 = 2;
pub const STV_PROTECTED: u8 = 3;

// Special section indices
pub const SHN_UNDEF: u16 = 0;
pub const SHN_ABS: u16 = 0xfff1;
pub const SHN_COMMON: u16 = 0xfff2;
pub const SHN_XINDEX: u16 = 0xffff;

// ─── Relocation Type Constants — x86_64 ───────────────────────────────────

pub const R_X86_64_NONE: u32 = 0;
pub const R_X86_64_64: u32 = 1;
pub const R_X86_64_PC32: u32 = 2;
pub const R_X86_64_GOT32: u32 = 3;
pub const R_X86_64_PLT32: u32 = 4;
pub const R_X86_64_COPY: u32 = 5;
pub const R_X86_64_GLOB_DAT: u32 = 6;
pub const R_X86_64_JUMP_SLOT: u32 = 7;
pub const R_X86_64_RELATIVE: u32 = 8;
pub const R_X86_64_GOTPCREL: u32 = 9;
pub const R_X86_64_32: u32 = 10;
pub const R_X86_64_32S: u32 = 11;
pub const R_X86_64_16: u32 = 12;
pub const R_X86_64_PC16: u32 = 13;
pub const R_X86_64_8: u32 = 14;
pub const R_X86_64_PC8: u32 = 15;
pub const R_X86_64_DTPMOD64: u32 = 16;
pub const R_X86_64_DTPOFF64: u32 = 17;
pub const R_X86_64_TPOFF64: u32 = 18;
pub const R_X86_64_TLSGD: u32 = 19;
pub const R_X86_64_TLSLD: u32 = 20;
pub const R_X86_64_DTPOFF32: u32 = 21;
pub const R_X86_64_GOTTPOFF: u32 = 22;
pub const R_X86_64_TPOFF32: u32 = 23;
pub const R_X86_64_PC64: u32 = 24;
pub const R_X86_64_GOTOFF64: u32 = 25;
pub const R_X86_64_GOTPC32: u32 = 26;
pub const R_X86_64_GOT64: u32 = 27;
pub const R_X86_64_GOTPCREL64: u32 = 28;
pub const R_X86_64_GOTPC64: u32 = 29;
pub const R_X86_64_GOTPLT64: u32 = 30;
pub const R_X86_64_PLTOFF64: u32 = 31;
pub const R_X86_64_SIZE32: u32 = 32;
pub const R_X86_64_SIZE64: u32 = 33;
pub const R_X86_64_GOTPC32_TLSDESC: u32 = 34;
pub const R_X86_64_TLSDESC_CALL: u32 = 35;
pub const R_X86_64_TLSDESC: u32 = 36;
pub const R_X86_64_IRELATIVE: u32 = 37;
pub const R_X86_64_RELATIVE64: u32 = 38;
pub const R_X86_64_PC32_BND: u32 = 39;
pub const R_X86_64_PLT32_BND: u32 = 40;
pub const R_X86_64_GOTPCRELX: u32 = 41;
pub const R_X86_64_REX_GOTPCRELX: u32 = 42;

/// Map of x86_64 relocation type to descriptive name.
pub fn x86_64_reloc_name(r_type: u32) -> &'static str {
    match r_type {
        R_X86_64_NONE => "R_X86_64_NONE",
        R_X86_64_64 => "R_X86_64_64",
        R_X86_64_PC32 => "R_X86_64_PC32",
        R_X86_64_GOT32 => "R_X86_64_GOT32",
        R_X86_64_PLT32 => "R_X86_64_PLT32",
        R_X86_64_COPY => "R_X86_64_COPY",
        R_X86_64_GLOB_DAT => "R_X86_64_GLOB_DAT",
        R_X86_64_JUMP_SLOT => "R_X86_64_JUMP_SLOT",
        R_X86_64_RELATIVE => "R_X86_64_RELATIVE",
        R_X86_64_GOTPCREL => "R_X86_64_GOTPCREL",
        R_X86_64_32 => "R_X86_64_32",
        R_X86_64_32S => "R_X86_64_32S",
        R_X86_64_16 => "R_X86_64_16",
        R_X86_64_PC16 => "R_X86_64_PC16",
        R_X86_64_8 => "R_X86_64_8",
        R_X86_64_PC8 => "R_X86_64_PC8",
        R_X86_64_DTPMOD64 => "R_X86_64_DTPMOD64",
        R_X86_64_DTPOFF64 => "R_X86_64_DTPOFF64",
        R_X86_64_TPOFF64 => "R_X86_64_TPOFF64",
        R_X86_64_TLSGD => "R_X86_64_TLSGD",
        R_X86_64_TLSLD => "R_X86_64_TLSLD",
        R_X86_64_DTPOFF32 => "R_X86_64_DTPOFF32",
        R_X86_64_GOTTPOFF => "R_X86_64_GOTTPOFF",
        R_X86_64_TPOFF32 => "R_X86_64_TPOFF32",
        R_X86_64_PC64 => "R_X86_64_PC64",
        R_X86_64_GOTOFF64 => "R_X86_64_GOTOFF64",
        R_X86_64_GOTPC32 => "R_X86_64_GOTPC32",
        R_X86_64_GOT64 => "R_X86_64_GOT64",
        R_X86_64_GOTPCREL64 => "R_X86_64_GOTPCREL64",
        R_X86_64_GOTPC64 => "R_X86_64_GOTPC64",
        R_X86_64_GOTPLT64 => "R_X86_64_GOTPLT64",
        R_X86_64_PLTOFF64 => "R_X86_64_PLTOFF64",
        R_X86_64_SIZE32 => "R_X86_64_SIZE32",
        R_X86_64_SIZE64 => "R_X86_64_SIZE64",
        R_X86_64_GOTPC32_TLSDESC => "R_X86_64_GOTPC32_TLSDESC",
        R_X86_64_TLSDESC_CALL => "R_X86_64_TLSDESC_CALL",
        R_X86_64_TLSDESC => "R_X86_64_TLSDESC",
        R_X86_64_IRELATIVE => "R_X86_64_IRELATIVE",
        R_X86_64_RELATIVE64 => "R_X86_64_RELATIVE64",
        R_X86_64_PC32_BND => "R_X86_64_PC32_BND",
        R_X86_64_PLT32_BND => "R_X86_64_PLT32_BND",
        R_X86_64_GOTPCRELX => "R_X86_64_GOTPCRELX",
        R_X86_64_REX_GOTPCRELX => "R_X86_64_REX_GOTPCRELX",
        _ => "R_X86_64_UNKNOWN",
    }
}

// ─── Relocation Type Constants — i386 ─────────────────────────────────────

pub const R_386_NONE: u32 = 0;
pub const R_386_32: u32 = 1;
pub const R_386_PC32: u32 = 2;
pub const R_386_GOT32: u32 = 3;
pub const R_386_PLT32: u32 = 4;
pub const R_386_COPY: u32 = 5;
pub const R_386_GLOB_DAT: u32 = 6;
pub const R_386_JUMP_SLOT: u32 = 7;
pub const R_386_RELATIVE: u32 = 8;
pub const R_386_GOTOFF: u32 = 9;
pub const R_386_GOTPC: u32 = 10;
pub const R_386_32PLT: u32 = 11;
pub const R_386_TLS_TPOFF: u32 = 14;
pub const R_386_TLS_IE: u32 = 15;
pub const R_386_TLS_GOTIE: u32 = 16;
pub const R_386_TLS_LE: u32 = 17;
pub const R_386_TLS_GD: u32 = 18;
pub const R_386_TLS_LDM: u32 = 19;
pub const R_386_16: u32 = 20;
pub const R_386_PC16: u32 = 21;
pub const R_386_8: u32 = 22;
pub const R_386_PC8: u32 = 23;
pub const R_386_TLS_GD_32: u32 = 24;
pub const R_386_TLS_GD_PUSH: u32 = 25;
pub const R_386_TLS_GD_CALL: u32 = 26;
pub const R_386_TLS_GD_POP: u32 = 27;
pub const R_386_TLS_LDM_32: u32 = 28;
pub const R_386_TLS_LDM_PUSH: u32 = 29;
pub const R_386_TLS_LDM_CALL: u32 = 30;
pub const R_386_TLS_LDM_POP: u32 = 31;
pub const R_386_TLS_LDO_32: u32 = 32;
pub const R_386_TLS_IE_32: u32 = 33;
pub const R_386_TLS_LE_32: u32 = 34;
pub const R_386_TLS_DTPMOD32: u32 = 35;
pub const R_386_TLS_DTPOFF32: u32 = 36;
pub const R_386_TLS_TPOFF32: u32 = 37;
pub const R_386_SIZE32: u32 = 38;
pub const R_386_TLS_GOTDESC: u32 = 39;
pub const R_386_TLS_DESC_CALL: u32 = 40;
pub const R_386_TLS_DESC: u32 = 41;
pub const R_386_IRELATIVE: u32 = 42;
pub const R_386_GOT32X: u32 = 43;

/// Map of i386 relocation type to descriptive name.
pub fn i386_reloc_name(r_type: u32) -> &'static str {
    match r_type {
        R_386_NONE => "R_386_NONE",
        R_386_32 => "R_386_32",
        R_386_PC32 => "R_386_PC32",
        R_386_GOT32 => "R_386_GOT32",
        R_386_PLT32 => "R_386_PLT32",
        R_386_COPY => "R_386_COPY",
        R_386_GLOB_DAT => "R_386_GLOB_DAT",
        R_386_JUMP_SLOT => "R_386_JUMP_SLOT",
        R_386_RELATIVE => "R_386_RELATIVE",
        R_386_GOTOFF => "R_386_GOTOFF",
        R_386_GOTPC => "R_386_GOTPC",
        R_386_32PLT => "R_386_32PLT",
        R_386_TLS_TPOFF => "R_386_TLS_TPOFF",
        R_386_TLS_IE => "R_386_TLS_IE",
        R_386_TLS_GOTIE => "R_386_TLS_GOTIE",
        R_386_TLS_LE => "R_386_TLS_LE",
        R_386_TLS_GD => "R_386_TLS_GD",
        R_386_TLS_LDM => "R_386_TLS_LDM",
        R_386_16 => "R_386_16",
        R_386_PC16 => "R_386_PC16",
        R_386_8 => "R_386_8",
        R_386_PC8 => "R_386_PC8",
        R_386_TLS_GD_32 => "R_386_TLS_GD_32",
        R_386_TLS_GD_PUSH => "R_386_TLS_GD_PUSH",
        R_386_TLS_GD_CALL => "R_386_TLS_GD_CALL",
        R_386_TLS_GD_POP => "R_386_TLS_GD_POP",
        R_386_TLS_LDM_32 => "R_386_TLS_LDM_32",
        R_386_TLS_LDM_PUSH => "R_386_TLS_LDM_PUSH",
        R_386_TLS_LDM_CALL => "R_386_TLS_LDM_CALL",
        R_386_TLS_LDM_POP => "R_386_TLS_LDM_POP",
        R_386_TLS_LDO_32 => "R_386_TLS_LDO_32",
        R_386_TLS_IE_32 => "R_386_TLS_IE_32",
        R_386_TLS_LE_32 => "R_386_TLS_LE_32",
        R_386_TLS_DTPMOD32 => "R_386_TLS_DTPMOD32",
        R_386_TLS_DTPOFF32 => "R_386_TLS_DTPOFF32",
        R_386_TLS_TPOFF32 => "R_386_TLS_TPOFF32",
        R_386_SIZE32 => "R_386_SIZE32",
        R_386_TLS_GOTDESC => "R_386_TLS_GOTDESC",
        R_386_TLS_DESC_CALL => "R_386_TLS_DESC_CALL",
        R_386_TLS_DESC => "R_386_TLS_DESC",
        R_386_IRELATIVE => "R_386_IRELATIVE",
        R_386_GOT32X => "R_386_GOT32X",
        _ => "R_386_UNKNOWN",
    }
}

// ─── Dynamic Entry Tags ───────────────────────────────────────────────────

pub const DT_NULL: u64 = 0;
pub const DT_NEEDED: u64 = 1;
pub const DT_PLTRELSZ: u64 = 2;
pub const DT_PLTGOT: u64 = 3;
pub const DT_HASH: u64 = 4;
pub const DT_STRTAB: u64 = 5;
pub const DT_SYMTAB: u64 = 6;
pub const DT_RELA: u64 = 7;
pub const DT_RELASZ: u64 = 8;
pub const DT_RELAENT: u64 = 9;
pub const DT_STRSZ: u64 = 10;
pub const DT_SYMENT: u64 = 11;
pub const DT_INIT: u64 = 12;
pub const DT_FINI: u64 = 13;
pub const DT_SONAME: u64 = 14;
pub const DT_RPATH: u64 = 15;
pub const DT_SYMBOLIC: u64 = 16;
pub const DT_REL: u64 = 17;
pub const DT_RELSZ: u64 = 18;
pub const DT_RELENT: u64 = 19;
pub const DT_PLTREL: u64 = 20;
pub const DT_DEBUG: u64 = 21;
pub const DT_TEXTREL: u64 = 22;
pub const DT_JMPREL: u64 = 23;
pub const DT_BIND_NOW: u64 = 24;
pub const DT_INIT_ARRAY: u64 = 25;
pub const DT_FINI_ARRAY: u64 = 26;
pub const DT_INIT_ARRAYSZ: u64 = 27;
pub const DT_FINI_ARRAYSZ: u64 = 28;
pub const DT_RUNPATH: u64 = 29;
pub const DT_FLAGS: u64 = 30;
pub const DT_ENCODING: u64 = 32;
pub const DT_PREINIT_ARRAY: u64 = 32;
pub const DT_PREINIT_ARRAYSZ: u64 = 33;
pub const DT_SYMTAB_SHNDX: u64 = 34;
pub const DT_GNU_HASH: u64 = 0x6ffffef5;
pub const DT_TLSDESC_PLT: u64 = 0x6ffffef6;
pub const DT_TLSDESC_GOT: u64 = 0x6ffffef7;
pub const DT_GNU_CONFLICT: u64 = 0x6ffffef8;
pub const DT_GNU_LIBLIST: u64 = 0x6ffffef9;
pub const DT_CONFIG: u64 = 0x6ffffefa;
pub const DT_DEPAUDIT: u64 = 0x6ffffefb;
pub const DT_AUDIT: u64 = 0x6ffffefc;
pub const DT_PLTPAD: u64 = 0x6ffffefd;
pub const DT_MOVETAB: u64 = 0x6ffffefe;
pub const DT_SYMINFO: u64 = 0x6ffffeff;
pub const DT_RELACOUNT: u64 = 0x6ffffff9;
pub const DT_RELCOUNT: u64 = 0x6ffffffa;
pub const DT_FLAGS_1: u64 = 0x6ffffffb;
pub const DT_VERDEF: u64 = 0x6ffffffc;
pub const DT_VERDEFNUM: u64 = 0x6ffffffd;
pub const DT_VERNEED: u64 = 0x6ffffffe;
pub const DT_VERNEEDNUM: u64 = 0x6fffffff;
pub const DT_VERSYM: u64 = 0x6ffffff0;

/// All dynamic tags as a constant slice for iterating.
pub const ALL_DYNAMIC_TAGS: &[(u64, &str)] = &[
    (DT_NULL, "DT_NULL"),
    (DT_NEEDED, "DT_NEEDED"),
    (DT_PLTRELSZ, "DT_PLTRELSZ"),
    (DT_PLTGOT, "DT_PLTGOT"),
    (DT_HASH, "DT_HASH"),
    (DT_STRTAB, "DT_STRTAB"),
    (DT_SYMTAB, "DT_SYMTAB"),
    (DT_RELA, "DT_RELA"),
    (DT_RELASZ, "DT_RELASZ"),
    (DT_RELAENT, "DT_RELAENT"),
    (DT_STRSZ, "DT_STRSZ"),
    (DT_SYMENT, "DT_SYMENT"),
    (DT_INIT, "DT_INIT"),
    (DT_FINI, "DT_FINI"),
    (DT_SONAME, "DT_SONAME"),
    (DT_RPATH, "DT_RPATH"),
    (DT_SYMBOLIC, "DT_SYMBOLIC"),
    (DT_REL, "DT_REL"),
    (DT_RELSZ, "DT_RELSZ"),
    (DT_RELENT, "DT_RELENT"),
    (DT_PLTREL, "DT_PLTREL"),
    (DT_DEBUG, "DT_DEBUG"),
    (DT_TEXTREL, "DT_TEXTREL"),
    (DT_JMPREL, "DT_JMPREL"),
    (DT_BIND_NOW, "DT_BIND_NOW"),
    (DT_INIT_ARRAY, "DT_INIT_ARRAY"),
    (DT_FINI_ARRAY, "DT_FINI_ARRAY"),
    (DT_INIT_ARRAYSZ, "DT_INIT_ARRAYSZ"),
    (DT_FINI_ARRAYSZ, "DT_FINI_ARRAYSZ"),
    (DT_RUNPATH, "DT_RUNPATH"),
    (DT_FLAGS, "DT_FLAGS"),
    (DT_ENCODING, "DT_ENCODING"),
    (DT_PREINIT_ARRAY, "DT_PREINIT_ARRAY"),
    (DT_PREINIT_ARRAYSZ, "DT_PREINIT_ARRAYSZ"),
    (DT_SYMTAB_SHNDX, "DT_SYMTAB_SHNDX"),
    (DT_GNU_HASH, "DT_GNU_HASH"),
    (DT_TLSDESC_PLT, "DT_TLSDESC_PLT"),
    (DT_TLSDESC_GOT, "DT_TLSDESC_GOT"),
    (DT_GNU_CONFLICT, "DT_GNU_CONFLICT"),
    (DT_GNU_LIBLIST, "DT_GNU_LIBLIST"),
    (DT_CONFIG, "DT_CONFIG"),
    (DT_DEPAUDIT, "DT_DEPAUDIT"),
    (DT_AUDIT, "DT_AUDIT"),
    (DT_PLTPAD, "DT_PLTPAD"),
    (DT_MOVETAB, "DT_MOVETAB"),
    (DT_SYMINFO, "DT_SYMINFO"),
    (DT_RELACOUNT, "DT_RELACOUNT"),
    (DT_RELCOUNT, "DT_RELCOUNT"),
    (DT_FLAGS_1, "DT_FLAGS_1"),
    (DT_VERDEF, "DT_VERDEF"),
    (DT_VERDEFNUM, "DT_VERDEFNUM"),
    (DT_VERNEED, "DT_VERNEED"),
    (DT_VERNEEDNUM, "DT_VERNEEDNUM"),
    (DT_VERSYM, "DT_VERSYM"),
];

// ─── DF Flags ─────────────────────────────────────────────────────────────

pub const DF_ORIGIN: u64 = 0x1;
pub const DF_SYMBOLIC: u64 = 0x2;
pub const DF_TEXTREL: u64 = 0x4;
pub const DF_BIND_NOW: u64 = 0x8;
pub const DF_STATIC_TLS: u64 = 0x10;
pub const DF_1_NOW: u64 = 0x1;
pub const DF_1_GLOBAL: u64 = 0x2;
pub const DF_1_NODELETE: u64 = 0x8;
pub const DF_1_INITFIRST: u64 = 0x20;
pub const DF_1_NOOPEN: u64 = 0x40;
pub const DF_1_ORIGIN: u64 = 0x80;
pub const DF_1_INTERPOSE: u64 = 0x400;
pub const DF_1_NODEFLIB: u64 = 0x800;
pub const DF_1_NODUMP: u64 = 0x1000;
pub const DF_1_CONFALT: u64 = 0x2000;
pub const DF_1_PIE: u64 = 0x8000000;

// ─── Note Section Types ───────────────────────────────────────────────────

pub const NT_GNU_BUILD_ID: u32 = 3;
pub const NT_GNU_GOLD_VERSION: u32 = 4;
pub const NT_GNU_PROPERTY_TYPE_0: u32 = 5;
pub const NT_GNU_ABI_TAG: u32 = 1;

pub const ELF_NOTE_GNU: &str = "GNU";
pub const ELF_NOTE_LINUX: &str = "Linux";

// ─── Compression ──────────────────────────────────────────────────────────

pub const ELFCOMPRESS_ZLIB: u32 = 1;
pub const ELFCOMPRESS_ZSTD: u32 = 2;
pub const ELFCOMPRESS_LOOS: u32 = 0x60000000;
pub const ELFCOMPRESS_HIOS: u32 = 0x6fffffff;

// ─── The ch_type field for compression headers in section data. ───────────

pub const CH_TYPE_ZLIB: u32 = 1;
pub const CH_TYPE_ZSTD: u32 = 2;

// ─── Data Structures ──────────────────────────────────────────────────────

/// An ELF identification header (e_ident).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ElfIdent {
    pub magic: [u8; 4],
    pub class: u8,
    pub data: u8,
    pub version: u8,
    pub osabi: u8,
    pub abiversion: u8,
    pub padding: [u8; 7],
}

impl Default for ElfIdent {
    fn default() -> Self {
        let mut ident = ElfIdent {
            magic: ELF_MAGIC_BYTES,
            class: ELFCLASS64,
            data: ELFDATA2LSB,
            version: EV_CURRENT as u8,
            osabi: ELFOSABI_NONE,
            abiversion: 0,
            padding: [0; 7],
        };
        ident
    }
}

impl ElfIdent {
    /// Create a new ELF ident for 64-bit x86.
    pub fn new_x86_64() -> Self {
        ElfIdent {
            magic: ELF_MAGIC_BYTES,
            class: ELFCLASS64,
            data: ELFDATA2LSB,
            version: 1,
            osabi: ELFOSABI_SYSV,
            abiversion: 0,
            padding: [0; 7],
        }
    }

    /// Create a new ELF ident for 32-bit x86.
    pub fn new_x86_32() -> Self {
        ElfIdent {
            magic: ELF_MAGIC_BYTES,
            class: ELFCLASS32,
            data: ELFDATA2LSB,
            version: 1,
            osabi: ELFOSABI_SYSV,
            abiversion: 0,
            padding: [0; 7],
        }
    }

    /// Check if this ident represents a 64-bit ELF file.
    pub fn is_64bit(&self) -> bool {
        self.class == ELFCLASS64
    }

    /// Check if this ident represents a 32-bit ELF file.
    pub fn is_32bit(&self) -> bool {
        self.class == ELFCLASS32
    }

    /// Check if the magic bytes are valid.
    pub fn is_valid_magic(&self) -> bool {
        self.magic == ELF_MAGIC_BYTES
    }

    /// Serialize the ident to a 16-byte buffer.
    pub fn to_bytes(&self) -> [u8; 16] {
        let mut buf = [0u8; 16];
        buf[EI_MAG0..EI_MAG0 + 4].copy_from_slice(&self.magic);
        buf[EI_CLASS] = self.class;
        buf[EI_DATA] = self.data;
        buf[EI_VERSION] = self.version;
        buf[EI_OSABI] = self.osabi;
        buf[EI_ABIVERSION] = self.abiversion;
        buf[EI_PAD..].copy_from_slice(&self.padding);
        buf
    }

    /// Deserialize an ElfIdent from a 16-byte buffer.
    pub fn from_bytes(bytes: &[u8; 16]) -> Self {
        let mut magic = [0u8; 4];
        magic.copy_from_slice(&bytes[0..4]);
        let mut padding = [0u8; 7];
        padding.copy_from_slice(&bytes[9..16]);
        ElfIdent {
            magic,
            class: bytes[EI_CLASS],
            data: bytes[EI_DATA],
            version: bytes[EI_VERSION],
            osabi: bytes[EI_OSABI],
            abiversion: bytes[EI_ABIVERSION],
            padding,
        }
    }
}

/// A parsed ELF header (Ehdr).
#[derive(Debug, Clone)]
pub struct X86ElfHeader {
    pub ident: ElfIdent,
    pub e_type: u16,
    pub e_machine: u16,
    pub e_version: u32,
    pub e_entry: u64,
    pub e_phoff: u64,
    pub e_shoff: u64,
    pub e_flags: u32,
    pub e_ehsize: u16,
    pub e_phentsize: u16,
    pub e_phnum: u16,
    pub e_shentsize: u16,
    pub e_shnum: u16,
    pub e_shstrndx: u16,
}

impl Default for X86ElfHeader {
    fn default() -> Self {
        X86ElfHeader {
            ident: ElfIdent::new_x86_64(),
            e_type: ET_REL,
            e_machine: EM_X86_64,
            e_version: 1,
            e_entry: 0,
            e_phoff: 0,
            e_shoff: 0,
            e_flags: 0,
            e_ehsize: 64,
            e_phentsize: 56,
            e_phnum: 0,
            e_shentsize: 64,
            e_shnum: 0,
            e_shstrndx: 0,
        }
    }
}

impl X86ElfHeader {
    /// Create a new ELF header for an x86_64 object file.
    pub fn new_x86_64() -> Self {
        X86ElfHeader {
            ident: ElfIdent::new_x86_64(),
            e_type: ET_REL,
            e_machine: EM_X86_64,
            e_version: 1,
            e_entry: 0,
            e_phoff: 0,
            e_shoff: 0,
            e_flags: 0,
            e_ehsize: 64,
            e_phentsize: 56,
            e_phnum: 0,
            e_shentsize: 64,
            e_shnum: 0,
            e_shstrndx: 0,
        }
    }

    /// Create a new ELF header for an i386 object file.
    pub fn new_x86_32() -> Self {
        X86ElfHeader {
            ident: ElfIdent::new_x86_32(),
            e_type: ET_REL,
            e_machine: EM_386,
            e_version: 1,
            e_entry: 0,
            e_phoff: 0,
            e_shoff: 0,
            e_flags: 0,
            e_ehsize: 52,
            e_phentsize: 32,
            e_phnum: 0,
            e_shentsize: 40,
            e_shnum: 0,
            e_shstrndx: 0,
        }
    }

    /// Check if this is a 64-bit ELF file.
    pub fn is_64bit(&self) -> bool {
        self.ident.is_64bit()
    }

    /// Check if this is a shared object (.so).
    pub fn is_shared_object(&self) -> bool {
        self.e_type == ET_DYN
    }

    /// Check if this is an executable.
    pub fn is_executable(&self) -> bool {
        self.e_type == ET_EXEC
    }

    /// Check if this is a relocatable (.o).
    pub fn is_relocatable(&self) -> bool {
        self.e_type == ET_REL
    }
}

/// A program header entry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct X86ProgramHeader {
    pub p_type: u32,
    pub p_flags: u32,
    pub p_offset: u64,
    pub p_vaddr: u64,
    pub p_paddr: u64,
    pub p_filesz: u64,
    pub p_memsz: u64,
    pub p_align: u64,
}

impl X86ProgramHeader {
    pub fn new_load(vaddr: u64, offset: u64, filesz: u64, memsz: u64, flags: u32) -> Self {
        X86ProgramHeader {
            p_type: PT_LOAD,
            p_flags: flags,
            p_offset: offset,
            p_vaddr: vaddr,
            p_paddr: vaddr,
            p_filesz: filesz,
            p_memsz: memsz,
            p_align: 0x1000,
        }
    }

    pub fn new_dynamic(offset: u64, size: u64) -> Self {
        X86ProgramHeader {
            p_type: PT_DYNAMIC,
            p_flags: PF_R | PF_W,
            p_offset: offset,
            p_vaddr: 0,
            p_paddr: 0,
            p_filesz: size,
            p_memsz: size,
            p_align: 8,
        }
    }

    pub fn new_interp(offset: u64, size: u64) -> Self {
        X86ProgramHeader {
            p_type: PT_INTERP,
            p_flags: PF_R,
            p_offset: offset,
            p_vaddr: 0,
            p_paddr: 0,
            p_filesz: size,
            p_memsz: size,
            p_align: 1,
        }
    }

    pub fn new_note(offset: u64, size: u64) -> Self {
        X86ProgramHeader {
            p_type: PT_NOTE,
            p_flags: PF_R,
            p_offset: offset,
            p_vaddr: 0,
            p_paddr: 0,
            p_filesz: size,
            p_memsz: size,
            p_align: 4,
        }
    }

    pub fn new_tls(vaddr: u64, offset: u64, filesz: u64, memsz: u64) -> Self {
        X86ProgramHeader {
            p_type: PT_TLS,
            p_flags: PF_R,
            p_offset: offset,
            p_vaddr: vaddr,
            p_paddr: vaddr,
            p_filesz: filesz,
            p_memsz: memsz,
            p_align: 1,
        }
    }

    pub fn new_gnu_stack(flags: u32, size: u64) -> Self {
        X86ProgramHeader {
            p_type: PT_GNU_STACK,
            p_flags: flags,
            p_offset: 0,
            p_vaddr: 0,
            p_paddr: 0,
            p_filesz: 0,
            p_memsz: size,
            p_align: 0,
        }
    }

    pub fn new_gnu_relro(offset: u64, size: u64) -> Self {
        X86ProgramHeader {
            p_type: PT_GNU_RELRO,
            p_flags: PF_R,
            p_offset: offset,
            p_vaddr: 0,
            p_paddr: 0,
            p_filesz: size,
            p_memsz: size,
            p_align: 1,
        }
    }

    pub fn new_gnu_eh_frame(offset: u64, size: u64) -> Self {
        X86ProgramHeader {
            p_type: PT_GNU_EH_FRAME,
            p_flags: PF_R,
            p_offset: offset,
            p_vaddr: 0,
            p_paddr: 0,
            p_filesz: size,
            p_memsz: size,
            p_align: 4,
        }
    }

    pub fn new_gnu_property(offset: u64, size: u64) -> Self {
        X86ProgramHeader {
            p_type: PT_GNU_PROPERTY,
            p_flags: PF_R,
            p_offset: offset,
            p_vaddr: 0,
            p_paddr: 0,
            p_filesz: size,
            p_memsz: size,
            p_align: 8,
        }
    }

    pub fn type_name(&self) -> &'static str {
        match self.p_type {
            PT_NULL => "PT_NULL",
            PT_LOAD => "PT_LOAD",
            PT_DYNAMIC => "PT_DYNAMIC",
            PT_INTERP => "PT_INTERP",
            PT_NOTE => "PT_NOTE",
            PT_SHLIB => "PT_SHLIB",
            PT_PHDR => "PT_PHDR",
            PT_TLS => "PT_TLS",
            PT_GNU_EH_FRAME => "PT_GNU_EH_FRAME",
            PT_GNU_STACK => "PT_GNU_STACK",
            PT_GNU_RELRO => "PT_GNU_RELRO",
            PT_GNU_PROPERTY => "PT_GNU_PROPERTY",
            _ => {
                if self.p_type >= PT_LOOS && self.p_type <= PT_HIOS {
                    "PT_LOOS+"
                } else if self.p_type >= PT_LOPROC && self.p_type <= PT_HIPROC {
                    "PT_LOPROC+"
                } else {
                    "PT_UNKNOWN"
                }
            }
        }
    }

    pub fn flags_string(&self) -> String {
        let mut s = String::new();
        if self.p_flags & PF_R != 0 {
            s.push('R');
        }
        if self.p_flags & PF_W != 0 {
            s.push('W');
        }
        if self.p_flags & PF_X != 0 {
            s.push('X');
        }
        if s.is_empty() {
            s.push_str("---");
        }
        s
    }
}

/// A section header entry.
#[derive(Debug, Clone)]
pub struct X86SectionHeader {
    pub sh_name: u32,
    pub sh_type: u32,
    pub sh_flags: u64,
    pub sh_addr: u64,
    pub sh_offset: u64,
    pub sh_size: u64,
    pub sh_link: u32,
    pub sh_info: u32,
    pub sh_addralign: u64,
    pub sh_entsize: u64,
    /// Resolved section name (from string table)
    pub name: String,
}

impl X86SectionHeader {
    pub fn new(name: &str, sh_type: u32, sh_flags: u64, sh_offset: u64, sh_size: u64) -> Self {
        X86SectionHeader {
            sh_name: 0,
            sh_type,
            sh_flags,
            sh_addr: 0,
            sh_offset,
            sh_size,
            sh_link: 0,
            sh_info: 0,
            sh_addralign: 1,
            sh_entsize: 0,
            name: name.to_string(),
        }
    }

    pub fn type_name(&self) -> &'static str {
        match self.sh_type {
            SHT_NULL => "NULL",
            SHT_PROGBITS => "PROGBITS",
            SHT_SYMTAB => "SYMTAB",
            SHT_STRTAB => "STRTAB",
            SHT_RELA => "RELA",
            SHT_HASH => "HASH",
            SHT_DYNAMIC => "DYNAMIC",
            SHT_NOTE => "NOTE",
            SHT_NOBITS => "NOBITS",
            SHT_REL => "REL",
            SHT_SHLIB => "SHLIB",
            SHT_DYNSYM => "DYNSYM",
            SHT_INIT_ARRAY => "INIT_ARRAY",
            SHT_FINI_ARRAY => "FINI_ARRAY",
            SHT_PREINIT_ARRAY => "PREINIT_ARRAY",
            SHT_GROUP => "GROUP",
            SHT_SYMTAB_SHNDX => "SYMTAB_SHNDX",
            SHT_GNU_ATTRIBUTES => "GNU_ATTRIBUTES",
            SHT_GNU_HASH => "GNU_HASH",
            SHT_GNU_LIBLIST => "GNU_LIBLIST",
            SHT_GNU_VERDEF => "GNU_VERDEF",
            SHT_GNU_VERNEED => "GNU_VERNEED",
            SHT_GNU_VERSYM => "GNU_VERSYM",
            _ => "UNKNOWN",
        }
    }

    pub fn flags_string(&self) -> String {
        let mut flags = String::new();
        if self.sh_flags & SHF_WRITE != 0 {
            flags.push('W');
        }
        if self.sh_flags & SHF_ALLOC != 0 {
            flags.push('A');
        }
        if self.sh_flags & SHF_EXECINSTR != 0 {
            flags.push('X');
        }
        if self.sh_flags & SHF_MERGE != 0 {
            flags.push('M');
        }
        if self.sh_flags & SHF_STRINGS != 0 {
            flags.push('S');
        }
        if self.sh_flags & SHF_GROUP != 0 {
            flags.push('G');
        }
        if self.sh_flags & SHF_TLS != 0 {
            flags.push('T');
        }
        if self.sh_flags & SHF_COMPRESSED != 0 {
            flags.push('C');
        }
        if self.sh_flags & SHF_EXCLUDE != 0 {
            flags.push('E');
        }
        if flags.is_empty() {
            flags.push_str("-");
        }
        flags
    }
}

/// A symbol table entry.
#[derive(Debug, Clone)]
pub struct X86Symbol {
    pub st_name: u32,
    pub st_info: u8,
    pub st_other: u8,
    pub st_shndx: u16,
    pub st_value: u64,
    pub st_size: u64,
    /// Resolved symbol name (from string table)
    pub name: String,
}

impl X86Symbol {
    pub fn new(name: &str, st_info: u8, st_shndx: u16, st_value: u64, st_size: u64) -> Self {
        X86Symbol {
            st_name: 0,
            st_info,
            st_other: 0,
            st_shndx,
            st_value,
            st_size,
            name: name.to_string(),
        }
    }

    pub fn bind(&self) -> u8 {
        self.st_info >> 4
    }

    pub fn st_type(&self) -> u8 {
        self.st_info & 0x0f
    }

    pub fn visibility(&self) -> u8 {
        self.st_other & 0x03
    }

    pub fn bind_name(&self) -> &'static str {
        match self.bind() {
            STB_LOCAL => "LOCAL",
            STB_GLOBAL => "GLOBAL",
            STB_WEAK => "WEAK",
            STB_GNU_UNIQUE => "GNU_UNIQUE",
            _ => "UNKNOWN",
        }
    }

    pub fn type_name(&self) -> &'static str {
        match self.st_type() {
            STT_NOTYPE => "NOTYPE",
            STT_OBJECT => "OBJECT",
            STT_FUNC => "FUNC",
            STT_SECTION => "SECTION",
            STT_FILE => "FILE",
            STT_COMMON => "COMMON",
            STT_TLS => "TLS",
            STT_GNU_IFUNC => "GNU_IFUNC",
            _ => "UNKNOWN",
        }
    }

    pub fn visibility_name(&self) -> &'static str {
        match self.visibility() {
            STV_DEFAULT => "DEFAULT",
            STV_INTERNAL => "INTERNAL",
            STV_HIDDEN => "HIDDEN",
            STV_PROTECTED => "PROTECTED",
            _ => "UNKNOWN",
        }
    }

    pub fn is_defined(&self) -> bool {
        self.st_shndx != SHN_UNDEF
    }
}

/// A relocation entry (with explicit addend).
#[derive(Debug, Clone)]
pub struct X86Relocation {
    pub r_offset: u64,
    pub r_type: u32,
    pub r_sym: u32,
    pub r_addend: i64,
    pub symbol_name: Option<String>,
}

impl X86Relocation {
    pub fn new(offset: u64, r_type: u32, sym: u32, addend: i64) -> Self {
        X86Relocation {
            r_offset: offset,
            r_type,
            r_sym: sym,
            r_addend: addend,
            symbol_name: None,
        }
    }

    pub fn type_name(&self, machine: u16) -> &'static str {
        match machine {
            EM_X86_64 => x86_64_reloc_name(self.r_type),
            EM_386 => i386_reloc_name(self.r_type),
            _ => "UNKNOWN",
        }
    }
}

/// A dynamic entry.
#[derive(Debug, Clone)]
pub struct X86DynamicEntry {
    pub d_tag: u64,
    pub d_val: u64,
}

impl X86DynamicEntry {
    pub fn new(tag: u64, val: u64) -> Self {
        X86DynamicEntry {
            d_tag: tag,
            d_val: val,
        }
    }

    pub fn tag_name(&self) -> &'static str {
        for &(tag, name) in ALL_DYNAMIC_TAGS {
            if tag == self.d_tag {
                return name;
            }
        }
        "UNKNOWN"
    }
}

/// A version definition entry (GNU Verdef).
#[derive(Debug, Clone)]
pub struct X86Verdef {
    pub vd_version: u16,
    pub vd_flags: u16,
    pub vd_ndx: u16,
    pub vd_cnt: u16,
    pub vd_hash: u32,
    pub vd_aux: u32,
    pub vd_next: u32,
    pub version_name: String,
}

impl X86Verdef {
    pub fn new(index: u16, hash: u32, name: &str) -> Self {
        X86Verdef {
            vd_version: 1,
            vd_flags: 0,
            vd_ndx: index,
            vd_cnt: 1,
            vd_hash: hash,
            vd_aux: 20,
            vd_next: 0,
            version_name: name.to_string(),
        }
    }
}

/// A version requirement entry (GNU Verneed).
#[derive(Debug, Clone)]
pub struct X86Verneed {
    pub vn_version: u16,
    pub vn_cnt: u16,
    pub vn_file: u32,
    pub vn_aux: u32,
    pub vn_next: u32,
    pub file_name: String,
    pub needed_versions: Vec<X86Vernaux>,
}

impl X86Verneed {
    pub fn new(file: &str) -> Self {
        X86Verneed {
            vn_version: 1,
            vn_cnt: 0,
            vn_file: 0,
            vn_aux: 16,
            vn_next: 0,
            file_name: file.to_string(),
            needed_versions: Vec::new(),
        }
    }

    pub fn add_needed(&mut self, hash: u32, flags: u16, other: u16, name: &str) {
        self.needed_versions.push(X86Vernaux {
            vna_hash: hash,
            vna_flags: flags,
            vna_other: other,
            vna_name: name.to_string(),
        });
        self.vn_cnt += 1;
    }
}

/// Auxiliary information for a Verneed entry.
#[derive(Debug, Clone)]
pub struct X86Vernaux {
    pub vna_hash: u32,
    pub vna_flags: u16,
    pub vna_other: u16,
    pub vna_name: String,
}

/// A note section descriptor.
#[derive(Debug, Clone)]
pub struct X86Note {
    pub n_type: u32,
    pub n_name: String,
    pub n_desc: Vec<u8>,
}

impl X86Note {
    pub fn new(n_type: u32, name: &str, desc: Vec<u8>) -> Self {
        X86Note {
            n_type,
            n_name: name.to_string(),
            n_desc: desc,
        }
    }

    /// Create a GNU build ID note.
    pub fn new_build_id(build_id: &[u8]) -> Self {
        X86Note::new(NT_GNU_BUILD_ID, ELF_NOTE_GNU, build_id.to_vec())
    }

    /// Create a GNU ABI tag note.
    pub fn new_abi_tag(os: u32, major: u32, minor: u32, patch: u32) -> Self {
        let mut desc = Vec::with_capacity(16);
        desc.extend_from_slice(&os.to_le_bytes());
        desc.extend_from_slice(&major.to_le_bytes());
        desc.extend_from_slice(&minor.to_le_bytes());
        desc.extend_from_slice(&patch.to_le_bytes());
        X86Note::new(NT_GNU_ABI_TAG, ELF_NOTE_GNU, desc)
    }

    /// Create a GNU gold version note.
    pub fn new_gold_version(version: &str) -> Self {
        X86Note::new(NT_GNU_GOLD_VERSION, ELF_NOTE_GNU, version.as_bytes().to_vec())
    }

    pub fn type_name(&self) -> &'static str {
        match self.n_type {
            NT_GNU_BUILD_ID => "NT_GNU_BUILD_ID",
            NT_GNU_GOLD_VERSION => "NT_GNU_GOLD_VERSION",
            NT_GNU_PROPERTY_TYPE_0 => "NT_GNU_PROPERTY_TYPE_0",
            NT_GNU_ABI_TAG => "NT_GNU_ABI_TAG",
            _ => "UNKNOWN",
        }
    }
}

/// A SysV hash table entry (not the bucket/chain, just the descriptor).
#[derive(Debug, Clone)]
pub struct X86HashTable {
    pub nbucket: u32,
    pub nchain: u32,
    pub buckets: Vec<u32>,
    pub chains: Vec<u32>,
}

impl X86HashTable {
    pub fn new(nbucket: u32, nchain: u32) -> Self {
        X86HashTable {
            nbucket,
            nchain,
            buckets: vec![0u32; nbucket as usize],
            chains: vec![0u32; nchain as usize],
        }
    }

    pub fn lookup(&self, name_hash: u32, get_sym_hash: impl Fn(usize) -> Option<u32>) -> Option<usize> {
        let bucket_idx = (name_hash % self.nbucket) as usize;
        if bucket_idx >= self.buckets.len() {
            return None;
        }
        let mut sym_idx = self.buckets[bucket_idx] as usize;
        while sym_idx != 0 && sym_idx < self.chains.len() {
            if let Some(sh) = get_sym_hash(sym_idx) {
                if sh == name_hash {
                    return Some(sym_idx);
                }
            }
            sym_idx = self.chains[sym_idx] as usize;
        }
        None
    }
}

/// A GNU hash table for efficient symbol lookup.
#[derive(Debug, Clone)]
pub struct X86GnuHashTable {
    pub nbuckets: u32,
    pub symoffset: u32,
    pub bloom_size: u32,
    pub bloom_shift: u32,
    pub bloom: Vec<u64>,
    pub buckets: Vec<u32>,
    pub chain: Vec<u32>,
}

impl X86GnuHashTable {
    pub fn new(nbuckets: u32, symoffset: u32, bloom_size: u32, bloom_shift: u32) -> Self {
        X86GnuHashTable {
            nbuckets,
            symoffset,
            bloom_size,
            bloom_shift,
            bloom: vec![0u64; bloom_size as usize],
            buckets: vec![0u32; nbuckets as usize],
            chain: Vec::new(),
        }
    }

    pub fn lookup(&self, name_hash: u32, get_hash: impl Fn(usize) -> Option<u32>) -> Option<usize> {
        if self.bloom_size == 0 {
            return None;
        }
        let bm = name_hash;
        let bit0 = (bm / 64) % self.bloom_size;
        let bit1 = ((bm >> self.bloom_shift) / 64) % self.bloom_size;
        let mask0 = 1u64 << (bm % 64);
        let mask1 = 1u64 << ((bm >> self.bloom_shift) % 64);
        if (self.bloom[bit0 as usize] & mask0) == 0 || (self.bloom[bit1 as usize] & mask1) == 0 {
            return None;
        }
        let bucket_idx = (name_hash % self.nbuckets) as usize;
        if bucket_idx >= self.buckets.len() {
            return None;
        }
        let mut sym_idx = self.buckets[bucket_idx] as usize;
        loop {
            if sym_idx >= self.chain.len() {
                return None;
            }
            let h = self.chain[sym_idx];
            if (h | 1) == (name_hash | 1) {
                if let Some(sh) = get_hash(sym_idx + self.symoffset as usize) {
                    if sh == name_hash {
                        return Some(sym_idx + self.symoffset as usize);
                    }
                }
            }
            if h & 1 != 0 {
                break;
            }
            sym_idx += 1;
        }
        None
    }
}

// ─── COMDAT / Merge Info ──────────────────────────────────────────────────

/// Information about a COMDAT group.
#[derive(Debug, Clone)]
pub struct X86ComdatGroup {
    pub name: String,
    pub signature: u32,
    pub flags: u32,
    pub member_sections: Vec<u32>,
}

impl X86ComdatGroup {
    pub fn new(name: &str, signature: u32) -> Self {
        X86ComdatGroup {
            name: name.to_string(),
            signature,
            flags: 0,
            member_sections: Vec::new(),
        }
    }

    pub fn add_member(&mut self, section_index: u32) {
        self.member_sections.push(section_index);
    }
}

/// A descriptor for compressed section data.
#[derive(Debug, Clone)]
pub struct X86CompressedSection {
    pub ch_type: u32,
    pub ch_size: u64,
    pub ch_addralign: u64,
    pub decompressed_data: Vec<u8>,
}

impl X86CompressedSection {
    pub fn new(ch_type: u32, original_size: u64, alignment: u64, data: Vec<u8>) -> Self {
        X86CompressedSection {
            ch_type,
            ch_size: original_size,
            ch_addralign: alignment,
            decompressed_data: data,
        }
    }

    pub fn is_zlib(&self) -> bool {
        self.ch_type == ELFCOMPRESS_ZLIB
    }

    pub fn is_zstd(&self) -> bool {
        self.ch_type == ELFCOMPRESS_ZSTD
    }
}

// ─── ARM Exception Table Stub ─────────────────────────────────────────────

/// Stub for ARM exception table entries.
/// Present for cross-platform ELF tooling but primarily relevant for ARM targets.
#[derive(Debug, Clone)]
pub struct ArmExidxEntry {
    pub addr: u64,
    pub data: u32,
}

impl ArmExidxEntry {
    pub fn new(addr: u64, data: u32) -> Self {
        ArmExidxEntry { addr, data }
    }
}

// ─── The Main X86ELFDeep Struct ───────────────────────────────────────────

/// Deep ELF utilities for X86 platforms.
///
/// Provides a complete API for parsing and constructing ELF files
/// targeted at x86 and x86_64 architectures.
#[derive(Debug)]
pub struct X86ELFDeep {
    pub header: X86ElfHeader,
    pub program_headers: Vec<X86ProgramHeader>,
    pub section_headers: Vec<X86SectionHeader>,
    pub symbols: Vec<X86Symbol>,
    pub dynamic_symbols: Vec<X86Symbol>,
    pub relocations: Vec<X86Relocation>,
    pub dynamic_entries: Vec<X86DynamicEntry>,
    pub section_data: BTreeMap<String, Vec<u8>>,
    pub string_tables: HashMap<String, Vec<u8>>,
    pub notes: Vec<X86Note>,
    pub verdefs: Vec<X86Verdef>,
    pub verneeds: Vec<X86Verneed>,
    pub hash_table: Option<X86HashTable>,
    pub gnu_hash_table: Option<X86GnuHashTable>,
    pub comdat_groups: Vec<X86ComdatGroup>,
    pub compressed_sections: BTreeMap<String, X86CompressedSection>,
    pub arm_exidx_entries: Vec<ArmExidxEntry>,
    pub shstrtab: Vec<u8>,
    pub strtab: Vec<u8>,
    pub dynstr: Vec<u8>,
    pub file_size: u64,
    pub valid: bool,
    pub errors: Vec<String>,
    pub warnings: Vec<String>,
}

impl X86ELFDeep {
    /// Create a new, empty X86ELFDeep instance for x86_64.
    pub fn new() -> Self {
        X86ELFDeep {
            header: X86ElfHeader::new_x86_64(),
            program_headers: Vec::new(),
            section_headers: Vec::new(),
            symbols: Vec::new(),
            dynamic_symbols: Vec::new(),
            relocations: Vec::new(),
            dynamic_entries: Vec::new(),
            section_data: BTreeMap::new(),
            string_tables: HashMap::new(),
            notes: Vec::new(),
            verdefs: Vec::new(),
            verneeds: Vec::new(),
            hash_table: None,
            gnu_hash_table: None,
            comdat_groups: Vec::new(),
            compressed_sections: BTreeMap::new(),
            arm_exidx_entries: Vec::new(),
            shstrtab: Vec::new(),
            strtab: Vec::new(),
            dynstr: Vec::new(),
            file_size: 0,
            valid: true,
            errors: Vec::new(),
            warnings: Vec::new(),
        }
    }

    /// Create for i386.
    pub fn new_i386() -> Self {
        let mut elf = Self::new();
        elf.header = X86ElfHeader::new_x86_32();
        elf
    }

    /// Validate the entire ELF structure and populate errors/warnings.
    pub fn validate(&mut self) -> bool {
        self.errors.clear();
        self.warnings.clear();
        self.valid = true;

        if !self.header.ident.is_valid_magic() {
            self.errors.push("Invalid ELF magic".to_string());
            self.valid = false;
        }

        if self.header.ident.version != 1 {
            self.warnings.push(format!(
                "Unexpected ELF version {} (expected 1)",
                self.header.ident.version
            ));
        }

        if self.header.e_machine != EM_X86_64 && self.header.e_machine != EM_386 {
            self.warnings.push(format!(
                "Unexpected machine type 0x{:x} for X86 (expected 0x{:x} or 0x{:x})",
                self.header.e_machine, EM_X86_64, EM_386
            ));
        }

        // Validate program headers
        for (i, ph) in self.program_headers.iter().enumerate() {
            if ph.p_type == PT_LOAD {
                if ph.p_filesz > ph.p_memsz {
                    self.errors.push(format!(
                        "Program header {}: p_filesz ({}) > p_memsz ({})",
                        i, ph.p_filesz, ph.p_memsz
                    ));
                    self.valid = false;
                }
                if ph.p_align > 0 && ph.p_vaddr % ph.p_align != ph.p_offset % ph.p_align {
                    self.warnings.push(format!(
                        "Program header {}: vaddr/offset alignment mismatch",
                        i
                    ));
                }
            }
        }

        // Validate section headers
        for (i, sh) in self.section_headers.iter().enumerate() {
            if sh.sh_type == SHT_SYMTAB || sh.sh_type == SHT_DYNSYM {
                if sh.sh_entsize == 0 {
                    self.warnings.push(format!(
                        "Section {} ({}) is a symbol table but sh_entsize is 0",
                        i, sh.name
                    ));
                }
            }
            if sh.sh_type == SHT_RELA || sh.sh_type == SHT_REL {
                if sh.sh_entsize == 0 {
                    self.warnings.push(format!(
                        "Section {} ({}) is a relocation table but sh_entsize is 0",
                        i, sh.name
                    ));
                }
            }
            if sh.sh_flags & SHF_ALLOC != 0 && sh.sh_addr == 0 && sh.sh_type != SHT_NOBITS {
                self.warnings.push(format!(
                    "Section {} ({}) has ALLOC flag but address is 0",
                    i, sh.name
                ));
            }
        }

        // Check for required sections in executables/shared objects
        if self.header.e_type == ET_EXEC || self.header.e_type == ET_DYN {
            let has_interp = self
                .program_headers
                .iter()
                .any(|ph| ph.p_type == PT_INTERP);
            let has_load = self
                .program_headers
                .iter()
                .any(|ph| ph.p_type == PT_LOAD);

            if !has_load {
                self.errors
                    .push("Executable/shared object has no PT_LOAD segment".to_string());
                self.valid = false;
            }
            if self.header.e_type == ET_EXEC && !has_interp {
                self.warnings
                    .push("Executable has no PT_INTERP (no dynamic linker)".to_string());
            }
        }

        // Validate symbol table
        let seen_names: HashSet<&str> = self.symbols.iter().map(|s| s.name.as_str()).collect();
        if seen_names.len() != self.symbols.len() {
            self.warnings
                .push("Duplicate symbol names found in symbol table".to_string());
        }

        // Validate dynamic entries
        let mut seen_tags = HashSet::new();
        for entry in &self.dynamic_entries {
            if !seen_tags.insert(entry.d_tag) && entry.d_tag != DT_NULL {
                self.warnings.push(format!(
                    "Duplicate dynamic tag {} found",
                    entry.tag_name()
                ));
            }
        }

        self.valid
    }

    // ─── ELF Parsing ──────────────────────────────────────────────────────

    /// Parse an ELF file from raw bytes.
    pub fn parse(&mut self, data: &[u8]) -> Result<(), String> {
        if data.len() < 64 {
            return Err("ELF data too short (minimum 64 bytes)".to_string());
        }
        self.file_size = data.len() as u64;

        // Parse ident
        let mut ident_bytes = [0u8; 16];
        if data.len() < 16 {
            return Err("ELF data too short for e_ident".to_string());
        }
        ident_bytes.copy_from_slice(&data[..16]);
        self.header.ident = ElfIdent::from_bytes(&ident_bytes);

        if !self.header.ident.is_valid_magic() {
            return Err("Invalid ELF magic bytes".to_string());
        }

        let is_64bit = self.header.ident.is_64bit();

        // Parse ELF header fields
        if is_64bit {
            self.parse_header_64(data)?;
        } else {
            self.parse_header_32(data)?;
        }

        // Parse program headers
        self.parse_program_headers(data, is_64bit)?;

        // Parse section headers
        self.parse_section_headers(data, is_64bit)?;

        // Parse string tables
        self.parse_string_tables(data)?;

        // Parse symbol tables
        self.parse_symbol_tables(data, is_64bit)?;

        // Parse dynamic entries
        self.parse_dynamic_entries(data, is_64bit)?;

        // Parse relocations
        self.parse_relocations(data, is_64bit)?;

        // Parse notes
        self.parse_notes(data)?;

        // Final validation
        self.validate();

        Ok(())
    }

    fn parse_header_64(&mut self, data: &[u8]) -> Result<(), String> {
        if data.len() < 64 {
            return Err("ELF64 header requires at least 64 bytes".to_string());
        }
        self.header.e_type = u16::from_le_bytes([data[16], data[17]]);
        self.header.e_machine = u16::from_le_bytes([data[18], data[19]]);
        self.header.e_version = u32::from_le_bytes([data[20], data[21], data[22], data[23]]);
        self.header.e_entry = u64::from_le_bytes([
            data[24], data[25], data[26], data[27], data[28], data[29], data[30], data[31],
        ]);
        self.header.e_phoff = u64::from_le_bytes([
            data[32], data[33], data[34], data[35], data[36], data[37], data[38], data[39],
        ]);
        self.header.e_shoff = u64::from_le_bytes([
            data[40], data[41], data[42], data[43], data[44], data[45], data[46], data[47],
        ]);
        self.header.e_flags = u32::from_le_bytes([data[48], data[49], data[50], data[51]]);
        self.header.e_ehsize = u16::from_le_bytes([data[52], data[53]]);
        self.header.e_phentsize = u16::from_le_bytes([data[54], data[55]]);
        self.header.e_phnum = u16::from_le_bytes([data[56], data[57]]);
        self.header.e_shentsize = u16::from_le_bytes([data[58], data[59]]);
        self.header.e_shnum = u16::from_le_bytes([data[60], data[61]]);
        self.header.e_shstrndx = u16::from_le_bytes([data[62], data[63]]);
        Ok(())
    }

    fn parse_header_32(&mut self, data: &[u8]) -> Result<(), String> {
        if data.len() < 52 {
            return Err("ELF32 header requires at least 52 bytes".to_string());
        }
        self.header.e_type = u16::from_le_bytes([data[16], data[17]]);
        self.header.e_machine = u16::from_le_bytes([data[18], data[19]]);
        self.header.e_version = u32::from_le_bytes([data[20], data[21], data[22], data[23]]);
        self.header.e_entry = u32::from_le_bytes([data[24], data[25], data[26], data[27]]) as u64;
        self.header.e_phoff = u32::from_le_bytes([data[28], data[29], data[30], data[31]]) as u64;
        self.header.e_shoff = u32::from_le_bytes([data[32], data[33], data[34], data[35]]) as u64;
        self.header.e_flags = u32::from_le_bytes([data[36], data[37], data[38], data[39]]);
        self.header.e_ehsize = u16::from_le_bytes([data[40], data[41]]);
        self.header.e_phentsize = u16::from_le_bytes([data[42], data[43]]);
        self.header.e_phnum = u16::from_le_bytes([data[44], data[45]]);
        self.header.e_shentsize = u16::from_le_bytes([data[46], data[47]]);
        self.header.e_shnum = u16::from_le_bytes([data[48], data[49]]);
        self.header.e_shstrndx = u16::from_le_bytes([data[50], data[51]]);
        Ok(())
    }

    fn parse_program_headers(&mut self, data: &[u8], is_64bit: bool) -> Result<(), String> {
        let phoff = self.header.e_phoff as usize;
        let phnum = self.header.e_phnum as usize;
        let phentsize = self.header.e_phentsize as usize;

        if phoff == 0 || phnum == 0 {
            return Ok(());
        }

        if phentsize == 0 {
            return Err("Program header entry size is zero".to_string());
        }

        for i in 0..phnum {
            let offset = phoff + i * phentsize;
            if offset + phentsize > data.len() {
                self.warnings.push(format!(
                    "Program header {} exceeds file bounds",
                    i
                ));
                break;
            }

            let ph = if is_64bit {
                X86ProgramHeader {
                    p_type: u32::from_le_bytes([
                        data[offset], data[offset + 1], data[offset + 2], data[offset + 3],
                    ]),
                    p_flags: u32::from_le_bytes([
                        data[offset + 4],
                        data[offset + 5],
                        data[offset + 6],
                        data[offset + 7],
                    ]),
                    p_offset: u64::from_le_bytes([
                        data[offset + 8],
                        data[offset + 9],
                        data[offset + 10],
                        data[offset + 11],
                        data[offset + 12],
                        data[offset + 13],
                        data[offset + 14],
                        data[offset + 15],
                    ]),
                    p_vaddr: u64::from_le_bytes([
                        data[offset + 16],
                        data[offset + 17],
                        data[offset + 18],
                        data[offset + 19],
                        data[offset + 20],
                        data[offset + 21],
                        data[offset + 22],
                        data[offset + 23],
                    ]),
                    p_paddr: u64::from_le_bytes([
                        data[offset + 24],
                        data[offset + 25],
                        data[offset + 26],
                        data[offset + 27],
                        data[offset + 28],
                        data[offset + 29],
                        data[offset + 30],
                        data[offset + 31],
                    ]),
                    p_filesz: u64::from_le_bytes([
                        data[offset + 32],
                        data[offset + 33],
                        data[offset + 34],
                        data[offset + 35],
                        data[offset + 36],
                        data[offset + 37],
                        data[offset + 38],
                        data[offset + 39],
                    ]),
                    p_memsz: u64::from_le_bytes([
                        data[offset + 40],
                        data[offset + 41],
                        data[offset + 42],
                        data[offset + 43],
                        data[offset + 44],
                        data[offset + 45],
                        data[offset + 46],
                        data[offset + 47],
                    ]),
                    p_align: u64::from_le_bytes([
                        data[offset + 48],
                        data[offset + 49],
                        data[offset + 50],
                        data[offset + 51],
                        data[offset + 52],
                        data[offset + 53],
                        data[offset + 54],
                        data[offset + 55],
                    ]),
                }
            } else {
                X86ProgramHeader {
                    p_type: u32::from_le_bytes([
                        data[offset], data[offset + 1], data[offset + 2], data[offset + 3],
                    ]),
                    p_offset: u32::from_le_bytes([
                        data[offset + 4],
                        data[offset + 5],
                        data[offset + 6],
                        data[offset + 7],
                    ]) as u64,
                    p_vaddr: u32::from_le_bytes([
                        data[offset + 8],
                        data[offset + 9],
                        data[offset + 10],
                        data[offset + 11],
                    ]) as u64,
                    p_paddr: u32::from_le_bytes([
                        data[offset + 12],
                        data[offset + 13],
                        data[offset + 14],
                        data[offset + 15],
                    ]) as u64,
                    p_filesz: u32::from_le_bytes([
                        data[offset + 16],
                        data[offset + 17],
                        data[offset + 18],
                        data[offset + 19],
                    ]) as u64,
                    p_memsz: u32::from_le_bytes([
                        data[offset + 20],
                        data[offset + 21],
                        data[offset + 22],
                        data[offset + 23],
                    ]) as u64,
                    p_flags: u32::from_le_bytes([
                        data[offset + 24],
                        data[offset + 25],
                        data[offset + 26],
                        data[offset + 27],
                    ]),
                    p_align: u32::from_le_bytes([
                        data[offset + 28],
                        data[offset + 29],
                        data[offset + 30],
                        data[offset + 31],
                    ]) as u64,
                }
            };
            self.program_headers.push(ph);
        }
        Ok(())
    }

    fn parse_section_headers(&mut self, data: &[u8], is_64bit: bool) -> Result<(), String> {
        let shoff = self.header.e_shoff as usize;
        let shnum = self.header.e_shnum as usize;
        let shentsize = self.header.e_shentsize as usize;

        if shoff == 0 || shnum == 0 {
            return Ok(());
        }

        if shentsize == 0 {
            return Err("Section header entry size is zero".to_string());
        }

        for i in 0..shnum {
            let offset = shoff + i * shentsize;
            if offset + shentsize > data.len() {
                self.warnings.push(format!("Section header {} exceeds file bounds", i));
                break;
            }

            let sh = if is_64bit {
                X86SectionHeader {
                    sh_name: u32::from_le_bytes([
                        data[offset], data[offset + 1], data[offset + 2], data[offset + 3],
                    ]),
                    sh_type: u32::from_le_bytes([
                        data[offset + 4],
                        data[offset + 5],
                        data[offset + 6],
                        data[offset + 7],
                    ]),
                    sh_flags: u64::from_le_bytes([
                        data[offset + 8],
                        data[offset + 9],
                        data[offset + 10],
                        data[offset + 11],
                        data[offset + 12],
                        data[offset + 13],
                        data[offset + 14],
                        data[offset + 15],
                    ]),
                    sh_addr: u64::from_le_bytes([
                        data[offset + 16],
                        data[offset + 17],
                        data[offset + 18],
                        data[offset + 19],
                        data[offset + 20],
                        data[offset + 21],
                        data[offset + 22],
                        data[offset + 23],
                    ]),
                    sh_offset: u64::from_le_bytes([
                        data[offset + 24],
                        data[offset + 25],
                        data[offset + 26],
                        data[offset + 27],
                        data[offset + 28],
                        data[offset + 29],
                        data[offset + 30],
                        data[offset + 31],
                    ]),
                    sh_size: u64::from_le_bytes([
                        data[offset + 32],
                        data[offset + 33],
                        data[offset + 34],
                        data[offset + 35],
                        data[offset + 36],
                        data[offset + 37],
                        data[offset + 38],
                        data[offset + 39],
                    ]),
                    sh_link: u32::from_le_bytes([
                        data[offset + 40],
                        data[offset + 41],
                        data[offset + 42],
                        data[offset + 43],
                    ]),
                    sh_info: u32::from_le_bytes([
                        data[offset + 44],
                        data[offset + 45],
                        data[offset + 46],
                        data[offset + 47],
                    ]),
                    sh_addralign: u64::from_le_bytes([
                        data[offset + 48],
                        data[offset + 49],
                        data[offset + 50],
                        data[offset + 51],
                        data[offset + 52],
                        data[offset + 53],
                        data[offset + 54],
                        data[offset + 55],
                    ]),
                    sh_entsize: u64::from_le_bytes([
                        data[offset + 56],
                        data[offset + 57],
                        data[offset + 58],
                        data[offset + 59],
                        data[offset + 60],
                        data[offset + 61],
                        data[offset + 62],
                        data[offset + 63],
                    ]),
                    name: String::new(),
                }
            } else {
                X86SectionHeader {
                    sh_name: u32::from_le_bytes([
                        data[offset], data[offset + 1], data[offset + 2], data[offset + 3],
                    ]),
                    sh_type: u32::from_le_bytes([
                        data[offset + 4],
                        data[offset + 5],
                        data[offset + 6],
                        data[offset + 7],
                    ]),
                    sh_flags: u32::from_le_bytes([
                        data[offset + 8],
                        data[offset + 9],
                        data[offset + 10],
                        data[offset + 11],
                    ]) as u64,
                    sh_addr: u32::from_le_bytes([
                        data[offset + 12],
                        data[offset + 13],
                        data[offset + 14],
                        data[offset + 15],
                    ]) as u64,
                    sh_offset: u32::from_le_bytes([
                        data[offset + 16],
                        data[offset + 17],
                        data[offset + 18],
                        data[offset + 19],
                    ]) as u64,
                    sh_size: u32::from_le_bytes([
                        data[offset + 20],
                        data[offset + 21],
                        data[offset + 22],
                        data[offset + 23],
                    ]) as u64,
                    sh_link: u32::from_le_bytes([
                        data[offset + 24],
                        data[offset + 25],
                        data[offset + 26],
                        data[offset + 27],
                    ]),
                    sh_info: u32::from_le_bytes([
                        data[offset + 28],
                        data[offset + 29],
                        data[offset + 30],
                        data[offset + 31],
                    ]),
                    sh_addralign: u32::from_le_bytes([
                        data[offset + 32],
                        data[offset + 33],
                        data[offset + 34],
                        data[offset + 35],
                    ]) as u64,
                    sh_entsize: u32::from_le_bytes([
                        data[offset + 36],
                        data[offset + 37],
                        data[offset + 38],
                        data[offset + 39],
                    ]) as u64,
                    name: String::new(),
                }
            };
            self.section_headers.push(sh);
        }
        Ok(())
    }

    fn parse_string_tables(&mut self, data: &[u8]) -> Result<(), String> {
        // Parse .shstrtab
        let shstrndx = self.header.e_shstrndx as usize;
        if shstrndx > 0 && shstrndx < self.section_headers.len() {
            let sh = &self.section_headers[shstrndx - 1]; // adjust if 0-index
            let off = sh.sh_offset as usize;
            let size = sh.sh_size as usize;
            if off + size <= data.len() {
                self.shstrtab = data[off..off + size].to_vec();
                // Resolve section names
                for section in self.section_headers.iter_mut() {
                    let name_offset = section.sh_name as usize;
                    if name_offset < self.shstrtab.len() {
                        let end = self.shstrtab[name_offset..]
                            .iter()
                            .position(|&b| b == 0)
                            .unwrap_or(self.shstrtab.len() - name_offset);
                        section.name = String::from_utf8_lossy(
                            &self.shstrtab[name_offset..name_offset + end],
                        )
                        .to_string();
                    }
                }
            }
        }
        // Resolve names using the "proper" index (0-indexed sections inside the loop below)
        // Actually, let's fix section name resolution more robustly:
        for i in 0..self.section_headers.len() {
            let sh = &self.section_headers[i];
            let name_off = sh.sh_name as usize;
            if !self.shstrtab.is_empty() && name_off < self.shstrtab.len() {
                let end = self.shstrtab[name_off..]
                    .iter()
                    .position(|&b| b == 0)
                    .unwrap_or(self.shstrtab.len() - name_off);
                let name = String::from_utf8_lossy(&self.shstrtab[name_off..name_off + end]).to_string();
                self.section_headers[i].name = name;
            }
        }

        // Parse .strtab
        if let Some(strtab_idx) = self.find_section_index(".strtab") {
            let sh = &self.section_headers[strtab_idx];
            if sh.sh_type == SHT_STRTAB {
                let off = sh.sh_offset as usize;
                let size = sh.sh_size as usize;
                if off + size <= data.len() {
                    self.strtab = data[off..off + size].to_vec();
                }
            }
        }

        // Parse .dynstr
        if let Some(dynstr_idx) = self.find_section_index(".dynstr") {
            let sh = &self.section_headers[dynstr_idx];
            if sh.sh_type == SHT_STRTAB {
                let off = sh.sh_offset as usize;
                let size = sh.sh_size as usize;
                if off + size <= data.len() {
                    self.dynstr = data[off..off + size].to_vec();
                }
            }
        }

        Ok(())
    }

    fn find_section_index(&self, name: &str) -> Option<usize> {
        self.section_headers.iter().position(|sh| sh.name == name)
    }

    fn parse_symbol_tables(&mut self, data: &[u8], is_64bit: bool) -> Result<(), String> {
        // Parse .symtab
        if let Some(symtab_idx) = self.find_section_index(".symtab") {
            let sh = &self.section_headers[symtab_idx];
            self.symbols = self.parse_sym_entries(data, sh, is_64bit, &self.strtab);
        }

        // Parse .dynsym
        if let Some(dynsym_idx) = self.find_section_index(".dynsym") {
            let sh = &self.section_headers[dynsym_idx];
            self.dynamic_symbols = self.parse_sym_entries(data, sh, is_64bit, &self.dynstr);
        }

        Ok(())
    }

    fn parse_sym_entries(
        &self,
        data: &[u8],
        sh: &X86SectionHeader,
        is_64bit: bool,
        strtab: &[u8],
    ) -> Vec<X86Symbol> {
        let mut symbols = Vec::new();
        let off = sh.sh_offset as usize;
        let size = sh.sh_size as usize;
        let entsize = if sh.sh_entsize > 0 {
            sh.sh_entsize as usize
        } else if is_64bit {
            24
        } else {
            16
        };

        let count = if entsize > 0 { size / entsize } else { 0 };

        for i in 0..count {
            let entry_off = off + i * entsize;
            if entry_off + entsize > data.len() {
                break;
            }

            let (sym, name) = if is_64bit {
                let st_name = u32::from_le_bytes([
                    data[entry_off],
                    data[entry_off + 1],
                    data[entry_off + 2],
                    data[entry_off + 3],
                ]);
                let st_info = data[entry_off + 4];
                let st_other = data[entry_off + 5];
                let st_shndx =
                    u16::from_le_bytes([data[entry_off + 6], data[entry_off + 7]]);
                let st_value = u64::from_le_bytes([
                    data[entry_off + 8],
                    data[entry_off + 9],
                    data[entry_off + 10],
                    data[entry_off + 11],
                    data[entry_off + 12],
                    data[entry_off + 13],
                    data[entry_off + 14],
                    data[entry_off + 15],
                ]);
                let st_size = u64::from_le_bytes([
                    data[entry_off + 16],
                    data[entry_off + 17],
                    data[entry_off + 18],
                    data[entry_off + 19],
                    data[entry_off + 20],
                    data[entry_off + 21],
                    data[entry_off + 22],
                    data[entry_off + 23],
                ]);
                let name = read_strtab(strtab, st_name as usize);
                (X86Symbol {
                    st_name,
                    st_info,
                    st_other,
                    st_shndx,
                    st_value,
                    st_size,
                    name: name.clone(),
                }, name)
            } else {
                let st_name = u32::from_le_bytes([
                    data[entry_off],
                    data[entry_off + 1],
                    data[entry_off + 2],
                    data[entry_off + 3],
                ]);
                let st_value = u32::from_le_bytes([
                    data[entry_off + 4],
                    data[entry_off + 5],
                    data[entry_off + 6],
                    data[entry_off + 7],
                ]) as u64;
                let st_size = u32::from_le_bytes([
                    data[entry_off + 8],
                    data[entry_off + 9],
                    data[entry_off + 10],
                    data[entry_off + 11],
                ]) as u64;
                let st_info = data[entry_off + 12];
                let st_other = data[entry_off + 13];
                let st_shndx =
                    u16::from_le_bytes([data[entry_off + 14], data[entry_off + 15]]);
                let name = read_strtab(strtab, st_name as usize);
                (X86Symbol {
                    st_name,
                    st_info,
                    st_other,
                    st_shndx,
                    st_value,
                    st_size,
                    name: name.clone(),
                }, name)
            };
            symbols.push(sym);
        }

        symbols
    }

    fn parse_dynamic_entries(&mut self, data: &[u8], is_64bit: bool) -> Result<(), String> {
        if let Some(dyn_idx) = self.find_section_index(".dynamic") {
            let sh = &self.section_headers[dyn_idx];
            let off = sh.sh_offset as usize;
            let size = sh.sh_size as usize;
            let entsize = if sh.sh_entsize > 0 {
                sh.sh_entsize as usize
            } else if is_64bit {
                16
            } else {
                8
            };
            let count = if entsize > 0 { size / entsize } else { 0 };

            for i in 0..count {
                let entry_off = off + i * entsize;
                if entry_off + entsize > data.len() {
                    break;
                }
                let entry = if is_64bit {
                    X86DynamicEntry {
                        d_tag: u64::from_le_bytes([
                            data[entry_off],
                            data[entry_off + 1],
                            data[entry_off + 2],
                            data[entry_off + 3],
                            data[entry_off + 4],
                            data[entry_off + 5],
                            data[entry_off + 6],
                            data[entry_off + 7],
                        ]),
                        d_val: u64::from_le_bytes([
                            data[entry_off + 8],
                            data[entry_off + 9],
                            data[entry_off + 10],
                            data[entry_off + 11],
                            data[entry_off + 12],
                            data[entry_off + 13],
                            data[entry_off + 14],
                            data[entry_off + 15],
                        ]),
                    }
                } else {
                    X86DynamicEntry {
                        d_tag: u32::from_le_bytes([
                            data[entry_off],
                            data[entry_off + 1],
                            data[entry_off + 2],
                            data[entry_off + 3],
                        ]) as u64,
                        d_val: u32::from_le_bytes([
                            data[entry_off + 4],
                            data[entry_off + 5],
                            data[entry_off + 6],
                            data[entry_off + 7],
                        ]) as u64,
                    }
                };
                if entry.d_tag == DT_NULL {
                    break;
                }
                self.dynamic_entries.push(entry);
            }
        }
        Ok(())
    }

    fn parse_relocations(&mut self, data: &[u8], is_64bit: bool) -> Result<(), String> {
        for idx in 0..self.section_headers.len() {
            let sh = &self.section_headers[idx];
            if sh.sh_type != SHT_RELA && sh.sh_type != SHT_REL {
                continue;
            }
            let has_addend = sh.sh_type == SHT_RELA;
            let off = sh.sh_offset as usize;
            let size = sh.sh_size as usize;
            let entsize = sh.sh_entsize as usize;
            let count = if entsize > 0 { size / entsize } else { 0 };

            for i in 0..count {
                let entry_off = off + i * entsize;
                if entry_off + entsize > data.len() {
                    break;
                }
                let reloc = if is_64bit && has_addend {
                    // ELF64 RELA: r_offset(8) r_info(8) r_addend(8)
                    X86Relocation::new(
                        u64::from_le_bytes([
                            data[entry_off],
                            data[entry_off + 1],
                            data[entry_off + 2],
                            data[entry_off + 3],
                            data[entry_off + 4],
                            data[entry_off + 5],
                            data[entry_off + 6],
                            data[entry_off + 7],
                        ]),
                        u32::from_le_bytes([
                            data[entry_off + 8],
                            data[entry_off + 9],
                            data[entry_off + 10],
                            data[entry_off + 11],
                        ]),
                        u32::from_le_bytes([
                            data[entry_off + 12],
                            data[entry_off + 13],
                            data[entry_off + 14],
                            data[entry_off + 15],
                        ]),
                        i64::from_le_bytes([
                            data[entry_off + 16],
                            data[entry_off + 17],
                            data[entry_off + 18],
                            data[entry_off + 19],
                            data[entry_off + 20],
                            data[entry_off + 21],
                            data[entry_off + 22],
                            data[entry_off + 23],
                        ]),
                    )
                } else if is_64bit && !has_addend {
                    // ELF64 REL: r_offset(8) r_info(8)
                    X86Relocation::new(
                        u64::from_le_bytes([
                            data[entry_off],
                            data[entry_off + 1],
                            data[entry_off + 2],
                            data[entry_off + 3],
                            data[entry_off + 4],
                            data[entry_off + 5],
                            data[entry_off + 6],
                            data[entry_off + 7],
                        ]),
                        u32::from_le_bytes([
                            data[entry_off + 8],
                            data[entry_off + 9],
                            data[entry_off + 10],
                            data[entry_off + 11],
                        ]),
                        u32::from_le_bytes([
                            data[entry_off + 12],
                            data[entry_off + 13],
                            data[entry_off + 14],
                            data[entry_off + 15],
                        ]),
                        0,
                    )
                } else if has_addend {
                    // ELF32 RELA: r_offset(4) r_info(4) r_addend(4)
                    X86Relocation::new(
                        u32::from_le_bytes([
                            data[entry_off],
                            data[entry_off + 1],
                            data[entry_off + 2],
                            data[entry_off + 3],
                        ]) as u64,
                        u32::from_le_bytes([
                            data[entry_off + 4],
                            data[entry_off + 5],
                            data[entry_off + 6],
                            data[entry_off + 7],
                        ]),
                        u32::from_le_bytes([
                            data[entry_off + 4],
                            data[entry_off + 5],
                            data[entry_off + 6],
                            data[entry_off + 7],
                        ]) >> 8,
                        i32::from_le_bytes([
                            data[entry_off + 8],
                            data[entry_off + 9],
                            data[entry_off + 10],
                            data[entry_off + 11],
                        ]) as i64,
                    )
                } else {
                    // ELF32 REL: r_offset(4) r_info(4)
                    X86Relocation::new(
                        u32::from_le_bytes([
                            data[entry_off],
                            data[entry_off + 1],
                            data[entry_off + 2],
                            data[entry_off + 3],
                        ]) as u64,
                        u32::from_le_bytes([
                            data[entry_off + 4],
                            data[entry_off + 5],
                            data[entry_off + 6],
                            data[entry_off + 7],
                        ]),
                        u32::from_le_bytes([
                            data[entry_off + 4],
                            data[entry_off + 5],
                            data[entry_off + 6],
                            data[entry_off + 7],
                        ]) >> 8,
                        0,
                    )
                };
                // Resolve r_sym to the symbol table
                let r_sym = reloc.r_sym;
                // ELF64 r_info stores sym in upper 32 bits
                self.relocations.push(reloc);
            }
        }
        Ok(())
    }

    fn parse_notes(&mut self, data: &[u8]) -> Result<(), String> {
        for idx in 0..self.section_headers.len() {
            let sh = &self.section_headers[idx];
            if sh.sh_type != SHT_NOTE {
                continue;
            }
            let off = sh.sh_offset as usize;
            let end = off + sh.sh_size as usize;
            let mut pos = off;
            while pos + 12 <= end.min(data.len()) {
                let n_namesz = u32::from_le_bytes([
                    data[pos], data[pos + 1], data[pos + 2], data[pos + 3],
                ]) as usize;
                let n_descsz = u32::from_le_bytes([
                    data[pos + 4], data[pos + 5], data[pos + 6], data[pos + 7],
                ]) as usize;
                let n_type = u32::from_le_bytes([
                    data[pos + 8], data[pos + 9], data[pos + 10], data[pos + 11],
                ]);

                let name_start = pos + 12;
                let name_end = name_start + n_namesz;
                let desc_start = (name_end + 3) & !3; // 4-byte aligned
                let desc_end = desc_start + n_descsz;

                if name_end > data.len() || desc_end > data.len() {
                    break;
                }

                let name = String::from_utf8_lossy(&data[name_start..name_end])
                    .trim_end_matches('\0')
                    .to_string();
                let desc = data[desc_start..desc_end].to_vec();

                self.notes.push(X86Note::new(n_type, &name, desc));

                pos = (desc_end + 3) & !3;
            }
        }
        Ok(())
    }

    // ─── ELF Writing ──────────────────────────────────────────────────────

    /// Write the full ELF file to a byte vector.
    pub fn to_bytes(&self) -> Result<Vec<u8>, String> {
        let is_64bit = self.header.ident.is_64bit();
        let mut buf = Vec::new();

        // Write ELF header
        buf.extend_from_slice(&self.header.ident.to_bytes());
        self.write_ehdr_fields(&mut buf, is_64bit)?;

        Ok(buf)
    }

    fn write_ehdr_fields(&self, buf: &mut Vec<u8>, is_64bit: bool) -> Result<(), String> {
        buf.extend_from_slice(&self.header.e_type.to_le_bytes());
        buf.extend_from_slice(&self.header.e_machine.to_le_bytes());
        buf.extend_from_slice(&self.header.e_version.to_le_bytes());
        if is_64bit {
            buf.extend_from_slice(&self.header.e_entry.to_le_bytes());
            buf.extend_from_slice(&self.header.e_phoff.to_le_bytes());
            buf.extend_from_slice(&self.header.e_shoff.to_le_bytes());
        } else {
            buf.extend_from_slice(&(self.header.e_entry as u32).to_le_bytes());
            buf.extend_from_slice(&(self.header.e_phoff as u32).to_le_bytes());
            buf.extend_from_slice(&(self.header.e_shoff as u32).to_le_bytes());
        }
        buf.extend_from_slice(&self.header.e_flags.to_le_bytes());
        buf.extend_from_slice(&self.header.e_ehsize.to_le_bytes());
        buf.extend_from_slice(&self.header.e_phentsize.to_le_bytes());
        buf.extend_from_slice(&self.header.e_phnum.to_le_bytes());
        buf.extend_from_slice(&self.header.e_shentsize.to_le_bytes());
        buf.extend_from_slice(&self.header.e_shnum.to_le_bytes());
        buf.extend_from_slice(&self.header.e_shstrndx.to_le_bytes());
        Ok(())
    }

    /// Get a string from a string table by offset.
    pub fn get_string_from_tab(&self, tab: &[u8], offset: usize) -> String {
        read_strtab(tab, offset)
    }

    /// Find a symbol by name in the symbol table.
    pub fn find_symbol(&self, name: &str) -> Option<&X86Symbol> {
        self.symbols.iter().find(|s| s.name == name)
    }

    /// Find a dynamic symbol by name.
    pub fn find_dynamic_symbol(&self, name: &str) -> Option<&X86Symbol> {
        self.dynamic_symbols.iter().find(|s| s.name == name)
    }

    /// Get all symbols of a specific type.
    pub fn symbols_by_type(&self, st_type: u8) -> Vec<&X86Symbol> {
        self.symbols
            .iter()
            .filter(|s| s.st_type() == st_type)
            .collect()
    }

    /// Get all symbols with a specific binding.
    pub fn symbols_by_binding(&self, bind: u8) -> Vec<&X86Symbol> {
        self.symbols
            .iter()
            .filter(|s| s.bind() == bind)
            .collect()
    }

    /// Get exported symbols (global + weak).
    pub fn exported_symbols(&self) -> Vec<&X86Symbol> {
        self.symbols
            .iter()
            .filter(|s| s.bind() == STB_GLOBAL || s.bind() == STB_WEAK)
            .filter(|s| s.is_defined())
            .collect()
    }

    /// Get all section data by section name.
    pub fn get_section_data(&self, name: &str) -> Option<&[u8]> {
        self.section_data.get(name).map(|v| v.as_slice())
    }

    /// Get all relocation types used in this file.
    pub fn relocation_types_used(&self) -> HashSet<u32> {
        self.relocations.iter().map(|r| r.r_type).collect()
    }

    /// Count relocations by type.
    pub fn relocation_type_counts(&self) -> HashMap<u32, usize> {
        let mut counts = HashMap::new();
        for r in &self.relocations {
            *counts.entry(r.r_type).or_insert(0) += 1;
        }
        counts
    }

    /// Get a dynamic entry value by tag.
    pub fn get_dynamic(&self, tag: u64) -> Option<u64> {
        self.dynamic_entries
            .iter()
            .find(|e| e.d_tag == tag)
            .map(|e| e.d_val)
    }

    /// Get all dynamic entries of a specific tag.
    pub fn get_dynamic_all(&self, tag: u64) -> Vec<u64> {
        self.dynamic_entries
            .iter()
            .filter(|e| e.d_tag == tag)
            .map(|e| e.d_val)
            .collect()
    }

    /// Check if a particular dynamic flag is set.
    pub fn has_dynamic_flag(&self, flag: u64) -> bool {
        if let Some(flags) = self.get_dynamic(DT_FLAGS) {
            return flags & flag != 0;
        }
        false
    }

    /// Check if DF_1 flag is set.
    pub fn has_dynamic_flag_1(&self, flag: u64) -> bool {
        if let Some(flags) = self.get_dynamic(DT_FLAGS_1) {
            return flags & flag != 0;
        }
        false
    }

    /// Compute total segment sizes.
    pub fn total_load_size(&self) -> u64 {
        self.program_headers
            .iter()
            .filter(|ph| ph.p_type == PT_LOAD)
            .map(|ph| ph.p_memsz)
            .sum()
    }

    /// Build a GnuHashTable from symbol data.
    pub fn build_gnu_hash(&mut self, nbuckets: u32, symoffset: u32, bloom_shift: u32) {
        let dynsym_count = self.dynamic_symbols.len() as u32;
        if dynsym_count <= symoffset {
            return;
        }
        let ndynsyms = dynsym_count - symoffset;
        let bloom_size = if nbuckets > 0 {
            (ndynsyms / nbuckets.max(1)).max(1).next_power_of_two()
        } else {
            1
        };

        let mut table = X86GnuHashTable::new(nbuckets, symoffset, bloom_size, bloom_shift);
        table.chain = vec![0u32; ndynsyms as usize];

        // Fill bloom filter and chains
        for i in 0..ndynsyms as usize {
            let sym_idx = symoffset as usize + i;
            if sym_idx >= self.dynamic_symbols.len() {
                break;
            }
            let h = elf_gnu_hash(&self.dynamic_symbols[sym_idx].name);
            let bm = h;
            let bit0 = (bm / 64) % bloom_size as u32;
            let bit1 = ((bm >> bloom_shift) / 64) % bloom_size as u32;
            table.bloom[bit0 as usize] |= 1u64 << (bm % 64);
            table.bloom[bit1 as usize] |= 1u64 << ((bm >> bloom_shift) % 64);
            table.chain[i] = h & !1;
            if i == ndynsyms as usize - 1
                || self.sym_gnu_hash(symoffset as usize + i + 1) % nbuckets
                    != h % nbuckets
            {
                table.chain[i] |= 1;
            }
        }

        // Fill buckets
        for i in 0..ndynsyms as usize {
            let h = elf_gnu_hash(&self.dynamic_symbols[symoffset as usize + i].name);
            let bucket = (h % nbuckets) as usize;
            if table.buckets[bucket] == 0 {
                table.buckets[bucket] = i as u32;
            }
        }

        self.gnu_hash_table = Some(table);
    }

    fn sym_gnu_hash(&self, idx: usize) -> u32 {
        if idx < self.dynamic_symbols.len() {
            elf_gnu_hash(&self.dynamic_symbols[idx].name)
        } else {
            0
        }
    }

    /// Generate a human-readable report of the ELF file.
    pub fn report(&self) -> String {
        let mut r = String::new();
        r.push_str("=== X86 ELF Deep Report ===\n\n");
        r.push_str(&format!(
            "Class: {}\n",
            if self.header.ident.is_64bit() {
                "ELF64"
            } else {
                "ELF32"
            }
        ));
        r.push_str(&format!(
            "Machine: {}\n",
            match self.header.e_machine {
                EM_X86_64 => "x86_64",
                EM_386 => "i386",
                _ => "Unknown",
            }
        ));
        r.push_str(&format!(
            "Type: {}\n",
            match self.header.e_type {
                ET_REL => "REL (relocatable)",
                ET_EXEC => "EXEC (executable)",
                ET_DYN => "DYN (shared object)",
                ET_CORE => "CORE (core dump)",
                _ => "Unknown",
            }
        ));
        r.push_str(&format!("Entry point: 0x{:x}\n", self.header.e_entry));
        r.push_str(&format!("Program headers: {}\n", self.program_headers.len()));
        r.push_str(&format!("Section headers: {}\n", self.section_headers.len()));
        r.push_str(&format!("Symbols: {}\n", self.symbols.len()));
        r.push_str(&format!("Dynamic symbols: {}\n", self.dynamic_symbols.len()));
        r.push_str(&format!("Relocations: {}\n", self.relocations.len()));
        r.push_str(&format!("Dynamic entries: {}\n", self.dynamic_entries.len()));
        r.push_str(&format!("Notes: {}\n", self.notes.len()));
        r.push_str(&format!("Valid: {}\n", self.valid));
        if !self.errors.is_empty() {
            r.push_str("\nErrors:\n");
            for e in &self.errors {
                r.push_str(&format!("  - {}\n", e));
            }
        }
        if !self.warnings.is_empty() {
            r.push_str("\nWarnings:\n");
            for w in &self.warnings {
                r.push_str(&format!("  - {}\n", w));
            }
        }
        r
    }
}

impl Default for X86ELFDeep {
    fn default() -> Self {
        Self::new()
    }
}

// ─── ELF Utility Functions ────────────────────────────────────────────────

/// Read a null-terminated string from a string table buffer.
pub fn read_strtab(tab: &[u8], offset: usize) -> String {
    if offset >= tab.len() {
        return String::new();
    }
    let end = tab[offset..]
        .iter()
        .position(|&b| b == 0)
        .unwrap_or(tab.len() - offset);
    String::from_utf8_lossy(&tab[offset..offset + end]).to_string()
}

/// Compute the GNU-style ELF symbol hash.
pub fn elf_gnu_hash(name: &str) -> u32 {
    let mut h: u32 = 5381;
    for b in name.as_bytes() {
        h = h.wrapping_mul(33).wrapping_add(*b as u32);
    }
    h
}

/// Compute the classic SysV ELF symbol hash.
pub fn elf_hash(name: &str) -> u32 {
    let mut h: u32 = 0;
    for b in name.as_bytes() {
        h = (h << 4).wrapping_add(*b as u32);
        let g = h & 0xf0000000;
        if g != 0 {
            h ^= g >> 24;
        }
        h &= !g;
    }
    h
}

/// Encode st_info from bind and type.
pub fn x86_st_info(bind: u8, st_type: u8) -> u8 {
    ((bind & 0x0f) << 4) | (st_type & 0x0f)
}

/// Encode st_other from visibility.
pub fn x86_st_other(visibility: u8) -> u8 {
    visibility & 0x03
}

/// Decode ELF64 r_info into (sym, type).
pub fn x86_elf64_r_info(r_info: u64) -> (u32, u32) {
    ((r_info >> 32) as u32, (r_info & 0xffffffff) as u32)
}

/// Encode ELF64 r_info from sym and type.
pub fn x86_elf64_r_info_encode(sym: u32, r_type: u32) -> u64 {
    ((sym as u64) << 32) | (r_type as u64)
}

/// Decode ELF32 r_info.
pub fn x86_elf32_r_info(r_info: u32) -> (u32, u32) {
    ((r_info >> 8) as u32, (r_info & 0xff) as u32)
}

/// Encode ELF32 r_info.
pub fn x86_elf32_r_info_encode(sym: u32, r_type: u32) -> u32 {
    ((sym as u32) << 8) | (r_type as u32 & 0xff)
}

/// Check whether a relocation type requires a GOT entry.
pub fn x86_reloc_needs_got_x86_64(r_type: u32) -> bool {
    matches!(
        r_type,
        R_X86_64_GOT32
            | R_X86_64_GOTPCREL
            | R_X86_64_GOTTPOFF
            | R_X86_64_GOTPCRELX
            | R_X86_64_REX_GOTPCRELX
            | R_X86_64_GOTPC32_TLSDESC
    )
}

/// Check whether a relocation type is a TLS relocation.
pub fn x86_reloc_is_tls(r_type: u32, machine: u16) -> bool {
    match machine {
        EM_X86_64 => matches!(
            r_type,
            R_X86_64_DTPMOD64
                | R_X86_64_DTPOFF64
                | R_X86_64_TPOFF64
                | R_X86_64_TLSGD
                | R_X86_64_TLSLD
                | R_X86_64_DTPOFF32
                | R_X86_64_GOTTPOFF
                | R_X86_64_TPOFF32
                | R_X86_64_TLSDESC
                | R_X86_64_TLSDESC_CALL
                | R_X86_64_GOTPC32_TLSDESC
        ),
        EM_386 => matches!(
            r_type,
            R_386_TLS_TPOFF
                | R_386_TLS_IE
                | R_386_TLS_GOTIE
                | R_386_TLS_LE
                | R_386_TLS_GD
                | R_386_TLS_LDM
                | R_386_TLS_GD_32
                | R_386_TLS_GD_PUSH
                | R_386_TLS_GD_CALL
                | R_386_TLS_GD_POP
                | R_386_TLS_LDM_32
                | R_386_TLS_LDM_PUSH
                | R_386_TLS_LDM_CALL
                | R_386_TLS_LDM_POP
                | R_386_TLS_LDO_32
                | R_386_TLS_IE_32
                | R_386_TLS_LE_32
                | R_386_TLS_DTPMOD32
                | R_386_TLS_DTPOFF32
                | R_386_TLS_TPOFF32
                | R_386_TLS_GOTDESC
                | R_386_TLS_DESC_CALL
                | R_386_TLS_DESC
        ),
        _ => false,
    }
}

/// Check whether a relocation type is PC-relative.
pub fn x86_reloc_is_pc_relative(r_type: u32, machine: u16) -> bool {
    match machine {
        EM_X86_64 => matches!(
            r_type,
            R_X86_64_PC32
                | R_X86_64_PC16
                | R_X86_64_PC8
                | R_X86_64_PC64
                | R_X86_64_PLT32
                | R_X86_64_GOTPCREL
                | R_X86_64_GOTPCRELX
                | R_X86_64_REX_GOTPCRELX
                | R_X86_64_PC32_BND
                | R_X86_64_PLT32_BND
        ),
        EM_386 => matches!(
            r_type,
            R_386_PC32 | R_386_PC16 | R_386_PC8 | R_386_PLT32 | R_386_GOTPC
        ),
        _ => false,
    }
}

/// Classify the ELF file type based on header.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86ElfClass {
    Elf32,
    Elf64,
}

impl X86ElfClass {
    pub fn from_ident(class: u8) -> Self {
        match class {
            ELFCLASS32 => X86ElfClass::Elf32,
            ELFCLASS64 => X86ElfClass::Elf64,
            _ => X86ElfClass::Elf64, // default
        }
    }
}

// ─── Tests ────────────────────────────────────────────────────────────────

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

    // ── Utils ─────────────────────────────────────────────────────────

    fn make_minimal_elf64_data() -> Vec<u8> {
        let mut data = vec![0u8; 120];
        // e_ident
        data[0..4].copy_from_slice(&ELF_MAGIC_BYTES);
        data[EI_CLASS] = ELFCLASS64;
        data[EI_DATA] = ELFDATA2LSB;
        data[EI_VERSION] = 1;
        data[EI_OSABI] = ELFOSABI_SYSV;
        // e_type = ET_REL
        data[16..18].copy_from_slice(&1u16.to_le_bytes());
        // e_machine = EM_X86_64
        data[18..20].copy_from_slice(&62u16.to_le_bytes());
        // e_version
        data[20..24].copy_from_slice(&1u32.to_le_bytes());
        // e_ehsize
        data[52..54].copy_from_slice(&64u16.to_le_bytes());
        // e_phentsize
        data[54..56].copy_from_slice(&56u16.to_le_bytes());
        // e_shentsize
        data[58..60].copy_from_slice(&64u16.to_le_bytes());
        data
    }

    fn make_minimal_elf32_data() -> Vec<u8> {
        let mut data = vec![0u8; 52];
        data[0..4].copy_from_slice(&ELF_MAGIC_BYTES);
        data[EI_CLASS] = ELFCLASS32;
        data[EI_DATA] = ELFDATA2LSB;
        data[EI_VERSION] = 1;
        data[16..18].copy_from_slice(&1u16.to_le_bytes()); // ET_REL
        data[18..20].copy_from_slice(&3u16.to_le_bytes()); // EM_386
        data[20..24].copy_from_slice(&1u32.to_le_bytes());
        data[40..42].copy_from_slice(&52u16.to_le_bytes());
        data[42..44].copy_from_slice(&32u16.to_le_bytes());
        data[46..48].copy_from_slice(&40u16.to_le_bytes());
        data
    }

    // ── Ident Tests ───────────────────────────────────────────────────

    #[test]
    fn test_ident_default() {
        let ident = ElfIdent::default();
        assert_eq!(ident.magic, ELF_MAGIC_BYTES);
        assert_eq!(ident.class, ELFCLASS64);
        assert_eq!(ident.data, ELFDATA2LSB);
    }

    #[test]
    fn test_ident_x86_64() {
        let ident = ElfIdent::new_x86_64();
        assert!(ident.is_64bit());
        assert!(!ident.is_32bit());
        assert!(ident.is_valid_magic());
        assert_eq!(ident.osabi, ELFOSABI_SYSV);
    }

    #[test]
    fn test_ident_x86_32() {
        let ident = ElfIdent::new_x86_32();
        assert!(ident.is_32bit());
        assert!(!ident.is_64bit());
        assert!(ident.is_valid_magic());
    }

    #[test]
    fn test_ident_roundtrip() {
        let ident = ElfIdent::new_x86_64();
        let bytes = ident.to_bytes();
        let parsed = ElfIdent::from_bytes(&bytes);
        assert_eq!(ident, parsed);
    }

    #[test]
    fn test_ident_roundtrip_32() {
        let ident = ElfIdent::new_x86_32();
        let bytes = ident.to_bytes();
        let parsed = ElfIdent::from_bytes(&bytes);
        assert_eq!(ident, parsed);
    }

    #[test]
    fn test_ident_invalid_magic() {
        let mut ident = ElfIdent::new_x86_64();
        ident.magic = [0, 0, 0, 0];
        assert!(!ident.is_valid_magic());
    }

    // ── Header Tests ──────────────────────────────────────────────────

    #[test]
    fn test_elf_header_default() {
        let hdr = X86ElfHeader::default();
        assert_eq!(hdr.e_machine, EM_X86_64);
        assert_eq!(hdr.e_type, ET_REL);
        assert!(hdr.is_64bit());
        assert!(hdr.is_relocatable());
    }

    #[test]
    fn test_elf_header_x86_64() {
        let hdr = X86ElfHeader::new_x86_64();
        assert!(hdr.is_64bit());
        assert_eq!(hdr.e_machine, EM_X86_64);
    }

    #[test]
    fn test_elf_header_x86_32() {
        let hdr = X86ElfHeader::new_x86_32();
        assert!(!hdr.is_64bit());
        assert_eq!(hdr.e_machine, EM_386);
    }

    #[test]
    fn test_elf_header_type_checks() {
        let mut hdr = X86ElfHeader::new_x86_64();
        hdr.e_type = ET_EXEC;
        assert!(hdr.is_executable());
        assert!(!hdr.is_shared_object());
        hdr.e_type = ET_DYN;
        assert!(hdr.is_shared_object());
        assert!(!hdr.is_executable());
    }

    // ── Program Header Tests ──────────────────────────────────────────

    #[test]
    fn test_phdr_load() {
        let ph = X86ProgramHeader::new_load(0x400000, 0x1000, 0x5000, 0x6000, PF_R | PF_X);
        assert_eq!(ph.p_type, PT_LOAD);
        assert_eq!(ph.p_vaddr, 0x400000);
        assert_eq!(ph.p_flags, PF_R | PF_X);
        assert_eq!(ph.type_name(), "PT_LOAD");
        assert!(ph.flags_string().contains('R'));
        assert!(ph.flags_string().contains('X'));
    }

    #[test]
    fn test_phdr_dynamic() {
        let ph = X86ProgramHeader::new_dynamic(0x2000, 0x100);
        assert_eq!(ph.p_type, PT_DYNAMIC);
        assert_eq!(ph.p_flags, PF_R | PF_W);
    }

    #[test]
    fn test_phdr_interp() {
        let ph = X86ProgramHeader::new_interp(0x200, 0x20);
        assert_eq!(ph.p_type, PT_INTERP);
        assert_eq!(ph.p_align, 1);
    }

    #[test]
    fn test_phdr_note() {
        let ph = X86ProgramHeader::new_note(0x300, 0x80);
        assert_eq!(ph.p_type, PT_NOTE);
    }

    #[test]
    fn test_phdr_tls() {
        let ph = X86ProgramHeader::new_tls(0x600000, 0x4000, 0x100, 0x200);
        assert_eq!(ph.p_type, PT_TLS);
        assert_eq!(ph.p_memsz, 0x200);
    }

    #[test]
    fn test_phdr_gnu_stack() {
        let ph = X86ProgramHeader::new_gnu_stack(PF_R | PF_W, 0x100000);
        assert_eq!(ph.p_type, PT_GNU_STACK);
        assert_eq!(ph.p_flags, PF_R | PF_W);
    }

    #[test]
    fn test_phdr_gnu_relro() {
        let ph = X86ProgramHeader::new_gnu_relro(0x5000, 0x2000);
        assert_eq!(ph.p_type, PT_GNU_RELRO);
    }

    #[test]
    fn test_phdr_gnu_eh_frame() {
        let ph = X86ProgramHeader::new_gnu_eh_frame(0x6000, 0x1000);
        assert_eq!(ph.p_type, PT_GNU_EH_FRAME);
    }

    #[test]
    fn test_phdr_gnu_property() {
        let ph = X86ProgramHeader::new_gnu_property(0x7000, 0x100);
        assert_eq!(ph.p_type, PT_GNU_PROPERTY);
    }

    #[test]
    fn test_phdr_flags_string() {
        let ph = X86ProgramHeader::new_load(0, 0, 0, 0, PF_R | PF_W | PF_X);
        assert_eq!(ph.flags_string(), "RWX");
        let ph2 = X86ProgramHeader::new_load(0, 0, 0, 0, 0);
        assert_eq!(ph2.flags_string(), "---");
    }

    // ── Section Header Tests ──────────────────────────────────────────

    #[test]
    fn test_section_header_new() {
        let sh = X86SectionHeader::new(".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR, 0, 100);
        assert_eq!(sh.name, ".text");
        assert_eq!(sh.sh_type, SHT_PROGBITS);
        assert_eq!(sh.type_name(), "PROGBITS");
        assert_eq!(sh.sh_flags, SHF_ALLOC | SHF_EXECINSTR);
    }

    #[test]
    fn test_section_header_flags_string() {
        let sh = X86SectionHeader::new(".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE, 0, 100);
        assert!(sh.flags_string().contains('W'));
        assert!(sh.flags_string().contains('A'));
        let sh2 = X86SectionHeader::new(".tbss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE | SHF_TLS, 0, 100);
        assert!(sh2.flags_string().contains('T'));
    }

    #[test]
    fn test_section_type_names() {
        let sh = X86SectionHeader::new("", SHT_SYMTAB, 0, 0, 0);
        assert_eq!(sh.type_name(), "SYMTAB");
        let sh2 = X86SectionHeader::new("", SHT_DYNSYM, 0, 0, 0);
        assert_eq!(sh2.type_name(), "DYNSYM");
        let sh3 = X86SectionHeader::new("", SHT_GNU_HASH, 0, 0, 0);
        assert_eq!(sh3.type_name(), "GNU_HASH");
        let sh4 = X86SectionHeader::new("", SHT_GNU_VERDEF, 0, 0, 0);
        assert_eq!(sh4.type_name(), "GNU_VERDEF");
        let sh5 = X86SectionHeader::new("", 0x9999, 0, 0, 0);
        assert_eq!(sh5.type_name(), "UNKNOWN");
    }

    // ── Symbol Tests ──────────────────────────────────────────────────

    #[test]
    fn test_symbol_new() {
        let sym = X86Symbol::new("main", x86_st_info(STB_GLOBAL, STT_FUNC), 1, 0x4000, 0x50);
        assert_eq!(sym.name, "main");
        assert_eq!(sym.bind(), STB_GLOBAL);
        assert_eq!(sym.st_type(), STT_FUNC);
        assert_eq!(sym.visibility(), STV_DEFAULT);
        assert!(sym.is_defined());
    }

    #[test]
    fn test_symbol_bind_names() {
        let sym = X86Symbol::new("foo", x86_st_info(STB_LOCAL, STT_OBJECT), 0, 0, 0);
        assert_eq!(sym.bind_name(), "LOCAL");
        let sym2 = X86Symbol::new("bar", x86_st_info(STB_WEAK, STT_FUNC), 0, 0, 0);
        assert_eq!(sym2.bind_name(), "WEAK");
        let sym3 = X86Symbol::new("baz", x86_st_info(STB_GNU_UNIQUE, STT_OBJECT), 0, 0, 0);
        assert_eq!(sym3.bind_name(), "GNU_UNIQUE");
    }

    #[test]
    fn test_symbol_type_names() {
        let sym = X86Symbol::new("a", x86_st_info(STB_GLOBAL, STT_NOTYPE), 0, 0, 0);
        assert_eq!(sym.type_name(), "NOTYPE");
        let sym2 = X86Symbol::new("b", x86_st_info(STB_GLOBAL, STT_FILE), 0, 0, 0);
        assert_eq!(sym2.type_name(), "FILE");
        let sym3 = X86Symbol::new("c", x86_st_info(STB_GLOBAL, STT_TLS), 0, 0, 0);
        assert_eq!(sym3.type_name(), "TLS");
        let sym4 = X86Symbol::new("d", x86_st_info(STB_GLOBAL, STT_GNU_IFUNC), 0, 0, 0);
        assert_eq!(sym4.type_name(), "GNU_IFUNC");
    }

    #[test]
    fn test_symbol_visibility_names() {
        let sym = X86Symbol::new("a", x86_st_info(STB_GLOBAL, STT_FUNC), 0, 0, 0);
        sym.st_other = 0; // STV_DEFAULT
        let sym2 = X86Symbol::new("b", x86_st_info(STB_GLOBAL, STT_FUNC), 0, 0, 0);
        sym2.st_other = 0;
        assert_eq!(sym2.visibility_name(), "DEFAULT");
        let sym3 = X86Symbol::new("c", x86_st_info(STB_GLOBAL, STT_FUNC), 0, 0, 0);
        sym3.st_other = 0;
        assert_eq!(sym3.visibility_name(), "DEFAULT");
    }

    #[test]
    fn test_symbol_undefined() {
        let sym = X86Symbol::new("undef", x86_st_info(STB_GLOBAL, STT_NOTYPE), SHN_UNDEF, 0, 0);
        assert!(!sym.is_defined());
    }

    #[test]
    fn test_symbol_visibility_encoding() {
        let sym = X86Symbol::new(
            "hidden_sym",
            x86_st_info(STB_GLOBAL, STT_FUNC),
            1,
            0x1000,
            0x10,
        );
        let sym = X86Symbol {
            st_other: x86_st_other(STV_HIDDEN),
            ..sym
        };
        assert_eq!(sym.visibility(), STV_HIDDEN);
        assert_eq!(sym.visibility_name(), "HIDDEN");
    }

    // ── Relocation Tests ──────────────────────────────────────────────

    #[test]
    fn test_relocation_new() {
        let reloc = X86Relocation::new(0x100, R_X86_64_PC32, 5, -4);
        assert_eq!(reloc.r_offset, 0x100);
        assert_eq!(reloc.r_type, R_X86_64_PC32);
        assert_eq!(reloc.r_sym, 5);
        assert_eq!(reloc.r_addend, -4);
    }

    #[test]
    fn test_x86_64_reloc_names() {
        assert_eq!(x86_64_reloc_name(R_X86_64_NONE), "R_X86_64_NONE");
        assert_eq!(x86_64_reloc_name(R_X86_64_64), "R_X86_64_64");
        assert_eq!(x86_64_reloc_name(R_X86_64_GOTPCREL), "R_X86_64_GOTPCREL");
        assert_eq!(x86_64_reloc_name(R_X86_64_IRELATIVE), "R_X86_64_IRELATIVE");
        assert_eq!(x86_64_reloc_name(R_X86_64_GOTPCRELX), "R_X86_64_GOTPCRELX");
        assert_eq!(x86_64_reloc_name(99999), "R_X86_64_UNKNOWN");
    }

    #[test]
    fn test_i386_reloc_names() {
        assert_eq!(i386_reloc_name(R_386_NONE), "R_386_NONE");
        assert_eq!(i386_reloc_name(R_386_32), "R_386_32");
        assert_eq!(i386_reloc_name(R_386_PC32), "R_386_PC32");
        assert_eq!(i386_reloc_name(R_386_TLS_GD), "R_386_TLS_GD");
        assert_eq!(i386_reloc_name(R_386_IRELATIVE), "R_386_IRELATIVE");
        assert_eq!(i386_reloc_name(99999), "R_386_UNKNOWN");
    }

    #[test]
    fn test_relocation_type_name() {
        let r = X86Relocation::new(0, R_X86_64_PC32, 0, 0);
        assert_eq!(r.type_name(EM_X86_64), "R_X86_64_PC32");
        let r2 = X86Relocation::new(0, R_386_PC32, 0, 0);
        assert_eq!(r2.type_name(EM_386), "R_386_PC32");
    }

    #[test]
    fn test_reloc_needs_got() {
        assert!(x86_reloc_needs_got_x86_64(R_X86_64_GOTPCREL));
        assert!(x86_reloc_needs_got_x86_64(R_X86_64_GOT32));
        assert!(x86_reloc_needs_got_x86_64(R_X86_64_GOTPCRELX));
        assert!(!x86_reloc_needs_got_x86_64(R_X86_64_PC32));
        assert!(!x86_reloc_needs_got_x86_64(R_X86_64_64));
    }

    #[test]
    fn test_reloc_is_tls() {
        assert!(x86_reloc_is_tls(R_X86_64_TLSGD, EM_X86_64));
        assert!(x86_reloc_is_tls(R_X86_64_TPOFF64, EM_X86_64));
        assert!(!x86_reloc_is_tls(R_X86_64_PC32, EM_X86_64));
        assert!(x86_reloc_is_tls(R_386_TLS_GD, EM_386));
        assert!(!x86_reloc_is_tls(R_386_32, EM_386));
    }

    #[test]
    fn test_reloc_is_pc_relative() {
        assert!(x86_reloc_is_pc_relative(R_X86_64_PC32, EM_X86_64));
        assert!(x86_reloc_is_pc_relative(R_X86_64_PLT32, EM_X86_64));
        assert!(x86_reloc_is_pc_relative(R_X86_64_GOTPCREL, EM_X86_64));
        assert!(!x86_reloc_is_pc_relative(R_X86_64_64, EM_X86_64));
        assert!(x86_reloc_is_pc_relative(R_386_PC32, EM_386));
        assert!(!x86_reloc_is_pc_relative(R_386_32, EM_386));
    }

    // ── Dynamic Entry Tests ───────────────────────────────────────────

    #[test]
    fn test_dynamic_entry_new() {
        let e = X86DynamicEntry::new(DT_NEEDED, 5);
        assert_eq!(e.d_tag, DT_NEEDED);
        assert_eq!(e.d_val, 5);
        assert_eq!(e.tag_name(), "DT_NEEDED");
    }

    #[test]
    fn test_all_dynamic_tags_known() {
        let e = X86DynamicEntry::new(DT_SONAME, 0);
        assert_eq!(e.tag_name(), "DT_SONAME");
        let e2 = X86DynamicEntry::new(DT_RUNPATH, 0);
        assert_eq!(e2.tag_name(), "DT_RUNPATH");
        let e3 = X86DynamicEntry::new(DT_FLAGS_1, 0);
        assert_eq!(e3.tag_name(), "DT_FLAGS_1");
        let e4 = X86DynamicEntry::new(999999, 0);
        assert_eq!(e4.tag_name(), "UNKNOWN");
    }

    // ── Note Tests ────────────────────────────────────────────────────

    #[test]
    fn test_note_build_id() {
        let id = vec![0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe];
        let note = X86Note::new_build_id(&id);
        assert_eq!(note.n_name, ELF_NOTE_GNU);
        assert_eq!(note.n_type, NT_GNU_BUILD_ID);
        assert_eq!(note.n_desc, id);
        assert_eq!(note.type_name(), "NT_GNU_BUILD_ID");
    }

    #[test]
    fn test_note_abi_tag() {
        let note = X86Note::new_abi_tag(0, 3, 2, 1);
        assert_eq!(note.n_name, ELF_NOTE_GNU);
        assert_eq!(note.n_type, NT_GNU_ABI_TAG);
        assert_eq!(note.type_name(), "NT_GNU_ABI_TAG");
        assert_eq!(note.n_desc.len(), 16);
    }

    #[test]
    fn test_note_gold_version() {
        let note = X86Note::new_gold_version("1.16");
        assert_eq!(note.n_name, ELF_NOTE_GNU);
        assert_eq!(note.n_type, NT_GNU_GOLD_VERSION);
        assert_eq!(note.type_name(), "NT_GNU_GOLD_VERSION");
        assert_eq!(note.n_desc, b"1.16".to_vec());
    }

    // ── Hash Table Tests ──────────────────────────────────────────────

    #[test]
    fn test_elf_hash_computation() {
        let h1 = elf_hash("main");
        let h2 = elf_hash("main");
        assert_eq!(h1, h2);
        assert!(elf_hash("") == 0 || elf_hash("") != 0);
    }

    #[test]
    fn test_elf_gnu_hash_computation() {
        let h1 = elf_gnu_hash("printf");
        let h2 = elf_gnu_hash("printf");
        assert_eq!(h1, h2);
        assert!(elf_gnu_hash("x") != 0);
    }

    #[test]
    fn test_elf_hash_different_names() {
        assert_ne!(elf_hash("foo"), elf_hash("bar"));
    }

    #[test]
    fn test_elf_gnu_hash_different_names() {
        assert_ne!(elf_gnu_hash("foo"), elf_gnu_hash("bar"));
    }

    #[test]
    fn test_hash_table_new() {
        let ht = X86HashTable::new(8, 20);
        assert_eq!(ht.nbucket, 8);
        assert_eq!(ht.nchain, 20);
        assert_eq!(ht.buckets.len(), 8);
        assert_eq!(ht.chains.len(), 20);
    }

    #[test]
    fn test_hash_table_lookup_empty() {
        let ht = X86HashTable::new(4, 4);
        assert_eq!(ht.lookup(100, |_| Some(100)), None);
    }

    #[test]
    fn test_gnu_hash_table_new() {
        let ght = X86GnuHashTable::new(8, 0, 4, 5);
        assert_eq!(ght.nbuckets, 8);
        assert_eq!(ght.symoffset, 0);
        assert_eq!(ght.bloom_size, 4);
        assert_eq!(ght.bloom_shift, 5);
    }

    #[test]
    fn test_gnu_hash_table_lookup_empty() {
        let ght = X86GnuHashTable::new(8, 0, 0, 5);
        assert_eq!(ght.lookup(100, |_| Some(100)), None);
    }

    // ── Version Definition Tests ──────────────────────────────────────

    #[test]
    fn test_verdef_new() {
        let vd = X86Verdef::new(1, elf_hash("GLIBC_2.0"), "GLIBC_2.0");
        assert_eq!(vd.vd_version, 1);
        assert_eq!(vd.vd_ndx, 1);
        assert_eq!(vd.version_name, "GLIBC_2.0");
    }

    #[test]
    fn test_verneed_new() {
        let mut vn = X86Verneed::new("libc.so.6");
        assert_eq!(vn.file_name, "libc.so.6");
        assert_eq!(vn.vn_cnt, 0);
        vn.add_needed(elf_hash("GLIBC_2.0"), 0, 2, "GLIBC_2.0");
        assert_eq!(vn.vn_cnt, 1);
        assert_eq!(vn.needed_versions.len(), 1);
        assert_eq!(vn.needed_versions[0].vna_name, "GLIBC_2.0");
    }

    // ── COMDAT Tests ──────────────────────────────────────────────────

    #[test]
    fn test_comdat_group() {
        let mut cg = X86ComdatGroup::new(".group1", 2);
        assert_eq!(cg.name, ".group1");
        assert_eq!(cg.signature, 2);
        cg.add_member(3);
        cg.add_member(4);
        assert_eq!(cg.member_sections.len(), 2);
    }

    // ── Compressed Section Tests ──────────────────────────────────────

    #[test]
    fn test_compressed_section() {
        let cs = X86CompressedSection::new(ELFCOMPRESS_ZLIB, 1024, 16, vec![1, 2, 3]);
        assert!(cs.is_zlib());
        assert!(!cs.is_zstd());
        assert_eq!(cs.ch_size, 1024);
        assert_eq!(cs.ch_addralign, 16);
        assert_eq!(cs.decompressed_data.len(), 3);
    }

    #[test]
    fn test_compressed_section_zstd() {
        let cs = X86CompressedSection::new(ELFCOMPRESS_ZSTD, 2048, 8, vec![]);
        assert!(cs.is_zstd());
        assert!(!cs.is_zlib());
    }

    // ── X86ELFDeep Tests ──────────────────────────────────────────────

    #[test]
    fn test_x86_elf_deep_new() {
        let elf = X86ELFDeep::new();
        assert_eq!(elf.header.e_machine, EM_X86_64);
        assert!(elf.valid);
        assert!(elf.errors.is_empty());
        assert!(elf.warnings.is_empty());
    }

    #[test]
    fn test_x86_elf_deep_i386() {
        let elf = X86ELFDeep::new_i386();
        assert_eq!(elf.header.e_machine, EM_386);
        assert!(!elf.header.ident.is_64bit());
    }

    #[test]
    fn test_validate_empty_elf() {
        let mut elf = X86ELFDeep::new();
        assert!(elf.validate());
    }

    #[test]
    fn test_validate_invalid_magic() {
        let mut elf = X86ELFDeep::new();
        elf.header.ident.magic = [0x00, 0x00, 0x00, 0x00];
        assert!(!elf.validate());
        assert!(!elf.errors.is_empty());
    }

    #[test]
    fn test_validate_exec_no_load() {
        let mut elf = X86ELFDeep::new();
        elf.header.e_type = ET_EXEC;
        assert!(!elf.validate());
    }

    #[test]
    fn test_validate_exec_with_load_no_interp() {
        let mut elf = X86ELFDeep::new();
        elf.header.e_type = ET_EXEC;
        elf.program_headers
            .push(X86ProgramHeader::new_load(0x400000, 0, 0x100, 0x100, PF_R | PF_X));
        assert!(elf.validate());
    }

    #[test]
    fn test_parse_minimal_elf64() {
        let data = make_minimal_elf64_data();
        let mut elf = X86ELFDeep::new();
        assert!(elf.parse(&data).is_ok());
        assert_eq!(elf.header.e_machine, EM_X86_64);
    }

    #[test]
    fn test_parse_minimal_elf32() {
        let data = make_minimal_elf32_data();
        let mut elf = X86ELFDeep::new_i386();
        assert!(elf.parse(&data).is_ok());
        assert_eq!(elf.header.e_machine, EM_386);
    }

    #[test]
    fn test_parse_too_short() {
        let data = vec![0u8; 10];
        let mut elf = X86ELFDeep::new();
        assert!(elf.parse(&data).is_err());
    }

    #[test]
    fn test_parse_bad_magic() {
        let mut data = make_minimal_elf64_data();
        data[0] = 0x00;
        let mut elf = X86ELFDeep::new();
        assert!(elf.parse(&data).is_err());
    }

    #[test]
    fn test_elf_report() {
        let elf = X86ELFDeep::new();
        let report = elf.report();
        assert!(report.contains("X86 ELF Deep Report"));
        assert!(report.contains("x86_64"));
        assert!(report.contains("Valid: true"));
    }

    #[test]
    fn test_find_symbol() {
        let mut elf = X86ELFDeep::new();
        elf.symbols
            .push(X86Symbol::new("main", x86_st_info(STB_GLOBAL, STT_FUNC), 1, 0x4000, 0x50));
        assert!(elf.find_symbol("main").is_some());
        assert!(elf.find_symbol("nonexistent").is_none());
    }

    #[test]
    fn test_find_dynamic_symbol() {
        let mut elf = X86ELFDeep::new();
        elf.dynamic_symbols
            .push(X86Symbol::new("printf", x86_st_info(STB_GLOBAL, STT_FUNC), 0, 0, 0));
        assert!(elf.find_dynamic_symbol("printf").is_some());
        assert!(elf.find_dynamic_symbol("nonexistent").is_none());
    }

    #[test]
    fn test_symbols_by_type() {
        let mut elf = X86ELFDeep::new();
        elf.symbols.push(X86Symbol::new(
            "f1",
            x86_st_info(STB_GLOBAL, STT_FUNC),
            1,
            0x1000,
            0x10,
        ));
        elf.symbols.push(X86Symbol::new(
            "f2",
            x86_st_info(STB_GLOBAL, STT_FUNC),
            2,
            0x2000,
            0x20,
        ));
        elf.symbols.push(X86Symbol::new(
            "obj1",
            x86_st_info(STB_GLOBAL, STT_OBJECT),
            3,
            0x3000,
            0x30,
        ));
        let funcs = elf.symbols_by_type(STT_FUNC);
        assert_eq!(funcs.len(), 2);
        let objs = elf.symbols_by_type(STT_OBJECT);
        assert_eq!(objs.len(), 1);
    }

    #[test]
    fn test_symbols_by_binding() {
        let mut elf = X86ELFDeep::new();
        elf.symbols.push(X86Symbol::new(
            "local1",
            x86_st_info(STB_LOCAL, STT_OBJECT),
            0,
            0,
            0,
        ));
        elf.symbols.push(X86Symbol::new(
            "global1",
            x86_st_info(STB_GLOBAL, STT_FUNC),
            0,
            0,
            0,
        ));
        assert_eq!(elf.symbols_by_binding(STB_LOCAL).len(), 1);
        assert_eq!(elf.symbols_by_binding(STB_GLOBAL).len(), 1);
    }

    #[test]
    fn test_exported_symbols() {
        let mut elf = X86ELFDeep::new();
        elf.symbols.push(X86Symbol::new(
            "exported",
            x86_st_info(STB_GLOBAL, STT_FUNC),
            1,
            0x4000,
            0x10,
        ));
        elf.symbols.push(X86Symbol::new(
            "hidden",
            x86_st_info(STB_LOCAL, STT_OBJECT),
            2,
            0x5000,
            0x10,
        ));
        elf.symbols.push(X86Symbol::new(
            "undef_global",
            x86_st_info(STB_GLOBAL, STT_NOTYPE),
            SHN_UNDEF,
            0,
            0,
        ));
        let exported = elf.exported_symbols();
        assert_eq!(exported.len(), 1);
        assert_eq!(exported[0].name, "exported");
    }

    #[test]
    fn test_relocation_types_used() {
        let mut elf = X86ELFDeep::new();
        elf.relocations
            .push(X86Relocation::new(0, R_X86_64_PC32, 0, 0));
        elf.relocations
            .push(X86Relocation::new(8, R_X86_64_64, 0, 0));
        elf.relocations
            .push(X86Relocation::new(16, R_X86_64_PC32, 0, 0));
        let types = elf.relocation_types_used();
        assert_eq!(types.len(), 2);
        assert!(types.contains(&R_X86_64_PC32));
        assert!(types.contains(&R_X86_64_64));
    }

    #[test]
    fn test_relocation_type_counts() {
        let mut elf = X86ELFDeep::new();
        elf.relocations
            .push(X86Relocation::new(0, R_X86_64_PC32, 0, 0));
        elf.relocations
            .push(X86Relocation::new(8, R_X86_64_PC32, 0, 0));
        elf.relocations
            .push(X86Relocation::new(16, R_X86_64_64, 0, 0));
        let counts = elf.relocation_type_counts();
        assert_eq!(counts.get(&R_X86_64_PC32), Some(&2));
        assert_eq!(counts.get(&R_X86_64_64), Some(&1));
    }

    #[test]
    fn test_dynamic_operations() {
        let mut elf = X86ELFDeep::new();
        elf.dynamic_entries
            .push(X86DynamicEntry::new(DT_NEEDED, 1));
        elf.dynamic_entries
            .push(X86DynamicEntry::new(DT_FLAGS, DF_BIND_NOW | DF_TEXTREL));
        elf.dynamic_entries
            .push(X86DynamicEntry::new(DT_FLAGS_1, DF_1_PIE));
        assert_eq!(elf.get_dynamic(DT_NEEDED), Some(1));
        assert!(elf.has_dynamic_flag(DF_BIND_NOW));
        assert!(elf.has_dynamic_flag_1(DF_1_PIE));
        assert!(!elf.has_dynamic_flag_1(DF_1_NOW));
    }

    #[test]
    fn test_total_load_size() {
        let mut elf = X86ELFDeep::new();
        elf.program_headers
            .push(X86ProgramHeader::new_load(0, 0, 0x100, 0x200, PF_R));
        elf.program_headers
            .push(X86ProgramHeader::new_load(0, 0x100, 0x300, 0x300, PF_R | PF_W));
        assert_eq!(elf.total_load_size(), 0x200 + 0x300);
    }

    #[test]
    fn test_read_strtab() {
        let tab = b"hello\0world\0";
        assert_eq!(read_strtab(tab, 0), "hello");
        assert_eq!(read_strtab(tab, 6), "world");
        assert_eq!(read_strtab(tab, 100), "");
    }

    #[test]
    fn test_x86_st_info() {
        let info = x86_st_info(STB_GLOBAL, STT_FUNC);
        assert_eq!(info >> 4, STB_GLOBAL);
        assert_eq!(info & 0x0f, STT_FUNC);
    }

    #[test]
    fn test_x86_st_other() {
        assert_eq!(x86_st_other(STV_HIDDEN), STV_HIDDEN);
        assert_eq!(x86_st_other(STV_PROTECTED), STV_PROTECTED);
    }

    #[test]
    fn test_elf64_r_info_roundtrip() {
        let (sym, typ) = x86_elf64_r_info(x86_elf64_r_info_encode(42, R_X86_64_PC32));
        assert_eq!(sym, 42);
        assert_eq!(typ, R_X86_64_PC32);
    }

    #[test]
    fn test_elf32_r_info_roundtrip() {
        let (sym, typ) = x86_elf32_r_info(x86_elf32_r_info_encode(42, R_386_PC32));
        assert_eq!(sym, 42);
        assert_eq!(typ, R_386_PC32);
    }

    #[test]
    fn test_elf_class_from_ident() {
        assert_eq!(
            X86ElfClass::from_ident(ELFCLASS64),
            X86ElfClass::Elf64
        );
        assert_eq!(
            X86ElfClass::from_ident(ELFCLASS32),
            X86ElfClass::Elf32
        );
    }

    #[test]
    fn test_default_elf_deep() {
        let elf = X86ELFDeep::default();
        assert_eq!(elf.header.e_machine, EM_X86_64);
    }

    #[test]
    fn test_hash_table_lookup_finds_value() {
        let mut ht = X86HashTable::new(4, 4);
        let h = elf_hash("test");
        ht.buckets[(h % 4) as usize] = 0;
        ht.chains[0] = 3; // end marker but no match
        assert_eq!(ht.lookup(h, |_| Some(999)), None);
    }

    #[test]
    fn test_all_reloc_names_coverage() {
        for rt in 0..50u32 {
            let name = x86_64_reloc_name(rt);
            assert!(!name.is_empty());
        }
        for rt in 0..50u32 {
            let name = i386_reloc_name(rt);
            assert!(!name.is_empty());
        }
    }

    #[test]
    fn test_parse_with_section_headers() {
        let mut data = vec![0u8; 256];
        data[0..4].copy_from_slice(&ELF_MAGIC_BYTES);
        data[EI_CLASS] = ELFCLASS64;
        data[EI_DATA] = ELFDATA2LSB;
        data[EI_VERSION] = 1;
        data[16..18].copy_from_slice(&ET_REL.to_le_bytes());
        data[18..20].copy_from_slice(&EM_X86_64.to_le_bytes());
        data[20..24].copy_from_slice(&1u32.to_le_bytes());
        data[52..54].copy_from_slice(&64u16.to_le_bytes());
        data[58..60].copy_from_slice(&64u16.to_le_bytes());
        // e_shoff = 120, e_shnum = 2, e_shstrndx = 1
        data[40..48].copy_from_slice(&120u64.to_le_bytes());
        data[60..62].copy_from_slice(&2u16.to_le_bytes());
        data[62..64].copy_from_slice(&1u16.to_le_bytes());
        // Section 0 at offset 120: all zeros
        // Section 1 at offset 184: SHT_STRTAB (type=3)
        data[184..188].copy_from_slice(&3u32.to_le_bytes()); // sh_type = SHT_STRTAB
        data[188..192].copy_from_slice(&0u32.to_le_bytes()); // sh_name = 0
        data[200..208].copy_from_slice(&0u64.to_le_bytes()); // sh_offset = 0
        data[208..216].copy_from_slice(&10u64.to_le_bytes()); // sh_size = 10
        data[216..220].copy_from_slice(&0u32.to_le_bytes()); // sh_link

        let mut elf = X86ELFDeep::new();
        assert!(elf.parse(&data).is_ok());
    }

    #[test]
    fn test_all_phdr_types_covered() {
        let types = [
            PT_NULL,
            PT_LOAD,
            PT_DYNAMIC,
            PT_INTERP,
            PT_NOTE,
            PT_SHLIB,
            PT_PHDR,
            PT_TLS,
            PT_GNU_EH_FRAME,
            PT_GNU_STACK,
            PT_GNU_RELRO,
            PT_GNU_PROPERTY,
        ];
        for t in &types {
            let mut ph = X86ProgramHeader::new_load(0, 0, 0, 0, 0);
            ph.p_type = *t;
            let name = ph.type_name();
            assert!(!name.is_empty());
            assert_ne!(name, "UNKNOWN");
        }
    }

    #[test]
    fn test_section_flags_string_exhaustive() {
        let all_flags = SHF_WRITE
            | SHF_ALLOC
            | SHF_EXECINSTR
            | SHF_MERGE
            | SHF_STRINGS
            | SHF_GROUP
            | SHF_TLS
            | SHF_COMPRESSED
            | SHF_EXCLUDE;
        let sh = X86SectionHeader::new("test", SHT_PROGBITS, all_flags, 0, 0);
        let fs = sh.flags_string();
        assert!(fs.contains('W'));
        assert!(fs.contains('A'));
        assert!(fs.contains('X'));
        assert!(fs.contains('M'));
        assert!(fs.contains('S'));
        assert!(fs.contains('G'));
        assert!(fs.contains('T'));
        assert!(fs.contains('C'));
        assert!(fs.contains('E'));
    }

    #[test]
    fn test_build_gnu_hash_empty() {
        let mut elf = X86ELFDeep::new();
        elf.build_gnu_hash(8, 0, 5);
        assert!(elf.gnu_hash_table.is_some());
    }

    #[test]
    fn test_build_gnu_hash_with_symbols() {
        let mut elf = X86ELFDeep::new();
        elf.dynamic_symbols.push(X86Symbol::new(
            "sym1",
            x86_st_info(STB_GLOBAL, STT_FUNC),
            0,
            0,
            0,
        ));
        elf.dynamic_symbols.push(X86Symbol::new(
            "sym2",
            x86_st_info(STB_GLOBAL, STT_FUNC),
            0,
            0,
            0,
        ));
        elf.build_gnu_hash(4, 0, 5);
        assert!(elf.gnu_hash_table.is_some());
        let ght = elf.gnu_hash_table.as_ref().unwrap();
        assert_eq!(ght.nbuckets, 4);
    }

    #[test]
    fn test_arm_exidx_entry() {
        let entry = ArmExidxEntry::new(0x1000, 0x80b0a8b2);
        assert_eq!(entry.addr, 0x1000);
        assert_eq!(entry.data, 0x80b0a8b2);
    }

    #[test]
    fn test_all_shflags_constant() {
        assert_eq!(ALL_SHFLAGS.len(), 12);
        for (flag, name) in ALL_SHFLAGS {
            assert!(*flag > 0);
            assert!(!name.is_empty());
        }
    }

    #[test]
    fn test_all_dynamic_tags_constant() {
        assert!(ALL_DYNAMIC_TAGS.len() > 40);
        for (tag, name) in ALL_DYNAMIC_TAGS {
            assert!(*tag > 0 || *tag == DT_NULL);
            assert!(!name.is_empty());
        }
    }

    #[test]
    fn test_elf_deep_no_panic_on_edge_cases() {
        let mut elf = X86ELFDeep::new();
        // Various operations on empty state should not panic
        assert!(elf.find_symbol("foo").is_none());
        assert!(elf.find_dynamic_symbol("bar").is_none());
        assert_eq!(elf.symbols_by_type(STT_FUNC).len(), 0);
        assert_eq!(elf.exported_symbols().len(), 0);
        assert_eq!(elf.relocation_types_used().len(), 0);
        assert!(elf.get_dynamic(DT_NEEDED).is_none());
        assert!(!elf.has_dynamic_flag(DF_BIND_NOW));
        assert_eq!(elf.total_load_size(), 0);
    }

    #[test]
    fn test_parse_empty_program_headers() {
        let data = make_minimal_elf64_data();
        let mut elf = X86ELFDeep::new();
        elf.parse(&data).unwrap();
        assert!(elf.program_headers.is_empty());
    }

    #[test]
    fn test_all_phdr_constructors() {
        let ph = X86ProgramHeader::new_load(0, 0, 0, 0, 0);
        assert_eq!(ph.p_type, PT_LOAD);
        let ph = X86ProgramHeader::new_dynamic(0, 0);
        assert_eq!(ph.p_type, PT_DYNAMIC);
        let ph = X86ProgramHeader::new_interp(0, 0);
        assert_eq!(ph.p_type, PT_INTERP);
        let ph = X86ProgramHeader::new_note(0, 0);
        assert_eq!(ph.p_type, PT_NOTE);
        let ph = X86ProgramHeader::new_tls(0, 0, 0, 0);
        assert_eq!(ph.p_type, PT_TLS);
        let ph = X86ProgramHeader::new_gnu_stack(0, 0);
        assert_eq!(ph.p_type, PT_GNU_STACK);
        let ph = X86ProgramHeader::new_gnu_relro(0, 0);
        assert_eq!(ph.p_type, PT_GNU_RELRO);
        let ph = X86ProgramHeader::new_gnu_eh_frame(0, 0);
        assert_eq!(ph.p_type, PT_GNU_EH_FRAME);
        let ph = X86ProgramHeader::new_gnu_property(0, 0);
        assert_eq!(ph.p_type, PT_GNU_PROPERTY);
    }

    #[test]
    fn test_reloc_needs_got_exhaustive() {
        let got_types = [
            R_X86_64_GOT32,
            R_X86_64_GOTPCREL,
            R_X86_64_GOTTPOFF,
            R_X86_64_GOTPCRELX,
            R_X86_64_REX_GOTPCRELX,
            R_X86_64_GOTPC32_TLSDESC,
        ];
        for t in &got_types {
            assert!(x86_reloc_needs_got_x86_64(*t));
        }
        let non_got_types = [R_X86_64_PC32, R_X86_64_64, R_X86_64_COPY, R_X86_64_JUMP_SLOT];
        for t in &non_got_types {
            assert!(!x86_reloc_needs_got_x86_64(*t));
        }
    }

    #[test]
    fn test_phdr_type_name_many() {
        // Every common type should return non-empty
        let types = &[
            PT_NULL,
            PT_LOAD,
            PT_DYNAMIC,
            PT_INTERP,
            PT_NOTE,
            PT_SHLIB,
            PT_PHDR,
            PT_TLS,
            PT_GNU_EH_FRAME,
            PT_GNU_STACK,
            PT_GNU_RELRO,
            PT_GNU_PROPERTY,
        ];
        for t in types {
            let ph = X86ProgramHeader {
                p_type: *t,
                p_flags: 0,
                p_offset: 0,
                p_vaddr: 0,
                p_paddr: 0,
                p_filesz: 0,
                p_memsz: 0,
                p_align: 0,
            };
            let tn = ph.type_name();
            assert!(!tn.is_empty(), "Empty type_name for p_type={}", t);
        }
    }
}