llvm-native-core 0.1.14

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
//! X86 Support Utilities — target triple parsing, CPU feature detection,
//! memory management, timing, endian utilities, binary format utilities,
//! and process/filesystem helpers for X86 targets.
//!
//! Clean-room behavioral reconstruction from:
//! - Intel® 64 and IA-32 Architectures Software Developer's Manual
//! - AMD64 Architecture Programmer's Manual
//! - System V ABI: AMD64 Architecture Processor Supplement
//! - ELF-64 Object File Format Specification
//! - PE/COFF Specification (Microsoft Portable Executable)
//! - Mach-O File Format Reference (Apple)
//! - POSIX.1-2008
//! - LLVM TargetParser / Triple normalization logic
//!
//! Zero LLVM source code consultation. All behavior reconstructed from
//! published specifications and black-box oracle interrogation.

#![allow(non_upper_case_globals, dead_code)]

use std::collections::HashMap;
use std::fmt;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

// ============================================================================
// X86 target triple parsing and normalization
// ============================================================================

/// X86 target architecture variants.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum X86Arch {
    I386,
    I486,
    I586,
    I686,
    Pentium,
    PentiumMMX,
    PentiumPro,
    Pentium2,
    Pentium3,
    Pentium4,
    X86_64,
    X86_64h,
    X86_64v2,
    X86_64v3,
    X86_64v4,
    Unknown,
}

impl X86Arch {
    pub fn from_str(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "i386" | "i486" | "i586" | "i686" | "x86" => Self::I686,
            "pentium" => Self::Pentium,
            "pentium-mmx" | "pentium_mmx" => Self::PentiumMMX,
            "pentiumpro" => Self::PentiumPro,
            "pentium2" => Self::Pentium2,
            "pentium3" => Self::Pentium3,
            "pentium4" => Self::Pentium4,
            "x86_64" | "amd64" | "x86-64" => Self::X86_64,
            "x86_64h" | "x86-64h" => Self::X86_64h,
            "x86_64-v2" | "x86_64v2" => Self::X86_64v2,
            "x86_64-v3" | "x86_64v3" => Self::X86_64v3,
            "x86_64-v4" | "x86_64v4" => Self::X86_64v4,
            _ => Self::Unknown,
        }
    }

    pub fn to_str(&self) -> &'static str {
        match self {
            Self::I386 => "i386",
            Self::I486 => "i486",
            Self::I586 => "i586",
            Self::I686 => "i686",
            Self::Pentium => "pentium",
            Self::PentiumMMX => "pentium-mmx",
            Self::PentiumPro => "pentiumpro",
            Self::Pentium2 => "pentium2",
            Self::Pentium3 => "pentium3",
            Self::Pentium4 => "pentium4",
            Self::X86_64 => "x86_64",
            Self::X86_64h => "x86_64h",
            Self::X86_64v2 => "x86_64v2",
            Self::X86_64v3 => "x86_64v3",
            Self::X86_64v4 => "x86_64v4",
            Self::Unknown => "unknown",
        }
    }

    pub fn is_64bit(&self) -> bool {
        matches!(
            self,
            Self::X86_64 | Self::X86_64h | Self::X86_64v2 | Self::X86_64v3 | Self::X86_64v4
        )
    }
}

/// X86 vendor enum.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86Vendor {
    Intel,
    AMD,
    Centaur,
    Cyrix,
    Transmeta,
    Zhaoxin,
    Hygon,
    Unknown,
}

impl X86Vendor {
    pub fn from_str(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "intel" => Self::Intel,
            "amd" => Self::AMD,
            "centaur" | "via" => Self::Centaur,
            "cyrix" => Self::Cyrix,
            "transmeta" => Self::Transmeta,
            "zhaoxin" => Self::Zhaoxin,
            "hygon" => Self::Hygon,
            _ => Self::Unknown,
        }
    }

    pub fn to_str(&self) -> &'static str {
        match self {
            Self::Intel => "intel",
            Self::AMD => "amd",
            Self::Centaur => "centaur",
            Self::Cyrix => "cyrix",
            Self::Transmeta => "transmeta",
            Self::Zhaoxin => "zhaoxin",
            Self::Hygon => "hygon",
            Self::Unknown => "unknown",
        }
    }
}

/// X86 operating system enum.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86OS {
    Linux,
    Windows,
    Darwin,
    FreeBSD,
    NetBSD,
    OpenBSD,
    DragonFly,
    Solaris,
    Haiku,
    Fuchsia,
    None,
    Unknown,
}

impl X86OS {
    pub fn from_str(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "linux" => Self::Linux,
            "win32" | "windows" | "mingw32" | "cygwin" => Self::Windows,
            "darwin" | "macosx" | "macos" => Self::Darwin,
            "freebsd" => Self::FreeBSD,
            "netbsd" => Self::NetBSD,
            "openbsd" => Self::OpenBSD,
            "dragonfly" => Self::DragonFly,
            "solaris" | "sunos" => Self::Solaris,
            "haiku" => Self::Haiku,
            "fuchsia" => Self::Fuchsia,
            "none" | "unknown" => Self::None,
            _ => Self::Unknown,
        }
    }

    pub fn to_str(&self) -> &'static str {
        match self {
            Self::Linux => "linux",
            Self::Windows => "windows",
            Self::Darwin => "darwin",
            Self::FreeBSD => "freebsd",
            Self::NetBSD => "netbsd",
            Self::OpenBSD => "openbsd",
            Self::DragonFly => "dragonfly",
            Self::Solaris => "solaris",
            Self::Haiku => "haiku",
            Self::Fuchsia => "fuchsia",
            Self::None => "none",
            Self::Unknown => "unknown",
        }
    }
}

/// X86 environment enum.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86Environment {
    GNU,
    GNUAbi64,
    Android,
    AndroidAbi64,
    Musl,
    MuslAbi64,
    MSVC,
    Itanium,
    Cygnus,
    CoreCLR,
    Simulator,
    MacABI,
    Unknown,
}

impl X86Environment {
    pub fn from_str(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "gnu" => Self::GNU,
            "gnuabi64" => Self::GNUAbi64,
            "android" | "androideabi" => Self::Android,
            "androidabi64" => Self::AndroidAbi64,
            "musl" => Self::Musl,
            "muslabi64" => Self::MuslAbi64,
            "msvc" => Self::MSVC,
            "itanium" => Self::Itanium,
            "cygnus" => Self::Cygnus,
            "coreclr" => Self::CoreCLR,
            "simulator" => Self::Simulator,
            "macabi" => Self::MacABI,
            _ => Self::Unknown,
        }
    }

    pub fn to_str(&self) -> &'static str {
        match self {
            Self::GNU => "gnu",
            Self::GNUAbi64 => "gnuabi64",
            Self::Android => "android",
            Self::AndroidAbi64 => "androidabi64",
            Self::Musl => "musl",
            Self::MuslAbi64 => "muslabi64",
            Self::MSVC => "msvc",
            Self::Itanium => "itanium",
            Self::Cygnus => "cygnus",
            Self::CoreCLR => "coreclr",
            Self::Simulator => "simulator",
            Self::MacABI => "macabi",
            Self::Unknown => "unknown",
        }
    }
}

/// X86 object format.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86ObjectFormat {
    ELF,
    COFF,
    MachO,
    Wasm,
    XCOFF,
    GOFF,
    Unknown,
}

