llvm-native-core-ext 0.1.0

Extended modules for llvm-native-core: analysis passes, transforms, codegen extras, bitcode, linker, JIT, utilities. Part of the llvm-native workspace (https://crates.io/crates/llvm-native).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
//! LLVM Object Files — read/write object files in multiple formats.
//! Phase 3 — LLVM.OBJECT.1 Court.
//!
//! Supports:
//! - ELF header parsing (magic, class, endianness, machine, entry point)
//! - ELF section header parsing
//! - ELF symbol table parsing
//! - ELF relocation parsing
//! - ELF program header parsing
//! - ELF dynamic section parsing
//! - ELF note section parsing
//! - Mach-O parsing (header, load commands, sections, symbols)
//! - COFF/PE parsing (header, sections, symbols)
//! - Wasm detection
//! - Universal ObjectFile representation
//! - Basic disassembly helpers

use std::collections::HashMap;

// ============================================================================
// ELF Constants
// ============================================================================

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

/// Mach-O 64-bit magic
pub const MACHO_MAGIC_64: u32 = 0xFEEDFACF;
/// Mach-O 32-bit magic
pub const MACHO_MAGIC_32: u32 = 0xFEEDFACE;
/// Mach-O fat binary magic
pub const MACHO_FAT_MAGIC: u32 = 0xCAFEBABE;
/// Mach-O fat binary magic (reverse endian)
pub const MACHO_FAT_CIGAM: u32 = 0xBEBAFECA;

/// COFF/PE magic
pub const COFF_MAGIC_PE: u16 = 0x5A4D; // "MZ"

/// Wasm magic
pub const WASM_MAGIC: [u8; 4] = [0x00, 0x61, 0x73, 0x6D]; // \0asm

// ============================================================================
// ELF Type Definitions
// ============================================================================

/// ELF class: 32-bit or 64-bit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ElfClass {
    Elf32,
    Elf64,
}

/// ELF endianness.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ElfEndian {
    Little,
    Big,
}

/// ELF OS/ABI.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ElfOsAbi {
    SystemV,
    Linux,
    None,
}

/// ELF machine type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ElfMachine {
    X86_64,
    AArch64,
    ARM,
    X86,
    RiscV,
    None,
}

/// ELF identification header (e_ident[16]).
#[derive(Debug, Clone)]
pub struct ElfIdent {
    pub class: ElfClass,
    pub endian: ElfEndian,
    pub version: u8,
    pub os_abi: ElfOsAbi,
    pub abi_version: u8,
}

/// ELF header.
#[derive(Debug, Clone)]
pub struct ElfHeader {
    pub ident: ElfIdent,
    pub obj_type: u16,
    pub machine: ElfMachine,
    pub version: u32,
    pub entry: u64,
    pub phoff: u64, // program header offset
    pub shoff: u64, // section header offset
    pub flags: u32,
    pub ehsize: u16,    // ELF header size
    pub phentsize: u16, // program header entry size
    pub phnum: u16,     // program header count
    pub shentsize: u16, // section header entry size
    pub shnum: u16,     // section header count
    pub shstrndx: u16,  // section name string table index
}

/// ELF section header.
#[derive(Debug, Clone)]
pub struct ElfSectionHeader {
    pub name: String,
    pub sh_type: u32,
    pub flags: u64,
    pub addr: u64,
    pub offset: u64,
    pub size: u64,
    pub link: u32,
    pub info: u32,
    pub addralign: u64,
    pub entsize: u64,
}

/// ELF symbol.
#[derive(Debug, Clone)]
pub struct ElfSymbol {
    pub name: String,
    pub value: u64,
    pub size: u64,
    pub sym_type: u8,
    pub binding: u8,
    pub section_index: u16,
}

/// ELF relocation entry (RELA format, 64-bit).
#[derive(Debug, Clone)]
pub struct ElfRelocation {
    pub offset: u64,
    pub sym_index: u32,
    pub rel_type: u32,
    pub addend: i64,
}

/// ELF program header (segment).
#[derive(Debug, Clone)]
pub struct ElfProgramHeader {
    pub p_type: u32,
    pub flags: u32,
    pub offset: u64,
    pub vaddr: u64,
    pub paddr: u64,
    pub filesz: u64,
    pub memsz: u64,
    pub align: u64,
}

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

/// ELF note entry.
#[derive(Debug, Clone)]
pub struct ElfNote {
    pub name: String,
    pub desc_type: u32,
    pub desc: Vec<u8>,
}

// ============================================================================
// Mach-O Type Definitions
// ============================================================================

/// Mach-O header (32-bit or 64-bit).
#[derive(Debug, Clone)]
pub struct MachOHeader {
    pub magic: u32,
    pub cputype: u32,
    pub cpusubtype: u32,
    pub filetype: u32,
    pub ncmds: u32,
    pub sizeofcmds: u32,
    pub flags: u32,
    /// Present only for 64-bit (reserved field)
    pub reserved: u32,
}

/// Mach-O segment command (LC_SEGMENT_64).
#[derive(Debug, Clone)]
pub struct MachSegment {
    pub segname: String,
    pub vmaddr: u64,
    pub vmsize: u64,
    pub fileoff: u64,
    pub filesize: u64,
    pub maxprot: u32,
    pub initprot: u32,
    pub nsects: u32,
    pub flags: u32,
}

/// Mach-O section (within a segment).
#[derive(Debug, Clone)]
pub struct MachOSectionData {
    pub sectname: String,
    pub segname: String,
    pub addr: u64,
    pub size: u64,
    pub offset: u32,
    pub align: u32,
    pub reloff: u32,
    pub nreloc: u32,
    pub flags: u32,
    pub data: Vec<u8>,
}

/// Mach-O symtab command.
#[derive(Debug, Clone)]
pub struct MachSymtabCmd {
    pub symoff: u32,
    pub nsyms: u32,
    pub stroff: u32,
    pub strsize: u32,
}

/// Mach-O dysymtab command.
#[derive(Debug, Clone)]
pub struct MachDysymtabCmd {
    pub ilocalsym: u32,
    pub nlocalsym: u32,
    pub iextdefsym: u32,
    pub nextdefsym: u32,
    pub iundefsym: u32,
    pub nundefsym: u32,
}

/// Mach-O UUID command.
#[derive(Debug, Clone)]
pub struct MachUuidCmd {
    pub uuid: [u8; 16],
}

/// Mach-O version min command.
#[derive(Debug, Clone)]
pub struct MachVersionMinCmd {
    pub cmd: u32,
    pub version: u32,
    pub sdk: u32,
}

/// Mach-O load command variants.
#[derive(Debug, Clone)]
pub enum MachOLoadCommand {
    Segment(MachSegment),
    Symtab(MachSymtabCmd),
    Dysymtab(MachDysymtabCmd),
    Uuid(MachUuidCmd),
    VersionMinMacosx(MachVersionMinCmd),
    VersionMinIphoneos(MachVersionMinCmd),
    Unknown {
        cmd: u32,
        cmdsize: u32,
        data: Vec<u8>,
    },
}

/// Mach-O symbol (nlist_64).
#[derive(Debug, Clone)]
pub struct MachOSymbol {
    pub name: String,
    pub n_type: u8,
    pub n_sect: u8,
    pub n_desc: u16,
    pub n_value: u64,
}

// ============================================================================
// COFF/PE Type Definitions
// ============================================================================

/// COFF header.
#[derive(Debug, Clone)]
pub struct CoffHeader {
    pub machine: u16,
    pub num_sections: u16,
    pub timestamp: u32,
    pub symtab_offset: u32,
    pub num_symbols: u32,
    pub opt_header_size: u16,
    pub characteristics: u16,
}

/// COFF section header.
#[derive(Debug, Clone)]
pub struct CoffSectionHeader {
    pub name: String,
    pub virtual_size: u32,
    pub virtual_address: u32,
    pub raw_data_size: u32,
    pub raw_data_ptr: u32,
    pub reloc_ptr: u32,
    pub linenum_ptr: u32,
    pub num_relocs: u16,
    pub num_linenums: u16,
    pub characteristics: u32,
}

/// COFF symbol.
#[derive(Debug, Clone)]
pub struct CoffSymbol {
    pub name: String,
    pub value: u32,
    pub section_number: i16,
    pub sym_type: u16,
    pub storage_class: u8,
    pub num_aux: u8,
}

/// COFF relocation.
#[derive(Debug, Clone)]
pub struct CoffRelocation {
    pub virtual_address: u32,
    pub symbol_index: u32,
    pub rel_type: u16,
}

// ============================================================================
// Universal Object Format Enum
// ============================================================================

/// Universal object file format identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ObjectFormat {
    ELF32,
    ELF64,
    MachO32,
    MachO64,
    COFF,
    PE,
    Wasm,
    Unknown,
}

/// Auto-detect the object file format from magic bytes.
pub fn detect_format(data: &[u8]) -> Option<ObjectFormat> {
    if data.len() < 4 {
        return None;
    }

    // ELF: 0x7F 'E' 'L' 'F'
    if data[0..4] == ELF_MAGIC {
        if data.len() >= 5 {
            match data[4] {
                1 => return Some(ObjectFormat::ELF32),
                2 => return Some(ObjectFormat::ELF64),
                _ => return Some(ObjectFormat::ELF64),
            }
        }
        return Some(ObjectFormat::ELF64);
    }

    // Mach-O magic numbers
    if data.len() >= 4 {
        let magic = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
        match magic {
            MACHO_MAGIC_64 => return Some(ObjectFormat::MachO64),
            MACHO_MAGIC_32 => return Some(ObjectFormat::MachO32),
            MACHO_FAT_MAGIC | MACHO_FAT_CIGAM => return Some(ObjectFormat::MachO64),
            _ => {}
        }
        // Big-endian Mach-O
        let magic_be = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
        match magic_be {
            MACHO_MAGIC_64 => return Some(ObjectFormat::MachO64),
            MACHO_MAGIC_32 => return Some(ObjectFormat::MachO32),
            _ => {}
        }
    }

    // Wasm: \0asm
    if data.len() >= 4 && data[0..4] == WASM_MAGIC {
        return Some(ObjectFormat::Wasm);
    }

    // COFF/PE: "MZ" magic
    if data.len() >= 2 && data[0] == 0x4D && data[1] == 0x5A {
        return Some(ObjectFormat::PE);
    }

    // COFF object file: starts with machine type (0x8664, 0xAA64, 0x14C, etc.)
    if data.len() >= 2 {
        let machine = u16::from_le_bytes([data[0], data[1]]);
        match machine {
            0x8664 | 0xAA64 | 0x14C | 0x1C0 | 0x1C4 | 0x200 | 0x166 | 0x1F0 => {
                return Some(ObjectFormat::COFF);
            }
            _ => {}
        }
    }

    None
}

// ============================================================================
// Universal Object File Representation
// ============================================================================

/// A universal object file that can represent any format.
#[derive(Debug, Clone)]
pub struct ObjectFile {
    pub format: ObjectFormat,
    pub machine: String,
    pub sections: Vec<ObjectSection>,
    pub symbols: Vec<ObjectSymbol>,
    pub entry: u64,
    pub flags: u32,
}

/// A universal object section.
#[derive(Debug, Clone)]
pub struct ObjectSection {
    pub name: String,
    pub section_type: u32,
    pub data: Vec<u8>,
    pub vaddr: u64,
    pub size: u64,
    pub flags: u64,
}

/// A universal object symbol.
#[derive(Debug, Clone)]
pub struct ObjectSymbol {
    pub name: String,
    pub value: u64,
    pub size: u64,
    pub is_global: bool,
    pub is_function: bool,
    pub section_index: u16,
}

/// A disassembled instruction.
#[derive(Debug, Clone)]
pub struct DisassembledInst {
    pub address: u64,
    pub bytes: Vec<u8>,
    pub mnemonic: String,
    pub operands: String,
}

impl ObjectFile {
    /// Parse an object file from raw bytes, auto-detecting the format.
    pub fn parse(bytes: &[u8]) -> Option<Self> {
        let format = detect_format(bytes)?;
        match format {
            ObjectFormat::ELF32 | ObjectFormat::ELF64 => Self::parse_elf(bytes),
            ObjectFormat::MachO32 | ObjectFormat::MachO64 => Self::parse_macho(bytes),
            ObjectFormat::COFF | ObjectFormat::PE => Self::parse_coff(bytes),
            ObjectFormat::Wasm => Self::parse_wasm(bytes),
            ObjectFormat::Unknown => None,
        }
    }

    // === Format-specific Parsers ===

    /// Parse an ELF object file.
    fn parse_elf(bytes: &[u8]) -> Option<Self> {
        let header = Self::parse_elf_header(bytes)?;
        let machine = match header.machine {
            ElfMachine::X86_64 => "x86_64",
            ElfMachine::AArch64 => "aarch64",
            ElfMachine::ARM => "arm",
            ElfMachine::X86 => "x86",
            ElfMachine::RiscV => "riscv",
            ElfMachine::None => "unknown",
        };

        let class = match header.ident.class {
            ElfClass::Elf32 => ObjectFormat::ELF32,
            ElfClass::Elf64 => ObjectFormat::ELF64,
        };

        let mut sections = Vec::new();
        let mut symbols = Vec::new();

        // Parse section headers
        if let Ok(elf_sections) = Self::parse_elf_sections(bytes) {
            for sec in &elf_sections {
                let data = if sec.sh_type == sht::NOBITS {
                    Vec::new()
                } else if sec.offset > 0 && (sec.offset as usize) < bytes.len() {
                    let end = std::cmp::min((sec.offset + sec.size) as usize, bytes.len());
                    bytes[sec.offset as usize..end].to_vec()
                } else {
                    Vec::new()
                };

                sections.push(ObjectSection {
                    name: sec.name.clone(),
                    section_type: sec.sh_type,
                    data,
                    vaddr: sec.addr,
                    size: sec.size,
                    flags: sec.flags,
                });
            }
        }

        // Parse symbol table
        if let Ok(parsed_symbols) = Self::parse_elf_symbols(bytes) {
            for sym in parsed_symbols {
                symbols.push(ObjectSymbol {
                    name: sym.name,
                    value: sym.value,
                    size: sym.size,
                    is_global: sym.binding == stb::GLOBAL,
                    is_function: sym.sym_type == stt::FUNC,
                    section_index: sym.section_index,
                });
            }
        }

        Some(ObjectFile {
            format: class,
            machine: machine.to_string(),
            sections,
            symbols,
            entry: header.entry,
            flags: header.flags,
        })
    }

