llvm-native-core 0.1.4

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
//! X86 CFI CodeGen — Control Flow Integrity instrumentation (forward-edge:
//! type checks via bitmask/range checks, backward-edge: shadow stack), CFI
//! check lowering, CFI-related intrinsics (@llvm.type.test,
//! @llvm.type.checked.load, @llvm.bitset.test), cross-DSO CFI, CFI-icall,
//! CFI-vcall, KCFI (kernel CFI with hash-based checks).
//!
//! Clean-room behavioral reconstruction from:
//! - Control-Flow Integrity: Principles, Implementations, and Applications
//!   (Abadi, Budiu, Erlingsson, Ligatti)
//! - Clang CFI documentation: forward-edge CFI, backward-edge CFI
//! - Microsoft Control Flow Guard (CFG) documentation
//! - Google Kernel CFI (KCFI) design and Linux kernel integration
//! - Intel® CET (Control-flow Enforcement Technology) Specification
//! - llvm.type.test, llvm.type.checked.load, llvm.bitset.test intrinsics
//! - Cross-DSO CFI specification
//! - Shadow stack designs: Intel CET, Clang SafeStack continuation
//!
//! 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::{BTreeMap, HashMap, HashSet};
use std::fmt;

// ============================================================================
// CFI Constants
// ============================================================================

/// CFI type identifier size in bits.
pub const X86_CFI_TYPE_ID_SIZE: u32 = 32;

/// Maximum number of types in a CFI bitmask.
pub const X86_CFI_MAX_BITMASK_TYPES: u32 = 64;

/// Default alignment for CFI-checked function pointers.
pub const X86_CFI_FUNCTION_ALIGNMENT: u32 = 16;

/// KCFI hash size in bits (kernel CFI).
pub const X86_KCFI_HASH_SIZE: u32 = 32;

/// KCFI immediate prefix for distinguishing valid call targets.
pub const X86_KCFI_PREFIX_BYTE: u8 = 0xCC; // int3 as prefix

/// Shadow stack entry size for x86-64 (pointer size).
pub const X86_CFI_SHADOW_STACK_ENTRY_SIZE: u32 = 8;

/// Size of the CFI check failure stub.
pub const X86_CFI_CHECK_STUB_SIZE: u32 = 16;

// ============================================================================
// CFI Type Metadata
// ============================================================================

/// A CFI type entry for the type metadata table.
#[derive(Debug, Clone)]
pub struct X86CFITypeEntry {
    /// The type identifier string (mangled name).
    pub type_id: String,
    /// The numeric hash of the type identifier (for fast comparison).
    pub type_hash: u64,
    /// Index in the global type table.
    pub table_index: u32,
    /// Whether this type is used for virtual calls.
    pub used_in_vcall: bool,
    /// Whether this type is used for indirect calls.
    pub used_in_icall: bool,
    /// Bitmask position for this type (0-63).
    pub bitmask_pos: Option<u32>,
}

impl X86CFITypeEntry {
    pub fn new(type_id: &str, type_hash: u64, table_index: u32) -> Self {
        Self {
            type_id: type_id.to_string(),
            type_hash,
            table_index,
            used_in_vcall: false,
            used_in_icall: false,
            bitmask_pos: None,
        }
    }

    /// Mark as used in virtual calls.
    pub fn as_vcall(mut self) -> Self {
        self.used_in_vcall = true;
        self
    }

    /// Mark as used in indirect calls.
    pub fn as_icall(mut self) -> Self {
        self.used_in_icall = true;
        self
    }

    /// Set the bitmask position.
    pub fn with_bitmask_pos(mut self, pos: u32) -> Self {
        self.bitmask_pos = Some(pos);
        self
    }
}

// ============================================================================
// CFI Type Metadata Table
// ============================================================================

/// The CFI type metadata table for a module.
#[derive(Debug, Clone)]
pub struct X86CFITypeTable {
    /// All registered CFI types.
    pub types: Vec<X86CFITypeEntry>,
    /// Map from type ID string to table index.
    pub type_id_to_index: HashMap<String, u32>,
    /// Map from type hash to table index.
    pub hash_to_index: HashMap<u64, u32>,
    /// Total number of types.
    pub type_count: u32,
}

impl X86CFITypeTable {
    pub fn new() -> Self {
        Self {
            types: Vec::new(),
            type_id_to_index: HashMap::new(),
            hash_to_index: HashMap::new(),
            type_count: 0,
        }
    }

    /// Register a type in the table.
    pub fn register_type(&mut self, type_id: &str, type_hash: u64) -> u32 {
        if let Some(&idx) = self.type_id_to_index.get(type_id) {
            return idx;
        }
        let idx = self.type_count;
        let entry = X86CFITypeEntry::new(type_id, type_hash, idx);
        self.types.push(entry);
        self.type_id_to_index.insert(type_id.to_string(), idx);
        self.hash_to_index.insert(type_hash, idx);
        self.type_count += 1;
        idx
    }

    /// Look up a type by its ID string.
    pub fn lookup_by_id(&self, type_id: &str) -> Option<&X86CFITypeEntry> {
        self.type_id_to_index
            .get(type_id)
            .and_then(|&idx| self.types.get(idx as usize))
    }

    /// Look up a type by its hash.
    pub fn lookup_by_hash(&self, type_hash: u64) -> Option<&X86CFITypeEntry> {
        self.hash_to_index
            .get(&type_hash)
            .and_then(|&idx| self.types.get(idx as usize))
    }

    /// Get a type by table index.
    pub fn get_by_index(&self, index: u32) -> Option<&X86CFITypeEntry> {
        self.types.get(index as usize)
    }

    /// Number of types.
    pub fn len(&self) -> usize {
        self.types.len()
    }

    /// Whether the table is empty.
    pub fn is_empty(&self) -> bool {
        self.types.is_empty()
    }
}

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

// ============================================================================
// CFI Forward-Edge: Type Test (llvm.type.test)
// ============================================================================

/// Represents a @llvm.type.test intrinsic lowering.
#[derive(Debug, Clone)]
pub struct X86CFITypeTest {
    /// The pointer being tested.
    pub pointer: u64,
    /// The type identifier metadata.
    pub metadata: String,
    /// Expected type hash.
    pub expected_hash: u64,
    /// Source location.
    pub source_loc: Option<String>,
}

impl X86CFITypeTest {
    pub fn new(pointer: u64, metadata: &str, expected_hash: u64) -> Self {
        Self {
            pointer,
            metadata: metadata.to_string(),
            expected_hash,
            source_loc: None,
        }
    }

    /// Perform the type test against a given runtime type hash.
    pub fn test(&self, runtime_hash: u64) -> bool {
        runtime_hash == self.expected_hash
    }

    /// Generate the bitmask-based test code (for forward-edge CFI).
    pub fn generate_bitmask_test(&self, valid_types: &[u64]) -> X86CFIBitmaskCheck {
        let mut bitmask: u64 = 0;
        for &type_hash in valid_types {
            let pos = (type_hash % X86_CFI_MAX_BITMASK_TYPES as u64) as u32;
            bitmask |= 1u64 << pos;
        }
        X86CFIBitmaskCheck {
            pointer: self.pointer,
            bitmask,
            expected_hash: self.expected_hash,
        }
    }
}

/// A bitmask-based CFI check (forward-edge).
#[derive(Debug, Clone)]
pub struct X86CFIBitmaskCheck {
    /// The pointer being checked.
    pub pointer: u64,
    /// The bitmask of valid type positions.
    pub bitmask: u64,
    /// The expected type hash.
    pub expected_hash: u64,
}

impl X86CFIBitmaskCheck {
    /// Perform the bitmask test.
    pub fn check(&self, type_id: u64) -> bool {
        let pos = (type_id % X86_CFI_MAX_BITMASK_TYPES as u64) as u32;
        let mask_bit = 1u64 << pos;
        (self.bitmask & mask_bit) != 0
    }

    /// Emit the bitmask test as a pseudo-IR sequence description.
    pub fn emit_pseudo_ir(&self) -> String {
        format!(
            "  ; CFI bitmask check\n  %pos = and i64 %type_id, {}\n  %bit = shl i64 1, %pos\n  %ok = and i64 {}, %bit\n  %pass = icmp ne i64 %ok, 0",
            X86_CFI_MAX_BITMASK_TYPES - 1,
            self.bitmask,
        )
    }
}

// ============================================================================
// CFI Type Checked Load (llvm.type.checked.load)
// ============================================================================

/// Represents a @llvm.type.checked.load intrinsic lowering.
#[derive(Debug, Clone)]
pub struct X86CFITypeCheckedLoad {
    /// The pointer being loaded from.
    pub pointer: u64,
    /// The expected type identifier.
    pub type_metadata: String,
    /// The offset of the type hash within the vtable.
    pub hash_offset: i32,
    /// Whether this is for a virtual call.
    pub is_vcall: bool,
}

impl X86CFITypeCheckedLoad {
    pub fn new(pointer: u64, type_metadata: &str, hash_offset: i32) -> Self {
        Self {
            pointer,
            type_metadata: type_metadata.to_string(),
            hash_offset,
            is_vcall: false,
        }
    }

    /// Mark as a virtual call check.
    pub fn as_vcall(mut self) -> Self {
        self.is_vcall = true;
        self
    }

    /// Generate the address of the type hash within the vtable.
    pub fn hash_address(&self) -> u64 {
        (self.pointer as i64 + self.hash_offset as i64) as u64
    }

    /// Emit the pseudo-IR for the type checked load.
    pub fn emit_pseudo_ir(&self) -> String {
        format!(
            "  ; CFI type checked load\n  %vtable = load ptr, ptr %{ptr}\n  %hash_addr = getelementptr i8, ptr %vtable, i32 {off}\n  %hash = load i32, ptr %hash_addr\n  %ok = call i1 @llvm.type.test(ptr %{ptr}, metadata !\"{meta}\")\n  br i1 %ok, label %cfi.cont, label %cfi.fail",
            ptr = self.pointer,
            off = self.hash_offset,
            meta = self.type_metadata,
        )
    }
}

// ============================================================================
// CFI Bitset Test (llvm.bitset.test)
// ============================================================================