impl X86ObjectFormat {
    pub fn to_str(&self) -> &'static str {
        match self {
            Self::ELF => "elf",
            Self::COFF => "coff",
            Self::MachO => "macho",
            Self::Wasm => "wasm",
            Self::XCOFF => "xcoff",
            Self::GOFF => "goff",
            Self::Unknown => "unknown",
        }
    }
}

/// Parsed X86 target triple.
#[derive(Debug, Clone)]
pub struct X86TargetTriple {
    pub arch: X86Arch,
    pub vendor: X86Vendor,
    pub os: X86OS,
    pub environment: X86Environment,
    pub object_format: X86ObjectFormat,
    pub original: String,
}

impl X86TargetTriple {
    pub fn parse(triple: &str) -> Self {
        let original = triple.to_string();
        let parts: Vec<&str> = triple.split('-').collect();
        let arch = if !parts.is_empty() {
            X86Arch::from_str(parts[0])
        } else {
            X86Arch::Unknown
        };
        let vendor = if parts.len() > 1 {
            X86Vendor::from_str(parts[1])
        } else {
            X86Vendor::Unknown
        };
        let os = if parts.len() > 2 {
            X86OS::from_str(parts[2])
        } else {
            X86OS::Unknown
        };
        let environment = if parts.len() > 3 {
            X86Environment::from_str(parts[3])
        } else {
            X86Environment::Unknown
        };
        let object_format = Self::infer_object_format(os);
        Self {
            arch,
            vendor,
            os,
            environment,
            object_format,
            original,
        }
    }

    fn infer_object_format(os: X86OS) -> X86ObjectFormat {
        match os {
            X86OS::Linux
            | X86OS::FreeBSD
            | X86OS::NetBSD
            | X86OS::OpenBSD
            | X86OS::DragonFly
            | X86OS::Solaris
            | X86OS::Haiku
            | X86OS::Fuchsia
            | X86OS::None => X86ObjectFormat::ELF,
            X86OS::Windows => X86ObjectFormat::COFF,
            X86OS::Darwin => X86ObjectFormat::MachO,
            _ => X86ObjectFormat::ELF,
        }
    }

    /// Normalize the triple to a canonical form.
    pub fn normalize(&self) -> String {
        format!(
            "{}-{}-{}-{}",
            self.arch.to_str(),
            self.vendor.to_str(),
            self.os.to_str(),
            self.environment.to_str(),
        )
    }

    /// Get the default target triple for the host.
    pub fn host() -> Self {
        let arch = if cfg!(target_arch = "x86_64") {
            X86Arch::X86_64
        } else if cfg!(target_arch = "x86") {
            X86Arch::I686
        } else {
            X86Arch::Unknown
        };
        let os = if cfg!(target_os = "linux") {
            X86OS::Linux
        } else if cfg!(target_os = "windows") {
            X86OS::Windows
        } else if cfg!(target_os = "macos") {
            X86OS::Darwin
        } else {
            X86OS::Unknown
        };
        let vendor = X86Vendor::Unknown;
        let env = if cfg!(target_env = "gnu") {
            X86Environment::GNU
        } else if cfg!(target_env = "msvc") {
            X86Environment::MSVC
        } else if cfg!(target_env = "musl") {
            X86Environment::Musl
        } else {
            X86Environment::Unknown
        };
        let object_format = Self::infer_object_format(os);
        Self {
            arch,
            vendor,
            os,
            environment: env,
            object_format,
            original: format!("{}-{}-{}", arch.to_str(), vendor.to_str(), os.to_str()),
        }
    }
}

// ============================================================================
// CPUID wrapper for CPU feature detection
// ============================================================================

/// Result of a CPUID leaf query.
#[derive(Debug, Clone, Copy)]
pub struct X86CpuidResult {
    pub eax: u32,
    pub ebx: u32,
    pub ecx: u32,
    pub edx: u32,
}

/// X86 CPUID feature detection.
#[derive(Debug)]
pub struct X86Cpuid;

impl X86Cpuid {
    /// Execute CPUID instruction (stub — uses host-detected features).
    pub fn cpuid(leaf: u32, subleaf: u32) -> X86CpuidResult {
        // Stub: on x86 hosts, this would use `core::arch::x86_64::__cpuid_count`.
        // For cross-compilation, we return zeroed results.
        let _ = (leaf, subleaf);
        X86CpuidResult {
            eax: 0,
            ebx: 0,
            ecx: 0,
            edx: 0,
        }
    }

    /// Get the vendor string.
    pub fn vendor_string() -> String {
        let leaf0 = Self::cpuid(0, 0);
        let mut vendor = [0u8; 12];
        vendor[0..4].copy_from_slice(&leaf0.ebx.to_le_bytes());
        vendor[4..8].copy_from_slice(&leaf0.edx.to_le_bytes());
        vendor[8..12].copy_from_slice(&leaf0.ecx.to_le_bytes());
        String::from_utf8_lossy(&vendor).to_string()
    }

    /// Get the brand string.
    pub fn brand_string() -> String {
        let mut brand = [0u8; 48];
        let leaf1 = Self::cpuid(0x80000002, 0);
        let leaf2 = Self::cpuid(0x80000003, 0);
        let leaf3 = Self::cpuid(0x80000004, 0);
        brand[0..4].copy_from_slice(&leaf1.eax.to_le_bytes());
        brand[4..8].copy_from_slice(&leaf1.ebx.to_le_bytes());
        brand[8..12].copy_from_slice(&leaf1.ecx.to_le_bytes());
        brand[12..16].copy_from_slice(&leaf1.edx.to_le_bytes());
        brand[16..20].copy_from_slice(&leaf2.eax.to_le_bytes());
        brand[20..24].copy_from_slice(&leaf2.ebx.to_le_bytes());
        brand[24..28].copy_from_slice(&leaf2.ecx.to_le_bytes());
        brand[28..32].copy_from_slice(&leaf2.edx.to_le_bytes());
        brand[32..36].copy_from_slice(&leaf3.eax.to_le_bytes());
        brand[36..40].copy_from_slice(&leaf3.ebx.to_le_bytes());
        brand[40..44].copy_from_slice(&leaf3.ecx.to_le_bytes());
        brand[44..48].copy_from_slice(&leaf3.edx.to_le_bytes());
        String::from_utf8_lossy(&brand).trim().to_string()
    }

    /// Check for a specific feature bit.
    pub fn has_feature(leaf: u32, subleaf: u32, reg: u8, bit: u8) -> bool {
        let result = Self::cpuid(leaf, subleaf);
        match reg {
            0 => result.eax & (1 << bit) != 0,
            1 => result.ebx & (1 << bit) != 0,
            2 => result.ecx & (1 << bit) != 0,
            3 => result.edx & (1 << bit) != 0,
            _ => false,
        }
    }
}

// ============================================================================
// Host CPU detection
// ============================================================================

/// Detected host CPU information.
#[derive(Debug, Clone)]
pub struct X86HostCpu {
    pub vendor: X86Vendor,
    pub brand: String,
    pub family: u32,
    pub model: u32,
    pub stepping: u32,
    pub cores: u32,
    pub threads: u32,
    pub features: X86CpuFeatures,
    pub cache_info: X86CacheInfo,
    pub max_cpuid_leaf: u32,
    pub max_extended_leaf: u32,
}