    /// Parse a Mach-O object file.
    fn parse_macho(bytes: &[u8]) -> Option<Self> {
        let header = Self::parse_macho_header(bytes).ok()?;
        let machine = match header.cputype {
            0x01000007 => "x86_64",
            0x0100000C => "arm64",
            0x0000000C => "arm",
            0x00000007 => "x86",
            _ => "unknown",
        };

        let format = match header.magic {
            MACHO_MAGIC_64 => ObjectFormat::MachO64,
            MACHO_MAGIC_32 => ObjectFormat::MachO32,
            _ => return None,
        };

        let mut sections = Vec::new();
        let mut symbols = Vec::new();

        // Parse load commands
        if let Ok(commands) = Self::parse_macho_load_commands(bytes, &header) {
            for cmd in &commands {
                match cmd {
                    MachOLoadCommand::Segment(seg) => {
                        // Parse section headers within this segment
                        let seg_sections =
                            Self::parse_macho_sections_in_segment(bytes, seg, header.ncmds);
                        for s in seg_sections {
                            sections.push(ObjectSection {
                                name: s.sectname.clone(),
                                section_type: s.flags,
                                data: s.data.clone(),
                                vaddr: s.addr,
                                size: s.size,
                                flags: s.flags as u64,
                            });
                        }
                    }
                    MachOLoadCommand::Symtab(symtab_cmd) => {
                        if let Ok(macho_syms) = Self::parse_macho_symbols(bytes, symtab_cmd) {
                            for sym in macho_syms {
                                symbols.push(ObjectSymbol {
                                    name: sym.name,
                                    value: sym.n_value,
                                    size: 0,
                                    is_global: sym.n_type & 0x0E != 0,
                                    is_function: sym.n_type & 0x0E == 0x0E,
                                    section_index: sym.n_sect as u16,
                                });
                            }
                        }
                    }
                    _ => {}
                }
            }
        }

        Some(ObjectFile {
            format,
            machine: machine.to_string(),
            sections,
            symbols,
            entry: 0,
            flags: header.flags,
        })
    }

    /// Parse a COFF object file.
    fn parse_coff(bytes: &[u8]) -> Option<Self> {
        let header = Self::parse_coff_header(bytes).ok()?;
        let machine = match header.machine {
            0x8664 => "x86_64",
            0xAA64 => "aarch64",
            0x14C => "x86",
            0x1C4 => "arm",
            _ => "unknown",
        };

        let format = ObjectFormat::COFF;

        let sections = Self::parse_coff_sections(bytes, &header).unwrap_or_default();
        let symbols = Self::parse_coff_symbols(bytes, &header).unwrap_or_default();

        let universal_sections: Vec<ObjectSection> = sections
            .into_iter()
            .map(|s| ObjectSection {
                name: s.name,
                section_type: 1,
                data: Vec::new(), // Raw data not stored by default
                vaddr: s.virtual_address as u64,
                size: s.raw_data_size as u64,
                flags: s.characteristics as u64,
            })
            .collect();

        let universal_symbols: Vec<ObjectSymbol> = symbols
            .into_iter()
            .map(|s| ObjectSymbol {
                name: s.name,
                value: s.value as u64,
                size: 0,
                is_global: s.storage_class == 2,
                is_function: s.sym_type == 0x20,
                section_index: s.section_number.max(0) as u16,
            })
            .collect();

        Some(ObjectFile {
            format,
            machine: machine.to_string(),
            sections: universal_sections,
            symbols: universal_symbols,
            entry: 0,
            flags: header.characteristics as u32,
        })
    }

    /// Parse a Wasm module (minimal stub).
    fn parse_wasm(bytes: &[u8]) -> Option<Self> {
        if bytes.len() < 8 || bytes[0..4] != WASM_MAGIC {
            return None;
        }
        let _version = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
        Some(ObjectFile {
            format: ObjectFormat::Wasm,
            machine: "wasm32".to_string(),
            sections: Vec::new(),
            symbols: Vec::new(),
            entry: 0,
            flags: 0,
        })
    }

    // === ELF Parsing Methods ===

    /// Parse an ELF header from raw bytes.
    pub fn parse_elf_header(bytes: &[u8]) -> Option<ElfHeader> {
        if bytes.len() < 64 {
            return None;
        }

        // Check magic
        if bytes[0..4] != ELF_MAGIC {
            return None;
        }

        let class = match bytes[4] {
            1 => ElfClass::Elf32,
            2 => ElfClass::Elf64,
            _ => return None,
        };
        let endian = match bytes[5] {
            1 => ElfEndian::Little,
            2 => ElfEndian::Big,
            _ => return None,
        };
        let os_abi = match bytes[7] {
            0 => ElfOsAbi::SystemV,
            3 => ElfOsAbi::Linux,
            _ => ElfOsAbi::None,
        };

        let ident = ElfIdent {
            class,
            endian,
            version: bytes[6],
            os_abi,
            abi_version: bytes[8],
        };

        // Parse header for 64-bit LE (most common)
        let obj_type = u16::from_le_bytes([bytes[16], bytes[17]]);
        let machine = match u16::from_le_bytes([bytes[18], bytes[19]]) {
            62 => ElfMachine::X86_64,
            183 => ElfMachine::AArch64,
            40 => ElfMachine::ARM,
            3 => ElfMachine::X86,
            243 => ElfMachine::RiscV,
            _ => ElfMachine::None,
        };
        let entry = u64::from_le_bytes(bytes[24..32].try_into().ok()?);
        let phoff = u64::from_le_bytes(bytes[32..40].try_into().ok()?);
        let shoff = u64::from_le_bytes(bytes[40..48].try_into().ok()?);
        let flags = u32::from_le_bytes(bytes[48..52].try_into().ok()?);
        let ehsize = u16::from_le_bytes([bytes[52], bytes[53]]);
        let phentsize = u16::from_le_bytes([bytes[54], bytes[55]]);
        let phnum = u16::from_le_bytes([bytes[56], bytes[57]]);
        let shentsize = u16::from_le_bytes([bytes[58], bytes[59]]);
        let shnum = u16::from_le_bytes([bytes[60], bytes[61]]);
        let shstrndx = u16::from_le_bytes([bytes[62], bytes[63]]);

        Some(ElfHeader {
            ident,
            obj_type,
            machine,
            version: 0,
            entry,
            phoff,
            shoff,
            flags,
            ehsize,
            phentsize,
            phnum,
            shentsize,
            shnum,
            shstrndx,
        })
    }

    /// Parse ELF section headers and their data.
    pub fn parse_elf_sections(data: &[u8]) -> Result<Vec<ElfSectionHeader>, String> {
        let header = Self::parse_elf_header(data).ok_or("Invalid ELF header")?;
        let shoff = header.shoff as usize;
        let shnum = header.shnum as usize;
        let shentsize = header.shentsize as usize;

        if shoff == 0 || shnum == 0 || shentsize == 0 {
            return Ok(Vec::new());
        }

        // Read section name string table
        let shstrndx = header.shstrndx as usize;
        let shstrtab_offset = shoff + shstrndx * shentsize;
        let shstrtab = Self::_read_section_header_raw(data, shstrtab_offset);

        let mut sections = Vec::new();

        for i in 0..shnum {
            let sec_offset = shoff + i * shentsize;
            if sec_offset + shentsize > data.len() {
                break;
            }

            let name_offset = u32::from_le_bytes([
                data[sec_offset],
                data[sec_offset + 1],
                data[sec_offset + 2],
                data[sec_offset + 3],
            ]) as usize;

            let sh_type = u32::from_le_bytes([
                data[sec_offset + 4],
                data[sec_offset + 5],
                data[sec_offset + 6],
                data[sec_offset + 7],
            ]);

            let flags = u64::from_le_bytes(
                data[sec_offset + 8..sec_offset + 16]
                    .try_into()
                    .map_err(|_| "slice error")?,
            );

            let addr = u64::from_le_bytes(
                data[sec_offset + 16..sec_offset + 24]
                    .try_into()
                    .map_err(|_| "slice error")?,
            );

            let off = u64::from_le_bytes(
                data[sec_offset + 24..sec_offset + 32]
                    .try_into()
                    .map_err(|_| "slice error")?,
            );

            let size = u64::from_le_bytes(
                data[sec_offset + 32..sec_offset + 40]
                    .try_into()
                    .map_err(|_| "slice error")?,
            );

            let link = u32::from_le_bytes([
                data[sec_offset + 40],
                data[sec_offset + 41],
                data[sec_offset + 42],
                data[sec_offset + 43],
            ]);

            let info = u32::from_le_bytes([
                data[sec_offset + 44],
                data[sec_offset + 45],
                data[sec_offset + 46],
                data[sec_offset + 47],
            ]);

            let addralign = u64::from_le_bytes(
                data[sec_offset + 48..sec_offset + 56]
                    .try_into()
                    .map_err(|_| "slice error")?,
            );

            let entsize = u64::from_le_bytes(
                data[sec_offset + 56..sec_offset + 64]
                    .try_into()
                    .map_err(|_| "slice error")?,
            );

            // Read section name from shstrtab
            let name = if shstrtab_offset + name_offset < data.len() {
                let start = shstrtab_offset + name_offset;
                let end = data[start..]
                    .iter()
                    .position(|&b| b == 0)
                    .map(|p| start + p)
                    .unwrap_or(data.len());
                String::from_utf8_lossy(&data[start..end]).to_string()
            } else {
                String::new()
            };

            sections.push(ElfSectionHeader {
                name,
                sh_type,
                flags,
                addr,
                offset: off,
                size,
                link,
                info,
                addralign,
                entsize,
            });
        }

        Ok(sections)
    }

    /// Helper: read raw section header bytes for offset computation.
    fn _read_section_header_raw(data: &[u8], sec_offset: usize) -> usize {
        if sec_offset + 32 > data.len() {
            return 0;
        }
        u64::from_le_bytes(
            data[sec_offset + 24..sec_offset + 32]
                .try_into()
                .unwrap_or([0; 8]),
        ) as usize
    }

    /// Parse ELF symbols from the symbol table.
    pub fn parse_elf_symbols(data: &[u8]) -> Result<Vec<ElfSymbol>, String> {
        let header = Self::parse_elf_header(data).ok_or("Invalid ELF header")?;
        let sections = Self::parse_elf_sections(data)?;

        // Find .symtab and .strtab
        let symtab = sections.iter().find(|s| s.name == ".symtab");
        let strtab = sections.iter().find(|s| s.name == ".strtab");

        let (symtab, strtab) = match (symtab, strtab) {
            (Some(s), Some(t)) => (s, t),
            _ => return Ok(Vec::new()),
        };

        let sym_data = &data[symtab.offset as usize..(symtab.offset + symtab.size) as usize];
        let str_data = &data[strtab.offset as usize..(strtab.offset + strtab.size) as usize];

        let entry_size = 24; // ELF64 symtab entry
        let num_symbols = sym_data.len() / entry_size;

        let mut symbols = Vec::new();

        for i in 0..num_symbols {
            let off = i * entry_size;
            if off + entry_size > sym_data.len() {
                break;
            }

            let name_off = u32::from_le_bytes([
                sym_data[off],
                sym_data[off + 1],
                sym_data[off + 2],
                sym_data[off + 3],
            ]) as usize;

            let info = sym_data[off + 4];
            let binding = info >> 4;
            let sym_type = info & 0x0F;

            let section_index = u16::from_le_bytes([sym_data[off + 6], sym_data[off + 7]]);

            let value = u64::from_le_bytes(
                sym_data[off + 8..off + 16]
                    .try_into()
                    .map_err(|_| "slice error")?,
            );

            let size = u64::from_le_bytes(
                sym_data[off + 16..off + 24]
                    .try_into()
                    .map_err(|_| "slice error")?,
            );

            // Name from strtab
            let name = if name_off < str_data.len() {
                let end = str_data[name_off..]
                    .iter()
                    .position(|&b| b == 0)
                    .map(|p| name_off + p)
                    .unwrap_or(str_data.len());
                String::from_utf8_lossy(&str_data[name_off..end]).to_string()
            } else {
                String::new()
            };

            symbols.push(ElfSymbol {
                name,
                value,
                size,
                sym_type,
                binding,
                section_index,
            });
        }

        Ok(symbols)
    }

    /// Parse ELF relocations from a RELA section.
    pub fn parse_elf_relocations(
        data: &[u8],
        section: &ElfSectionHeader,
    ) -> Result<Vec<ElfRelocation>, String> {
        if section.sh_type != sht::RELA {
            return Ok(Vec::new());
        }

        let entry_size = 24; // ELF64 RELA
        let reloc_data = &data[section.offset as usize..(section.offset + section.size) as usize];
        let num_relocs = reloc_data.len() / entry_size;

        let mut relocs = Vec::new();

        for i in 0..num_relocs {
            let off = i * entry_size;
            if off + entry_size > reloc_data.len() {
                break;
            }

            let offset = u64::from_le_bytes(
                reloc_data[off..off + 8]
                    .try_into()
                    .map_err(|_| "slice error")?,
            );

            let r_info = u64::from_le_bytes(
                reloc_data[off + 8..off + 16]
                    .try_into()
                    .map_err(|_| "slice error")?,
            );

            let addend = i64::from_le_bytes(
                reloc_data[off + 16..off + 24]
                    .try_into()
                    .map_err(|_| "slice error")?,
            );

            relocs.push(ElfRelocation {
                offset,
                sym_index: (r_info >> 32) as u32,
                rel_type: (r_info & 0xFFFF_FFFF) as u32,
                addend,
            });
        }

        Ok(relocs)
    }

    /// Parse ELF program headers.
    pub fn parse_elf_program_headers(data: &[u8]) -> Result<Vec<ElfProgramHeader>, String> {
        let header = Self::parse_elf_header(data).ok_or("Invalid ELF header")?;
        let phoff = header.phoff as usize;
        let phnum = header.phnum as usize;
        let phentsize = header.phentsize as usize;

        if phoff == 0 || phnum == 0 || phentsize == 0 {
            return Ok(Vec::new());
        }

        let mut phdrs = Vec::new();

        for i in 0..phnum {
            let off = phoff + i * phentsize;
            if off + phentsize > data.len() {
                break;
            }

            let p_type =
                u32::from_le_bytes([data[off], data[off + 1], data[off + 2], data[off + 3]]);
            let flags =
                u32::from_le_bytes([data[off + 4], data[off + 5], data[off + 6], data[off + 7]]);

            let (p_offset, p_vaddr, p_paddr, p_filesz, p_memsz, p_align) = if phentsize >= 56 {
                // ELF64
                (
                    u64::from_le_bytes(data[off + 8..off + 16].try_into().unwrap()),
                    u64::from_le_bytes(data[off + 16..off + 24].try_into().unwrap()),
                    u64::from_le_bytes(data[off + 24..off + 32].try_into().unwrap()),
                    u64::from_le_bytes(data[off + 32..off + 40].try_into().unwrap()),
                    u64::from_le_bytes(data[off + 40..off + 48].try_into().unwrap()),
                    u64::from_le_bytes(data[off + 48..off + 56].try_into().unwrap()),
                )
            } else {
                (
                    u32::from_le_bytes([data[off + 4], data[off + 5], data[off + 6], data[off + 7]])
                        as u64,
                    u32::from_le_bytes([
                        data[off + 8],
                        data[off + 9],
                        data[off + 10],
                        data[off + 11],
                    ]) as u64,
                    u32::from_le_bytes([
                        data[off + 12],
                        data[off + 13],
                        data[off + 14],
                        data[off + 15],
                    ]) as u64,
                    u32::from_le_bytes([
                        data[off + 16],
                        data[off + 17],
                        data[off + 18],
                        data[off + 19],
                    ]) as u64,
                    u32::from_le_bytes([
                        data[off + 20],
                        data[off + 21],
                        data[off + 22],
                        data[off + 23],
                    ]) as u64,
                    u32::from_le_bytes([
                        data[off + 24],
                        data[off + 25],
                        data[off + 26],
                        data[off + 27],
                    ]) as u64,
                )
            };

            phdrs.push(ElfProgramHeader {
                p_type,
                flags,
                offset: p_offset,
                vaddr: p_vaddr,
                paddr: p_paddr,
                filesz: p_filesz,
                memsz: p_memsz,
                align: p_align,
            });
        }

        Ok(phdrs)
    }