/// Represents a @llvm.bitset.test lowering.
/// Used to test membership in a bitset of valid function pointers.
#[derive(Debug, Clone)]
pub struct X86CFIBitsetTest {
    /// The pointer being tested.
    pub pointer: u64,
    /// The name of the bitset.
    pub bitset_name: String,
    /// The global bitset data.
    pub bitset_data: Vec<u64>,
    /// Range check bounds (for range-based CFI).
    pub range_start: Option<u64>,
    pub range_end: Option<u64>,
}

impl X86CFIBitsetTest {
    pub fn new(pointer: u64, bitset_name: &str) -> Self {
        Self {
            pointer,
            bitset_name: bitset_name.to_string(),
            bitset_data: Vec::new(),
            range_start: None,
            range_end: None,
        }
    }

    /// Add bitset data words.
    pub fn with_bitset_data(mut self, data: Vec<u64>) -> Self {
        self.bitset_data = data;
        self
    }

    /// Set range check bounds.
    pub fn with_range(mut self, start: u64, end: u64) -> Self {
        self.range_start = Some(start);
        self.range_end = Some(end);
        self
    }

    /// Check if a pointer falls within the range.
    pub fn in_range(&self, addr: u64) -> bool {
        if let (Some(start), Some(end)) = (self.range_start, self.range_end) {
            addr >= start && addr < end
        } else {
            false
        }
    }

    /// Test a bit position in the bitset.
    pub fn test_bit(&self, bit_index: u64) -> bool {
        let word_idx = (bit_index / 64) as usize;
        let bit_pos = (bit_index % 64) as u32;
        if word_idx < self.bitset_data.len() {
            (self.bitset_data[word_idx] & (1u64 << bit_pos)) != 0
        } else {
            false
        }
    }

    /// Emit the pseudo-IR for the bitset test.
    pub fn emit_pseudo_ir(&self) -> String {
        let mut ir = String::new();
        ir.push_str(&format!("  ; CFI bitset test \"{}\"\n", self.bitset_name));
        if let (Some(start), Some(_end)) = (self.range_start, self.range_end) {
            ir.push_str(&format!(
                "  %in.range = icmp ult i64 %ptr, {}\n",
                start + (self.bitset_data.len() as u64 * 64)
            ));
        }
        ir.push_str("  %ok = call i1 @llvm.bitset.test(ptr %ptr, metadata !\"bitset_name\")\n");
        ir
    }
}

// ============================================================================
// CFI Cross-DSO Support
// ============================================================================

/// Cross-DSO CFI configuration.
#[derive(Debug, Clone)]
pub struct X86CFICrossDSOConfig {
    /// Whether cross-DSO CFI is enabled.
    pub enabled: bool,
    /// Path to the CFI type metadata for external shared objects.
    pub external_metadata_path: Option<String>,
    /// Whether to use the CFI shadow for cross-DSO checks.
    pub use_shadow: bool,
    /// Address of the CFI shadow base.
    pub shadow_base: u64,
    /// Scale factor for the shadow mapping.
    pub shadow_scale: u32,
}

impl Default for X86CFICrossDSOConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            external_metadata_path: None,
            use_shadow: false,
            shadow_base: 0,
            shadow_scale: 3,
        }
    }
}

/// A cross-DSO type check entry.
#[derive(Debug, Clone)]
pub struct X86CFICrossDSOCheck {
    /// Address of the indirect call.
    pub call_site: u64,
    /// The type being checked.
    pub type_id: String,
    /// Whether this call is in the main binary or a DSO.
    pub in_main_binary: bool,
    /// The external DSO name (if cross-DSO).
    pub dso_name: Option<String>,
}

impl X86CFICrossDSOCheck {
    pub fn new(call_site: u64, type_id: &str) -> Self {
        Self {
            call_site,
            type_id: type_id.to_string(),
            in_main_binary: true,
            dso_name: None,
        }
    }

    /// Mark as a cross-DSO check.
    pub fn cross_dso(mut self, dso_name: &str) -> Self {
        self.in_main_binary = false;
        self.dso_name = Some(dso_name.to_string());
        self
    }
}

// ============================================================================
// CFI Shadow Memory (for fast cross-DSO checks)
// ============================================================================

/// CFI shadow memory mapping for fast type checks.
#[derive(Debug, Clone)]
pub struct X86CFIShadow {
    /// Shadow base address.
    pub base: u64,
    /// Shadow size.
    pub size: u64,
    /// Shadow scale (shift amount for address to shadow mapping).
    pub scale: u32,
    /// The shadow memory buffer.
    pub shadow: Vec<u8>,
}

impl X86CFIShadow {
    pub fn new(base: u64, size: u64, scale: u32) -> Self {
        Self {
            base,
            size,
            scale,
            shadow: vec![0u8; size as usize],
        }
    }

    /// Compute the shadow address for an application address.
    pub fn app_to_shadow(&self, app_addr: u64) -> u64 {
        ((app_addr - self.base) >> self.scale) + self.base
    }

    /// Set the shadow byte at an application address.
    pub fn set(&mut self, app_addr: u64, value: u8) {
        let shadow_addr = self.app_to_shadow(app_addr);
        let offset = (shadow_addr - self.base) as usize;
        if offset < self.shadow.len() {
            self.shadow[offset] = value;
        }
    }

    /// Get the shadow byte for an application address.
    pub fn get(&self, app_addr: u64) -> u8 {
        let shadow_addr = self.app_to_shadow(app_addr);
        let offset = (shadow_addr - self.base) as usize;
        if offset < self.shadow.len() {
            self.shadow[offset]
        } else {
            0
        }
    }

    /// Fill a range of shadow memory.
    pub fn fill_range(&mut self, app_start: u64, app_end: u64, value: u8) {
        for addr in (app_start..app_end).step_by(1 << self.scale) {
            self.set(addr, value);
        }
    }
}

impl Default for X86CFIShadow {
    fn default() -> Self {
        Self::new(0, 0x10000000, 3)
    }
}

// ============================================================================
// CFI Backward-Edge: Shadow Stack
// ============================================================================

/// A shadow stack entry for backward-edge CFI.
#[derive(Debug, Clone)]
pub struct X86CFIShadowStackEntry {
    /// The return address stored.
    pub return_address: u64,
    /// Frame pointer at time of call.
    pub frame_pointer: u64,
    /// Whether this entry is valid.
    pub valid: bool,
    /// The call site address (for diagnostics).
    pub call_site: u64,
}

/// A shadow stack for backward-edge CFI (software-based).
#[derive(Debug, Clone)]
pub struct X86CFIShadowStack {
    /// The shadow stack entries (most recent first).
    pub entries: Vec<X86CFIShadowStackEntry>,
    /// Current shadow stack pointer.
    pub ssp: u64,
    /// Base address of the shadow stack.
    pub base: u64,
    /// Limit (top) of the shadow stack.
    pub limit: u64,
    /// Whether the shadow stack is active.
    pub active: bool,
    /// Number of entries pushed.
    pub total_pushes: u64,
    /// Number of entries popped.
    pub total_pops: u64,
    /// Number of mismatches detected.
    pub mismatches: u64,
}

impl X86CFIShadowStack {
    pub fn new(base: u64, size: u64) -> Self {
        Self {
            entries: Vec::new(),
            ssp: base,
            base,
            limit: base + size,
            active: false,
            total_pushes: 0,
            total_pops: 0,
            mismatches: 0,
        }
    }

    /// Push a return address and frame pointer onto the shadow stack.
    pub fn push(&mut self, return_address: u64, frame_pointer: u64, call_site: u64) {
        if self.ssp + X86_CFI_SHADOW_STACK_ENTRY_SIZE as u64 >= self.limit {
            // Overflow — shadow stack exhausted
            self.mismatches += 1;
            return;
        }
        self.entries.push(X86CFIShadowStackEntry {
            return_address,
            frame_pointer,
            valid: true,
            call_site,
        });
        self.ssp += X86_CFI_SHADOW_STACK_ENTRY_SIZE as u64;
        self.total_pushes += 1;
    }

    /// Pop and verify a return address.
    pub fn pop(&mut self, expected_address: u64) -> bool {
        self.total_pops += 1;
        if let Some(entry) = self.entries.pop() {
            self.ssp = self
                .ssp
                .saturating_sub(X86_CFI_SHADOW_STACK_ENTRY_SIZE as u64);
            if entry.return_address != expected_address {
                self.mismatches += 1;
                return false;
            }
            return true;
        }
        self.mismatches += 1;
        false
    }

    /// Peek at the top return address without popping.
    pub fn peek(&self) -> Option<u64> {
        self.entries.last().map(|e| e.return_address)
    }

    /// Get the current depth of the shadow stack.
    pub fn depth(&self) -> usize {
        self.entries.len()
    }

    /// Whether the shadow stack is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Reset the shadow stack.
    pub fn reset(&mut self) {
        self.entries.clear();
        self.ssp = self.base;
        self.mismatches = 0;
        self.total_pushes = 0;
        self.total_pops = 0;
    }
}

impl Default for X86CFIShadowStack {
    fn default() -> Self {
        Self::new(0x7f0000000000, 0x100000)
    }
}

// ============================================================================
// KCFI: Kernel CFI with Hash-Based Checks
// ============================================================================

/// KCFI hash function type.
pub type X86KCFIHashFn = fn(u64, u64) -> u32;

/// KCFI configuration for kernel-level CFI.
#[derive(Debug, Clone)]
pub struct X86KCFIConfig {
    /// Whether KCFI is enabled.
    pub enabled: bool,
    /// The immediate prefix (typically 0xCC = int3).
    pub prefix_byte: u8,
    /// Hash size in bits.
    pub hash_size: u32,
    /// Whether to check at indirect call sites.
    pub check_icall: bool,
    /// Whether to check at indirect jump sites.
    pub check_ijmp: bool,
    /// Hash function type.
    pub hash_fn_name: String,
}

impl Default for X86KCFIConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            prefix_byte: X86_KCFI_PREFIX_BYTE,
            hash_size: X86_KCFI_HASH_SIZE,
            check_icall: true,
            check_ijmp: true,
            hash_fn_name: "kcfi_hash".to_string(),
        }
    }
}