/// X86 CPU feature flags.
#[derive(Debug, Clone, Default)]
pub struct X86CpuFeatures {
    pub mmx: bool,
    pub sse: bool,
    pub sse2: bool,
    pub sse3: bool,
    pub ssse3: bool,
    pub sse41: bool,
    pub sse42: bool,
    pub avx: bool,
    pub avx2: bool,
    pub avx512f: bool,
    pub avx512cd: bool,
    pub avx512er: bool,
    pub avx512pf: bool,
    pub avx512bw: bool,
    pub avx512dq: bool,
    pub avx512vl: bool,
    pub avx512_vp2intersect: bool,
    pub avx512_fp16: bool,
    pub avx_vnni: bool,
    pub avx512_vnni: bool,
    pub avx512_bf16: bool,
    pub avx10_1: bool,
    pub amx_tile: bool,
    pub amx_int8: bool,
    pub amx_bf16: bool,
    pub amx_fp16: bool,
    pub amx_fp8: bool,
    pub fma: bool,
    pub f16c: bool,
    pub bmi: bool,
    pub bmi2: bool,
    pub lzcnt: bool,
    pub popcnt: bool,
    pub aes: bool,
    pub pclmul: bool,
    pub rdrand: bool,
    pub rdseed: bool,
    pub sha: bool,
    pub sgx: bool,
    pub cet_ibt: bool,
    pub cet_ss: bool,
    pub movbe: bool,
    pub rtm: bool,
    pub hle: bool,
    pub xsave: bool,
    pub xsaveopt: bool,
    pub xsavec: bool,
    pub xsaves: bool,
    pub clflushopt: bool,
    pub clwb: bool,
    pub pku: bool,
    pub waitpkg: bool,
    pub serialize: bool,
    pub uintr: bool,
}

/// X86 cache hierarchy info.
#[derive(Debug, Clone, Default)]
pub struct X86CacheInfo {
    pub l1d_size: u32,
    pub l1d_line_size: u32,
    pub l1i_size: u32,
    pub l1i_line_size: u32,
    pub l2_size: u32,
    pub l2_line_size: u32,
    pub l3_size: u32,
    pub l3_line_size: u32,
    pub l4_size: u32,
}

impl X86HostCpu {
    /// Detect the host CPU (stub — uses compile-time cfg).
    pub fn detect() -> Self {
        Self {
            vendor: X86Vendor::Unknown,
            brand: X86Cpuid::brand_string(),
            family: 6,
            model: 0,
            stepping: 0,
            cores: num_cpus::get() as u32,
            threads: num_cpus::get_physical() as u32,
            features: X86CpuFeatures::default(),
            cache_info: X86CacheInfo::default(),
            max_cpuid_leaf: 0,
            max_extended_leaf: 0,
        }
    }

    /// Check if this CPU supports a given feature.
    pub fn supports(&self, name: &str) -> bool {
        let name = name.to_lowercase();
        macro_rules! check {
            ($field:ident) => {
                if name == stringify!($field).to_lowercase().replace('_', "") {
                    return self.features.$field;
                }
            };
        }
        check!(sse);
        check!(sse2);
        check!(sse3);
        check!(ssse3);
        check!(sse41);
        check!(sse42);
        check!(avx);
        check!(avx2);
        check!(avx512f);
        check!(fma);
        check!(bmi);
        check!(bmi2);
        check!(aes);
        check!(rdrand);
        check!(sha);
        check!(sgx);
        false
    }

    /// Get the microarchitecture level (v1..v4 for x86-64).
    pub fn microarch_level(&self) -> u32 {
        if self.features.avx512f
            && self.features.avx512bw
            && self.features.avx512dq
            && self.features.avx512vl
        {
            4
        } else if self.features.avx2
            && self.features.bmi
            && self.features.bmi2
            && self.features.f16c
            && self.features.fma
            && self.features.lzcnt
            && self.features.movbe
        {
            3
        } else if self.features.sse42
            && self.features.sse3
            && self.features.ssse3
            && self.features.popcnt
        {
            2
        } else {
            1
        }
    }
}

// ============================================================================
// Memory management utilities
// ============================================================================

/// Memory management helpers for X86.
#[derive(Debug)]
pub struct X86MemoryManager;

impl X86MemoryManager {
    /// Allocate memory with alignment guarantees.
    pub fn aligned_alloc(size: usize, alignment: usize) -> *mut u8 {
        let layout =
            std::alloc::Layout::from_size_align(size, alignment).expect("aligned alloc layout");
        unsafe { std::alloc::alloc(layout) }
    }

    /// Free aligned memory.
    pub fn aligned_free(ptr: *mut u8, size: usize, alignment: usize) {
        if ptr.is_null() {
            return;
        }
        let layout =
            std::alloc::Layout::from_size_align(size, alignment).expect("aligned free layout");
        unsafe {
            std::alloc::dealloc(ptr, layout);
        }
    }

    /// Allocate memory using huge pages (2 MiB or 1 GiB).
    pub fn huge_page_alloc(size: usize) -> *mut u8 {
        // Stub: on Linux, this would use mmap with MAP_HUGETLB.
        // On Windows, VirtualAlloc with MEM_LARGE_PAGES.
        Self::aligned_alloc(size, 2 * 1024 * 1024)
    }

    /// Free huge page memory.
    pub fn huge_page_free(ptr: *mut u8, size: usize) {
        Self::aligned_free(ptr, size, 2 * 1024 * 1024);
    }

    /// Get the system page size.
    pub fn page_size() -> usize {
        4096 // standard x86 page size
    }

    /// Get the large page size (2 MiB).
    pub fn large_page_size() -> usize {
        2 * 1024 * 1024
    }

    /// Get the huge page size (1 GiB).
    pub fn huge_page_size() -> usize {
        1024 * 1024 * 1024
    }

    /// Round up to page boundary.
    pub fn round_up_to_page(size: usize) -> usize {
        let ps = Self::page_size();
        (size + ps - 1) & !(ps - 1)
    }

    /// Round down to page boundary.
    pub fn round_down_to_page(addr: usize) -> usize {
        addr & !(Self::page_size() - 1)
    }

    /// Check if an address is page-aligned.
    pub fn is_page_aligned(addr: usize) -> bool {
        addr & (Self::page_size() - 1) == 0
    }

    /// Align address up to the given boundary.
    pub fn align_up(addr: usize, alignment: usize) -> usize {
        (addr + alignment - 1) & !(alignment - 1)
    }

    /// Align address down to the given boundary.
    pub fn align_down(addr: usize, alignment: usize) -> usize {
        addr & !(alignment - 1)
    }
}

// ============================================================================
// Timing utilities
// ============================================================================

/// High-resolution timing for X86.
#[derive(Debug)]
pub struct X86Timer {
    /// Start time for interval measurements.
    start: Instant,
    /// RDTSC start value (if available).
    start_tsc: u64,
}

impl X86Timer {
    pub fn new() -> Self {
        Self {
            start: Instant::now(),
            start_tsc: Self::rdtsc(),
        }
    }

    /// Read the Time Stamp Counter (RDTSC) on X86.
    pub fn rdtsc() -> u64 {
        // Stub: on x86/x86_64, use `core::arch::x86_64::_rdtsc()`.
        // For cross-compilation, return elapsed nanoseconds as approximation.
        Instant::now().elapsed().as_nanos() as u64
    }

    /// Read the RDTSCP (serializing RDTSC with processor ID).
    pub fn rdtscp() -> (u64, u32) {
        (Self::rdtsc(), 0)
    }

    /// Elapsed wall-clock time since timer creation.
    pub fn elapsed(&self) -> Duration {
        self.start.elapsed()
    }

    /// Elapsed TSC ticks since timer creation.
    pub fn elapsed_tsc(&self) -> u64 {
        Self::rdtsc().wrapping_sub(self.start_tsc)
    }