    /// Parse ELF dynamic entries from .dynamic section.
    pub fn parse_elf_dynamic(data: &[u8]) -> Result<Vec<ElfDynamic>, String> {
        let sections = Self::parse_elf_sections(data).unwrap_or_default();
        let dynamic_sec = sections.iter().find(|s| s.name == ".dynamic");
        let dynamic_sec = match dynamic_sec {
            Some(s) => s,
            None => return Ok(Vec::new()),
        };

        let dyn_data =
            &data[dynamic_sec.offset as usize..(dynamic_sec.offset + dynamic_sec.size) as usize];
        let entry_size = 16; // ELF64 Dyn
        let num_entries = dyn_data.len() / entry_size;

        let mut entries = Vec::new();

        for i in 0..num_entries {
            let off = i * entry_size;
            if off + entry_size > dyn_data.len() {
                break;
            }
            let d_tag = u64::from_le_bytes(dyn_data[off..off + 8].try_into().unwrap());
            let d_val = u64::from_le_bytes(dyn_data[off + 8..off + 16].try_into().unwrap());
            entries.push(ElfDynamic { d_tag, d_val });
        }

        Ok(entries)
    }

    /// Parse ELF notes from a section.
    pub fn parse_elf_notes(
        data: &[u8],
        section: &ElfSectionHeader,
    ) -> Result<Vec<ElfNote>, String> {
        if section.sh_type != sht::NOTE {
            return Ok(Vec::new());
        }

        let note_data = &data[section.offset as usize..(section.offset + section.size) as usize];
        let mut notes = Vec::new();
        let mut pos = 0usize;

        while pos + 12 <= note_data.len() {
            let namesz = u32::from_le_bytes([
                note_data[pos],
                note_data[pos + 1],
                note_data[pos + 2],
                note_data[pos + 3],
            ]) as usize;
            let descsz = u32::from_le_bytes([
                note_data[pos + 4],
                note_data[pos + 5],
                note_data[pos + 6],
                note_data[pos + 7],
            ]) as usize;
            let desc_type = u32::from_le_bytes([
                note_data[pos + 8],
                note_data[pos + 9],
                note_data[pos + 10],
                note_data[pos + 11],
            ]);

            let name_start = pos + 12;
            let name_end = std::cmp::min(name_start + namesz, note_data.len());
            let name = String::from_utf8_lossy(&note_data[name_start..name_end])
                .trim_end_matches('\0')
                .to_string();

            // desc is 4-byte aligned after name
            let desc_start = (name_start + namesz + 3) & !3;
            let desc_end = std::cmp::min(desc_start + descsz, note_data.len());
            let desc = note_data[desc_start..desc_end].to_vec();

            notes.push(ElfNote {
                name,
                desc_type,
                desc,
            });

            // Move to next note (desc is also 4-byte aligned)
            pos = (desc_end + 3) & !3;
        }

        Ok(notes)
    }

    // === Mach-O Parsing Methods ===

    /// Parse a Mach-O header.
    pub fn parse_macho_header(data: &[u8]) -> Result<MachOHeader, String> {
        if data.len() < 32 {
            return Err("Data too short for Mach-O header".to_string());
        }

        let magic = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
        if magic != MACHO_MAGIC_64 && magic != MACHO_MAGIC_32 {
            // Try big-endian
            let magic_be = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
            if magic_be != MACHO_MAGIC_64 && magic_be != MACHO_MAGIC_32 {
                return Err(format!("Invalid Mach-O magic: 0x{:08X}", magic));
            }
        }

        let cputype = u32::from_le_bytes([data[4], data[5], data[6], data[7]]);
        let cpusubtype = u32::from_le_bytes([data[8], data[9], data[10], data[11]]);
        let filetype = u32::from_le_bytes([data[12], data[13], data[14], data[15]]);
        let ncmds = u32::from_le_bytes([data[16], data[17], data[18], data[19]]);
        let sizeofcmds = u32::from_le_bytes([data[20], data[21], data[22], data[23]]);
        let flags = u32::from_le_bytes([data[24], data[25], data[26], data[27]]);
        let reserved = if magic == MACHO_MAGIC_64 {
            u32::from_le_bytes([data[28], data[29], data[30], data[31]])
        } else {
            0
        };

        Ok(MachOHeader {
            magic,
            cputype,
            cpusubtype,
            filetype,
            ncmds,
            sizeofcmds,
            flags,
            reserved,
        })
    }

    /// Parse Mach-O load commands.
    pub fn parse_macho_load_commands(
        data: &[u8],
        header: &MachOHeader,
    ) -> Result<Vec<MachOLoadCommand>, String> {
        let mut commands = Vec::new();
        let mut offset: usize = if header.magic == MACHO_MAGIC_64 {
            32
        } else {
            28
        };
        let end_offset = offset + header.sizeofcmds as usize;

        while offset + 8 <= data.len() && offset < end_offset {
            let cmd = u32::from_le_bytes([
                data[offset],
                data[offset + 1],
                data[offset + 2],
                data[offset + 3],
            ]);
            let cmdsize = u32::from_le_bytes([
                data[offset + 4],
                data[offset + 5],
                data[offset + 6],
                data[offset + 7],
            ]) as usize;

            if cmdsize == 0 {
                break;
            }

            let cmd_data = if offset + cmdsize <= data.len() {
                &data[offset..offset + cmdsize]
            } else {
                &data[offset..]
            };

            match cmd {
                0x19 => {
                    // LC_SEGMENT_64
                    if let Some(seg) = Self::_parse_macho_segment_64(cmd_data) {
                        commands.push(MachOLoadCommand::Segment(seg));
                    }
                }
                0x02 => {
                    // LC_SYMTAB
                    if cmd_data.len() >= 24 {
                        let symoff = u32::from_le_bytes([
                            cmd_data[8],
                            cmd_data[9],
                            cmd_data[10],
                            cmd_data[11],
                        ]);
                        let nsyms = u32::from_le_bytes([
                            cmd_data[12],
                            cmd_data[13],
                            cmd_data[14],
                            cmd_data[15],
                        ]);
                        let stroff = u32::from_le_bytes([
                            cmd_data[16],
                            cmd_data[17],
                            cmd_data[18],
                            cmd_data[19],
                        ]);
                        let strsize = u32::from_le_bytes([
                            cmd_data[20],
                            cmd_data[21],
                            cmd_data[22],
                            cmd_data[23],
                        ]);
                        commands.push(MachOLoadCommand::Symtab(MachSymtabCmd {
                            symoff,
                            nsyms,
                            stroff,
                            strsize,
                        }));
                    }
                }
                0x0B => {
                    // LC_DYSYMTAB
                    if cmd_data.len() >= 32 {
                        let ilocalsym = u32::from_le_bytes([
                            cmd_data[8],
                            cmd_data[9],
                            cmd_data[10],
                            cmd_data[11],
                        ]);
                        let nlocalsym = u32::from_le_bytes([
                            cmd_data[12],
                            cmd_data[13],
                            cmd_data[14],
                            cmd_data[15],
                        ]);
                        let iextdefsym = u32::from_le_bytes([
                            cmd_data[16],
                            cmd_data[17],
                            cmd_data[18],
                            cmd_data[19],
                        ]);
                        let nextdefsym = u32::from_le_bytes([
                            cmd_data[20],
                            cmd_data[21],
                            cmd_data[22],
                            cmd_data[23],
                        ]);
                        let iundefsym = u32::from_le_bytes([
                            cmd_data[24],
                            cmd_data[25],
                            cmd_data[26],
                            cmd_data[27],
                        ]);
                        let nundefsym = u32::from_le_bytes([
                            cmd_data[28],
                            cmd_data[29],
                            cmd_data[30],
                            cmd_data[31],
                        ]);
                        commands.push(MachOLoadCommand::Dysymtab(MachDysymtabCmd {
                            ilocalsym,
                            nlocalsym,
                            iextdefsym,
                            nextdefsym,
                            iundefsym,
                            nundefsym,
                        }));
                    }
                }
                0x1B => {
                    // LC_UUID
                    if cmd_data.len() >= 24 {
                        let mut uuid = [0u8; 16];
                        uuid.copy_from_slice(&cmd_data[8..24]);
                        commands.push(MachOLoadCommand::Uuid(MachUuidCmd { uuid }));
                    }
                }
                0x24 => {
                    // LC_VERSION_MIN_MACOSX
                    if cmd_data.len() >= 16 {
                        let version = u32::from_le_bytes([
                            cmd_data[8],
                            cmd_data[9],
                            cmd_data[10],
                            cmd_data[11],
                        ]);
                        let sdk = u32::from_le_bytes([
                            cmd_data[12],
                            cmd_data[13],
                            cmd_data[14],
                            cmd_data[15],
                        ]);
                        commands.push(MachOLoadCommand::VersionMinMacosx(MachVersionMinCmd {
                            cmd,
                            version,
                            sdk,
                        }));
                    }
                }
                0x25 => {
                    // LC_VERSION_MIN_IPHONEOS
                    if cmd_data.len() >= 16 {
                        let version = u32::from_le_bytes([
                            cmd_data[8],
                            cmd_data[9],
                            cmd_data[10],
                            cmd_data[11],
                        ]);
                        let sdk = u32::from_le_bytes([
                            cmd_data[12],
                            cmd_data[13],
                            cmd_data[14],
                            cmd_data[15],
                        ]);
                        commands.push(MachOLoadCommand::VersionMinIphoneos(MachVersionMinCmd {
                            cmd,
                            version,
                            sdk,
                        }));
                    }
                }
                _ => {
                    commands.push(MachOLoadCommand::Unknown {
                        cmd,
                        cmdsize: cmdsize as u32,
                        data: cmd_data.to_vec(),
                    });
                }
            }

            offset += cmdsize;
        }

        Ok(commands)
    }

    /// Parse a Mach-O segment_64 command.
    fn _parse_macho_segment_64(data: &[u8]) -> Option<MachSegment> {
        if data.len() < 72 {
            return None;
        }
        let segname = String::from_utf8_lossy(&data[8..24])
            .trim_end_matches('\0')
            .to_string();
        let vmaddr = u64::from_le_bytes(data[24..32].try_into().ok()?);
        let vmsize = u64::from_le_bytes(data[32..40].try_into().ok()?);
        let fileoff = u64::from_le_bytes(data[40..48].try_into().ok()?);
        let filesize = u64::from_le_bytes(data[48..56].try_into().ok()?);
        let maxprot = u32::from_le_bytes([data[56], data[57], data[58], data[59]]);
        let initprot = u32::from_le_bytes([data[60], data[61], data[62], data[63]]);
        let nsects = u32::from_le_bytes([data[64], data[65], data[66], data[67]]);
        let flags = u32::from_le_bytes([data[68], data[69], data[70], data[71]]);

        Some(MachSegment {
            segname,
            vmaddr,
            vmsize,
            fileoff,
            filesize,
            maxprot,
            initprot,
            nsects,
            flags,
        })
    }

    /// Parse Mach-O sections within a segment.
    fn parse_macho_sections_in_segment(
        data: &[u8],
        seg: &MachSegment,
        _ncmds: u32,
    ) -> Vec<MachOSectionData> {
        // Section headers follow the segment command in the file.
        // For 64-bit, segment header is 72 bytes (cmd=8 + cmdsize=4 + segname=16 + vmaddr=8 +
        // vmsize=8 + fileoff=8 + filesize=8 + maxprot=4 + initprot=4 + nsects=4 + flags=4)
        // Sections are 80 bytes each.
        // Find the segment start in the file. This is approximate since we don't track
        // exact command offsets.
        let mut sections = Vec::new();
        // The section headers are at fileoff + offset within the segment's section data
        // We approximate section offset from the segment's fileoff
        let section_header_size = 80; // section_64
                                      // Sections start at seg.fileoff, each section header is 80 bytes
        for i in 0..seg.nsects as usize {
            let sec_off = seg.fileoff as usize + i * section_header_size;
            if sec_off + section_header_size > data.len() {
                break;
            }

            let sectname = String::from_utf8_lossy(&data[sec_off..sec_off + 16])
                .trim_end_matches('\0')
                .to_string();
            let s_segname = String::from_utf8_lossy(&data[sec_off + 16..sec_off + 32])
                .trim_end_matches('\0')
                .to_string();
            let addr = u64::from_le_bytes(
                data[sec_off + 32..sec_off + 40]
                    .try_into()
                    .unwrap_or([0; 8]),
            );
            let size = u64::from_le_bytes(
                data[sec_off + 40..sec_off + 48]
                    .try_into()
                    .unwrap_or([0; 8]),
            );
            let soff = u32::from_le_bytes([
                data[sec_off + 48],
                data[sec_off + 49],
                data[sec_off + 50],
                data[sec_off + 51],
            ]);
            let align = u32::from_le_bytes([
                data[sec_off + 52],
                data[sec_off + 53],
                data[sec_off + 54],
                data[sec_off + 55],
            ]);
            let reloff = u32::from_le_bytes([
                data[sec_off + 56],
                data[sec_off + 57],
                data[sec_off + 58],
                data[sec_off + 59],
            ]);
            let nreloc = u32::from_le_bytes([
                data[sec_off + 60],
                data[sec_off + 61],
                data[sec_off + 62],
                data[sec_off + 63],
            ]);
            let sflags = u32::from_le_bytes([
                data[sec_off + 64],
                data[sec_off + 65],
                data[sec_off + 66],
                data[sec_off + 67],
            ]);

            let sec_data = if soff > 0 && (soff as usize) < data.len() {
                let end = std::cmp::min((soff + size as u32) as usize, data.len());
                data[soff as usize..end].to_vec()
            } else {
                Vec::new()
            };

            sections.push(MachOSectionData {
                sectname,
                segname: s_segname,
                addr,
                size,
                offset: soff,
                align,
                reloff,
                nreloc,
                flags: sflags,
                data: sec_data,
            });
        }
        sections
    }