/// A KCFI hash entry for a valid call target.
#[derive(Debug, Clone)]
pub struct X86KCFITargetEntry {
    /// Address of the valid target.
    pub target_address: u64,
    /// The hash of the target's type signature.
    pub type_hash: u32,
    /// The function name for this target.
    pub function_name: Option<String>,
    /// Whether this is an indirect-call target.
    pub is_icall_target: bool,
}

impl X86KCFITargetEntry {
    pub fn new(target_address: u64, type_hash: u32) -> Self {
        Self {
            target_address,
            type_hash,
            function_name: None,
            is_icall_target: true,
        }
    }
}

/// The KCFI target registry.
#[derive(Debug, Clone)]
pub struct X86KCFIRegistry {
    /// All valid call targets.
    pub targets: Vec<X86KCFITargetEntry>,
    /// Hash map from target address to entry index.
    pub addr_to_index: HashMap<u64, usize>,
    /// Hash map from type hash to list of target indices.
    pub hash_to_targets: HashMap<u32, Vec<usize>>,
}

impl X86KCFIRegistry {
    pub fn new() -> Self {
        Self {
            targets: Vec::new(),
            addr_to_index: HashMap::new(),
            hash_to_targets: HashMap::new(),
        }
    }

    /// Register a valid call target.
    pub fn register_target(&mut self, target_address: u64, type_hash: u32) {
        let idx = self.targets.len();
        let entry = X86KCFITargetEntry::new(target_address, type_hash);
        self.targets.push(entry);
        self.addr_to_index.insert(target_address, idx);
        self.hash_to_targets
            .entry(type_hash)
            .or_insert_with(Vec::new)
            .push(idx);
    }

    /// Check if a target address is valid for a given type hash.
    pub fn is_valid_target(&self, target_address: u64, type_hash: u32) -> bool {
        if let Some(&idx) = self.addr_to_index.get(&target_address) {
            if let Some(entry) = self.targets.get(idx) {
                return entry.type_hash == type_hash;
            }
        }
        false
    }

    /// Get all targets with a given type hash.
    pub fn targets_with_hash(&self, type_hash: u32) -> Vec<&X86KCFITargetEntry> {
        self.hash_to_targets
            .get(&type_hash)
            .map(|indices| {
                indices
                    .iter()
                    .filter_map(|&i| self.targets.get(i))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Compute the KCFI hash for a function type.
    pub fn compute_hash(function_type: &str, salt: u64) -> u32 {
        // Simple FNV-1a hash for KCFI
        let mut hash: u32 = 0x811c9dc5u32.wrapping_add(salt as u32);
        for byte in function_type.as_bytes() {
            hash ^= *byte as u32;
            hash = hash.wrapping_mul(0x01000193);
        }
        hash
    }

    /// Number of registered targets.
    pub fn len(&self) -> usize {
        self.targets.len()
    }

    /// Whether the registry is empty.
    pub fn is_empty(&self) -> bool {
        self.targets.is_empty()
    }
}

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

// ============================================================================
// CFI ICall (Indirect Call) Check
// ============================================================================

/// A CFI indirect-call check point.
#[derive(Debug, Clone)]
pub struct X86CFIICallCheck {
    /// The address of the indirect call instruction.
    pub call_site: u64,
    /// The expected function type.
    pub function_type: String,
    /// The expected type hash.
    pub expected_hash: u64,
    /// The register or address holding the target.
    pub target_register: Option<String>,
    /// Whether this is a cross-DSO check.
    pub is_cross_dso: bool,
    /// Whether to use KCFI hash check.
    pub use_kcfi: bool,
}

impl X86CFIICallCheck {
    pub fn new(call_site: u64, function_type: &str, expected_hash: u64) -> Self {
        Self {
            call_site,
            function_type: function_type.to_string(),
            expected_hash,
            target_register: None,
            is_cross_dso: false,
            use_kcfi: false,
        }
    }

    /// Specify the target register.
    pub fn in_register(mut self, reg: &str) -> Self {
        self.target_register = Some(reg.to_string());
        self
    }

    /// Use KCFI hash checks.
    pub fn with_kcfi(mut self) -> Self {
        self.use_kcfi = true;
        self
    }

    /// Emit pseudo-IR for the indirect call check.
    pub fn emit_pseudo_ir(&self) -> String {
        let reg = self.target_register.as_deref().unwrap_or("unknown");
        format!(
            "  ; CFI icall check at {:#x}\n  %target = load ptr, ptr %{reg}\n  %ttype = ...\n  %ok = call i1 @llvm.type.test(ptr %target, metadata !\"{ty}\")\n  br i1 %ok, label %call.ok, label %trap",
            self.call_site,
            ty = self.function_type,
        )
    }
}

// ============================================================================
// CFI VCall (Virtual Call) Check
// ============================================================================

/// A CFI virtual-call check point.
#[derive(Debug, Clone)]
pub struct X86CFIVCallCheck {
    /// The address of the virtual call instruction.
    pub call_site: u64,
    /// The object pointer.
    pub object_ptr: u64,
    /// The class type being checked.
    pub class_type: String,
    /// The method being called.
    pub method_name: String,
    /// VTable offset for the method.
    pub vtable_offset: i32,
    /// The vtable entry offset.
    pub vtable_entry_index: u32,
    /// Whether this check uses the strict vtable verification.
    pub strict_vtable_check: bool,
}

impl X86CFIVCallCheck {
    pub fn new(
        call_site: u64,
        object_ptr: u64,
        class_type: &str,
        method_name: &str,
        vtable_offset: i32,
    ) -> Self {
        Self {
            call_site,
            object_ptr,
            class_type: class_type.to_string(),
            method_name: method_name.to_string(),
            vtable_offset,
            vtable_entry_index: 0,
            strict_vtable_check: false,
        }
    }

    /// Set the vtable entry index.
    pub fn at_vtable_index(mut self, index: u32) -> Self {
        self.vtable_entry_index = index;
        self
    }

    /// Enable strict vtable verification (check class hierarchy).
    pub fn strict(mut self) -> Self {
        self.strict_vtable_check = true;
        self
    }

    /// Emit pseudo-IR for the virtual call check.
    pub fn emit_pseudo_ir(&self) -> String {
        format!(
            "  ; CFI vcall check at {:#x}\n  %vtable = load ptr, ptr %obj\n  ; Load type hash from vtable (offset -8 or similar)\n  %hash_addr = getelementptr i8, ptr %vtable, i32 {voff}\n  %hash = load i32, ptr %hash_addr\n  %ok = icmp eq i32 %hash, ...\n  br i1 %ok, label %vcall.ok, label %trap",
            self.call_site,
            voff = -8i32,
        )
    }
}

// ============================================================================
// CFI Check Lowering (IR to Machine)
// ============================================================================

/// Describes a lowered CFI check sequence for X86.
#[derive(Debug, Clone)]
pub struct X86CFICheckLowering {
    /// The check type (icall, vcall, bitset).
    pub check_kind: X86CFICheckKind,
    /// The sequence of x86 instructions for the check.
    pub instructions: Vec<X86CFIInstr>,
    /// Whether this check traps on failure.
    pub traps_on_failure: bool,
    /// The trap address (for ud2 or call to __cfi_slowpath).
    pub trap_target: Option<u64>,
}

/// Kinds of CFI checks for lowering.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86CFICheckKind {
    /// Forward-edge indirect call check.
    ICall,
    /// Forward-edge virtual call check.
    VCall,
    /// Bitset-based test.
    Bitset,
    /// KCFI hash check.
    KCFI,
    /// Backward-edge shadow stack check.
    ShadowStack,
    /// Cross-DSO check.
    CrossDSO,
}

impl fmt::Display for X86CFICheckKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ICall => write!(f, "icall"),
            Self::VCall => write!(f, "vcall"),
            Self::Bitset => write!(f, "bitset"),
            Self::KCFI => write!(f, "kcfi"),
            Self::ShadowStack => write!(f, "shadow-stack"),
            Self::CrossDSO => write!(f, "cross-dso"),
        }
    }
}

/// A pseudo x86 instruction for CFI check lowering.
#[derive(Debug, Clone)]
pub struct X86CFIInstr {
    /// Mnemonic (e.g., "cmp", "je", "call", "ud2").
    pub mnemonic: String,
    /// Operand string.
    pub operand: String,
    /// Whether this is a label (not an instruction).
    pub is_label: bool,
}

impl X86CFIInstr {
    pub fn new(mnemonic: &str, operand: &str) -> Self {
        Self {
            mnemonic: mnemonic.to_string(),
            operand: operand.to_string(),
            is_label: false,
        }
    }

    pub fn label(name: &str) -> Self {
        Self {
            mnemonic: String::new(),
            operand: name.to_string(),
            is_label: true,
        }
    }
}

impl X86CFICheckLowering {
    pub fn new(kind: X86CFICheckKind) -> Self {
        Self {
            check_kind: kind,
            instructions: Vec::new(),
            traps_on_failure: true,
            trap_target: None,
        }
    }

    /// Add an instruction to the check sequence.
    pub fn emit(&mut self, mnemonic: &str, operand: &str) {
        self.instructions.push(X86CFIInstr::new(mnemonic, operand));
    }

    /// Emit a label.
    pub fn emit_label(&mut self, name: &str) {
        self.instructions.push(X86CFIInstr::label(name));
    }

    /// Build a standard forward-edge CFI check (bitmask-based).
    pub fn build_bitmask_check(
        target_reg: &str,
        scratch_reg: &str,
        type_hash: u64,
        bitmask: u64,
        failure_label: &str,
    ) -> Self {
        let mut lowering = Self::new(X86CFICheckKind::Bitset);
        // Load the type hash from the vtable/func prefix
        lowering.emit("mov", &format!("{}, [{} - 8]", scratch_reg, target_reg));
        lowering.emit(
            "and",
            &format!("{}, 0x{:x}", scratch_reg, X86_CFI_MAX_BITMASK_TYPES - 1),
        );
        lowering.emit("bt", &format!("{}, {}", bitmask, scratch_reg));
        lowering.emit("jnc", failure_label);
        lowering
    }