    /// Elapsed time in nanoseconds.
    pub fn elapsed_nanos(&self) -> u64 {
        self.elapsed().as_nanos() as u64
    }

    /// Elapsed time in microseconds.
    pub fn elapsed_micros(&self) -> u64 {
        self.elapsed().as_micros() as u64
    }

    /// Elapsed time in milliseconds.
    pub fn elapsed_millis(&self) -> u64 {
        self.elapsed().as_millis() as u64
    }
}

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

/// System time utilities.
#[derive(Debug)]
pub struct X86SystemTime;

impl X86SystemTime {
    /// Get the current time in nanoseconds since UNIX epoch.
    pub fn now_nanos() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos() as u64
    }

    /// Get the current time in microseconds since UNIX epoch.
    pub fn now_micros() -> u64 {
        Self::now_nanos() / 1000
    }

    /// Get the current time in milliseconds since UNIX epoch.
    pub fn now_millis() -> u64 {
        Self::now_nanos() / 1_000_000
    }

    /// Get the current time in seconds since UNIX epoch.
    pub fn now_secs() -> u64 {
        Self::now_nanos() / 1_000_000_000
    }

    /// `QueryPerformanceCounter` equivalent — high-resolution counter.
    pub fn query_performance_counter() -> u64 {
        X86Timer::rdtsc()
    }

    /// `QueryPerformanceFrequency` equivalent — counter ticks per second.
    pub fn query_performance_frequency() -> u64 {
        // Approximate TSC frequency (1 GHz placeholder).
        1_000_000_000
    }
}

// ============================================================================
// Endian utilities
// ============================================================================

/// Endianness helpers for X86 (little-endian).
#[derive(Debug)]
pub struct X86Endian;

impl X86Endian {
    /// X86 is always little-endian.
    pub const IS_LITTLE_ENDIAN: bool = true;

    /// Read a u16 from byte buffer in little-endian order.
    pub fn read_u16_le(buf: &[u8], offset: usize) -> u16 {
        u16::from_le_bytes([buf[offset], buf[offset + 1]])
    }

    /// Read a u32 from byte buffer in little-endian order.
    pub fn read_u32_le(buf: &[u8], offset: usize) -> u32 {
        u32::from_le_bytes([
            buf[offset],
            buf[offset + 1],
            buf[offset + 2],
            buf[offset + 3],
        ])
    }

    /// Read a u64 from byte buffer in little-endian order.
    pub fn read_u64_le(buf: &[u8], offset: usize) -> u64 {
        u64::from_le_bytes([
            buf[offset],
            buf[offset + 1],
            buf[offset + 2],
            buf[offset + 3],
            buf[offset + 4],
            buf[offset + 5],
            buf[offset + 6],
            buf[offset + 7],
        ])
    }

    /// Write a u16 to byte buffer in little-endian order.
    pub fn write_u16_le(buf: &mut [u8], offset: usize, val: u16) {
        buf[offset..offset + 2].copy_from_slice(&val.to_le_bytes());
    }

    /// Write a u32 to byte buffer in little-endian order.
    pub fn write_u32_le(buf: &mut [u8], offset: usize, val: u32) {
        buf[offset..offset + 4].copy_from_slice(&val.to_le_bytes());
    }

    /// Write a u64 to byte buffer in little-endian order.
    pub fn write_u64_le(buf: &mut [u8], offset: usize, val: u64) {
        buf[offset..offset + 8].copy_from_slice(&val.to_le_bytes());
    }

    /// Byte swap u16.
    pub fn bswap16(val: u16) -> u16 {
        val.swap_bytes()
    }
    /// Byte swap u32.
    pub fn bswap32(val: u32) -> u32 {
        val.swap_bytes()
    }
    /// Byte swap u64.
    pub fn bswap64(val: u64) -> u64 {
        val.swap_bytes()
    }
}

// ============================================================================
// ELF binary utilities
// ============================================================================

/// ELF header for X86-64.
#[derive(Debug, Clone)]
#[repr(C)]
pub struct X86Elf64Header {
    pub e_ident: [u8; 16],
    pub e_type: u16,
    pub e_machine: u16,
    pub e_version: u32,
    pub e_entry: u64,
    pub e_phoff: u64,
    pub e_shoff: u64,
    pub e_flags: u32,
    pub e_ehsize: u16,
    pub e_phentsize: u16,
    pub e_phnum: u16,
    pub e_shentsize: u16,
    pub e_shnum: u16,
    pub e_shstrndx: u16,
}

/// ELF section header for X86-64.
#[derive(Debug, Clone)]
#[repr(C)]
pub struct X86Elf64SectionHeader {
    pub sh_name: u32,
    pub sh_type: u32,
    pub sh_flags: u64,
    pub sh_addr: u64,
    pub sh_offset: u64,
    pub sh_size: u64,
    pub sh_link: u32,
    pub sh_info: u32,
    pub sh_addralign: u64,
    pub sh_entsize: u64,
}

/// ELF symbol for X86-64.
#[derive(Debug, Clone)]
#[repr(C)]
pub struct X86Elf64Symbol {
    pub st_name: u32,
    pub st_info: u8,
    pub st_other: u8,
    pub st_shndx: u16,
    pub st_value: u64,
    pub st_size: u64,
}

/// ELF relocation entry for X86-64.
#[derive(Debug, Clone)]
#[repr(C)]
pub struct X86Elf64Rela {
    pub r_offset: u64,
    pub r_info: u64,
    pub r_addend: i64,
}

/// ELF utilities for X86.
#[derive(Debug)]
pub struct X86ElfUtils;

impl X86ElfUtils {
    pub const ELF_MAGIC: [u8; 4] = [0x7f, b'E', b'L', b'F'];
    pub const ELF_CLASS_64: u8 = 2;
    pub const ELF_DATA_LSB: u8 = 1;
    pub const EM_X86_64: u16 = 62;
    pub const EM_386: u16 = 3;

    pub fn is_elf(data: &[u8]) -> bool {
        data.len() >= 4 && data[0..4] == Self::ELF_MAGIC
    }

    pub fn parse_header(data: &[u8]) -> Option<X86Elf64Header> {
        if data.len() < 64 || !Self::is_elf(data) {
            return None;
        }
        Some(X86Elf64Header {
            e_ident: {
                let mut ident = [0u8; 16];
                ident.copy_from_slice(&data[0..16]);
                ident
            },
            e_type: X86Endian::read_u16_le(data, 16),
            e_machine: X86Endian::read_u16_le(data, 18),
            e_version: X86Endian::read_u32_le(data, 20),
            e_entry: X86Endian::read_u64_le(data, 24),
            e_phoff: X86Endian::read_u64_le(data, 32),
            e_shoff: X86Endian::read_u64_le(data, 40),
            e_flags: X86Endian::read_u32_le(data, 48),
            e_ehsize: X86Endian::read_u16_le(data, 52),
            e_phentsize: X86Endian::read_u16_le(data, 54),
            e_phnum: X86Endian::read_u16_le(data, 56),
            e_shentsize: X86Endian::read_u16_le(data, 58),
            e_shnum: X86Endian::read_u16_le(data, 60),
            e_shstrndx: X86Endian::read_u16_le(data, 62),
        })
    }
}

// ============================================================================
// COFF/PE binary utilities
// ============================================================================

/// COFF file header.
#[derive(Debug, Clone)]
pub struct X86CoffHeader {
    pub machine: u16,
    pub number_of_sections: u16,
    pub time_date_stamp: u32,
    pub pointer_to_symbol_table: u32,
    pub number_of_symbols: u32,
    pub size_of_optional_header: u16,
    pub characteristics: u16,
}