    /// Parse Mach-O symbols from the symtab.
    pub fn parse_macho_symbols(
        data: &[u8],
        symtab: &MachSymtabCmd,
    ) -> Result<Vec<MachOSymbol>, String> {
        let sym_off = symtab.symoff as usize;
        let stroff = symtab.stroff as usize;
        let nsyms = symtab.nsyms as usize;
        let strsize = symtab.strsize as usize;

        if sym_off == 0 || stroff == 0 || nsyms == 0 {
            return Ok(Vec::new());
        }

        let entry_size = 16; // nlist_64
        let mut symbols = Vec::new();

        for i in 0..nsyms {
            let off = sym_off + i * entry_size;
            if off + entry_size > data.len() {
                break;
            }

            let n_strx =
                u32::from_le_bytes([data[off], data[off + 1], data[off + 2], data[off + 3]])
                    as usize;

            let n_type = data[off + 4];
            let n_sect = data[off + 5];
            let n_desc = u16::from_le_bytes([data[off + 6], data[off + 7]]);
            let n_value = u64::from_le_bytes(data[off + 8..off + 16].try_into().unwrap_or([0; 8]));

            let name = if n_strx < strsize {
                let name_start = stroff + n_strx;
                let name_end = data[name_start..]
                    .iter()
                    .position(|&b| b == 0)
                    .map(|p| name_start + p)
                    .unwrap_or(std::cmp::min(name_start + 256, data.len()));
                String::from_utf8_lossy(&data[name_start..name_end]).to_string()
            } else {
                String::new()
            };

            symbols.push(MachOSymbol {
                name,
                n_type,
                n_sect,
                n_desc,
                n_value,
            });
        }

        Ok(symbols)
    }

    // === COFF Parsing Methods ===

    /// Parse a COFF header.
    pub fn parse_coff_header(data: &[u8]) -> Result<CoffHeader, String> {
        if data.len() < 20 {
            return Err("Data too short for COFF header".to_string());
        }
        let machine = u16::from_le_bytes([data[0], data[1]]);
        let num_sections = u16::from_le_bytes([data[2], data[3]]);
        let timestamp = u32::from_le_bytes([data[4], data[5], data[6], data[7]]);
        let symtab_offset = u32::from_le_bytes([data[8], data[9], data[10], data[11]]);
        let num_symbols = u32::from_le_bytes([data[12], data[13], data[14], data[15]]);
        let opt_header_size = u16::from_le_bytes([data[16], data[17]]);
        let characteristics = u16::from_le_bytes([data[18], data[19]]);

        Ok(CoffHeader {
            machine,
            num_sections,
            timestamp,
            symtab_offset,
            num_symbols,
            opt_header_size,
            characteristics,
        })
    }

    /// Parse COFF section headers.
    pub fn parse_coff_sections(
        data: &[u8],
        header: &CoffHeader,
    ) -> Result<Vec<CoffSectionHeader>, String> {
        let mut sections = Vec::new();
        // Section headers start after: 20 (header) + opt_header_size
        let sec_start = 20 + header.opt_header_size as usize;
        let sec_entry_size = 40; // COFF section header size

        for i in 0..header.num_sections as usize {
            let off = sec_start + i * sec_entry_size;
            if off + sec_entry_size > data.len() {
                break;
            }

            let name = String::from_utf8_lossy(&data[off..off + 8])
                .trim_end_matches('\0')
                .to_string();

            let virtual_size =
                u32::from_le_bytes([data[off + 8], data[off + 9], data[off + 10], data[off + 11]]);
            let virtual_address = u32::from_le_bytes([
                data[off + 12],
                data[off + 13],
                data[off + 14],
                data[off + 15],
            ]);
            let raw_data_size = u32::from_le_bytes([
                data[off + 16],
                data[off + 17],
                data[off + 18],
                data[off + 19],
            ]);
            let raw_data_ptr = u32::from_le_bytes([
                data[off + 20],
                data[off + 21],
                data[off + 22],
                data[off + 23],
            ]);
            let reloc_ptr = u32::from_le_bytes([
                data[off + 24],
                data[off + 25],
                data[off + 26],
                data[off + 27],
            ]);
            let linenum_ptr = u32::from_le_bytes([
                data[off + 28],
                data[off + 29],
                data[off + 30],
                data[off + 31],
            ]);
            let num_relocs = u16::from_le_bytes([data[off + 32], data[off + 33]]);
            let num_linenums = u16::from_le_bytes([data[off + 34], data[off + 35]]);
            let characteristics = u32::from_le_bytes([
                data[off + 36],
                data[off + 37],
                data[off + 38],
                data[off + 39],
            ]);

            sections.push(CoffSectionHeader {
                name,
                virtual_size,
                virtual_address,
                raw_data_size,
                raw_data_ptr,
                reloc_ptr,
                linenum_ptr,
                num_relocs,
                num_linenums,
                characteristics,
            });
        }

        Ok(sections)
    }

    /// Parse COFF symbols.
    pub fn parse_coff_symbols(data: &[u8], header: &CoffHeader) -> Result<Vec<CoffSymbol>, String> {
        let symtab_offset = header.symtab_offset as usize;
        if symtab_offset == 0 || header.num_symbols == 0 {
            return Ok(Vec::new());
        }

        let mut symbols = Vec::new();
        let mut offset = symtab_offset;
        let entry_size = 18;

        // String table starts after symbol table
        let strtab_offset = symtab_offset + header.num_symbols as usize * entry_size;

        for _ in 0..header.num_symbols {
            if offset + entry_size > data.len() {
                break;
            }

            // Name: either 8-byte string or offset into string table
            let name = if data[offset] == 0
                && data[offset + 1] == 0
                && data[offset + 2] == 0
                && data[offset + 3] == 0
            {
                // Offset into string table
                let str_off = u32::from_le_bytes([
                    data[offset + 4],
                    data[offset + 5],
                    data[offset + 6],
                    data[offset + 7],
                ]) as usize;
                let name_start = strtab_offset + str_off;
                if name_start < data.len() {
                    let name_end = data[name_start..]
                        .iter()
                        .position(|&b| b == 0)
                        .map(|p| name_start + p)
                        .unwrap_or(data.len());
                    String::from_utf8_lossy(&data[name_start..name_end]).to_string()
                } else {
                    String::new()
                }
            } else {
                String::from_utf8_lossy(&data[offset..offset + 8])
                    .trim_end_matches('\0')
                    .to_string()
            };

            let value = u32::from_le_bytes([
                data[offset + 8],
                data[offset + 9],
                data[offset + 10],
                data[offset + 11],
            ]);
            let section_number = i16::from_le_bytes([data[offset + 12], data[offset + 13]]);
            let sym_type = u16::from_le_bytes([data[offset + 14], data[offset + 15]]);
            let storage_class = data[offset + 16];
            let num_aux = data[offset + 17];

            symbols.push(CoffSymbol {
                name,
                value,
                section_number,
                sym_type,
                storage_class,
                num_aux,
            });

            // Skip aux entries
            offset += entry_size + num_aux as usize * entry_size;
        }

        Ok(symbols)
    }

    // === Utility Methods ===

    /// Returns true if this is a valid ELF file.
    pub fn is_valid(&self) -> bool {
        self.format != ObjectFormat::Unknown
    }

    /// Get the machine type as a string.
    pub fn machine_name(&self) -> &str {
        &self.machine
    }

    /// Get a section by name.
    pub fn get_section(&self, name: &str) -> Option<&ObjectSection> {
        self.sections.iter().find(|s| s.name == name)
    }

    /// Get all symbols in a given section.
    pub fn get_symbols_in_section(&self, section_index: u16) -> Vec<&ObjectSymbol> {
        self.symbols
            .iter()
            .filter(|s| s.section_index == section_index)
            .collect()
    }

    /// Get all global symbols.
    pub fn get_global_symbols(&self) -> Vec<&ObjectSymbol> {
        self.symbols.iter().filter(|s| s.is_global).collect()
    }

    /// Get the number of sections.
    pub fn num_sections(&self) -> usize {
        self.sections.len()
    }

    /// Get the number of symbols.
    pub fn num_symbols(&self) -> usize {
        self.symbols.len()
    }

    /// Disassemble a section's data into instructions.
    /// This is a minimal stub — returns basic info about the section's contents.
    pub fn disassemble_section(
        data: &[u8],
        machine: &str,
        start_addr: u64,
    ) -> Vec<DisassembledInst> {
        let mut insts = Vec::new();
        let mut addr = start_addr;

        // Minimal disassembly: split data into 4-byte chunks for x86_64/arm64
        let chunk_size = match machine {
            "x86_64" | "x86" => 1, // variable length, but we approximate
            "aarch64" | "arm64" => 4,
            "arm" => 4,
            _ => 4,
        };

        let mut pos = 0usize;
        while pos + chunk_size <= data.len() {
            let actual_size = if machine == "x86_64" {
                // Very basic x86 length detection heuristic
                let b = data[pos];
                if b == 0x0F {
                    // Two-byte opcode
                    std::cmp::min(4, data.len() - pos)
                } else if b == 0xFF || b == 0x8B || b == 0x89 {
                    // ModR/M opcode — estimate 3 bytes
                    std::cmp::min(3, data.len() - pos)
                } else if b == 0xE8 || b == 0xE9 {
                    // call/jmp rel32
                    std::cmp::min(5, data.len() - pos)
                } else if b == 0xC3 || b == 0x90 || b == 0xCC {
                    1
                } else {
                    std::cmp::min(3, data.len() - pos)
                }
            } else {
                chunk_size
            };

            let end = std::cmp::min(pos + actual_size, data.len());
            let bytes = data[pos..end].to_vec();
            let mnemonic = if bytes.is_empty() {
                "??".to_string()
            } else if bytes.len() == 1 && bytes[0] == 0xC3 {
                "ret".to_string()
            } else if bytes.len() == 1 && bytes[0] == 0x90 {
                "nop".to_string()
            } else if bytes.len() >= 5 && bytes[0] == 0xE9 {
                "jmp".to_string()
            } else if bytes.len() >= 5 && bytes[0] == 0xE8 {
                "call".to_string()
            } else {
                format!("data{}", bytes.len())
            };

            insts.push(DisassembledInst {
                address: addr,
                bytes,
                mnemonic,
                operands: String::new(),
            });

            addr += actual_size as u64;
            pos += actual_size;
        }

        insts
    }

    /// Find function symbols in the object file: (name, address, size).
    pub fn find_function_symbols(&self) -> Vec<(String, u64, u64)> {
        self.symbols
            .iter()
            .filter(|s| s.is_function)
            .map(|s| (s.name.clone(), s.value, s.size))
            .collect()
    }
}

// ============================================================================
// Section Type Constants
// ============================================================================

/// Section type constants.
pub mod sht {
    pub const NULL: u32 = 0;
    pub const PROGBITS: u32 = 1;
    pub const SYMTAB: u32 = 2;
    pub const STRTAB: u32 = 3;
    pub const RELA: u32 = 4;
    pub const NOBITS: u32 = 8;
    pub const REL: u32 = 9;
    pub const DYNAMIC: u32 = 6;
    pub const NOTE: u32 = 7;
}

/// Symbol binding constants.
pub mod stb {
    pub const LOCAL: u8 = 0;
    pub const GLOBAL: u8 = 1;
    pub const WEAK: u8 = 2;
}

/// Symbol type constants.
pub mod stt {
    pub const NOTYPE: u8 = 0;
    pub const OBJECT: u8 = 1;
    pub const FUNC: u8 = 2;
    pub const SECTION: u8 = 3;
    pub const FILE: u8 = 4;
}

// ============================================================================
// XCOFF (AIX) Object Format
// ============================================================================

/// XCOFF magic numbers.
pub const XCOFF32_MAGIC: u16 = 0x01DF;
pub const XCOFF64_MAGIC: u16 = 0x01F7;

/// XCOFF file header (32-bit).
#[derive(Debug, Clone)]
pub struct XcoffFileHeader {
    pub magic: u16,
    pub num_sections: u16,
    pub timestamp: i32,
    pub symtab_offset: u64,
    pub symtab_count: i32,
    pub optional_header_size: u16,
    pub flags: u16,
}

/// XCOFF optional header (a.out-style).
#[derive(Debug, Clone)]
pub struct XcoffOptionalHeader {
    pub magic: u16, // 0x010B for 32-bit
    pub vstamp: u16,
    pub text_size: u64,
    pub data_size: u64,
    pub bss_size: u64,
    pub entry: u64,
    pub text_start: u64,
    pub data_start: u64,
    pub toc: u64,
}

/// XCOFF section header.
#[derive(Debug, Clone)]
pub struct XcoffSectionHeader {
    pub name: String,
    pub paddr: u64,
    pub vaddr: u64,
    pub size: u64,
    pub scnptr: u64,  // file offset to raw data
    pub relptr: u64,  // file offset to relocations
    pub lnnoptr: u64, // file offset to line numbers
    pub num_relocs: u32,
    pub num_lnno: u32,
    pub flags: u32,
}

/// XCOFF symbol table entry.
#[derive(Debug, Clone)]
pub struct XcoffSymbol {
    pub name: String,
    pub value: u64,
    pub section_number: i16,
    pub sym_type: u16,
    pub storage_class: u8,
    pub num_aux: u8,
    pub aux_entries: Vec<XcoffAuxEntry>,
}

/// XCOFF auxiliary entry variants.
#[derive(Debug, Clone)]
pub enum XcoffAuxEntry {
    /// CSECT auxiliary entry: symbol alignment, type, and size.
    Csect {
        length: u64,
        parm_hash: u32,
        sn_type: u8, // XTY_SD, XTY_LD, XTY_CM, XTY_ER
        smclas: u8,
        stab: u32,
        x_snstab: u16,
    },
    /// Function auxiliary entry.
    Function {
        offset_to_exception_table: u64,
        size_of_function: u64,
        line_number_pointer: u64,
        end_index: u32,
    },
    /// File auxiliary entry.
    File { name: String },
    /// Except auxiliary entry.
    Except,
}

/// XCOFF relocation entry.
#[derive(Debug, Clone)]
pub struct XcoffRelocation {
    pub vaddr: u64,
    pub symbol_index: u32,
    pub info: u8,
    pub rel_type: u8,
}

/// XCOFF loader section header.
#[derive(Debug, Clone)]
pub struct XcoffLoaderHeader {
    pub version: i32,
    pub num_symbols: i32,
    pub num_relocs: i32,
    pub import_file_id: i32,
    pub string_table_length: i32,
    pub init_pointer: u64,
    pub term_pointer: u64,
    pub entry_point: u64,
}

/// XCOFF line number entry.
#[derive(Debug, Clone)]
pub struct XcoffLineNumber {
    pub address: u64,
    pub line_number: u16,
}

impl XcoffFileHeader {
    /// Create a default XCOFF32 header.
    pub fn new_xcoff32() -> Self {
        XcoffFileHeader {
            magic: XCOFF32_MAGIC,
            num_sections: 0,
            timestamp: 0,
            symtab_offset: 0,
            symtab_count: 0,
            optional_header_size: 0,
            flags: 0,
        }
    }

    /// Create a default XCOFF64 header.
    pub fn new_xcoff64() -> Self {
        XcoffFileHeader {
            magic: XCOFF64_MAGIC,
            num_sections: 0,
            timestamp: 0,
            symtab_offset: 0,
            symtab_count: 0,
            optional_header_size: 0,
            flags: 0,
        }
    }

    /// Check if this is a 64-bit XCOFF file.
    pub fn is_64bit(&self) -> bool {
        self.magic == XCOFF64_MAGIC
    }
}