    /// Build a KCFI hash-based check.
    pub fn build_kcfi_check(
        target_addr: u64,
        type_hash: u32,
        temp_reg: &str,
        failure_label: &str,
    ) -> Self {
        let mut lowering = Self::new(X86CFICheckKind::KCFI);
        // Load the prefix byte before the target
        lowering.emit("mov", &format!("{}b, [{} - 5]", temp_reg, target_addr));
        lowering.emit("cmp", &format!("{}b, {}", temp_reg, X86_KCFI_PREFIX_BYTE));
        lowering.emit("jne", failure_label);
        // Load the hash from the target prefix area
        lowering.emit("mov", &format!("{}, [{} - 4]", temp_reg, target_addr));
        lowering.emit("cmp", &format!("{}, {}", temp_reg, type_hash));
        lowering.emit("jne", failure_label);
        lowering
    }

    /// Build a backward-edge shadow stack check.
    pub fn build_shadow_stack_check(
        return_address: u64,
        shadow_ptr: &str,
        failure_label: &str,
    ) -> Self {
        let mut lowering = Self::new(X86CFICheckKind::ShadowStack);
        lowering.emit("pop", shadow_ptr); // Pop from shadow stack
        lowering.emit("cmp", &format!("{}, {}", shadow_ptr, return_address));
        lowering.emit("jne", failure_label);
        lowering
    }

    /// Build a trap sequence (ud2).
    pub fn build_trap() -> Self {
        let mut lowering = Self::new(X86CFICheckKind::ICall);
        lowering.emit("ud2", "");
        lowering
    }

    /// Emit the full sequence as assembly text.
    pub fn emit_asm(&self) -> String {
        let mut asm = String::new();
        for instr in &self.instructions {
            if instr.is_label {
                asm.push_str(&format!("{}:\n", instr.operand));
            } else if instr.operand.is_empty() {
                asm.push_str(&format!("    {}\n", instr.mnemonic));
            } else {
                asm.push_str(&format!("    {} {}\n", instr.mnemonic, instr.operand));
            }
        }
        asm
    }

    /// Number of instructions.
    pub fn instr_count(&self) -> usize {
        self.instructions.len()
    }
}

// ============================================================================
// CFI Function Instrumentation
// ============================================================================

/// Instrumentation applied to a function for CFI.
#[derive(Debug, Clone)]
pub struct X86CFIFunctionInstrumentation {
    /// Name of the function.
    pub function_name: String,
    /// Whether the function has indirect calls.
    pub has_icall: bool,
    /// Whether the function has virtual calls.
    pub has_vcall: bool,
    /// Whether the function needs a shadow stack prologue.
    pub needs_shadow_stack_prologue: bool,
    /// Whether the function needs a shadow stack epilogue.
    pub needs_shadow_stack_epilogue: bool,
    /// Forward-edge checks lowered for this function.
    pub forward_edge_checks: Vec<X86CFICheckLowering>,
    /// Backward-edge checks lowered for this function.
    pub backward_edge_checks: Vec<X86CFICheckLowering>,
    /// CFI type for this function (as a call target).
    pub function_type_hash: Option<u64>,
    /// KCFI prefix installed.
    pub has_kcfi_prefix: bool,
}

impl X86CFIFunctionInstrumentation {
    pub fn new(function_name: &str) -> Self {
        Self {
            function_name: function_name.to_string(),
            has_icall: false,
            has_vcall: false,
            needs_shadow_stack_prologue: false,
            needs_shadow_stack_epilogue: false,
            forward_edge_checks: Vec::new(),
            backward_edge_checks: Vec::new(),
            function_type_hash: None,
            has_kcfi_prefix: false,
        }
    }

    /// Add a forward-edge CFI check.
    pub fn add_forward_check(&mut self, check: X86CFICheckLowering) {
        self.forward_edge_checks.push(check);
    }

    /// Add a backward-edge CFI check.
    pub fn add_backward_check(&mut self, check: X86CFICheckLowering) {
        self.backward_edge_checks.push(check);
    }

    /// Total number of CFI checks.
    pub fn total_checks(&self) -> usize {
        self.forward_edge_checks.len() + self.backward_edge_checks.len()
    }
}

// ============================================================================
// CFI Violation Reporting
// ============================================================================

/// A CFI violation report.
#[derive(Debug, Clone)]
pub struct X86CFIViolationReport {
    /// The address where the violation occurred.
    pub violation_address: u64,
    /// The kind of CFI check that failed.
    pub check_kind: X86CFICheckKind,
    /// The target address that was checked.
    pub target_address: u64,
    /// The expected type hash.
    pub expected_type_hash: Option<u64>,
    /// The actual type hash found.
    pub actual_type_hash: Option<u64>,
    /// The function where the violation occurred.
    pub function_name: Option<String>,
    /// Timestamp of the violation.
    pub timestamp: Option<u64>,
}

impl X86CFIViolationReport {
    pub fn new(violation_address: u64, check_kind: X86CFICheckKind, target_address: u64) -> Self {
        Self {
            violation_address,
            check_kind,
            target_address,
            expected_type_hash: None,
            actual_type_hash: None,
            function_name: None,
            timestamp: None,
        }
    }

    /// Format the report.
    pub fn format(&self) -> String {
        format!(
            "CFI violation: {} check failed at {:#x}\n  Target: {:#x}",
            self.check_kind, self.violation_address, self.target_address
        )
    }
}

// ============================================================================
// X86CFICodeGen — Top-level Orchestrator
// ============================================================================

/// The top-level X86 CFI codegen orchestrator.
///
/// Manages Control Flow Integrity instrumentation for X86 targets:
/// forward-edge type checks (bitmask/range), backward-edge shadow stack,
/// CFI intrinsics lowering, cross-DSO CFI, KCFI, and violation reporting.
#[derive(Debug, Clone)]
pub struct X86CFICodeGen {
    /// The global CFI type table.
    pub type_table: X86CFITypeTable,
    /// Forward-edge icall checks.
    pub icall_checks: Vec<X86CFIICallCheck>,
    /// Forward-edge vcall checks.
    pub vcall_checks: Vec<X86CFIVCallCheck>,
    /// Bitset tests.
    pub bitset_tests: Vec<X86CFIBitsetTest>,
    /// Type checked loads.
    pub type_checked_loads: Vec<X86CFITypeCheckedLoad>,
    /// Type tests.
    pub type_tests: Vec<X86CFITypeTest>,
    /// Cross-DSO configuration.
    pub cross_dso: X86CFICrossDSOConfig,
    /// Cross-DSO checks.
    pub cross_dso_checks: Vec<X86CFICrossDSOCheck>,
    /// CFI shadow memory.
    pub cfi_shadow: Option<X86CFIShadow>,
    /// Software shadow stack for backward-edge CFI.
    pub shadow_stack: X86CFIShadowStack,
    /// Whether backward-edge CFI (shadow stack) is enabled.
    pub backward_edge_enabled: bool,
    /// KCFI configuration.
    pub kcfi_config: X86KCFIConfig,
    /// KCFI target registry.
    pub kcfi_registry: X86KCFIRegistry,
    /// Per-function instrumentations.
    pub function_instrumentations: HashMap<String, X86CFIFunctionInstrumentation>,
    /// Violation reports.
    pub violations: Vec<X86CFIViolationReport>,
    /// Statistics.
    pub stats: X86CFICodeGenStats,
}

/// CFI codegen statistics.
#[derive(Debug, Clone, Default)]
pub struct X86CFICodeGenStats {
    /// Number of types registered.
    pub types_registered: u64,
    /// Number of icall checks inserted.
    pub icall_checks: u64,
    /// Number of vcall checks inserted.
    pub vcall_checks: u64,
    /// Number of bitset tests inserted.
    pub bitset_tests: u64,
    /// Number of type checked loads lowered.
    pub type_checked_loads: u64,
    /// Number of type tests lowered.
    pub type_tests: u64,
    /// Number of cross-DSO checks.
    pub cross_dso_checks: u64,
    /// Number of shadow stack entries pushed.
    pub shadow_stack_pushes: u64,
    /// Number of shadow stack entries popped.
    pub shadow_stack_pops: u64,
    /// Number of CFI violations.
    pub violations: u64,
    /// Number of functions instrumented.
    pub functions_instrumented: u64,
    /// Number of KCFI targets registered.
    pub kcfi_targets: u64,
    /// Whether CFI is active.
    pub cfi_active: bool,
}

impl X86CFICodeGen {
    /// Create a new CFI codegen instance.
    pub fn new() -> Self {
        Self {
            type_table: X86CFITypeTable::new(),
            icall_checks: Vec::new(),
            vcall_checks: Vec::new(),
            bitset_tests: Vec::new(),
            type_checked_loads: Vec::new(),
            type_tests: Vec::new(),
            cross_dso: X86CFICrossDSOConfig::default(),
            cross_dso_checks: Vec::new(),
            cfi_shadow: None,
            shadow_stack: X86CFIShadowStack::default(),
            backward_edge_enabled: false,
            kcfi_config: X86KCFIConfig::default(),
            kcfi_registry: X86KCFIRegistry::new(),
            function_instrumentations: HashMap::new(),
            violations: Vec::new(),
            stats: X86CFICodeGenStats::default(),
        }
    }

    /// Enable full CFI (forward + backward edge).
    pub fn enable_full_cfi(&mut self) {
        self.stats.cfi_active = true;
    }

    /// Enable backward-edge CFI (shadow stack).
    pub fn enable_backward_edge(&mut self, shadow_base: u64, shadow_size: u64) {
        self.backward_edge_enabled = true;
        self.shadow_stack = X86CFIShadowStack::new(shadow_base, shadow_size);
        self.shadow_stack.active = true;
    }

    /// Enable cross-DSO CFI.
    pub fn enable_cross_dso(&mut self, shadow_base: u64, shadow_size: u64) {
        self.cross_dso.enabled = true;
        self.cross_dso.use_shadow = true;
        self.cross_dso.shadow_base = shadow_base;
        self.cfi_shadow = Some(X86CFIShadow::new(
            shadow_base,
            shadow_size,
            self.cross_dso.shadow_scale,
        ));
    }

    /// Enable KCFI (kernel CFI).
    pub fn enable_kcfi(&mut self) {
        self.kcfi_config.enabled = true;
    }

    // ---- Type Registration ----

    /// Register a CFI type.
    pub fn register_type(&mut self, type_id: &str) -> u64 {
        let hash = Self::compute_type_hash(type_id);
        self.type_table.register_type(type_id, hash);
        self.stats.types_registered += 1;
        hash
    }