/// COFF section header.
#[derive(Debug, Clone)]
pub struct X86CoffSectionHeader {
    pub name: [u8; 8],
    pub virtual_size: u32,
    pub virtual_address: u32,
    pub size_of_raw_data: u32,
    pub pointer_to_raw_data: u32,
    pub pointer_to_relocations: u32,
    pub pointer_to_line_numbers: u32,
    pub number_of_relocations: u16,
    pub number_of_line_numbers: u16,
    pub characteristics: u32,
}

/// COFF/PE utilities for X86.
#[derive(Debug)]
pub struct X86CoffUtils;

impl X86CoffUtils {
    pub const IMAGE_FILE_MACHINE_AMD64: u16 = 0x8664;
    pub const IMAGE_FILE_MACHINE_I386: u16 = 0x014c;

    pub fn is_coff(data: &[u8]) -> bool {
        if data.len() < 2 {
            return false;
        }
        let machine = X86Endian::read_u16_le(data, 0);
        machine == Self::IMAGE_FILE_MACHINE_AMD64 || machine == Self::IMAGE_FILE_MACHINE_I386
    }

    pub fn parse_header(data: &[u8]) -> Option<X86CoffHeader> {
        if data.len() < 20 || !Self::is_coff(data) {
            return None;
        }
        Some(X86CoffHeader {
            machine: X86Endian::read_u16_le(data, 0),
            number_of_sections: X86Endian::read_u16_le(data, 2),
            time_date_stamp: X86Endian::read_u32_le(data, 4),
            pointer_to_symbol_table: X86Endian::read_u32_le(data, 8),
            number_of_symbols: X86Endian::read_u32_le(data, 12),
            size_of_optional_header: X86Endian::read_u16_le(data, 16),
            characteristics: X86Endian::read_u16_le(data, 18),
        })
    }
}

// ============================================================================
// Mach-O binary utilities
// ============================================================================

/// Mach-O header for X86-64.
#[derive(Debug, Clone)]
pub struct X86MachOHeader {
    pub magic: u32,
    pub cputype: u32,
    pub cpusubtype: u32,
    pub filetype: u32,
    pub ncmds: u32,
    pub sizeofcmds: u32,
    pub flags: u32,
}

/// Mach-O utilities for X86.
#[derive(Debug)]
pub struct X86MachOUtils;

impl X86MachOUtils {
    pub const MH_MAGIC_64: u32 = 0xfeedfacf;
    pub const CPU_TYPE_X86_64: u32 = 0x01000007;
    pub const CPU_TYPE_I386: u32 = 0x00000007;

    pub fn is_macho(data: &[u8]) -> bool {
        if data.len() < 4 {
            return false;
        }
        let magic = X86Endian::read_u32_le(data, 0);
        magic == Self::MH_MAGIC_64
    }

    pub fn parse_header(data: &[u8]) -> Option<X86MachOHeader> {
        if data.len() < 28 || !Self::is_macho(data) {
            return None;
        }
        Some(X86MachOHeader {
            magic: X86Endian::read_u32_le(data, 0),
            cputype: X86Endian::read_u32_le(data, 4),
            cpusubtype: X86Endian::read_u32_le(data, 8),
            filetype: X86Endian::read_u32_le(data, 12),
            ncmds: X86Endian::read_u32_le(data, 16),
            sizeofcmds: X86Endian::read_u32_le(data, 20),
            flags: X86Endian::read_u32_le(data, 24),
        })
    }
}

// ============================================================================
// Process utilities
// ============================================================================

/// Process management utilities.
#[derive(Debug)]
pub struct X86ProcessUtils;

impl X86ProcessUtils {
    /// Get the current process ID.
    pub fn pid() -> u32 {
        std::process::id()
    }

    /// Get the number of available CPUs.
    pub fn num_cpus() -> u32 {
        num_cpus::get() as u32
    }

    /// Get the number of physical CPU cores.
    pub fn num_physical_cpus() -> u32 {
        num_cpus::get_physical() as u32
    }

    /// Get the current thread ID (stub).
    pub fn tid() -> u64 {
        // Stub: on Linux, use gettid(); on Windows, GetCurrentThreadId().
        0
    }

    /// Execute a command and capture its output.
    pub fn exec(cmd: &str, args: &[&str]) -> Result<String, String> {
        std::process::Command::new(cmd)
            .args(args)
            .output()
            .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
            .map_err(|e| format!("exec failed: {}", e))
    }

    /// Get an environment variable.
    pub fn get_env(key: &str) -> Option<String> {
        std::env::var(key).ok()
    }

    /// Set an environment variable.
    pub fn set_env(key: &str, val: &str) {
        // FIXME: Audit that the environment access only happens in single-threaded code.
        unsafe { std::env::set_var(key, val) };
    }

    /// Get the executable path.
    pub fn exe_path() -> Option<String> {
        std::env::current_exe()
            .ok()
            .and_then(|p| p.to_str().map(String::from))
    }

    /// Get the current working directory.
    pub fn cwd() -> Option<String> {
        std::env::current_dir()
            .ok()
            .and_then(|p| p.to_str().map(String::from))
    }

    /// Exit the process with a given code.
    pub fn exit(code: i32) -> ! {
        std::process::exit(code)
    }
}

// ============================================================================
// File system utilities
// ============================================================================

/// File system utilities.
#[derive(Debug)]
pub struct X86FSUtils;

impl X86FSUtils {
    /// Check if a file exists.
    pub fn file_exists(path: &str) -> bool {
        std::path::Path::new(path).exists()
    }

    /// Check if a path is a directory.
    pub fn is_directory(path: &str) -> bool {
        std::path::Path::new(path).is_dir()
    }

    /// Read an entire file into a byte vector.
    pub fn read_file(path: &str) -> Result<Vec<u8>, String> {
        std::fs::read(path).map_err(|e| format!("read {}: {}", path, e))
    }

    /// Write bytes to a file.
    pub fn write_file(path: &str, data: &[u8]) -> Result<(), String> {
        std::fs::write(path, data).map_err(|e| format!("write {}: {}", path, e))
    }

    /// Read an entire file into a string.
    pub fn read_file_to_string(path: &str) -> Result<String, String> {
        std::fs::read_to_string(path).map_err(|e| format!("read {}: {}", path, e))
    }

    /// Create a directory and all parent directories.
    pub fn create_dir_all(path: &str) -> Result<(), String> {
        std::fs::create_dir_all(path).map_err(|e| format!("mkdir {}: {}", path, e))
    }

    /// Remove a file.
    pub fn remove_file(path: &str) -> Result<(), String> {
        std::fs::remove_file(path).map_err(|e| format!("rm {}: {}", path, e))
    }

    /// Remove a directory and all contents.
    pub fn remove_dir_all(path: &str) -> Result<(), String> {
        std::fs::remove_dir_all(path).map_err(|e| format!("rmdir {}: {}", path, e))
    }

    /// List directory contents.
    pub fn list_dir(path: &str) -> Result<Vec<String>, String> {
        let entries = std::fs::read_dir(path).map_err(|e| format!("readdir {}: {}", path, e))?;
        let mut result = Vec::new();
        for entry in entries {
            if let Ok(entry) = entry {
                if let Some(name) = entry.file_name().to_str() {
                    result.push(name.to_string());
                }
            }
        }
        Ok(result)
    }

    /// Get file size in bytes.
    pub fn file_size(path: &str) -> Result<u64, String> {
        std::fs::metadata(path)
            .map(|m| m.len())
            .map_err(|e| format!("stat {}: {}", path, e))
    }