// ============================================================================
// GOFF (z/OS) Object Format
// ============================================================================

/// GOFF record types.
pub const GOFF_ESD: u8 = 0x00;
pub const GOFF_TXT: u8 = 0x01;
pub const GOFF_RLD: u8 = 0x02;
pub const GOFF_END: u8 = 0x04;

/// GOFF header.
#[derive(Debug, Clone)]
pub struct GoffHeader {
    pub level: u8,
    pub length: u32,
}

/// GOFF External Symbol Dictionary (ESD) record.
#[derive(Debug, Clone)]
pub struct GoffEsdRecord {
    pub name: String,
    pub esd_type: u8, // SD, LD, ED, PR, PC, CM, WX, ER
    pub symbol_id: u32,
    pub binder: u8, // Binder association (ED types)
    pub amode: u8,  // Addressing mode (24, 31, 64)
    pub rmode: u8,  // Residence mode
    pub length: u64,
    pub alignment: u64,
}

/// GOFF ESD types.
pub mod goff_esd {
    pub const SD: u8 = 0x00; // Section Definition
    pub const LD: u8 = 0x01; // Label Definition
    pub const ED: u8 = 0x02; // External Definition
    pub const PR: u8 = 0x04; // Part Reference (internal)
    pub const PC: u8 = 0x05; // Part Code
    pub const CM: u8 = 0x06; // Common
    pub const WX: u8 = 0x08; // Weak External
    pub const ER: u8 = 0x0A; // External Reference
}

/// GOFF TXT (Text) record.
#[derive(Debug, Clone)]
pub struct GoffTxtRecord {
    pub section_id: u32,
    pub offset: u64,
    pub length: u32,
    pub data: Vec<u8>,
}

/// GOFF RLD (Relocation Directory) record.
#[derive(Debug, Clone)]
pub struct GoffRldRecord {
    pub symbol_id: u32,
    pub position: u64,
    pub length: u8,
    pub flags: u8,
    pub addend: i64,
}

impl GoffEsdRecord {
    /// Create a Section Definition ESD.
    pub fn new_sd(name: &str, id: u32, len: u64, align: u64, amode: u8, rmode: u8) -> Self {
        GoffEsdRecord {
            name: name.to_string(),
            esd_type: goff_esd::SD,
            symbol_id: id,
            binder: 0,
            amode,
            rmode,
            length: len,
            alignment: align,
        }
    }

    /// Create an External Reference ESD.
    pub fn new_er(name: &str, id: u32) -> Self {
        GoffEsdRecord {
            name: name.to_string(),
            esd_type: goff_esd::ER,
            symbol_id: id,
            binder: 0,
            amode: 0,
            rmode: 0,
            length: 0,
            alignment: 0,
        }
    }

    /// Create a Weak External ESD.
    pub fn new_wx(name: &str, id: u32) -> Self {
        GoffEsdRecord {
            name: name.to_string(),
            esd_type: goff_esd::WX,
            symbol_id: id,
            binder: 0,
            amode: 0,
            rmode: 0,
            length: 0,
            alignment: 0,
        }
    }

    /// Create a Common ESD.
    pub fn new_cm(name: &str, id: u32, len: u64, align: u64) -> Self {
        GoffEsdRecord {
            name: name.to_string(),
            esd_type: goff_esd::CM,
            symbol_id: id,
            binder: 0,
            amode: 0,
            rmode: 0,
            length: len,
            alignment: align,
        }
    }
}

// ============================================================================
// SPIR-V Binary Format
// ============================================================================

/// SPIR-V magic number.
pub const SPIRV_MAGIC: u32 = 0x07230203;

/// SPIR-V module header.
#[derive(Debug, Clone)]
pub struct SpirvHeader {
    pub magic: u32,
    pub version: u32,
    pub generator_magic: u32,
    pub bound: u32,  // All IDs will be < bound
    pub schema: u32, // 0 for SPIR-V
}

impl SpirvHeader {
    pub fn is_valid(&self) -> bool {
        self.magic == SPIRV_MAGIC
    }

    pub fn version_major(&self) -> u32 {
        (self.version >> 16) & 0xFF
    }

    pub fn version_minor(&self) -> u32 {
        (self.version >> 8) & 0xFF
    }
}

/// SPIR-V instruction (word stream).
#[derive(Debug, Clone)]
pub struct SpirvInstruction {
    pub word_count: u16,
    pub opcode: u16,
    pub operands: Vec<u32>,
}

/// SPIR-V module parser.
#[derive(Debug, Clone)]
pub struct SpirvModule {
    pub header: SpirvHeader,
    pub instructions: Vec<SpirvInstruction>,
}

impl SpirvModule {
    /// Parse a SPIR-V binary blob.
    pub fn parse(data: &[u8]) -> Result<Self, String> {
        if data.len() < 20 {
            return Err("SPIR-V data too short for header".to_string());
        }

        let magic = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
        if magic != SPIRV_MAGIC {
            return Err(format!("Invalid SPIR-V magic: 0x{:08X}", magic));
        }

        let header = SpirvHeader {
            magic,
            version: u32::from_le_bytes([data[4], data[5], data[6], data[7]]),
            generator_magic: u32::from_le_bytes([data[8], data[9], data[10], data[11]]),
            bound: u32::from_le_bytes([data[12], data[13], data[14], data[15]]),
            schema: u32::from_le_bytes([data[16], data[17], data[18], data[19]]),
        };

        let mut instructions: Vec<SpirvInstruction> = Vec::new();
        let mut offset = 20usize;

        while offset + 4 <= data.len() {
            let word0 = u32::from_le_bytes([
                data[offset],
                data[offset + 1],
                data[offset + 2],
                data[offset + 3],
            ]);
            let word_count = (word0 >> 16) as u16;
            let opcode = (word0 & 0xFFFF) as u16;

            if word_count == 0 {
                break;
            }

            let instr_end = offset + (word_count as usize) * 4;
            if instr_end > data.len() {
                return Err(format!(
                    "SPIR-V instruction extends past end of data at offset {}",
                    offset
                ));
            }

            let mut operands: Vec<u32> = Vec::with_capacity(word_count as usize - 1);
            for i in 1..word_count as usize {
                let word_offset = offset + i * 4;
                operands.push(u32::from_le_bytes([
                    data[word_offset],
                    data[word_offset + 1],
                    data[word_offset + 2],
                    data[word_offset + 3],
                ]));
            }

            instructions.push(SpirvInstruction {
                word_count,
                opcode,
                operands,
            });

            offset = instr_end;
        }

        Ok(SpirvModule {
            header,
            instructions,
        })
    }

    /// Get the number of instructions in this module.
    pub fn instruction_count(&self) -> usize {
        self.instructions.len()
    }
}

// ============================================================================
// Archive Format Extensions: Thin Archives, BSD/GNU Variants
// ============================================================================

/// Archive magic string.
pub const ARMAG: &str = "!<arch>\n";
/// Thin archive magic string.
pub const THIN_ARMAG: &str = "!<thin>\n";

/// Archive member header (ar_hdr).
#[derive(Debug, Clone)]
pub struct ArchiveMemberHeader {
    pub name: [u8; 16],
    pub date: [u8; 12],
    pub uid: [u8; 6],
    pub gid: [u8; 6],
    pub mode: [u8; 8],
    pub size: [u8; 10],
    pub fmag: [u8; 2], // "`\n"
}

/// Archive symbol table format variants.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArchiveSymbolTableFormat {
    /// SVR4/GNU ranlib format: big-endian 32-bit count + 32-bit offsets + strings
    Svr4Gnu,
    /// BSD format: long count + offsets + strings + ranlib structures
    Bsd,
    /// Darwin (macOS) variant.
    Darwin,
    /// AIX big-archive (big endian).
    Aix,
}

/// Parsed archive symbol table.
#[derive(Debug, Clone)]
pub struct ArchiveSymbolTable {
    pub format: ArchiveSymbolTableFormat,
    pub symbol_map: HashMap<String, usize>, // symbol name → member index
    pub member_names: Vec<String>,
}

/// A parsed archive file.
#[derive(Debug, Clone)]
pub struct ArchiveFile {
    pub is_thin: bool,
    pub members: Vec<ArchiveMember>,
    pub symbol_table: Option<ArchiveSymbolTable>,
    pub string_table: Vec<u8>, // long filename string table
}

/// A single member of an archive.
#[derive(Debug, Clone)]
pub struct ArchiveMember {
    pub name: String,
    pub header: ArchiveMemberHeader,
    pub data: Vec<u8>,
    pub member_index: usize,
}

impl ArchiveFile {
    /// Detect whether a byte slice looks like an archive (thin or regular).
    pub fn detect(data: &[u8]) -> bool {
        data.len() >= 8
            && (data.starts_with(ARMAG.as_bytes()) || data.starts_with(THIN_ARMAG.as_bytes()))
    }

    /// Parse a full archive (ar) file.
    pub fn parse(data: &[u8]) -> Result<Self, String> {
        if data.len() < 8 {
            return Err("Archive too short".to_string());
        }

        let is_thin = data.starts_with(THIN_ARMAG.as_bytes());
        let is_regular = data.starts_with(ARMAG.as_bytes());
        if !is_thin && !is_regular {
            return Err("Invalid archive magic".to_string());
        }

        let mut members: Vec<ArchiveMember> = Vec::new();
        let mut offset = 8usize; // skip magic
        let mut member_index = 0usize;

        while offset + 60 <= data.len() {
            // Read member header (60 bytes)
            let hdr_data = &data[offset..offset + 60];

            // Check for end-of-archive markers
            if hdr_data[0] == 0x00 || (hdr_data[0] == b'\n' && hdr_data[1] == b'\n') {
                break;
            }

            let mut header = ArchiveMemberHeader {
                name: [0u8; 16],
                date: [0u8; 12],
                uid: [0u8; 6],
                gid: [0u8; 6],
                mode: [0u8; 8],
                size: [0u8; 10],
                fmag: [0u8; 2],
            };

            header.name.copy_from_slice(&hdr_data[0..16]);
            header.date.copy_from_slice(&hdr_data[16..28]);
            header.uid.copy_from_slice(&hdr_data[28..34]);
            header.gid.copy_from_slice(&hdr_data[34..40]);
            header.mode.copy_from_slice(&hdr_data[40..48]);
            header.size.copy_from_slice(&hdr_data[48..58]);
            header.fmag.copy_from_slice(&hdr_data[58..60]);

            // Parse member size
            let size_str = std::str::from_utf8(&header.size)
                .map_err(|_| "Invalid size field in archive header".to_string())?
                .trim();
            let member_size: u64 = size_str
                .parse()
                .map_err(|_| format!("Invalid member size: {}", size_str))?;

            // Parse member name
            let name_bytes = &header.name;
            let name = if name_bytes[0] == b'/' && name_bytes[1] == b'/' {
                // System V/GNU long filename via string table
                format!("//long/name/{}", member_index)
            } else if name_bytes[0] == b'/' {
                // Extended name: /N where N is offset in string table
                format!("//ext/{}", member_index)
            } else if name_bytes[0] == b'#' && name_bytes[1] == b'1' && name_bytes[2] == b'/' {
                // Special member: symbol table
                String::from_utf8_lossy(&header.name).trim_end().to_string()
            } else {
                String::from_utf8_lossy(&header.name).trim_end().to_string()
            };

            offset += 60; // past header
            let data_end = offset + member_size as usize;
            if data_end > data.len() {
                return Err(format!("Archive member '{}' extends past EOF", name));
            }

            let member_data = data[offset..data_end].to_vec();
            members.push(ArchiveMember {
                name: name.clone(),
                header,
                data: member_data,
                member_index,
            });

            member_index += 1;
            // Align to even byte boundary (ar format padding)
            if member_size % 2 != 0 {
                offset = data_end + 1;
            } else {
                offset = data_end;
            }
        }

        Ok(ArchiveFile {
            is_thin,
            members,
            symbol_table: None,
            string_table: Vec::new(),
        })
    }

    /// Find a member by name.
    pub fn find_member(&self, name: &str) -> Option<&ArchiveMember> {
        self.members.iter().find(|m| m.name == name)
    }

    /// Get the number of members.
    pub fn member_count(&self) -> usize {
        self.members.len()
    }
}

/// Parse an XCOFF object file from raw bytes.
pub fn parse_xcoff(data: &[u8]) -> Result<XcoffFileHeader, String> {
    if data.len() < 20 {
        return Err("XCOFF data too short for header".to_string());
    }
    let magic = u16::from_be_bytes([data[0], data[1]]);
    if magic != XCOFF32_MAGIC && magic != XCOFF64_MAGIC {
        return Err(format!("Invalid XCOFF magic: 0x{:04X}", magic));
    }

    let num_sections = u16::from_be_bytes([data[2], data[3]]);
    let timestamp = i32::from_be_bytes([data[4], data[5], data[6], data[7]]);
    let symtab_offset = if magic == XCOFF64_MAGIC {
        u64::from_be_bytes([0, 0, 0, 0, data[8], data[9], data[10], data[11]])
    } else {
        u32::from_be_bytes([data[8], data[9], data[10], data[11]]) as u64
    };
    let symtab_count = i32::from_be_bytes([data[12], data[13], data[14], data[15]]);
    let optional_header_size = u16::from_be_bytes([data[16], data[17]]);
    let flags = u16::from_be_bytes([data[18], data[19]]);

    Ok(XcoffFileHeader {
        magic,
        num_sections,
        timestamp,
        symtab_offset,
        symtab_count,
        optional_header_size,
        flags,
    })
}

/// Parse XCOFF section headers.
pub fn parse_xcoff_sections(
    data: &[u8],
    header: &XcoffFileHeader,
) -> Result<Vec<XcoffSectionHeader>, String> {
    let mut sections: Vec<XcoffSectionHeader> = Vec::new();
    let hdr_size = if header.is_64bit() { 72 } else { 40 };
    let mut offset = 20 + header.optional_header_size as usize;

    for _ in 0..header.num_sections {
        if offset + hdr_size > data.len() {
            break;
        }

        // Read name (8 bytes)
        let name = String::from_utf8_lossy(&data[offset..offset + 8])
            .trim_end_matches('\0')
            .to_string();
        offset += 8;

        let paddr = u64::from_be_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
            data[offset + 4],
            data[offset + 5],
            data[offset + 6],
            data[offset + 7],
        ]);
        offset += 8;

        let vaddr = u64::from_be_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
            data[offset + 4],
            data[offset + 5],
            data[offset + 6],
            data[offset + 7],
        ]);
        offset += 8;

        let size = u64::from_be_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
            data[offset + 4],
            data[offset + 5],
            data[offset + 6],
            data[offset + 7],
        ]);
        offset += 8;

        let scnptr = u64::from_be_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
            data[offset + 4],
            data[offset + 5],
            data[offset + 6],
            data[offset + 7],
        ]);
        offset += 8;

        let relptr = u64::from_be_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
            data[offset + 4],
            data[offset + 5],
            data[offset + 6],
            data[offset + 7],
        ]);
        offset += 8;

        let lnnoptr = u64::from_be_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
            data[offset + 4],
            data[offset + 5],
            data[offset + 6],
            data[offset + 7],
        ]);
        offset += 8;

        let num_relocs = u32::from_be_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
        ]);
        offset += 4;

        let num_lnno = u32::from_be_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
        ]);
        offset += 4;

        let flags = u32::from_be_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
        ]);
        offset += 4;

        sections.push(XcoffSectionHeader {
            name,
            paddr,
            vaddr,
            size,
            scnptr,
            relptr,
            lnnoptr,
            num_relocs,
            num_lnno,
            flags,
        });
    }

    Ok(sections)
}