    /// Compute a hash for a type identifier string.
    pub fn compute_type_hash(type_id: &str) -> u64 {
        // FNV-1a 64-bit hash
        let mut hash: u64 = 0xcbf29ce484222325;
        for byte in type_id.as_bytes() {
            hash ^= *byte as u64;
            hash = hash.wrapping_mul(0x100000001b3);
        }
        hash
    }

    /// Look up a type by its hash.
    pub fn lookup_type(&self, type_hash: u64) -> Option<&X86CFITypeEntry> {
        self.type_table.lookup_by_hash(type_hash)
    }

    /// Get the number of registered types.
    pub fn type_count(&self) -> usize {
        self.type_table.len()
    }

    // ---- Forward-Edge: ICall Checks ----

    /// Add an indirect call CFI check.
    pub fn add_icall_check(&mut self, call_site: u64, function_type: &str, register: &str) {
        let hash = Self::compute_type_hash(function_type);
        self.register_type(function_type);
        let check = X86CFIICallCheck::new(call_site, function_type, hash).in_register(register);
        self.icall_checks.push(check);
        self.stats.icall_checks += 1;
    }

    /// Add an indirect call CFI check with KCFI.
    pub fn add_kcfi_icall_check(&mut self, call_site: u64, function_type: &str, register: &str) {
        let hash = Self::compute_type_hash(function_type);
        self.register_type(function_type);
        let check = X86CFIICallCheck::new(call_site, function_type, hash)
            .in_register(register)
            .with_kcfi();
        self.icall_checks.push(check);
        self.stats.icall_checks += 1;
    }

    // ---- Forward-Edge: VCall Checks ----

    /// Add a virtual call CFI check.
    pub fn add_vcall_check(
        &mut self,
        call_site: u64,
        object_ptr: u64,
        class_type: &str,
        method_name: &str,
        vtable_offset: i32,
    ) {
        self.register_type(class_type);
        let check = X86CFIVCallCheck::new(
            call_site,
            object_ptr,
            class_type,
            method_name,
            vtable_offset,
        );
        self.vcall_checks.push(check);
        self.stats.vcall_checks += 1;
    }

    // ---- Type Test (llvm.type.test) ----

    /// Lower a @llvm.type.test intrinsic.
    pub fn lower_type_test(&mut self, pointer: u64, metadata: &str, expected_hash: u64) {
        let test = X86CFITypeTest::new(pointer, metadata, expected_hash);
        self.type_tests.push(test);
        self.stats.type_tests += 1;
    }

    /// Lower a @llvm.type.checked.load intrinsic.
    pub fn lower_type_checked_load(&mut self, pointer: u64, type_metadata: &str, hash_offset: i32) {
        let load = X86CFITypeCheckedLoad::new(pointer, type_metadata, hash_offset);
        self.type_checked_loads.push(load);
        self.stats.type_checked_loads += 1;
    }

    /// Lower a @llvm.bitset.test intrinsic.
    pub fn lower_bitset_test(&mut self, pointer: u64, bitset_name: &str) -> &mut X86CFIBitsetTest {
        let test = X86CFIBitsetTest::new(pointer, bitset_name);
        self.bitset_tests.push(test);
        self.stats.bitset_tests += 1;
        self.bitset_tests.last_mut().unwrap()
    }

    // ---- Cross-DSO CFI ----

    /// Add a cross-DSO CFI check.
    pub fn add_cross_dso_check(&mut self, call_site: u64, type_id: &str, dso_name: Option<&str>) {
        let mut check = X86CFICrossDSOCheck::new(call_site, type_id);
        if let Some(dso) = dso_name {
            check = check.cross_dso(dso);
        }
        self.cross_dso_checks.push(check);
        self.stats.cross_dso_checks += 1;
    }

    // ---- KCFI ----

    /// Register a KCFI target.
    pub fn register_kcfi_target(&mut self, target_address: u64, function_type: &str) -> u32 {
        let type_hash = X86KCFIRegistry::compute_hash(function_type, 0);
        self.kcfi_registry
            .register_target(target_address, type_hash);
        self.stats.kcfi_targets += 1;
        type_hash
    }

    /// Check a KCFI target.
    pub fn kcfi_check_target(&self, target_address: u64, function_type: &str) -> bool {
        let type_hash = X86KCFIRegistry::compute_hash(function_type, 0);
        self.kcfi_registry
            .is_valid_target(target_address, type_hash)
    }

    // ---- Shadow Stack (Backward-Edge) ----

    /// Emit shadow stack push (at call site).
    pub fn shadow_stack_push(&mut self, return_address: u64, frame_pointer: u64, call_site: u64) {
        if !self.backward_edge_enabled {
            return;
        }
        self.shadow_stack
            .push(return_address, frame_pointer, call_site);
        self.stats.shadow_stack_pushes += 1;
    }

    /// Emit shadow stack pop and verify (at return site).
    pub fn shadow_stack_pop(&mut self, expected_address: u64) -> bool {
        if !self.backward_edge_enabled {
            return true; // bypass when disabled
        }
        let result = self.shadow_stack.pop(expected_address);
        self.stats.shadow_stack_pops += 1;
        if !result {
            self.report_violation(
                expected_address,
                X86CFICheckKind::ShadowStack,
                expected_address,
            );
        }
        result
    }

    // ---- Function Instrumentation ----

    /// Begin instrumenting a function for CFI.
    pub fn begin_function(&mut self, func_name: &str) {
        let instr = X86CFIFunctionInstrumentation::new(func_name);
        self.function_instrumentations
            .insert(func_name.to_string(), instr);
    }

    /// Get the instrumentation record for a function.
    pub fn get_function_instr(&self, func_name: &str) -> Option<&X86CFIFunctionInstrumentation> {
        self.function_instrumentations.get(func_name)
    }

    /// Get a mutable instrumentation record for a function.
    pub fn get_function_instr_mut(
        &mut self,
        func_name: &str,
    ) -> Option<&mut X86CFIFunctionInstrumentation> {
        self.function_instrumentations.get_mut(func_name)
    }

    /// Add a forward-edge check to a function's instrumentation.
    pub fn add_function_forward_check(&mut self, func_name: &str, check: X86CFICheckLowering) {
        if let Some(instr) = self.function_instrumentations.get_mut(func_name) {
            instr.add_forward_check(check);
            instr.has_icall = true;
        }
    }

    /// Finish instrumenting a function.
    pub fn end_function(&mut self, func_name: &str) {
        if let Some(instr) = self.function_instrumentations.get(func_name) {
            self.stats.functions_instrumented += 1;
            // If the function is a call target, register its type hash
            if let Some(type_hash) = instr.function_type_hash {
                if self.kcfi_config.enabled {
                    // Could register as KCFI target here
                    let _ = type_hash;
                }
            }
        }
    }

    // ---- Violation Reporting ----

    /// Report a CFI violation.
    pub fn report_violation(
        &mut self,
        violation_address: u64,
        check_kind: X86CFICheckKind,
        target_address: u64,
    ) {
        self.violations.push(X86CFIViolationReport::new(
            violation_address,
            check_kind,
            target_address,
        ));
        self.stats.violations += 1;
    }

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

    /// Format all violation reports.
    pub fn format_violations(&self) -> String {
        self.violations
            .iter()
            .map(|v| v.format())
            .collect::<Vec<_>>()
            .join("\n")
    }

    // ---- Lowering Pipeline ----

    /// Run the full CFI lowering pipeline.
    pub fn run_lowering_pipeline(&mut self) -> Vec<X86CFICheckLowering> {
        let mut all_checks = Vec::new();

        // Lower icall checks
        for icall in &self.icall_checks {
            if icall.use_kcfi {
                let kcfi_check = X86CFICheckLowering::build_kcfi_check(
                    icall.call_site,
                    icall.expected_hash as u32,
                    "eax",
                    ".Lcfi_fail",
                );
                all_checks.push(kcfi_check);
            } else {
                let bitmask: u64 = if self.type_table.len() <= X86_CFI_MAX_BITMASK_TYPES as usize {
                    (1u64 << self.type_table.len()) - 1
                } else {
                    u64::MAX
                };
                let bitmask_check = X86CFICheckLowering::build_bitmask_check(
                    icall.target_register.as_deref().unwrap_or("rax"),
                    "ecx",
                    icall.expected_hash,
                    bitmask,
                    ".Lcfi_fail",
                );
                all_checks.push(bitmask_check);
            }
        }

        // Lower vcall checks
        for _vcall in &self.vcall_checks {
            let vcall_check = X86CFICheckLowering::new(X86CFICheckKind::VCall);
            // vcall specifics would go here
            all_checks.push(vcall_check);
        }

        // Append trap stub
        all_checks.push(X86CFICheckLowering::build_trap());

        all_checks
    }

    // ---- CFI Shadow ----

    /// Set a CFI shadow byte for an address.
    pub fn cfi_shadow_set(&mut self, addr: u64, value: u8) {
        if let Some(ref mut shadow) = self.cfi_shadow {
            shadow.set(addr, value);
        }
    }

    /// Get a CFI shadow byte for an address.
    pub fn cfi_shadow_get(&self, addr: u64) -> u8 {
        self.cfi_shadow.as_ref().map_or(0, |s| s.get(addr))
    }

    // ---- Statistics ----

    /// Get codegen statistics.
    pub fn get_stats(&self) -> &X86CFICodeGenStats {
        &self.stats
    }