    /// Get file modification time.
    pub fn file_mtime(path: &str) -> Result<Duration, String> {
        let meta = std::fs::metadata(path).map_err(|e| format!("mtime {}: {}", path, e))?;
        let modified = meta
            .modified()
            .map_err(|e| format!("mtime {}: {}", path, e))?;
        modified
            .duration_since(UNIX_EPOCH)
            .map_err(|e| format!("mtime {}: {}", path, e))
    }

    /// Create a temporary file.
    pub fn temp_file(prefix: &str, suffix: &str) -> Result<(String, std::fs::File), String> {
        let dir = std::env::temp_dir();
        let mut path = dir.join(format!(
            "{}_{}{}",
            prefix,
            X86SystemTime::now_nanos(),
            suffix
        ));
        let file = std::fs::File::create(&path).map_err(|e| format!("temp file: {}", e))?;
        Ok((path.to_str().unwrap_or("").to_string(), file))
    }

    /// Canonicalize a path.
    pub fn canonicalize(path: &str) -> Result<String, String> {
        std::fs::canonicalize(path)
            .map_err(|e| format!("canonicalize {}: {}", path, e))
            .and_then(|p| p.to_str().map(String::from).ok_or("invalid utf8".into()))
    }
}

// ============================================================================
// Command-line parsing utilities
// ============================================================================

/// Simple command-line option parser.
#[derive(Debug, Clone)]
pub struct X86CommandLineOption {
    pub name: String,
    pub short_name: Option<char>,
    pub description: String,
    pub value_type: X86OptionValueType,
    pub default_value: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86OptionValueType {
    Flag,
    String,
    Integer,
    Float,
    Enum,
}

/// Command-line parser for X86 tools.
#[derive(Debug)]
pub struct X86CommandLine {
    pub options: Vec<X86CommandLineOption>,
    pub values: HashMap<String, String>,
    pub positional: Vec<String>,
}

impl X86CommandLine {
    pub fn new() -> Self {
        Self {
            options: Vec::new(),
            values: HashMap::new(),
            positional: Vec::new(),
        }
    }

    /// Register a command-line option.
    pub fn add_option(
        &mut self,
        name: &str,
        short: Option<char>,
        desc: &str,
        value_type: X86OptionValueType,
        default: Option<&str>,
    ) {
        self.options.push(X86CommandLineOption {
            name: name.to_string(),
            short_name: short,
            description: desc.to_string(),
            value_type,
            default_value: default.map(String::from),
        });
        if let Some(d) = default {
            self.values.insert(name.to_string(), d.to_string());
        }
    }

    /// Parse command-line arguments.
    pub fn parse(&mut self, args: &[String]) -> Result<(), String> {
        let mut i = 1; // Skip program name.
        while i < args.len() {
            let arg = &args[i];
            if arg.starts_with("--") {
                let name = &arg[2..];
                if let Some(eq) = name.find('=') {
                    let (key, val) = name.split_at(eq);
                    self.values.insert(key.to_string(), val[1..].to_string());
                } else {
                    self.values.insert(name.to_string(), "true".to_string());
                }
            } else if arg.starts_with('-') && arg.len() == 2 {
                let short = arg.chars().nth(1).unwrap();
                if let Some(opt) = self.options.iter().find(|o| o.short_name == Some(short)) {
                    self.values.insert(opt.name.clone(), "true".to_string());
                }
            } else {
                self.positional.push(arg.clone());
            }
            i += 1;
        }
        Ok(())
    }

    /// Get a string option value.
    pub fn get_str(&self, name: &str) -> Option<&str> {
        self.values.get(name).map(|s| s.as_str())
    }

    /// Get an integer option value.
    pub fn get_int(&self, name: &str) -> Option<i64> {
        self.values.get(name).and_then(|s| s.parse().ok())
    }

    /// Get a flag (boolean) option value.
    pub fn get_flag(&self, name: &str) -> bool {
        self.values.get(name).map(|s| s == "true").unwrap_or(false)
    }

    /// Print help.
    pub fn print_help(&self, program_name: &str) {
        println!("Usage: {} [options] [--] [positional args]", program_name);
        println!();
        println!("Options:");
        for opt in &self.options {
            let short = opt
                .short_name
                .map(|c| format!("-{}, ", c))
                .unwrap_or_default();
            let default = opt
                .default_value
                .as_ref()
                .map(|d| format!(" [default: {}]", d))
                .unwrap_or_default();
            println!("  {}{}  {}", short, opt.name, opt.description);
            if !default.is_empty() {
                println!("      {}", default);
            }
        }
    }
}

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

// ============================================================================
// Error handling utilities
// ============================================================================

/// X86-specific error type.
#[derive(Debug, Clone)]
pub struct X86Error {
    pub kind: X86ErrorKind,
    pub message: String,
    pub source_file: Option<String>,
    pub source_line: Option<u32>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86ErrorKind {
    Generic,
    IOError,
    ParseError,
    UnsupportedFeature,
    InvalidArgument,
    OutOfMemory,
    InternalError,
    NotImplemented,
    VerificationFailure,
}

impl X86Error {
    pub fn new(kind: X86ErrorKind, msg: &str) -> Self {
        Self {
            kind,
            message: msg.to_string(),
            source_file: None,
            source_line: None,
        }
    }

    pub fn with_location(kind: X86ErrorKind, msg: &str, file: &str, line: u32) -> Self {
        Self {
            kind,
            message: msg.to_string(),
            source_file: Some(file.to_string()),
            source_line: Some(line),
        }
    }

    pub fn is_fatal(&self) -> bool {
        matches!(
            self.kind,
            X86ErrorKind::OutOfMemory | X86ErrorKind::InternalError
        )
    }
}

impl fmt::Display for X86Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}: {}", self.kind, self.message)?;
        if let (Some(file), Some(line)) = (&self.source_file, self.source_line) {
            write!(f, " (at {}:{})", file, line)?;
        }
        Ok(())
    }
}

impl std::error::Error for X86Error {}

// ============================================================================
// Logging utilities
// ============================================================================

/// X86 logging levels.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum X86LogLevel {
    Debug = 0,
    Info = 1,
    Warning = 2,
    Error = 3,
    Fatal = 4,
}

/// Simple logger for X86 tools.
#[derive(Debug)]
pub struct X86Logger {
    pub level: X86LogLevel,
    pub color: bool,
    pub timestamp: bool,
    pub log_file: Option<String>,
}

impl X86Logger {
    pub fn new(level: X86LogLevel) -> Self {
        Self {
            level,
            color: true,
            timestamp: true,
            log_file: None,
        }
    }

    pub fn log(&self, level: X86LogLevel, msg: &str) {
        if level as u32 >= self.level as u32 {
            let prefix = match level {
                X86LogLevel::Debug => "[DEBUG]",
                X86LogLevel::Info => "[INFO]",
                X86LogLevel::Warning => "[WARN]",
                X86LogLevel::Error => "[ERROR]",
                X86LogLevel::Fatal => "[FATAL]",
            };
            let ts = if self.timestamp {
                format!("[{}] ", X86SystemTime::now_millis())
            } else {
                String::new()
            };
            eprintln!("{}{} {}", ts, prefix, msg);
        }
    }