/// Parse GOFF header from raw bytes.
pub fn parse_goff_header(data: &[u8]) -> Result<GoffHeader, String> {
    if data.len() < 4 {
        return Err("GOFF data too short".to_string());
    }
    let level = data[0];
    let length = u32::from_be_bytes([0, data[1], data[2], data[3]]);
    Ok(GoffHeader { level, length })
}

/// Convert archive member name from ar_hdr format.
pub fn archive_member_name(header: &ArchiveMemberHeader) -> String {
    let raw = &header.name;
    // Trim trailing spaces and slashes
    let end = raw
        .iter()
        .position(|&b| b == b' ' || b == b'/')
        .unwrap_or(16);
    String::from_utf8_lossy(&raw[..end])
        .trim_end_matches('/')
        .to_string()
}

/// Parse archive symbol table in SVR4/GNU format.
pub fn parse_archive_symtab_svr4(data: &[u8]) -> Result<ArchiveSymbolTable, String> {
    if data.len() < 4 {
        return Err("Symbol table too short".to_string());
    }

    // First 4 bytes: number of symbols (big-endian)
    let num_symbols = u32::from_be_bytes([data[0], data[1], data[2], data[3]]) as usize;

    // Next num_symbols * 4 bytes: offsets into member data
    let offset_end = 4 + num_symbols * 4;
    if data.len() < offset_end {
        return Err("Symbol table truncated".to_string());
    }

    let mut member_offsets: Vec<u32> = Vec::with_capacity(num_symbols);
    for i in 0..num_symbols {
        let off = u32::from_be_bytes([
            data[4 + i * 4],
            data[5 + i * 4],
            data[6 + i * 4],
            data[7 + i * 4],
        ]);
        member_offsets.push(off);
    }

    // Remaining bytes: string table of symbol names
    let strtab = &data[offset_end..];
    let mut symbol_map: HashMap<String, usize> = HashMap::new();
    let mut member_names: Vec<String> = Vec::new();

    // Parse null-terminated strings
    let mut start = 0usize;
    for i in 0..num_symbols {
        let end = strtab[start..]
            .iter()
            .position(|&b| b == 0)
            .map(|p| start + p)
            .unwrap_or(strtab.len());
        let name = String::from_utf8_lossy(&strtab[start..end]).to_string();
        symbol_map.insert(name.clone(), i);
        member_names.push(name);
        start = end + 1;
        if start >= strtab.len() {
            break;
        }
    }

    Ok(ArchiveSymbolTable {
        format: ArchiveSymbolTableFormat::Svr4Gnu,
        symbol_map,
        member_names,
    })
}

// ============================================================================
// Archive Format Utilities and AIX big-archive support
// ============================================================================

/// AIX big-archive magic ("<bigaf>\n").
pub const BIG_ARMAG: &str = "<bigaf>\n";

/// AIX big-archive fixed-length member header (fl_mem).
#[derive(Debug, Clone)]
pub struct BigArchiveMemberHeader {
    /// Member name (20 bytes, EBCDIC).
    pub name: [u8; 20],
    /// File offset to member data (20 bytes).
    pub first_page_offset: u64,
    /// File offset to next member header (20 bytes).
    pub next_member_offset: u64,
    /// File offset to previous member header (20 bytes).
    pub prev_member_offset: u64,
    /// Date in EBCDIC (12 bytes).
    pub date: [u8; 12],
    /// User ID (12 bytes, EBCDIC).
    pub uid: [u8; 12],
    /// Group ID (12 bytes, EBCDIC).
    pub gid: [u8; 12],
    /// File mode (12 bytes, EBCDIC).
    pub mode: [u8; 12],
    /// Member total size (20 bytes).
    pub size: u64,
}

/// Parsed AIX big-archive.
#[derive(Debug, Clone)]
pub struct BigArchiveFile {
    pub member_count: u64,
    pub gst_offset: u64,   // global symbol table offset
    pub gst64_offset: u64, // 64-bit global symbol table offset
    pub first_member_offset: u64,
    pub last_member_offset: u64,
    pub members: Vec<BigArchiveMember>,
}

/// A member of an AIX big-archive.
#[derive(Debug, Clone)]
pub struct BigArchiveMember {
    pub name: String,
    pub header: BigArchiveMemberHeader,
    pub data: Vec<u8>,
}

impl BigArchiveFile {
    /// Detect whether data is an AIX big-archive.
    pub fn detect(data: &[u8]) -> bool {
        data.len() >= 8 && data.starts_with(BIG_ARMAG.as_bytes())
    }

    /// Parse the fixed-length header (128 bytes).
    pub fn parse_header(data: &[u8]) -> Result<Self, String> {
        if !Self::detect(data) {
            return Err("Not a big archive".to_string());
        }
        if data.len() < 128 {
            return Err("Big archive header too short".to_string());
        }

        let member_count = u64::from_be_bytes([0, 0, 0, 0, 0, 0, 0, 0]);
        let gst_offset = u64::from_be_bytes([
            data[68], data[69], data[70], data[71], data[72], data[73], data[74], data[75],
        ]);
        let gst64_offset = u64::from_be_bytes([
            data[76], data[77], data[78], data[79], data[80], data[81], data[82], data[83],
        ]);
        let first_member_offset = u64::from_be_bytes([
            data[84], data[85], data[86], data[87], data[88], data[89], data[90], data[91],
        ]);
        let last_member_offset = u64::from_be_bytes([
            data[92], data[93], data[94], data[95], data[96], data[97], data[98], data[99],
        ]);

        Ok(BigArchiveFile {
            member_count,
            gst_offset,
            gst64_offset,
            first_member_offset,
            last_member_offset,
            members: Vec::new(),
        })
    }
}

/// WASM custom section header.
#[derive(Debug, Clone)]
pub struct WasmCustomSection {
    pub name: String,
    pub data: Vec<u8>,
}

/// WASM linking section (for object files).
#[derive(Debug, Clone)]
pub struct WasmLinkingSection {
    pub version: u32,
    pub symbol_table: Vec<WasmSymbolInfo>,
    pub segment_info: Vec<WasmSegmentInfo>,
    pub init_functions: Vec<u32>,
    pub comdat_info: Vec<WasmComdatInfo>,
}

/// WASM symbol info entry.
#[derive(Debug, Clone)]
pub struct WasmSymbolInfo {
    pub kind: u8, // SYMTAB_FUNCTION, SYMTAB_DATA, SYMTAB_GLOBAL, SYMTAB_SECTION
    pub flags: u32,
    pub index: u32,
}

/// WASM segment info.
#[derive(Debug, Clone)]
pub struct WasmSegmentInfo {
    pub name: String,
    pub alignment: u32,
    pub flags: u32,
}

/// WASM COMDAT info.
#[derive(Debug, Clone)]
pub struct WasmComdatInfo {
    pub name: String,
    pub flags: u32,
}

impl WasmLinkingSection {
    pub fn new() -> Self {
        WasmLinkingSection {
            version: 2,
            symbol_table: Vec::new(),
            segment_info: Vec::new(),
            init_functions: Vec::new(),
            comdat_info: Vec::new(),
        }
    }

    pub fn add_symbol(&mut self, info: WasmSymbolInfo) {
        self.symbol_table.push(info);
    }

    pub fn add_segment(&mut self, info: WasmSegmentInfo) {
        self.segment_info.push(info);
    }
}

/// Thin archive member: stores only the path, not the data.
#[derive(Debug, Clone)]
pub struct ThinArchiveMember {
    pub name: String,
    pub path: String, // path to the actual object file
    pub header: ArchiveMemberHeader,
}

/// Detect thin archives.
pub fn is_thin_archive(data: &[u8]) -> bool {
    data.len() >= 8 && data.starts_with(THIN_ARMAG.as_bytes())
}

/// Parse a thin archive (only stores member paths).
pub fn parse_thin_archive(data: &[u8]) -> Result<Vec<ThinArchiveMember>, String> {
    if !is_thin_archive(data) {
        return Err("Not a thin archive".to_string());
    }
    let mut members: Vec<ThinArchiveMember> = Vec::new();
    let mut offset = 8usize;

    while offset + 60 <= data.len() {
        let hdr_data = &data[offset..offset + 60];
        if hdr_data[0] == 0x00 {
            break;
        }

        let mut header = ArchiveMemberHeader {
            name: [0u8; 16],
            date: [0u8; 12],
            uid: [0u8; 6],
            gid: [0u8; 6],
            mode: [0u8; 8],
            size: [0u8; 10],
            fmag: [0u8; 2],
        };
        header.name.copy_from_slice(&hdr_data[0..16]);
        header.date.copy_from_slice(&hdr_data[16..28]);
        header.uid.copy_from_slice(&hdr_data[28..34]);
        header.gid.copy_from_slice(&hdr_data[34..40]);
        header.mode.copy_from_slice(&hdr_data[40..48]);
        header.size.copy_from_slice(&hdr_data[48..58]);
        header.fmag.copy_from_slice(&hdr_data[58..60]);

        let name = archive_member_name(&header);
        let member_size: u64 = std::str::from_utf8(&header.size)
            .unwrap_or("0")
            .trim()
            .parse()
            .unwrap_or(0);

        // For thin archives, the "data" is the path to the real file
        let path_data = if offset + 60 + member_size as usize <= data.len() {
            &data[offset + 60..offset + 60 + member_size as usize]
        } else {
            &[]
        };
        let path = String::from_utf8_lossy(path_data)
            .trim_end_matches('\0')
            .trim_end_matches('\n')
            .to_string();

        members.push(ThinArchiveMember { name, path, header });

        offset += 60 + member_size as usize;
        if member_size % 2 != 0 {
            offset += 1;
        }
    }

    Ok(members)
}

// ============================================================================
// XCOFF64 (AIX) Object File Support
// ============================================================================

/// XCOFF magic numbers.
pub const XCOFF_MAGIC_32: u16 = 0x01DF;
pub const XCOFF_MAGIC_64: u16 = 0x01F7;

/// XCOFF file header (64-bit).
#[derive(Debug, Clone)]
pub struct Xcoff64Header {
    pub magic: u16,
    pub nscns: u16,
    pub timdat: u32,
    pub symptr: u64,
    pub nsyms: u32,
    pub opthdr: u16,
    pub flags: u16,
}

/// XCOFF section header (64-bit).
#[derive(Debug, Clone)]
pub struct Xcoff64SectionHeader {
    pub name: String,
    pub paddr: u64,
    pub vaddr: u64,
    pub size: u64,
    pub scnptr: u64,
    pub relptr: u64,
    pub lnnoptr: u64,
    pub nreloc: u32,
    pub nlnno: u32,
    pub flags: u32,
}

/// XCOFF symbol table entry (64-bit).
#[derive(Debug, Clone)]
pub struct Xcoff64Symbol {
    pub name: String,
    pub value: u64,
    pub n_scnum: i16,
    pub n_type: u16,
    pub n_sclass: u8,
    pub n_numaux: u8,
}

// XCOFF auxiliary entry types — using existing XcoffAuxEntry enum defined above (line ~1985).
// All XCOFF parser code below has been adapted to use existing type field names.

/// XCOFF relocation entry (64-bit).
#[derive(Debug, Clone)]
pub struct Xcoff64Relocation {
    pub vaddr: u64,
    pub symbol_index: u32,
    pub rtype: u8,
    pub rsize: u8,
}

/// XCOFF64 object file representation.
#[derive(Debug, Clone)]
pub struct Xcoff64ObjectFile {
    pub header: Xcoff64Header,
    pub sections: Vec<Xcoff64SectionHeader>,
    pub symbols: Vec<Xcoff64Symbol>,
    pub aux_entries: Vec<Vec<XcoffAuxEntry>>,
    pub relocations: Vec<Vec<Xcoff64Relocation>>,
    pub string_table: Vec<u8>,
}