    /// Reset all state.
    pub fn reset(&mut self) {
        self.type_table = X86CFITypeTable::new();
        self.icall_checks.clear();
        self.vcall_checks.clear();
        self.bitset_tests.clear();
        self.type_checked_loads.clear();
        self.type_tests.clear();
        self.cross_dso_checks.clear();
        self.cfi_shadow = None;
        self.shadow_stack.reset();
        self.kcfi_registry = X86KCFIRegistry::new();
        self.function_instrumentations.clear();
        self.violations.clear();
        self.stats = X86CFICodeGenStats::default();
    }
}

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

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

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

    // --- Type Table Tests ---

    #[test]
    fn test_type_table_new() {
        let table = X86CFITypeTable::new();
        assert!(table.is_empty());
        assert_eq!(table.len(), 0);
    }

    #[test]
    fn test_type_table_register() {
        let mut table = X86CFITypeTable::new();
        let idx = table.register_type("MyClass", 0xABCD);
        assert_eq!(idx, 0);
        assert_eq!(table.len(), 1);
    }

    #[test]
    fn test_type_table_dedup() {
        let mut table = X86CFITypeTable::new();
        let idx1 = table.register_type("MyClass", 0xABCD);
        let idx2 = table.register_type("MyClass", 0xABCD);
        assert_eq!(idx1, idx2);
        assert_eq!(table.len(), 1);
    }

    #[test]
    fn test_type_table_lookup_by_id() {
        let mut table = X86CFITypeTable::new();
        table.register_type("Base", 0x1111);
        assert!(table.lookup_by_id("Base").is_some());
        assert!(table.lookup_by_id("Nonexistent").is_none());
    }

    #[test]
    fn test_type_table_lookup_by_hash() {
        let mut table = X86CFITypeTable::new();
        table.register_type("Derived", 0x2222);
        assert!(table.lookup_by_hash(0x2222).is_some());
        assert!(table.lookup_by_hash(0x9999).is_none());
    }

    #[test]
    fn test_type_table_get_by_index() {
        let mut table = X86CFITypeTable::new();
        table.register_type("T1", 0x1);
        table.register_type("T2", 0x2);
        assert_eq!(table.get_by_index(0).unwrap().type_id, "T1");
        assert_eq!(table.get_by_index(1).unwrap().type_id, "T2");
        assert!(table.get_by_index(99).is_none());
    }

    // --- Type Entry Tests ---

    #[test]
    fn test_type_entry_new() {
        let entry = X86CFITypeEntry::new("MyType", 0xABCD, 0);
        assert_eq!(entry.type_id, "MyType");
        assert_eq!(entry.type_hash, 0xABCD);
        assert_eq!(entry.table_index, 0);
        assert!(!entry.used_in_vcall);
        assert!(!entry.used_in_icall);
    }

    #[test]
    fn test_type_entry_flags() {
        let entry = X86CFITypeEntry::new("T", 0x1, 0)
            .as_vcall()
            .as_icall()
            .with_bitmask_pos(5);
        assert!(entry.used_in_vcall);
        assert!(entry.used_in_icall);
        assert_eq!(entry.bitmask_pos, Some(5));
    }

    // --- Bitmask Check Tests ---

    #[test]
    fn test_bitmask_check() {
        let check = X86CFIBitmaskCheck {
            pointer: 0x4000,
            bitmask: 0b1010, // positions 1 and 3 are valid
            expected_hash: 0xABCD,
        };
        // type_hash=1 => pos=1 => bit 1 is 0b0010 -> should be in mask (0b1010 & 0b0010 = 0b0010)
        assert!(check.check(1));
        // type_hash=2 => pos=2 => bit 2 is 0b0100 -> mask 0b1010 & 0b0100 = 0
        assert!(!check.check(2));
        // type_hash=3 => pos=3 => bit 3 is 0b1000 -> mask 0b1010 & 0b1000 = 0b1000
        assert!(check.check(3));
    }

    #[test]
    fn test_bitmask_check_emit_pseudo_ir() {
        let check = X86CFIBitmaskCheck {
            pointer: 0x4000,
            bitmask: 0xFF00,
            expected_hash: 0x42,
        };
        let ir = check.emit_pseudo_ir();
        assert!(ir.contains("CFI bitmask check"));
        assert!(ir.contains("shl"));
        assert!(ir.contains("and"));
    }

    // --- Type Test Tests ---

    #[test]
    fn test_type_test_new() {
        let test = X86CFITypeTest::new(0x5000, "!cfi_type_MyClass", 0xABCD);
        assert_eq!(test.pointer, 0x5000);
        assert_eq!(test.expected_hash, 0xABCD);
    }

    #[test]
    fn test_type_test_pass() {
        let test = X86CFITypeTest::new(0x5000, "!t", 0x42);
        assert!(test.test(0x42));
    }

    #[test]
    fn test_type_test_fail() {
        let test = X86CFITypeTest::new(0x5000, "!t", 0x42);
        assert!(!test.test(0x99));
    }

    #[test]
    fn test_type_test_generate_bitmask() {
        let test = X86CFITypeTest::new(0x5000, "!t", 0x42);
        let valid_types = vec![0x42, 0x106, 0x234];
        let bm_check = test.generate_bitmask_test(&valid_types);
        // The bitmask should have bits set at positions: 0x42 % 64, 0x106 % 64, 0x234 % 64
        assert!(bm_check.check(0x42));
        assert!(bm_check.check(0x106));
        assert!(bm_check.check(0x234));
    }

    // --- Type Checked Load Tests ---

    #[test]
    fn test_type_checked_load_new() {
        let load = X86CFITypeCheckedLoad::new(0x6000, "!meta_Base", -8);
        assert_eq!(load.pointer, 0x6000);
        assert_eq!(load.hash_offset, -8);
        assert!(!load.is_vcall);
    }

    #[test]
    fn test_type_checked_load_as_vcall() {
        let load = X86CFITypeCheckedLoad::new(0x6000, "!meta_Base", -8).as_vcall();
        assert!(load.is_vcall);
    }

    #[test]
    fn test_type_checked_load_hash_address() {
        let load = X86CFITypeCheckedLoad::new(0x6000, "!meta", -8);
        assert_eq!(load.hash_address(), 0x6000 - 8);
    }

    #[test]
    fn test_type_checked_load_emit_pseudo_ir() {
        let load = X86CFITypeCheckedLoad::new(0x7000, "!meta_Base", -8);
        let ir = load.emit_pseudo_ir();
        assert!(ir.contains("llvm.type.test"));
        assert!(ir.contains("cfi.cont"));
        assert!(ir.contains("cfi.fail"));
    }

    // --- Bitset Test Tests ---

    #[test]
    fn test_bitset_test_new() {
        let bs = X86CFIBitsetTest::new(0x8000, "bs_func_ptrs");
        assert_eq!(bs.pointer, 0x8000);
        assert_eq!(bs.bitset_name, "bs_func_ptrs");
        assert!(bs.bitset_data.is_empty());
    }

    #[test]
    fn test_bitset_test_with_data() {
        let bs = X86CFIBitsetTest::new(0x8000, "bs").with_bitset_data(vec![0b1010, 0xFFFF]);
        assert_eq!(bs.bitset_data.len(), 2);
    }

    #[test]
    fn test_bitset_test_range() {
        let bs = X86CFIBitsetTest::new(0x8000, "bs").with_range(0x1000, 0x2000);
        assert!(bs.in_range(0x1500));
        assert!(!bs.in_range(0x999));
        assert!(!bs.in_range(0x2500));
    }

    #[test]
    fn test_bitset_test_bit() {
        let bs = X86CFIBitsetTest::new(0x8000, "bs").with_bitset_data(vec![0b1010]);
        assert!(bs.test_bit(1)); // bit 1 is set
        assert!(bs.test_bit(3)); // bit 3 is set
        assert!(!bs.test_bit(0)); // bit 0 is not set
        assert!(!bs.test_bit(2)); // bit 2 is not set
        assert!(!bs.test_bit(99)); // out of range
    }

    #[test]
    fn test_bitset_test_emit_pseudo_ir() {
        let bs = X86CFIBitsetTest::new(0x8000, "my_bitset")
            .with_range(0x1000, 0x2000)
            .with_bitset_data(vec![0xFF]);
        let ir = bs.emit_pseudo_ir();
        assert!(ir.contains("CFI bitset test"));
        assert!(ir.contains("llvm.bitset.test"));
    }

    // --- Cross-DSO Tests ---

    #[test]
    fn test_cross_dso_check_new() {
        let check = X86CFICrossDSOCheck::new(0x9000, "FuncPtr");
        assert!(check.in_main_binary);
        assert!(check.dso_name.is_none());
    }

    #[test]
    fn test_cross_dso_check_dso() {
        let check = X86CFICrossDSOCheck::new(0x9000, "FuncPtr").cross_dso("libfoo.so");
        assert!(!check.in_main_binary);
        assert_eq!(check.dso_name, Some("libfoo.so".to_string()));
    }

    // --- CFI Shadow Tests ---

    #[test]
    fn test_cfi_shadow_new() {
        let shadow = X86CFIShadow::new(0x7f000000, 0x1000, 3);
        assert_eq!(shadow.base, 0x7f000000);
        assert_eq!(shadow.size, 0x1000);
        assert_eq!(shadow.scale, 3);
    }

    #[test]
    fn test_cfi_shadow_set_get() {
        let mut shadow = X86CFIShadow::new(0x100000, 0x1000, 3);
        let app_addr = 0x100000;
        shadow.set(app_addr, 0xAB);
        assert_eq!(shadow.get(app_addr), 0xAB);
    }

    #[test]
    fn test_cfi_shadow_fill_range() {
        let mut shadow = X86CFIShadow::new(0x100000, 0x1000, 3);
        shadow.fill_range(0x100000, 0x100100, 0xFF);
        assert_eq!(shadow.get(0x100000), 0xFF);
    }

    // --- Shadow Stack Tests ---

    #[test]
    fn test_shadow_stack_new() {
        let ss = X86CFIShadowStack::new(0x7f000000, 0x1000);
        assert_eq!(ss.base, 0x7f000000);
        assert_eq!(ss.limit, 0x7f000000 + 0x1000);
        assert!(!ss.active);
        assert!(ss.is_empty());
    }

    #[test]
    fn test_shadow_stack_push_pop() {
        let mut ss = X86CFIShadowStack::new(0x7000, 0x1000);
        ss.active = true;
        ss.push(0x401234, 0x7ff0, 0x401000);
        assert_eq!(ss.depth(), 1);
        assert_eq!(ss.peek(), Some(0x401234));
        assert!(ss.pop(0x401234));
        assert_eq!(ss.depth(), 0);
    }

    #[test]
    fn test_shadow_stack_pop_mismatch() {
        let mut ss = X86CFIShadowStack::new(0x7000, 0x1000);
        ss.active = true;
        ss.push(0xAAAA, 0x1000, 0x5000);
        assert!(!ss.pop(0xBBBB));
        assert_eq!(ss.mismatches, 1);
    }

    #[test]
    fn test_shadow_stack_pop_empty() {
        let mut ss = X86CFIShadowStack::new(0x7000, 0x1000);
        ss.active = true;
        assert!(!ss.pop(0x1234));
        assert_eq!(ss.mismatches, 1);
    }

    #[test]
    fn test_shadow_stack_reset() {
        let mut ss = X86CFIShadowStack::new(0x7000, 0x1000);
        ss.active = true;
        ss.push(0x1, 0x2, 0x3);
        ss.push(0x4, 0x5, 0x6);
        ss.reset();
        assert!(ss.is_empty());
        assert_eq!(ss.depth(), 0);
        assert_eq!(ss.mismatches, 0);
    }

    // --- KCFI Tests ---

    #[test]
    fn test_kcfi_registry_new() {
        let reg = X86KCFIRegistry::new();
        assert!(reg.is_empty());
        assert_eq!(reg.len(), 0);
    }

    #[test]
    fn test_kcfi_register_target() {
        let mut reg = X86KCFIRegistry::new();
        reg.register_target(0x4000, 0xABCD);
        assert_eq!(reg.len(), 1);
        assert!(reg.is_valid_target(0x4000, 0xABCD));
    }

    #[test]
    fn test_kcfi_invalid_target() {
        let mut reg = X86KCFIRegistry::new();
        reg.register_target(0x4000, 0xABCD);
        assert!(!reg.is_valid_target(0x4000, 0xFFFF)); // wrong hash
        assert!(!reg.is_valid_target(0x5000, 0xABCD)); // wrong address
    }

    #[test]
    fn test_kcfi_compute_hash() {
        let h1 = X86KCFIRegistry::compute_hash("void(int)", 0);
        let h2 = X86KCFIRegistry::compute_hash("void(int)", 0);
        assert_eq!(h1, h2); // deterministic
        let h3 = X86KCFIRegistry::compute_hash("int(float)", 0);
        assert_ne!(h1, h3); // different types
    }

    #[test]
    fn test_kcfi_targets_with_hash() {
        let mut reg = X86KCFIRegistry::new();
        reg.register_target(0x1000, 0xAAAA);
        reg.register_target(0x2000, 0xAAAA);
        reg.register_target(0x3000, 0xBBBB);
        let targets = reg.targets_with_hash(0xAAAA);
        assert_eq!(targets.len(), 2);
        let targets_b = reg.targets_with_hash(0xBBBB);
        assert_eq!(targets_b.len(), 1);
    }

    // --- Check Lowering Tests ---

    #[test]
    fn test_check_lowering_new() {
        let lowering = X86CFICheckLowering::new(X86CFICheckKind::ICall);
        assert_eq!(lowering.check_kind, X86CFICheckKind::ICall);
        assert!(lowering.traps_on_failure);
        assert_eq!(lowering.instr_count(), 0);
    }

    #[test]
    fn test_check_lowering_emit() {
        let mut lowering = X86CFICheckLowering::new(X86CFICheckKind::Bitset);
        lowering.emit("mov", "eax, [rcx - 8]");
        lowering.emit("cmp", "eax, 0x42");
        lowering.emit("jne", ".Lfail");
        assert_eq!(lowering.instr_count(), 3);
    }

    #[test]
    fn test_check_lowering_emit_label() {
        let mut lowering = X86CFICheckLowering::new(X86CFICheckKind::ICall);
        lowering.emit_label(".Lcfi_ok");
        lowering.emit("call", "rax");
        assert_eq!(lowering.instr_count(), 2);
    }

    #[test]
    fn test_build_bitmask_check() {
        let check = X86CFICheckLowering::build_bitmask_check("rax", "ecx", 0x42, 0xFF00, ".Lfail");
        assert!(check.instr_count() > 0);
        // First instruction should be mov
        assert_eq!(check.instructions[0].mnemonic, "mov");
    }

    #[test]
    fn test_build_kcfi_check() {
        let check = X86CFICheckLowering::build_kcfi_check(0x4000, 0xABCD, "eax", ".Lfail");
        assert!(check.instr_count() > 0);
    }

    #[test]
    fn test_build_shadow_stack_check() {
        let check = X86CFICheckLowering::build_shadow_stack_check(0x401000, "r10", ".Lfail");
        assert!(check.instr_count() > 0);
        assert_eq!(check.instructions[0].mnemonic, "pop");
    }

    #[test]
    fn test_build_trap() {
        let check = X86CFICheckLowering::build_trap();
        assert_eq!(check.instructions[0].mnemonic, "ud2");
    }

    #[test]
    fn test_emit_asm() {
        let mut check = X86CFICheckLowering::new(X86CFICheckKind::ICall);
        check.emit("mov", "eax, [rcx]");
        check.emit("cmp", "eax, 0x42");
        let asm = check.emit_asm();
        assert!(asm.contains("mov"));
        assert!(asm.contains("cmp"));
    }

    // --- Check Kind Display Tests ---

    #[test]
    fn test_check_kind_display() {
        assert_eq!(format!("{}", X86CFICheckKind::ICall), "icall");
        assert_eq!(format!("{}", X86CFICheckKind::VCall), "vcall");
        assert_eq!(format!("{}", X86CFICheckKind::Bitset), "bitset");
        assert_eq!(format!("{}", X86CFICheckKind::KCFI), "kcfi");
        assert_eq!(format!("{}", X86CFICheckKind::ShadowStack), "shadow-stack");
        assert_eq!(format!("{}", X86CFICheckKind::CrossDSO), "cross-dso");
    }

    // --- Function Instrumentation Tests ---

    #[test]
    fn test_func_instr_new() {
        let fi = X86CFIFunctionInstrumentation::new("my_func");
        assert_eq!(fi.function_name, "my_func");
        assert!(!fi.has_icall);
        assert!(!fi.has_vcall);
        assert_eq!(fi.total_checks(), 0);
    }

    #[test]
    fn test_func_instr_add_checks() {
        let mut fi = X86CFIFunctionInstrumentation::new("func");
        fi.add_forward_check(X86CFICheckLowering::new(X86CFICheckKind::ICall));
        fi.add_backward_check(X86CFICheckLowering::new(X86CFICheckKind::ShadowStack));
        assert_eq!(fi.total_checks(), 2);
    }

    // --- Violation Report Tests ---

    #[test]
    fn test_violation_report_new() {
        let report = X86CFIViolationReport::new(0x4000, X86CFICheckKind::ICall, 0xDEAD);
        assert_eq!(report.violation_address, 0x4000);
        assert_eq!(report.target_address, 0xDEAD);
        assert!(report.format().contains("CFI violation"));
    }

    // --- X86CFICodeGen Tests ---

    #[test]
    fn test_codegen_new() {
        let cg = X86CFICodeGen::new();
        assert!(!cg.stats.cfi_active);
        assert!(!cg.backward_edge_enabled);
        assert_eq!(cg.type_count(), 0);
    }

    #[test]
    fn test_codegen_enable_full_cfi() {
        let mut cg = X86CFICodeGen::new();
        cg.enable_full_cfi();
        assert!(cg.stats.cfi_active);
    }

    #[test]
    fn test_codegen_enable_backward_edge() {
        let mut cg = X86CFICodeGen::new();
        cg.enable_backward_edge(0x7000000, 0x10000);
        assert!(cg.backward_edge_enabled);
        assert!(cg.shadow_stack.active);
    }

    #[test]
    fn test_codegen_enable_cross_dso() {
        let mut cg = X86CFICodeGen::new();
        cg.enable_cross_dso(0x8000000, 0x100000);
        assert!(cg.cross_dso.enabled);
        assert!(cg.cfi_shadow.is_some());
    }

    #[test]
    fn test_codegen_enable_kcfi() {
        let mut cg = X86CFICodeGen::new();
        cg.enable_kcfi();
        assert!(cg.kcfi_config.enabled);
    }

    #[test]
    fn test_codegen_register_type() {
        let mut cg = X86CFICodeGen::new();
        let hash = cg.register_type("MyClass");
        assert!(hash != 0);
        assert_eq!(cg.type_count(), 1);
        assert_eq!(cg.stats.types_registered, 1);
    }

    #[test]
    fn test_codegen_compute_type_hash() {
        let h1 = X86CFICodeGen::compute_type_hash("int()");
        let h2 = X86CFICodeGen::compute_type_hash("int()");
        assert_eq!(h1, h2);
        let h3 = X86CFICodeGen::compute_type_hash("float()");
        assert_ne!(h1, h3);
    }

    #[test]
    fn test_codegen_add_icall_check() {
        let mut cg = X86CFICodeGen::new();
        cg.add_icall_check(0x4000, "void(int)", "rax");
        assert_eq!(cg.icall_checks.len(), 1);
        assert_eq!(cg.stats.icall_checks, 1);
        assert_eq!(cg.type_count(), 1);
    }

    #[test]
    fn test_codegen_add_kcfi_icall_check() {
        let mut cg = X86CFICodeGen::new();
        cg.enable_kcfi();
        cg.add_kcfi_icall_check(0x5000, "int(char*)", "rbx");
        assert!(cg.icall_checks[0].use_kcfi);
        assert_eq!(cg.stats.icall_checks, 1);
    }

    #[test]
    fn test_codegen_add_vcall_check() {
        let mut cg = X86CFICodeGen::new();
        cg.add_vcall_check(0x6000, 0x1000, "Base", "foo", -8);
        assert_eq!(cg.vcall_checks.len(), 1);
        assert_eq!(cg.stats.vcall_checks, 1);
    }

    #[test]
    fn test_codegen_lower_type_test() {
        let mut cg = X86CFICodeGen::new();
        cg.lower_type_test(0x7000, "!meta_Base", 0xABCD);
        assert_eq!(cg.type_tests.len(), 1);
        assert_eq!(cg.stats.type_tests, 1);
    }

    #[test]
    fn test_codegen_lower_type_checked_load() {
        let mut cg = X86CFICodeGen::new();
        cg.lower_type_checked_load(0x8000, "!meta_Base", -8);
        assert_eq!(cg.type_checked_loads.len(), 1);
        assert_eq!(cg.stats.type_checked_loads, 1);
    }

    #[test]
    fn test_codegen_lower_bitset_test() {
        let mut cg = X86CFICodeGen::new();
        {
            let test = cg.lower_bitset_test(0x9000, "bs1");
            test.with_range(0x1000, 0x2000);
        }
        assert_eq!(cg.bitset_tests.len(), 1);
        assert_eq!(cg.stats.bitset_tests, 1);
    }

    #[test]
    fn test_codegen_add_cross_dso_check() {
        let mut cg = X86CFICodeGen::new();
        cg.add_cross_dso_check(0xA000, "FnType", Some("libfoo.so"));
        assert_eq!(cg.cross_dso_checks.len(), 1);
        assert_eq!(
            cg.cross_dso_checks[0].dso_name.as_deref(),
            Some("libfoo.so")
        );
    }

    #[test]
    fn test_codegen_register_kcfi_target() {
        let mut cg = X86CFICodeGen::new();
        cg.enable_kcfi();
        let hash = cg.register_kcfi_target(0xB000, "void(void)");
        assert!(hash != 0);
        assert_eq!(cg.stats.kcfi_targets, 1);
        assert!(cg.kcfi_check_target(0xB000, "void(void)"));
    }

    #[test]
    fn test_codegen_shadow_stack_push_pop() {
        let mut cg = X86CFICodeGen::new();
        cg.enable_backward_edge(0x7000, 0x1000);
        cg.shadow_stack_push(0x401234, 0x7ff0, 0x401000);
        assert_eq!(cg.stats.shadow_stack_pushes, 1);
        assert!(cg.shadow_stack_pop(0x401234));
        assert_eq!(cg.stats.shadow_stack_pops, 1);
        assert_eq!(cg.stats.violations, 0);
    }

    #[test]
    fn test_codegen_shadow_stack_pop_violation() {
        let mut cg = X86CFICodeGen::new();
        cg.enable_backward_edge(0x7000, 0x1000);
        cg.shadow_stack_push(0xAAAA, 0x1000, 0x5000);
        assert!(!cg.shadow_stack_pop(0xBBBB));
        assert_eq!(cg.stats.violations, 1);
    }

    #[test]
    fn test_codegen_shadow_stack_disabled_bypass() {
        let mut cg = X86CFICodeGen::new();
        // Shadow stack not enabled; pop should succeed regardless
        assert!(cg.shadow_stack_pop(0xDEAD));
        assert_eq!(cg.stats.shadow_stack_pops, 0);
    }

    #[test]
    fn test_codegen_begin_end_function() {
        let mut cg = X86CFICodeGen::new();
        cg.begin_function("worker");
        assert!(cg.get_function_instr("worker").is_some());
        cg.end_function("worker");
        assert_eq!(cg.stats.functions_instrumented, 1);
    }

    #[test]
    fn test_codegen_add_function_forward_check() {
        let mut cg = X86CFICodeGen::new();
        cg.begin_function("fn");
        let check = X86CFICheckLowering::new(X86CFICheckKind::ICall);
        cg.add_function_forward_check("fn", check);
        let instr = cg.get_function_instr("fn").unwrap();
        assert_eq!(instr.forward_edge_checks.len(), 1);
        assert!(instr.has_icall);
    }

    #[test]
    fn test_codegen_report_violation() {
        let mut cg = X86CFICodeGen::new();
        cg.report_violation(0xDEAD, X86CFICheckKind::ICall, 0xBEEF);
        assert_eq!(cg.violation_count(), 1);
        assert_eq!(cg.stats.violations, 1);
    }

    #[test]
    fn test_codegen_format_violations() {
        let mut cg = X86CFICodeGen::new();
        cg.report_violation(0x1000, X86CFICheckKind::VCall, 0x2000);
        cg.report_violation(0x3000, X86CFICheckKind::ShadowStack, 0x4000);
        let formatted = cg.format_violations();
        assert!(formatted.contains("vcall"));
        assert!(formatted.contains("shadow-stack"));
    }

    #[test]
    fn test_codegen_run_lowering_pipeline() {
        let mut cg = X86CFICodeGen::new();
        cg.add_icall_check(0x4000, "int()", "rax");
        cg.add_icall_check(0x4100, "void(char*)", "rbx");
        let checks = cg.run_lowering_pipeline();
        // Should have checks for both icalls + a trap
        assert!(checks.len() >= 3);
    }

    #[test]
    fn test_codegen_cfi_shadow_set_get() {
        let mut cg = X86CFICodeGen::new();
        cg.enable_cross_dso(0x100000, 0x10000);
        cg.cfi_shadow_set(0x100100, 0xAB);
        assert_eq!(cg.cfi_shadow_get(0x100100), 0xAB);
    }

    #[test]
    fn test_codegen_get_stats() {
        let mut cg = X86CFICodeGen::new();
        cg.enable_full_cfi();
        cg.register_type("T1");
        cg.register_type("T2");
        cg.add_icall_check(0x4000, "T1", "rax");
        let stats = cg.get_stats();
        assert_eq!(stats.types_registered, 2);
        assert_eq!(stats.icall_checks, 1);
        assert!(stats.cfi_active);
    }

    #[test]
    fn test_codegen_reset() {
        let mut cg = X86CFICodeGen::new();
        cg.enable_full_cfi();
        cg.register_type("T");
        cg.add_icall_check(0x4000, "T", "rax");
        cg.enable_backward_edge(0x7000, 0x1000);
        cg.shadow_stack_push(0x1234, 0x1000, 0x4000);
        cg.reset();
        assert_eq!(cg.type_count(), 0);
        assert_eq!(cg.icall_checks.len(), 0);
        assert_eq!(cg.stats.icall_checks, 0);
        assert!(!cg.shadow_stack.active);
    }

    #[test]
    fn test_codegen_comprehensive_workflow() {
        let mut cg = X86CFICodeGen::new();
        cg.enable_full_cfi();
        cg.enable_backward_edge(0x7f000000, 0x100000);
        cg.enable_cross_dso(0x80000000, 0x1000000);
        cg.enable_kcfi();

        // Register types
        let h1 = cg.register_type("Base");
        let h2 = cg.register_type("Derived");
        let h3 = cg.register_type("void(int)");
        assert_eq!(cg.type_count(), 3);

        // Forward-edge checks
        cg.add_icall_check(0x401000, "void(int)", "rax");
        cg.add_vcall_check(0x401100, 0x7fff1000, "Base", "virtualMethod", -8);

        // Type tests
        cg.lower_type_test(0x402000, "!meta_Base", h1);
        cg.lower_type_checked_load(0x402100, "!meta_Base", -8);

        // Bitset test
        {
            let bs = cg.lower_bitset_test(0x403000, "bs_func_table");
            bs.with_range(0x400000, 0x500000)
                .with_bitset_data(vec![0xFFFFFFFF, 0x0F]);
        }

        // Cross-DSO
        cg.add_cross_dso_check(0x404000, "void(int)", Some("libplugin.so"));

        // KCFI
        let kcfi_hash = cg.register_kcfi_target(0x405000, "void(void)");
        assert!(kcfi_hash != 0);

        // Shadow stack
        cg.shadow_stack_push(0x401234, 0x7fffef00, 0x401000);
        cg.shadow_stack_push(0x402345, 0x7fffee00, 0x402000);

        // Function instrumentation
        cg.begin_function("main");
        let bitmask_check =
            X86CFICheckLowering::build_bitmask_check("rax", "ecx", h3, 0xFF, ".Lfail");
        cg.add_function_forward_check("main", bitmask_check);
        cg.end_function("main");

        assert_eq!(cg.stats.types_registered, 3);
        assert_eq!(cg.stats.icall_checks, 1);
        assert_eq!(cg.stats.vcall_checks, 1);
        assert_eq!(cg.stats.type_tests, 1);
        assert_eq!(cg.stats.type_checked_loads, 1);
        assert_eq!(cg.stats.bitset_tests, 1);
        assert_eq!(cg.stats.cross_dso_checks, 1);
        assert_eq!(cg.stats.kcfi_targets, 1);
        assert_eq!(cg.stats.shadow_stack_pushes, 2);
        assert_eq!(cg.stats.functions_instrumented, 1);
    }

    #[test]
    fn test_icall_check_emit_pseudo_ir() {
        let check = X86CFIICallCheck::new(0x4000, "int(float)", 0xABCD);
        let ir = check.emit_pseudo_ir();
        assert!(ir.contains("llvm.type.test"));
        assert!(ir.contains("int(float)"));
    }

    #[test]
    fn test_vcall_check_emit_pseudo_ir() {
        let check = X86CFIVCallCheck::new(0x5000, 0x1000, "Base", "f", -8);
        let ir = check.emit_pseudo_ir();
        assert!(ir.contains("CFI vcall check"));
        assert!(ir.contains("vtable"));
    }

    #[test]
    fn test_function_instr_kcfi_prefix() {
        let mut fi = X86CFIFunctionInstrumentation::new("kernel_fn");
        assert!(!fi.has_kcfi_prefix);
        fi.has_kcfi_prefix = true;
        assert!(fi.has_kcfi_prefix);
    }

    #[test]
    fn test_violation_report_with_details() {
        let mut report = X86CFIViolationReport::new(0xDEAD, X86CFICheckKind::KCFI, 0xBEEF);
        report.expected_type_hash = Some(0x1234);
        report.actual_type_hash = Some(0x5678);
        report.function_name = Some("do_work".to_string());
        let formatted = report.format();
        assert!(formatted.contains("0xdead"));
        assert!(formatted.contains("0xbeef"));
    }

    #[test]
    fn test_check_kind_all_values() {
        let kinds = vec![
            X86CFICheckKind::ICall,
            X86CFICheckKind::VCall,
            X86CFICheckKind::Bitset,
            X86CFICheckKind::KCFI,
            X86CFICheckKind::ShadowStack,
            X86CFICheckKind::CrossDSO,
        ];
        for kind in kinds {
            let s = format!("{}", kind);
            assert!(!s.is_empty());
        }
    }

    #[test]
    fn test_cross_dso_config_default() {
        let cfg = X86CFICrossDSOConfig::default();
        assert!(!cfg.enabled);
        assert!(!cfg.use_shadow);
        assert_eq!(cfg.shadow_scale, 3);
    }

    #[test]
    fn test_kcfi_config_default() {
        let cfg = X86KCFIConfig::default();
        assert!(!cfg.enabled);
        assert_eq!(cfg.prefix_byte, X86_KCFI_PREFIX_BYTE);
        assert!(cfg.check_icall);
    }
}