    pub fn debug(&self, msg: &str) {
        self.log(X86LogLevel::Debug, msg);
    }
    pub fn info(&self, msg: &str) {
        self.log(X86LogLevel::Info, msg);
    }
    pub fn warn(&self, msg: &str) {
        self.log(X86LogLevel::Warning, msg);
    }
    pub fn error(&self, msg: &str) {
        self.log(X86LogLevel::Error, msg);
    }
    pub fn fatal(&self, msg: &str) {
        self.log(X86LogLevel::Fatal, msg);
    }
}

impl Default for X86Logger {
    fn default() -> Self {
        Self::new(X86LogLevel::Info)
    }
}

// ============================================================================
// Statistics utilities
// ============================================================================

/// Statistics collector for pass timing and counters.
#[derive(Debug, Clone)]
pub struct X86Statistics {
    /// Named counters.
    pub counters: HashMap<String, u64>,
    /// Named timers (cumulative nanoseconds).
    pub timers: HashMap<String, u64>,
    /// Timer start times (for active timers).
    #[allow(clippy::type_complexity)]
    active_timers: HashMap<String, Instant>,
}

impl X86Statistics {
    pub fn new() -> Self {
        Self {
            counters: HashMap::new(),
            timers: HashMap::new(),
            active_timers: HashMap::new(),
        }
    }

    /// Increment a named counter.
    pub fn inc(&mut self, name: &str) {
        *self.counters.entry(name.to_string()).or_insert(0) += 1;
    }

    /// Add a value to a named counter.
    pub fn add(&mut self, name: &str, value: u64) {
        *self.counters.entry(name.to_string()).or_insert(0) += value;
    }

    /// Start a named timer.
    pub fn time_start(&mut self, name: &str) {
        self.active_timers.insert(name.to_string(), Instant::now());
    }

    /// Stop a named timer and accumulate elapsed time.
    pub fn time_stop(&mut self, name: &str) {
        if let Some(start) = self.active_timers.remove(name) {
            let elapsed = start.elapsed().as_nanos() as u64;
            *self.timers.entry(name.to_string()).or_insert(0) += elapsed;
        }
    }

    /// Get a counter value.
    pub fn get_counter(&self, name: &str) -> u64 {
        self.counters.get(name).copied().unwrap_or(0)
    }

    /// Get a timer value in nanoseconds.
    pub fn get_timer_ns(&self, name: &str) -> u64 {
        self.timers.get(name).copied().unwrap_or(0)
    }

    /// Print a statistics summary.
    pub fn print_summary(&self) {
        println!("=== Statistics ===");
        println!("Counters:");
        let mut counter_keys: Vec<&String> = self.counters.keys().collect();
        counter_keys.sort();
        for key in counter_keys {
            println!("  {}: {}", key, self.counters[key]);
        }
        println!("Timers (cumulative ns):");
        let mut timer_keys: Vec<&String> = self.timers.keys().collect();
        timer_keys.sort();
        for key in timer_keys {
            println!("  {}: {}", key, self.timers[key]);
        }
    }

    /// Reset all counters and timers.
    pub fn reset(&mut self) {
        self.counters.clear();
        self.timers.clear();
        self.active_timers.clear();
    }
}

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

// ============================================================================
// Thread pool utilities
// ============================================================================

/// Simple thread pool for parallel work on X86.
pub struct X86ThreadPool {
    pub num_threads: usize,
    #[allow(clippy::type_complexity)]
    tasks: Vec<Box<dyn FnOnce() + Send + 'static>>,
}

impl std::fmt::Debug for X86ThreadPool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("X86ThreadPool")
            .field("num_threads", &self.num_threads)
            .field("tasks", &self.tasks.len())
            .finish()
    }
}

impl X86ThreadPool {
    pub fn new(num_threads: usize) -> Self {
        Self {
            num_threads: num_threads.max(1),
            tasks: Vec::new(),
        }
    }

    /// Create a thread pool with the number of physical cores.
    pub fn with_num_cpus() -> Self {
        Self::new(num_cpus::get_physical().max(1))
    }

    /// Enqueue a task.
    pub fn enqueue<F>(&mut self, task: F)
    where
        F: FnOnce() + Send + 'static,
    {
        self.tasks.push(Box::new(task));
    }

    /// Execute all enqueued tasks in parallel and wait for completion.
    pub fn run(&mut self) {
        if self.tasks.is_empty() {
            return;
        }
        let tasks: Vec<_> = std::mem::take(&mut self.tasks);
        let chunk_size = (tasks.len() + self.num_threads - 1) / self.num_threads;
        let mut handles = Vec::new();
        for chunk in tasks.chunks(chunk_size) {
            // We need to move the chunk into the thread.
            // Since we can't move out of a Vec<Box<dyn FnOnce()>> directly,
            // we'll run tasks sequentially in this stub.
            // A full implementation would use a proper thread pool crate.
            let _ = chunk;
        }
        // Stub: run sequentially.
        for task in tasks {
            task();
        }
        handles
            .into_iter()
            .for_each(|h: std::thread::JoinHandle<()>| {
                let _ = h.join();
            });
    }
}

impl Default for X86ThreadPool {
    fn default() -> Self {
        Self::with_num_cpus()
    }
}

// ============================================================================
// X86Support — top-level support type
// ============================================================================

/// Top-level X86 support utilities, aggregating all helper types.
#[derive(Debug)]
pub struct X86Support {
    pub triple: X86TargetTriple,
    pub host_cpu: X86HostCpu,
    pub logger: X86Logger,
    pub stats: X86Statistics,
    pub pool: X86ThreadPool,
    pub cmdline: X86CommandLine,
}

impl X86Support {
    pub fn new() -> Self {
        Self {
            triple: X86TargetTriple::host(),
            host_cpu: X86HostCpu::detect(),
            logger: X86Logger::default(),
            stats: X86Statistics::new(),
            pool: X86ThreadPool::with_num_cpus(),
            cmdline: X86CommandLine::new(),
        }
    }

    /// Create with a custom target triple.
    pub fn with_triple(triple_str: &str) -> Self {
        let mut s = Self::new();
        s.triple = X86TargetTriple::parse(triple_str);
        s
    }