/// Parse an XCOFF64 object file from raw data.
pub fn parse_xcoff64(data: &[u8]) -> Result<Xcoff64ObjectFile, String> {
    if data.len() < 24 {
        return Err("data too short for XCOFF64 header".into());
    }

    let magic = u16::from_be_bytes([data[0], data[1]]);
    if magic != XCOFF_MAGIC_64 {
        return Err(format!("invalid XCOFF64 magic: {:#06x}", magic));
    }

    let nscns = u16::from_be_bytes([data[2], data[3]]);
    let timdat = u32::from_be_bytes([data[4], data[5], data[6], data[7]]);
    let symptr = u64::from_be_bytes([
        data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15],
    ]);
    let nsyms = u32::from_be_bytes([data[16], data[17], data[18], data[19]]);
    let opthdr = u16::from_be_bytes([data[20], data[21]]);
    let flags = u16::from_be_bytes([data[22], data[23]]);

    let header = Xcoff64Header {
        magic,
        nscns,
        timdat,
        symptr,
        nsyms,
        opthdr,
        flags,
    };

    // Parse section headers (72 bytes each for 64-bit).
    let shdr_offset: usize = 24 + opthdr as usize;
    let shdr_size: usize = 72;
    let mut sections: Vec<Xcoff64SectionHeader> = Vec::with_capacity(nscns as usize);

    for i in 0..nscns as usize {
        let off = shdr_offset + i * shdr_size;
        if off + shdr_size > data.len() {
            break;
        }

        // Section name (8 bytes, null-padded).
        let name_end = data[off..off + 8].iter().position(|&b| b == 0).unwrap_or(8);
        let name = String::from_utf8_lossy(&data[off..off + name_end]).into_owned();

        let paddr = u64::from_be_bytes([
            data[off + 8],
            data[off + 9],
            data[off + 10],
            data[off + 11],
            data[off + 12],
            data[off + 13],
            data[off + 14],
            data[off + 15],
        ]);
        let vaddr = u64::from_be_bytes([
            data[off + 16],
            data[off + 17],
            data[off + 18],
            data[off + 19],
            data[off + 20],
            data[off + 21],
            data[off + 22],
            data[off + 23],
        ]);
        let size = u64::from_be_bytes([
            data[off + 24],
            data[off + 25],
            data[off + 26],
            data[off + 27],
            data[off + 28],
            data[off + 29],
            data[off + 30],
            data[off + 31],
        ]);
        let scnptr = u64::from_be_bytes([
            data[off + 32],
            data[off + 33],
            data[off + 34],
            data[off + 35],
            data[off + 36],
            data[off + 37],
            data[off + 38],
            data[off + 39],
        ]);
        let relptr = u64::from_be_bytes([
            data[off + 40],
            data[off + 41],
            data[off + 42],
            data[off + 43],
            data[off + 44],
            data[off + 45],
            data[off + 46],
            data[off + 47],
        ]);
        let lnnoptr = u64::from_be_bytes([
            data[off + 48],
            data[off + 49],
            data[off + 50],
            data[off + 51],
            data[off + 52],
            data[off + 53],
            data[off + 54],
            data[off + 55],
        ]);
        let nreloc = u32::from_be_bytes([
            data[off + 56],
            data[off + 57],
            data[off + 58],
            data[off + 59],
        ]);
        let nlnno = u32::from_be_bytes([
            data[off + 60],
            data[off + 61],
            data[off + 62],
            data[off + 63],
        ]);
        let flags_val = u32::from_be_bytes([
            data[off + 64],
            data[off + 65],
            data[off + 66],
            data[off + 67],
        ]);

        sections.push(Xcoff64SectionHeader {
            name,
            paddr,
            vaddr,
            size,
            scnptr,
            relptr,
            lnnoptr,
            nreloc,
            nlnno,
            flags: flags_val,
        });
    }

    // Parse symbol table.
    let mut symbols: Vec<Xcoff64Symbol> = Vec::new();
    let mut aux_entries: Vec<Vec<XcoffAuxEntry>> = Vec::new();

    let sym_size: usize = 18; // 64-bit symbol entry size
    let strtab_off = symptr as usize + nsyms as usize * sym_size;
    let string_table = if strtab_off + 4 <= data.len() {
        let strtab_len = u32::from_be_bytes([
            data[strtab_off],
            data[strtab_off + 1],
            data[strtab_off + 2],
            data[strtab_off + 3],
        ]) as usize;
        if strtab_off + strtab_len <= data.len() {
            data[strtab_off..strtab_off + strtab_len].to_vec()
        } else {
            vec![0u8; 4]
        }
    } else {
        vec![0u8; 4]
    };

    let mut sym_idx: usize = 0;
    while sym_idx < nsyms as usize {
        let off = symptr as usize + sym_idx * sym_size;
        if off + sym_size > data.len() {
            break;
        }

        // Symbol name (8 bytes).
        let name = if data[off] == 0
            && data[off + 1] == 0
            && data[off + 2] == 0
            && data[off + 3] == 0
        {
            // Long name: offset in string table.
            let stroff =
                u32::from_be_bytes([data[off + 4], data[off + 5], data[off + 6], data[off + 7]])
                    as usize;
            let end = string_table[stroff..]
                .iter()
                .position(|&b| b == 0)
                .map(|p| stroff + p)
                .unwrap_or(string_table.len());
            String::from_utf8_lossy(&string_table[stroff..end.min(string_table.len())]).into_owned()
        } else {
            let end = data[off..off + 8].iter().position(|&b| b == 0).unwrap_or(8);
            String::from_utf8_lossy(&data[off..off + end]).into_owned()
        };

        let value = u64::from_be_bytes([
            data[off + 8],
            data[off + 9],
            data[off + 10],
            data[off + 11],
            data[off + 12],
            data[off + 13],
            data[off + 14],
            data[off + 15],
        ]);
        let n_scnum = i16::from_be_bytes([data[off + 16], data[off + 17]]);
        let n_type = u16::from_be_bytes([data[off + 18], data[off + 19]]);
        let n_sclass = data[off + 20];
        let n_numaux = data[off + 21];

        let sym = Xcoff64Symbol {
            name,
            value,
            n_scnum,
            n_type,
            n_sclass,
            n_numaux,
        };
        symbols.push(sym);

        // Parse auxiliary entries.
        let mut aux: Vec<XcoffAuxEntry> = Vec::new();
        let sclass = data[off + 20];

        for a in 0..n_numaux as usize {
            let aux_off = off + (1 + a) * sym_size;
            if aux_off + sym_size > data.len() {
                break;
            }

            match sclass {
                // C_EXT, C_HIDEXT, C_WEAKEXT: CSECT aux entry.
                2 | 107 | 111 => {
                    let scnlen = u64::from_be_bytes([
                        data[aux_off],
                        data[aux_off + 1],
                        data[aux_off + 2],
                        data[aux_off + 3],
                        data[aux_off + 4],
                        data[aux_off + 5],
                        data[aux_off + 6],
                        data[aux_off + 7],
                    ]);
                    let parmhash = u32::from_be_bytes([
                        data[aux_off + 8],
                        data[aux_off + 9],
                        data[aux_off + 10],
                        data[aux_off + 11],
                    ]);
                    let snstype = u16::from_be_bytes([data[aux_off + 12], data[aux_off + 13]]);
                    let smclass = data[aux_off + 14];
                    let smtype = data[aux_off + 15];
                    let stabcnt = u16::from_be_bytes([data[aux_off + 16], data[aux_off + 17]]);

                    aux.push(XcoffAuxEntry::Csect {
                        length: scnlen,
                        parm_hash: parmhash,
                        sn_type: snstype as u8,
                        smclas: smclass,
                        stab: 0,
                        x_snstab: stabcnt,
                    });
                }
                // Function aux entry (n_numaux >= 1 after a function symbol).
                _ => {
                    let size = u64::from_be_bytes([
                        data[aux_off],
                        data[aux_off + 1],
                        data[aux_off + 2],
                        data[aux_off + 3],
                        data[aux_off + 4],
                        data[aux_off + 5],
                        data[aux_off + 6],
                        data[aux_off + 7],
                    ]);
                    let lineno = u64::from_be_bytes([
                        data[aux_off + 8],
                        data[aux_off + 9],
                        data[aux_off + 10],
                        data[aux_off + 11],
                        data[aux_off + 12],
                        data[aux_off + 13],
                        data[aux_off + 14],
                        data[aux_off + 15],
                    ]);
                    let fcnptr = u64::from_be_bytes([
                        data[aux_off + 16],
                        data[aux_off + 17],
                        data[aux_off + 18],
                        data[aux_off + 19],
                        data[aux_off + 20],
                        data[aux_off + 21],
                        data[aux_off + 22],
                        data[aux_off + 23],
                    ]);

                    aux.push(XcoffAuxEntry::Function {
                        offset_to_exception_table: 0,
                        size_of_function: size,
                        line_number_pointer: lineno,
                        end_index: 0,
                    });
                }
            }
        }

        aux_entries.push(aux);
        sym_idx += 1 + n_numaux as usize;
    }

    // Parse relocations for each section.
    let mut relocations: Vec<Vec<Xcoff64Relocation>> = Vec::new();
    for sec in &sections {
        let mut sec_relocs: Vec<Xcoff64Relocation> = Vec::new();
        let rel_size: usize = 14;
        for r in 0..sec.nreloc as usize {
            let roff = sec.relptr as usize + r * rel_size;
            if roff + rel_size > data.len() {
                break;
            }
            let vaddr = u64::from_be_bytes([
                data[roff],
                data[roff + 1],
                data[roff + 2],
                data[roff + 3],
                data[roff + 4],
                data[roff + 5],
                data[roff + 6],
                data[roff + 7],
            ]);
            let symbol_index = u32::from_be_bytes([
                data[roff + 8],
                data[roff + 9],
                data[roff + 10],
                data[roff + 11],
            ]);
            let rtype = data[roff + 12];
            let rsize = data[roff + 13];

            sec_relocs.push(Xcoff64Relocation {
                vaddr,
                symbol_index,
                rtype,
                rsize,
            });
        }
        relocations.push(sec_relocs);
    }

    Ok(Xcoff64ObjectFile {
        header,
        sections,
        symbols,
        aux_entries,
        relocations,
        string_table,
    })
}

impl ObjectFile {
    /// Convert an XCOFF64 object file to the universal ObjectFile representation.
    pub fn from_xcoff64(xcoff: &Xcoff64ObjectFile, data: &[u8]) -> Self {
        let mut sections = Vec::new();
        for sec in &xcoff.sections {
            let sec_data = if sec.size > 0 && sec.scnptr > 0 {
                let start = sec.scnptr as usize;
                let end = (start + sec.size as usize).min(data.len());
                if start < data.len() {
                    data[start..end].to_vec()
                } else {
                    Vec::new()
                }
            } else {
                Vec::new()
            };

            sections.push(ObjectSection {
                name: sec.name.clone(),
                section_type: sec.flags,
                data: sec_data,
                vaddr: sec.vaddr,
                size: sec.size,
                flags: sec.flags as u64,
            });
        }

        let mut symbols = Vec::new();
        for sym in &xcoff.symbols {
            let is_global = matches!(sym.n_sclass, 2 | 107 | 111); // C_EXT, C_HIDEXT, C_WEAKEXT
            symbols.push(ObjectSymbol {
                name: sym.name.clone(),
                value: sym.value,
                size: 0,
                is_global,
                is_function: sym.n_type & 0x20 != 0,
                section_index: sym.n_scnum as u16,
            });
        }

        ObjectFile {
            format: ObjectFormat::Unknown, // XCOFF is not in the enum; using Unknown
            machine: "powerpc64".to_string(),
            sections,
            symbols,
            entry: 0,
            flags: xcoff.header.flags as u32,
        }
    }
}

// ============================================================================
// GOFF (z/OS) Object File Support — additional parser/reader
// ============================================================================

/// GOFF object file representation (using existing record types).
#[derive(Debug, Clone)]
pub struct GoffObjectFile {
    pub esd_entries: Vec<GoffEsdRecord>,
    pub txt_records: Vec<GoffTxtRecord>,
    pub rld_records: Vec<GoffRldRecord>,
    pub section_data: HashMap<u32, Vec<u8>>,
}

/// Parse a GOFF (z/OS) object file from raw ESD/TXT/RLD/END records.
pub fn parse_goff(data: &[u8]) -> Result<GoffObjectFile, String> {
    if data.len() < 4 {
        return Err("data too short for GOFF".into());
    }

    let mut esd_entries: Vec<GoffEsdRecord> = Vec::new();
    let mut txt_records: Vec<GoffTxtRecord> = Vec::new();
    let mut rld_records: Vec<GoffRldRecord> = Vec::new();
    let mut section_data: HashMap<u32, Vec<u8>> = HashMap::new();

    let mut pos: usize = 0;
    while pos + 4 <= data.len() {
        let record_length =
            u32::from_be_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize;

        if record_length == 0 {
            pos += 4;
            continue;
        }
        if pos + 4 + record_length > data.len() {
            break;
        }

        let record_type = data[pos + 4];
        let record_data = &data[pos + 5..pos + 4 + record_length];

        match record_type {
            // ESD record (type 0x00)
            0x00 => {
                let mut rpos: usize = 0;
                while rpos + 8 <= record_data.len() {
                    let entry_type = record_data[rpos];
                    let symbol_id = u32::from_be_bytes([
                        record_data[rpos + 1],
                        record_data[rpos + 2],
                        record_data[rpos + 3],
                        record_data[rpos + 4],
                    ]);
                    let name_len = record_data[rpos + 5] as usize;
                    let name = if rpos + 6 + name_len <= record_data.len() {
                        String::from_utf8_lossy(&record_data[rpos + 6..rpos + 6 + name_len])
                            .into_owned()
                    } else {
                        String::new()
                    };

                    let amode = *record_data.get(rpos + 6 + name_len).unwrap_or(&0);
                    let rmode = *record_data.get(rpos + 7 + name_len).unwrap_or(&0);
                    let length = if rpos + 8 + name_len + 8 <= record_data.len() {
                        u64::from_be_bytes([
                            record_data[rpos + 8 + name_len],
                            record_data[rpos + 9 + name_len],
                            record_data[rpos + 10 + name_len],
                            record_data[rpos + 11 + name_len],
                            record_data[rpos + 12 + name_len],
                            record_data[rpos + 13 + name_len],
                            record_data[rpos + 14 + name_len],
                            record_data[rpos + 15 + name_len],
                        ])
                    } else {
                        0
                    };
                    let alignment = if rpos + 16 + name_len + 8 <= record_data.len() {
                        u64::from_be_bytes([
                            record_data[rpos + 16 + name_len],
                            record_data[rpos + 17 + name_len],
                            record_data[rpos + 18 + name_len],
                            record_data[rpos + 19 + name_len],
                            record_data[rpos + 20 + name_len],
                            record_data[rpos + 21 + name_len],
                            record_data[rpos + 22 + name_len],
                            record_data[rpos + 23 + name_len],
                        ])
                    } else {
                        0
                    };

                    esd_entries.push(GoffEsdRecord {
                        name,
                        esd_type: entry_type,
                        symbol_id,
                        binder: 0,
                        amode,
                        rmode,
                        length,
                        alignment,
                    });

                    rpos += 13 + name_len + 3;
                }
            }
            // TXT record (type 0x01)
            0x01 => {
                if record_data.len() >= 12 {
                    let section_id = u32::from_be_bytes([
                        record_data[0],
                        record_data[1],
                        record_data[2],
                        record_data[3],
                    ]);
                    let offset = u64::from_be_bytes([
                        record_data[4],
                        record_data[5],
                        record_data[6],
                        record_data[7],
                        0,
                        0,
                        0,
                        0,
                    ]);
                    let data_length = u32::from_be_bytes([
                        record_data[8],
                        record_data[9],
                        record_data[10],
                        record_data[11],
                    ]) as usize;

                    let txt_data = if 12 + data_length <= record_data.len() {
                        record_data[12..12 + data_length].to_vec()
                    } else {
                        record_data[12..].to_vec()
                    };

                    txt_records.push(GoffTxtRecord {
                        section_id,
                        offset,
                        length: data_length as u32,
                        data: txt_data.clone(),
                    });

                    let sec = section_data.entry(section_id).or_default();
                    let end_offset = offset as usize + txt_data.len();
                    if end_offset > sec.len() {
                        sec.resize(end_offset, 0);
                    }
                    sec[offset as usize..offset as usize + txt_data.len()]
                        .copy_from_slice(&txt_data);
                }
            }
            // RLD record (type 0x02)
            0x02 => {
                let mut rpos: usize = 0;
                while rpos + 10 <= record_data.len() {
                    let symbol_id = u32::from_be_bytes([
                        record_data[rpos],
                        record_data[rpos + 1],
                        record_data[rpos + 2],
                        record_data[rpos + 3],
                    ]);
                    let position = u64::from_be_bytes([
                        record_data[rpos + 4],
                        record_data[rpos + 5],
                        record_data[rpos + 6],
                        record_data[rpos + 7],
                        0,
                        0,
                        0,
                        0,
                    ]);
                    let reloc_len = record_data[rpos + 8];
                    let flags_val = record_data[rpos + 9];
                    let addend = if rpos + 18 <= record_data.len() {
                        i64::from_be_bytes([
                            record_data[rpos + 10],
                            record_data[rpos + 11],
                            record_data[rpos + 12],
                            record_data[rpos + 13],
                            record_data[rpos + 14],
                            record_data[rpos + 15],
                            record_data[rpos + 16],
                            record_data[rpos + 17],
                        ])
                    } else {
                        0
                    };

                    rld_records.push(GoffRldRecord {
                        symbol_id,
                        position,
                        length: reloc_len,
                        flags: flags_val,
                        addend,
                    });

                    rpos += 18;
                }
            }
            // END record (type 0x03)
            0x03 => {
                break;
            }
            _ => {}
        }

        pos += 4 + record_length;
    }

    Ok(GoffObjectFile {
        esd_entries,
        txt_records,
        rld_records,
        section_data,
    })
}