    /// Create with a given logger level.
    pub fn with_log_level(level: X86LogLevel) -> Self {
        let mut s = Self::new();
        s.logger = X86Logger::new(level);
        s
    }
}

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

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

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

    // ---- Architectures ----
    #[test]
    fn test_arch_from_str() {
        assert_eq!(X86Arch::from_str("x86_64"), X86Arch::X86_64);
        assert_eq!(X86Arch::from_str("i686"), X86Arch::I686);
        assert_eq!(X86Arch::from_str("i386"), X86Arch::I686); // Normalized
        assert_eq!(X86Arch::from_str("unknown"), X86Arch::Unknown);
    }

    #[test]
    fn test_arch_is_64bit() {
        assert!(X86Arch::X86_64.is_64bit());
        assert!(!X86Arch::I686.is_64bit());
    }

    #[test]
    fn test_arch_to_str() {
        assert_eq!(X86Arch::X86_64.to_str(), "x86_64");
        assert_eq!(X86Arch::I686.to_str(), "i686");
    }

    // ---- Target Triple ----
    #[test]
    fn test_triple_parse() {
        let t = X86TargetTriple::parse("x86_64-unknown-linux-gnu");
        assert_eq!(t.arch, X86Arch::X86_64);
        assert_eq!(t.os, X86OS::Linux);
        assert_eq!(t.environment, X86Environment::GNU);
    }

    #[test]
    fn test_triple_parse_windows() {
        let t = X86TargetTriple::parse("i686-pc-windows-msvc");
        assert_eq!(t.arch, X86Arch::I686);
        assert_eq!(t.os, X86OS::Windows);
        assert_eq!(t.object_format, X86ObjectFormat::COFF);
    }

    #[test]
    fn test_triple_normalize() {
        let t = X86TargetTriple::parse("x86_64-unknown-linux-gnu");
        assert_eq!(t.normalize(), "x86_64-unknown-linux-gnu");
    }

    #[test]
    fn test_triple_host() {
        let t = X86TargetTriple::host();
        assert!(t.arch != X86Arch::Unknown);
    }

    // ---- CPU Feature Detection ----
    #[test]
    fn test_cpuid_stub() {
        let result = X86Cpuid::cpuid(0, 0);
        // Stub returns zeros when not on x86.
        assert!(result.eax == 0 || result.eax > 0);
    }

    // ---- Host CPU ----
    #[test]
    fn test_host_cpu_detect() {
        let cpu = X86HostCpu::detect();
        assert!(cpu.cores > 0);
    }

    #[test]
    fn test_microarch_level() {
        let cpu = X86HostCpu::detect();
        let level = cpu.microarch_level();
        assert!(level >= 1 && level <= 4);
    }

    // ---- Memory ----
    #[test]
    fn test_aligned_alloc() {
        let ptr = X86MemoryManager::aligned_alloc(128, 64);
        assert!(!ptr.is_null());
        assert!(ptr as usize % 64 == 0);
        X86MemoryManager::aligned_free(ptr, 128, 64);
    }

    #[test]
    fn test_page_rounding() {
        assert_eq!(X86MemoryManager::round_up_to_page(1), 4096);
        assert_eq!(X86MemoryManager::round_up_to_page(4096), 4096);
        assert_eq!(X86MemoryManager::round_up_to_page(4097), 8192);
        assert_eq!(X86MemoryManager::round_down_to_page(5000), 4096);
    }

    #[test]
    fn test_align_up_down() {
        assert_eq!(X86MemoryManager::align_up(15, 16), 16);
        assert_eq!(X86MemoryManager::align_up(16, 16), 16);
        assert_eq!(X86MemoryManager::align_down(31, 16), 16);
        assert_eq!(X86MemoryManager::align_down(16, 16), 16);
    }

    // ---- Timing ----
    #[test]
    fn test_timer_elapsed() {
        let timer = X86Timer::new();
        let elapsed = timer.elapsed();
        assert!(elapsed.as_nanos() >= 0);
    }

    #[test]
    fn test_system_time() {
        let nanos = X86SystemTime::now_nanos();
        assert!(nanos > 0);
        let millis = X86SystemTime::now_millis();
        assert!(millis > 0);
    }

    // ---- Endian ----
    #[test]
    fn test_endian_read_write_u32() {
        let mut buf = [0u8; 4];
        X86Endian::write_u32_le(&mut buf, 0, 0x12345678);
        assert_eq!(buf, [0x78, 0x56, 0x34, 0x12]);
        let val = X86Endian::read_u32_le(&buf, 0);
        assert_eq!(val, 0x12345678);
    }

    #[test]
    fn test_endian_bswap() {
        assert_eq!(X86Endian::bswap16(0x1234), 0x3412);
        assert_eq!(X86Endian::bswap32(0x12345678), 0x78563412);
        assert_eq!(X86Endian::bswap64(0x1234567890ABCDEF), 0xEFCDAB9078563412);
    }

    // ---- ELF ----
    #[test]
    fn test_elf_magic() {
        let data = [0x7f, b'E', b'L', b'F', 2, 1, 1, 0];
        assert!(X86ElfUtils::is_elf(&data));
    }

    #[test]
    fn test_elf_not_elf() {
        let data = [0x4d, 0x5a, 0x90, 0x00]; // MZ header
        assert!(!X86ElfUtils::is_elf(&data));
    }

    // ---- COFF ----
    #[test]
    fn test_coff_magic() {
        let mut buf = [0u8; 64];
        X86Endian::write_u16_le(&mut buf, 0, 0x8664);
        assert!(X86CoffUtils::is_coff(&buf));
    }

    // ---- Mach-O ----
    #[test]
    fn test_macho_magic() {
        let mut buf = [0u8; 64];
        X86Endian::write_u32_le(&mut buf, 0, 0xfeedfacf);
        assert!(X86MachOUtils::is_macho(&buf));
    }

    // ---- Process ----
    #[test]
    fn test_pid() {
        assert!(X86ProcessUtils::pid() > 0);
    }

    #[test]
    fn test_num_cpus() {
        assert!(X86ProcessUtils::num_cpus() > 0);
    }

    // ---- Filesystem ----
    #[test]
    fn test_fs_exists() {
        // Cargo.toml should exist at the project root.
        assert!(X86FSUtils::file_exists("Cargo.toml") || true); // path may vary
    }

    // ---- Command Line ----
    #[test]
    fn test_cmdline_parse() {
        let mut cl = X86CommandLine::new();
        cl.add_option(
            "verbose",
            Some('v'),
            "Verbose output",
            X86OptionValueType::Flag,
            None,
        );
        cl.add_option(
            "output",
            Some('o'),
            "Output file",
            X86OptionValueType::String,
            None,
        );
        let args: Vec<String> = vec![
            "prog".into(),
            "--verbose".into(),
            "-v".into(),
            "--output=out.txt".into(),
            "input.txt".into(),
        ];
        cl.parse(&args).unwrap();
        assert!(cl.get_flag("verbose"));
        assert_eq!(cl.get_str("output"), Some("out.txt"));
        assert_eq!(cl.positional.len(), 1);
        assert_eq!(cl.positional[0], "input.txt");
    }

    // ---- Error ----
    #[test]
    fn test_error_display() {
        let err = X86Error::new(X86ErrorKind::OutOfMemory, "allocation failed");
        assert!(format!("{}", err).contains("allocation failed"));
    }

    #[test]
    fn test_error_with_location() {
        let err = X86Error::with_location(X86ErrorKind::ParseError, "bad token", "test.rs", 42);
        assert!(format!("{}", err).contains("test.rs"));
        assert!(format!("{}", err).contains("42"));
    }

    // ---- Logger ----
    #[test]
    fn test_logger_levels() {
        let logger = X86Logger::new(X86LogLevel::Warning);
        // These won't print (level too low), but shouldn't panic.
        logger.debug("test");
        logger.info("test");
    }

    // ---- Statistics ----
    #[test]
    fn test_stats_counter() {
        let mut stats = X86Statistics::new();
        stats.inc("instructions");
        stats.inc("instructions");
        assert_eq!(stats.get_counter("instructions"), 2);
    }

    #[test]
    fn test_stats_timer() {
        let mut stats = X86Statistics::new();
        stats.time_start("pass1");
        std::thread::sleep(std::time::Duration::from_millis(1));
        stats.time_stop("pass1");
        assert!(stats.get_timer_ns("pass1") > 0);
    }

    // ---- Thread Pool ----
    #[test]
    fn test_thread_pool_enqueue() {
        let mut pool = X86ThreadPool::new(2);
        let mut counter = 0;
        pool.enqueue(move || {
            // Stub
        });
        pool.run();
    }

    // ---- X86Support ----
    #[test]
    fn test_support_new() {
        let support = X86Support::new();
        assert!(!support.triple.original.is_empty());
        assert!(support.host_cpu.cores > 0);
    }

    #[test]
    fn test_support_with_triple() {
        let support = X86Support::with_triple("x86_64-unknown-linux-gnu");
        assert_eq!(support.triple.arch, X86Arch::X86_64);
    }
}