impl ObjectFile {
    /// Convert a GOFF object file to the universal ObjectFile representation.
    pub fn from_goff(goff: &GoffObjectFile) -> Self {
        use llvm_native_core::object_file::goff_esd;
        let mut sections = Vec::new();
        let mut symbols = Vec::new();

        for esd in &goff.esd_entries {
            match esd.esd_type {
                goff_esd::SD => {
                    let sec_data = goff
                        .section_data
                        .get(&esd.symbol_id)
                        .cloned()
                        .unwrap_or_default();
                    sections.push(ObjectSection {
                        name: esd.name.clone(),
                        section_type: goff_esd::SD as u32,
                        data: sec_data,
                        vaddr: 0,
                        size: esd.length,
                        flags: 0,
                    });
                }
                goff_esd::LD | goff_esd::ED => {
                    symbols.push(ObjectSymbol {
                        name: esd.name.clone(),
                        value: 0,
                        size: esd.length,
                        is_global: esd.esd_type == goff_esd::ED,
                        is_function: false,
                        section_index: 1,
                    });
                }
                goff_esd::CM => {
                    symbols.push(ObjectSymbol {
                        name: esd.name.clone(),
                        value: 0,
                        size: esd.length,
                        is_global: true,
                        is_function: false,
                        section_index: 0,
                    });
                }
                goff_esd::WX => {
                    symbols.push(ObjectSymbol {
                        name: esd.name.clone(),
                        value: 0,
                        size: 0,
                        is_global: true,
                        is_function: false,
                        section_index: 0,
                    });
                }
                _ => {}
            }
        }

        ObjectFile {
            format: ObjectFormat::Unknown,
            machine: "s390x".to_string(),
            sections,
            symbols,
            entry: 0,
            flags: 0,
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    // === Format Detection Tests ===

    #[test]
    fn test_detect_format_elf64() {
        let mut data = vec![0u8; 64];
        data[0..4].copy_from_slice(&ELF_MAGIC);
        data[4] = 2; // ELFCLASS64
        let format = detect_format(&data);
        assert_eq!(format, Some(ObjectFormat::ELF64));
    }

    #[test]
    fn test_detect_format_elf32() {
        let mut data = vec![0u8; 64];
        data[0..4].copy_from_slice(&ELF_MAGIC);
        data[4] = 1; // ELFCLASS32
        let format = detect_format(&data);
        assert_eq!(format, Some(ObjectFormat::ELF32));
    }

    #[test]
    fn test_detect_format_macho64() {
        let data = vec![0xCF, 0xFA, 0xED, 0xFE, 0, 0, 0, 0]; // MH_MAGIC_64 LE
        let format = detect_format(&data);
        assert_eq!(format, Some(ObjectFormat::MachO64));
    }

    #[test]
    fn test_detect_format_wasm() {
        let data = vec![0x00, 0x61, 0x73, 0x6D, 1, 0, 0, 0]; // \0asm + version 1
        let format = detect_format(&data);
        assert_eq!(format, Some(ObjectFormat::Wasm));
    }

    #[test]
    fn test_detect_format_coff_x86_64() {
        let data = vec![0x64, 0x86, 0, 0, 0, 0, 0, 0]; // IMAGE_FILE_MACHINE_AMD64
        let format = detect_format(&data);
        assert_eq!(format, Some(ObjectFormat::COFF));
    }

    #[test]
    fn test_detect_format_none() {
        let data = vec![0xDE, 0xAD, 0xBE, 0xEF];
        let format = detect_format(&data);
        assert_eq!(format, None);
    }

    // === ELF Parsing Tests ===

    #[test]
    fn test_parse_elf_header_valid() {
        let mut data = vec![0u8; 64];
        data[0..4].copy_from_slice(&ELF_MAGIC);
        data[4] = 2; // ELFCLASS64
        data[5] = 1; // ELFDATA2LSB
        data[6] = 1;
        data[7] = 0;
        // e_machine = EM_X86_64
        data[18] = 62;
        data[19] = 0;
        let header = ObjectFile::parse_elf_header(&data);
        assert!(header.is_some());
        let h = header.unwrap();
        assert_eq!(h.machine, ElfMachine::X86_64);
        assert_eq!(h.ident.class, ElfClass::Elf64);
    }

    #[test]
    fn test_parse_elf_header_invalid_magic() {
        let data = vec![0u8; 64];
        let header = ObjectFile::parse_elf_header(&data);
        assert!(header.is_none());
    }

    #[test]
    fn test_parse_elf_header_aarch64() {
        let mut data = vec![0u8; 64];
        data[0..4].copy_from_slice(&ELF_MAGIC);
        data[4] = 2;
        data[5] = 1;
        data[6] = 1;
        data[7] = 0;
        data[18] = 183;
        data[19] = 0;
        let header = ObjectFile::parse_elf_header(&data);
        assert!(header.is_some());
        assert_eq!(header.unwrap().machine, ElfMachine::AArch64);
    }

    #[test]
    fn test_parse_elf_program_headers_empty() {
        let mut data = vec![0u8; 64];
        data[0..4].copy_from_slice(&ELF_MAGIC);
        data[4] = 2;
        data[5] = 1;
        data[6] = 1;
        data[56..58].copy_from_slice(&0u16.to_le_bytes()); // phnum = 0
        let phdrs = ObjectFile::parse_elf_program_headers(&data);
        assert!(phdrs.is_ok());
        assert!(phdrs.unwrap().is_empty());
    }

    #[test]
    fn test_object_file_parse_elf() {
        let mut data = vec![0u8; 128];
        data[0..4].copy_from_slice(&ELF_MAGIC);
        data[4] = 2; // ELFCLASS64
        data[5] = 1;
        data[6] = 1;
        data[7] = 0;
        data[18] = 62;
        data[19] = 0;
        // Set shoff far enough away for shstrndx
        data[60] = 1;
        data[61] = 0;
        // Section header table at offset 80
        data[40..48].copy_from_slice(&80u64.to_le_bytes());
        data[58] = 64; // shentsize = 64
        data[60] = 1; // shnum = 1
        data[62] = 1; // shstrndx = 1
        let obj = ObjectFile::parse(&data);
        assert!(obj.is_some());
        let obj = obj.unwrap();
        assert_eq!(obj.machine_name(), "x86_64");
        assert!(obj.is_valid());
    }

    // === Mach-O Parsing Tests ===

    #[test]
    fn test_parse_macho_header_valid() {
        let mut data = vec![0u8; 32];
        data[0..4].copy_from_slice(&[0xCF, 0xFA, 0xED, 0xFE]); // MH_MAGIC_64 LE
        data[4..8].copy_from_slice(&0x01000007u32.to_le_bytes()); // CPU_TYPE_X86_64
        data[12..16].copy_from_slice(&1u32.to_le_bytes()); // MH_OBJECT
        let header = ObjectFile::parse_macho_header(&data);
        assert!(header.is_ok());
        let h = header.unwrap();
        assert_eq!(h.cputype, 0x01000007);
        assert_eq!(h.filetype, 1);
    }

    #[test]
    fn test_parse_macho_header_invalid() {
        let data = vec![0u8; 32];
        let header = ObjectFile::parse_macho_header(&data);
        assert!(header.is_err());
    }

    #[test]
    fn test_parse_macho_load_commands_empty() {
        let mut data = vec![0u8; 32];
        data[0..4].copy_from_slice(&[0xCF, 0xFA, 0xED, 0xFE]);
        data[4..8].copy_from_slice(&0x01000007u32.to_le_bytes());
        data[12..16].copy_from_slice(&1u32.to_le_bytes());
        data[16..20].copy_from_slice(&0u32.to_le_bytes()); // ncmds = 0
        data[20..24].copy_from_slice(&0u32.to_le_bytes()); // sizeofcmds = 0
        let header = ObjectFile::parse_macho_header(&data).unwrap();
        let cmds = ObjectFile::parse_macho_load_commands(&data, &header);
        assert!(cmds.is_ok());
        assert!(cmds.unwrap().is_empty());
    }

    // === COFF Parsing Tests ===

    #[test]
    fn test_parse_coff_header_valid() {
        let data = vec![
            0x64, 0x86, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        ];
        let header = ObjectFile::parse_coff_header(&data);
        assert!(header.is_ok());
        let h = header.unwrap();
        assert_eq!(h.machine, 0x8664);
        assert_eq!(h.num_sections, 2);
    }

    #[test]
    fn test_parse_coff_header_invalid() {
        let data = vec![0u8; 10];
        let header = ObjectFile::parse_coff_header(&data);
        assert!(header.is_err());
    }

    // === Universal ObjectFile Tests ===

    #[test]
    fn test_object_file_get_section() {
        let obj = ObjectFile {
            format: ObjectFormat::ELF64,
            machine: "x86_64".to_string(),
            sections: vec![ObjectSection {
                name: ".text".to_string(),
                section_type: 1,
                data: vec![0x90, 0xC3],
                vaddr: 0,
                size: 2,
                flags: 6,
            }],
            symbols: Vec::new(),
            entry: 0,
            flags: 0,
        };
        let sec = obj.get_section(".text");
        assert!(sec.is_some());
        assert_eq!(sec.unwrap().data, vec![0x90, 0xC3]);
    }

    #[test]
    fn test_object_file_get_global_symbols() {
        let obj = ObjectFile {
            format: ObjectFormat::ELF64,
            machine: "x86_64".to_string(),
            sections: Vec::new(),
            symbols: vec![
                ObjectSymbol {
                    name: "main".to_string(),
                    value: 0x1000,
                    size: 32,
                    is_global: true,
                    is_function: true,
                    section_index: 1,
                },
                ObjectSymbol {
                    name: "helper".to_string(),
                    value: 0x1020,
                    size: 16,
                    is_global: false,
                    is_function: true,
                    section_index: 1,
                },
            ],
            entry: 0,
            flags: 0,
        };
        let globals = obj.get_global_symbols();
        assert_eq!(globals.len(), 1);
        assert_eq!(globals[0].name, "main");
    }

    #[test]
    fn test_object_file_find_function_symbols() {
        let obj = ObjectFile {
            format: ObjectFormat::ELF64,
            machine: "x86_64".to_string(),
            sections: Vec::new(),
            symbols: vec![
                ObjectSymbol {
                    name: "main".to_string(),
                    value: 0x1000,
                    size: 32,
                    is_global: true,
                    is_function: true,
                    section_index: 1,
                },
                ObjectSymbol {
                    name: "data_val".to_string(),
                    value: 0x2000,
                    size: 4,
                    is_global: true,
                    is_function: false,
                    section_index: 2,
                },
            ],
            entry: 0,
            flags: 0,
        };
        let funcs = obj.find_function_symbols();
        assert_eq!(funcs.len(), 1);
        assert_eq!(funcs[0].0, "main");
    }

    #[test]
    fn test_disassemble_section_x86_64() {
        let data = vec![0xC3, 0x90, 0xE9, 0x00, 0x00, 0x00, 0x00];
        let insts = ObjectFile::disassemble_section(&data, "x86_64", 0x1000);
        assert!(!insts.is_empty());
        assert_eq!(insts[0].mnemonic, "ret");
        assert_eq!(insts[0].address, 0x1000);
    }

    #[test]
    fn test_disassemble_section_arm64() {
        let data = vec![0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF];
        let insts = ObjectFile::disassemble_section(&data, "aarch64", 0x8000);
        assert_eq!(insts.len(), 2);
    }

    #[test]
    fn test_num_sections_and_symbols() {
        let obj = ObjectFile {
            format: ObjectFormat::ELF64,
            machine: "x86_64".to_string(),
            sections: vec![ObjectSection {
                name: ".text".to_string(),
                section_type: 1,
                data: vec![],
                vaddr: 0,
                size: 0,
                flags: 0,
            }],
            symbols: vec![ObjectSymbol {
                name: "main".to_string(),
                value: 0,
                size: 0,
                is_global: true,
                is_function: true,
                section_index: 1,
            }],
            entry: 0,
            flags: 0,
        };
        assert_eq!(obj.num_sections(), 1);
        assert_eq!(obj.num_symbols(), 1);
    }

    #[test]
    fn test_parse_elf_sections_data() {
        // Create a minimal valid ELF64 with sections
        let mut data = vec![0u8; 256];
        data[0..4].copy_from_slice(&ELF_MAGIC);
        data[4] = 2;
        data[5] = 1;
        data[6] = 1;
        data[16..18].copy_from_slice(&1u16.to_le_bytes()); // ET_REL
        data[18..20].copy_from_slice(&62u16.to_le_bytes()); // EM_X86_64
        data[40..48].copy_from_slice(&192u64.to_le_bytes()); // shoff = 192
        data[58] = 64; // shentsize
        data[60] = 1; // shnum = 1 (NULL only)
        data[62] = 1; // shstrndx
        let sections = ObjectFile::parse_elf_sections(&data);
        assert!(sections.is_ok());
    }

    #[test]
    fn test_get_symbols_in_section() {
        let obj = ObjectFile {
            format: ObjectFormat::ELF64,
            machine: "x86_64".to_string(),
            sections: Vec::new(),
            symbols: vec![
                ObjectSymbol {
                    name: "a".to_string(),
                    value: 0,
                    size: 0,
                    is_global: false,
                    is_function: true,
                    section_index: 1,
                },
                ObjectSymbol {
                    name: "b".to_string(),
                    value: 0,
                    size: 0,
                    is_global: true,
                    is_function: true,
                    section_index: 2,
                },
            ],
            entry: 0,
            flags: 0,
        };
        let sec1_syms = obj.get_symbols_in_section(1);
        assert_eq!(sec1_syms.len(), 1);
        assert_eq!(sec1_syms[0].name, "a");
    }

    #[test]
    fn test_parse_elf_dynamic_empty() {
        let data = vec![0u8; 64];
        let dynamic = ObjectFile::parse_elf_dynamic(&data);
        assert!(dynamic.is_ok());
    }

    #[test]
    fn test_parse_wasm() {
        let data = vec![0x00, 0x61, 0x73, 0x6D, 1, 0, 0, 0];
        let obj = ObjectFile::parse(&data);
        assert!(obj.is_some());
        let obj = obj.unwrap();
        assert_eq!(obj.format, ObjectFormat::Wasm);
    }

    // Legacy type test (kept for backward compat)
    #[test]
    fn test_object_file_is_valid() {
        let mut data = vec![0u8; 64];
        data[0..4].copy_from_slice(&ELF_MAGIC);
        data[4] = 2;
        data[5] = 1;
        data[6] = 1;
        data[18] = 62;
        let obj = ObjectFile::parse(&data);
        assert!(obj.is_some());
        assert!(obj.unwrap().is_valid());
    }
}