llvm-native-core 0.1.6

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
//! X86 ASan Full — Complete AddressSanitizer & HWASan runtime for X86.
//!
//! This module provides a production-grade AddressSanitizer (ASan) and
//! Hardware-assisted AddressSanitizer (HWASan) runtime implementation
//! specific to X86 and X86-64 targets.
//!
//! Clean-room behavioral reconstruction from:
//! - AddressSanitizer algorithm paper (Serebryany et al. 2012)
//! - AddressSanitizer: A Fast Address Sanity Checker (USENIX ATC 2012)
//! - HWASan design document (clang documentation)
//! - Intel® 64 and IA-32 Architectures Software Developer's Manual
//! - System V Application Binary Interface: AMD64 Architecture Processor
//!
//! Zero LLVM source code consultation. All behavior reconstructed from
//! published specifications and black-box oracle interrogation.
//!
//! ## Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────┐
//! │                     X86ASanFull                              │
//! │  ┌──────────────┐ ┌─────────────┐ ┌──────────────────────┐ │
//! │  │ Shadow Memory │ │ Error       │ │ Allocator +         │ │
//! │  │ (64/32-bit)   │ │ Reporting   │ │ Quarantine           │ │
//! │  └──────────────┘ └─────────────┘ └──────────────────────┘ │
//! │  ┌──────────────┐ ┌─────────────┐ ┌──────────────────────┐ │
//! │  │ Stack Instr  │ │ Global Instr│ │ Heap + Container     │ │
//! │  │ (redzones)   │ │ (ODR check) │ │ Overflow Detection   │ │
//! │  └──────────────┘ └─────────────┘ └──────────────────────┘ │
//! │  ┌──────────────┐ ┌─────────────┐                          │
//! │  │ Fake Stack   │ │ Scope       │                          │
//! │  │ (UAR detect) │ │ Tracker     │                          │
//! │  └──────────────┘ └─────────────┘                          │
//! └─────────────────────────────────────────────────────────────┘
//! ┌─────────────────────────────────────────────────────────────┐
//! │                    X86HWASan                                │
//! │  ┌──────────────┐ ┌─────────────┐ ┌──────────────────────┐ │
//! │  │ Tag Generator│ │ Memory Tags │ │ Stack/Heap/Global    │ │
//! │  │ (random)     │ │ (per-granule)│ │ Tagging              │ │
//! │  └──────────────┘ └─────────────┘ └──────────────────────┘ │
//! │  ┌──────────────┐ ┌─────────────┐ ┌──────────────────────┐ │
//! │  │ Short Granule│ │ Kernel       │ │ MTE Support          │ │
//! │  │ Support      │ │ HWASan Stubs │ │ (probing)            │ │
//! │  └──────────────┘ └─────────────┘ └──────────────────────┘ │
//! └─────────────────────────────────────────────────────────────┘
//! ```

#![allow(non_upper_case_globals, dead_code)]

use crate::hwasan::*;
use crate::sanitize::*;
use crate::x86::*;
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::fmt;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering};
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};

// ============================================================================
// ASan Constants — shadow mapping, granularity, redzone sizes
// ============================================================================

/// Shadow scale: log2 of shadow granularity. 1 shadow byte per 8 app bytes.
pub const X86_ASAN_SHADOW_SCALE: u8 = 3;

/// Shadow granularity: how many application bytes per shadow byte.
pub const X86_ASAN_SHADOW_GRANULARITY: u64 = 1u64 << X86_ASAN_SHADOW_SCALE; // 8

/// Shadow mask: for computing offset within a granule.
pub const X86_ASAN_SHADOW_MASK: u64 = X86_ASAN_SHADOW_GRANULARITY - 1; // 7

/// Default shadow offset for x86-64 Linux (without ASLR).
pub const X86_ASAN_SHADOW_OFFSET_64_DEFAULT: u64 = 0x7fff8000;

/// Shadow offset for x86-64 Linux with ASLR.
pub const X86_ASAN_SHADOW_OFFSET_64_ASLR: u64 = 0x10007fff8000;

/// Shadow offset for i386 (32-bit) Linux.
pub const X86_ASAN_SHADOW_OFFSET_32: u64 = 0x20000000;

/// Maximum shadow memory size (for 64-bit address space).
pub const X86_ASAN_MAX_SHADOW_SIZE_64: u64 = 0x200000000000; // 32 TB

/// Default redzone size for stack variables.
pub const X86_ASAN_STACK_REDZONE_SIZE: u64 = 32;

/// Default redzone size for globals.
pub const X86_ASAN_GLOBAL_REDZONE_SIZE: u64 = 32;

/// Default redzone size for heap allocations.
pub const X86_ASAN_HEAP_REDZONE_SIZE: u64 = 32;

/// Minimum redzone size for any allocation.
pub const X86_ASAN_MIN_REDZONE_SIZE: u64 = 16;

/// Maximum redzone size for stack variables.
pub const X86_ASAN_MAX_STACK_REDZONE_SIZE: u64 = 256;

/// Default quarantine size (bytes) for heap use-after-free detection.
pub const X86_ASAN_QUARANTINE_MAX_SIZE: u64 = 256 * 1024 * 1024; // 256 MB

/// Default thread-local quarantine cache size.
pub const X86_ASAN_THREAD_QUARANTINE_SIZE: u64 = 1024 * 1024; // 1 MB

/// Maximum allocation size handled by the primary allocator.
pub const X86_ASAN_MAX_PRIMARY_ALLOC_SIZE: u64 = 256 * 1024; // 256 KB

/// Maximum fake stack entries for use-after-return detection.
pub const X86_ASAN_FAKE_STACK_MAX_ENTRIES: usize = 256;

/// Minimum size for the fake stack.
pub const X86_ASAN_FAKE_STACK_MIN_SIZE: u64 = 1024 * 1024; // 1 MB

/// Maximum stack trace depth for error reports.
pub const X86_ASAN_MAX_STACK_DEPTH: usize = 256;

/// Number of shadow bit pairs for error suppression hash.
pub const X86_ASAN_SUPPRESSION_HASH_BITS: u32 = 16;

/// Maximum number of reports before throttling.
pub const X86_ASAN_MAX_REPORTS: u64 = 5000;

/// Report deduplication window (in seconds).
pub const X86_ASAN_REPORT_DEDUP_WINDOW: u64 = 60;

/// HWASan granule size (16 bytes on X86, matching AArch64 MTE).
pub const X86_HWASAN_GRANULE_SIZE: u64 = 16;

/// HWASan tag bits (8 bits).
pub const X86_HWASAN_TAG_BITS: u8 = 8;

/// HWASan tag mask (0xFF).
pub const X86_HWASAN_TAG_MASK: u64 = (1u64 << X86_HWASAN_TAG_BITS) - 1;

/// HWASan tag shift for tagged pointers (top byte).
pub const X86_HWASAN_TAG_SHIFT: u8 = 56;

/// HWASan maximum tag value (1-254, 0 is reserved for untagged, 255 sometimes).
pub const X86_HWASAN_MAX_TAG: u8 = 254;

/// HWASan untagged value (no tag).
pub const X86_HWASAN_UNTAGGED: u8 = 0;

/// HWASan address mask for stripping tags.
pub const X86_HWASAN_ADDR_MASK: u64 = (1u64 << X86_HWASAN_TAG_SHIFT) - 1;

/// HWASan short granule mask: tags for sub-16-byte allocations.
pub const X86_HWASAN_SHORT_GRANULE_MASK: u8 = 0xF0;

/// HWASan kernel shadow offset (virtual address space).
pub const X86_HWASAN_KERNEL_SHADOW_OFFSET: u64 = 0xffff_ff00_0000_0000;

/// HWASan kernel shadow scale.
pub const X86_HWASAN_KERNEL_SHADOW_SCALE: u8 = 4;

// ============================================================================
// Shadow Memory Byte Values — encoding the addressability of each 8-byte
// application memory granule.
// ============================================================================

/// Shadow byte encodings for ASan. Each shadow byte describes the
/// addressability of 8 application bytes (the granule).
///
/// Positive values: partially addressable (value = number of addressable bytes
/// from the start of the granule, 1-7).
///
/// Zero: fully addressable (all 8 bytes accessible).
///
/// Negative values: poisoned (not addressable) with specific poison reasons.
pub mod x86_asan_shadow_byte {
    // -- Addressable states --
    /// Fully addressable: all 8 bytes of the granule are accessible.
    pub const ADDRESSABLE: i8 = 0;
    /// Partially addressable: only first 1 byte accessible.
    pub const PARTIAL1: i8 = 1;
    /// Partially addressable: only first 2 bytes accessible.
    pub const PARTIAL2: i8 = 2;
    /// Partially addressable: only first 3 bytes accessible.
    pub const PARTIAL3: i8 = 3;
    /// Partially addressable: only first 4 bytes accessible.
    pub const PARTIAL4: i8 = 4;
    /// Partially addressable: only first 5 bytes accessible.
    pub const PARTIAL5: i8 = 5;
    /// Partially addressable: only first 6 bytes accessible.
    pub const PARTIAL6: i8 = 6;
    /// Partially addressable: only first 7 bytes accessible.
    pub const PARTIAL7: i8 = 7;

    // -- Poison states --
    /// Heap left redzone (before malloc'd block).
    pub const HEAP_LEFT_REDZONE: i8 = -1;
    /// Heap right redzone (after malloc'd block).
    pub const HEAP_RIGHT_REDZONE: i8 = -2;
    /// Stack left redzone (before alloca'd variable).
    pub const STACK_LEFT_REDZONE: i8 = -3;
    /// Stack mid redzone (between adjacent stack variables).
    pub const STACK_MID_REDZONE: i8 = -4;
    /// Stack right redzone (after alloca'd variable).
    pub const STACK_RIGHT_REDZONE: i8 = -5;
    /// Stack use-after-return redzone (fake stack entry freed).
    pub const STACK_UAR_REDZONE: i8 = -6;
    /// Global redzone (around global variables).
    pub const GLOBAL_REDZONE: i8 = -7;
    /// Intra-object redzone (container overflow detection).
    pub const INTRA_OBJECT_REDZONE: i8 = -8;
    /// Freed memory (heap use-after-free).
    pub const FREED: i8 = -9;
    /// Stack use-after-scope (variable out of lexical scope).
    pub const STACK_USE_AFTER_SCOPE: i8 = -10;
    /// ODR-violation indicator.
    pub const ODR_VIOLATION: i8 = -11;
    /// Wild pointer / invalid address.
    pub const INVALID: i8 = -12;
    /// Allocator internal metadata poison.
    pub const ALLOCATOR_METADATA: i8 = -13;
    /// Low shadow gap (unaddressable region).
    pub const SHADOW_GAP: i8 = -14;
    /// High shadow gap (unaddressable region).
    pub const HIGH_SHADOW_GAP: i8 = -15;
    /// User-poisoned (manual __asan_poison_memory_region).
    pub const USER_POISON: i8 = -16;
    /// Quarantine poison (freed but not yet recycled).
    pub const QUARANTINE: i8 = -17;

    /// Returns true if the shadow byte indicates fully or partially
    /// addressable memory.
    pub fn is_addressable(v: i8) -> bool {
        v >= ADDRESSABLE && v <= PARTIAL7
    }

    /// Returns true if the shadow byte indicates poisoned (unaddressable)
    /// memory.
    pub fn is_poisoned(v: i8) -> bool {
        v < ADDRESSABLE
    }

    /// Returns true if the shadow byte indicates freed memory (heap UAF).
    pub fn is_freed(v: i8) -> bool {
        v == FREED
    }

    /// Returns true if the byte indicates a redzone.
    pub fn is_redzone(v: i8) -> bool {
        v == HEAP_LEFT_REDZONE
            || v == HEAP_RIGHT_REDZONE
            || v == STACK_LEFT_REDZONE
            || v == STACK_MID_REDZONE
            || v == STACK_RIGHT_REDZONE
            || v == STACK_UAR_REDZONE
            || v == GLOBAL_REDZONE
    }

    /// Returns the number of addressable bytes if partially addressable.
    pub fn addr_bytes(v: i8) -> u8 {
        if v >= 1 && v <= 7 {
            v as u8
        } else if v == ADDRESSABLE {
            8
        } else {
            0
        }
    }

    /// Convert shadow byte to a human-readable description for diagnostics.
    pub fn describe(v: i8) -> &'static str {
        match v {
            ADDRESSABLE => "addressable",
            PARTIAL1 => "partially addressable (1 byte)",
            PARTIAL2 => "partially addressable (2 bytes)",
            PARTIAL3 => "partially addressable (3 bytes)",
            PARTIAL4 => "partially addressable (4 bytes)",
            PARTIAL5 => "partially addressable (5 bytes)",
            PARTIAL6 => "partially addressable (6 bytes)",
            PARTIAL7 => "partially addressable (7 bytes)",
            HEAP_LEFT_REDZONE => "heap left redzone",
            HEAP_RIGHT_REDZONE => "heap right redzone",
            STACK_LEFT_REDZONE => "stack left redzone",
            STACK_MID_REDZONE => "stack mid redzone",
            STACK_RIGHT_REDZONE => "stack right redzone",
            STACK_UAR_REDZONE => "stack use-after-return",
            GLOBAL_REDZONE => "global redzone",
            INTRA_OBJECT_REDZONE => "container overflow redzone",
            FREED => "freed (heap-use-after-free)",
            STACK_USE_AFTER_SCOPE => "stack-use-after-scope",
            ODR_VIOLATION => "odr-violation indicator",
            INVALID => "invalid address",
            ALLOCATOR_METADATA => "allocator metadata",
            SHADOW_GAP => "shadow gap",
            HIGH_SHADOW_GAP => "high shadow gap",
            USER_POISON => "user-poisoned",
            QUARANTINE => "quarantined (use-after-free)",
            _ => "unknown poison",
        }
    }

    /// Convert a shadow byte to an error type category for reporting.
    pub fn error_category(v: i8) -> &'static str {
        match v {
            HEAP_LEFT_REDZONE | HEAP_RIGHT_REDZONE => "heap-buffer-overflow",
            STACK_LEFT_REDZONE | STACK_MID_REDZONE | STACK_RIGHT_REDZONE => {
                "stack-buffer-overflow"
            }
            STACK_UAR_REDZONE => "stack-use-after-return",
            GLOBAL_REDZONE => "global-buffer-overflow",
            INTRA_OBJECT_REDZONE => "container-overflow",
            FREED | QUARANTINE => "heap-use-after-free",
            STACK_USE_AFTER_SCOPE => "stack-use-after-scope",
            ODR_VIOLATION => "odr-violation",
            USER_POISON => "use-after-poison",
            INVALID => "wild-pointer-access",
            SHADOW_GAP | HIGH_SHADOW_GAP => "shadow-gap-access",
            _ => "unknown-crash",
        }
    }
}

// Bring shadow byte constants into scope for this module.
use x86_asan_shadow_byte::*;

// ============================================================================
// X86ASanShadowMap — platform-specific shadow address mapping
// ============================================================================

/// Target architecture variant for shadow mapping selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86AsanTargetArch {
    X8664,
    X8664WithAslr,
    I386,
    X32,
}

impl X86AsanTargetArch {
    /// Detect the architecture from pointer width.
    pub fn from_pointer_width(width: u8) -> Self {
        match width {
            64 => X86AsanTargetArch::X8664,
            32 => X86AsanTargetArch::I386,
            _ => X86AsanTargetArch::X8664,
        }
    }
}

/// Shadow memory mapping for X86 ASan.
///
/// Translates application addresses to/from shadow addresses.
#[derive(Debug, Clone)]
pub struct X86ASanShadowMap {
    /// The shadow offset added during address translation.
    pub shadow_offset: u64,
    /// The target architecture (determines offset value).
    pub arch: X86AsanTargetArch,
    /// Whether the shadow memory region has been allocated.
    pub shadow_allocated: bool,
    /// Shadow memory base address (after mmap).
    pub shadow_base: u64,
    /// Shadow memory size.
    pub shadow_size: u64,
    /// User-addressable region start.
    pub app_region_start: u64,
    /// User-addressable region end.
    pub app_region_end: u64,
    /// The shadow memory buffer (simulated in user-space).
    shadow_buffer: Vec<u8>,
}

impl X86ASanShadowMap {
    /// Create a new shadow map for the given architecture.
    pub fn new(arch: X86AsanTargetArch) -> Self {
        let shadow_offset = match arch {
            X86AsanTargetArch::X8664 => X86_ASAN_SHADOW_OFFSET_64_DEFAULT,
            X86AsanTargetArch::X8664WithAslr => X86_ASAN_SHADOW_OFFSET_64_ASLR,
            X86AsanTargetArch::I386 => X86_ASAN_SHADOW_OFFSET_32,
            X86AsanTargetArch::X32 => X86_ASAN_SHADOW_OFFSET_32,
        };

        let (app_start, app_end, shadow_size) = match arch {
            X86AsanTargetArch::X8664 | X86AsanTargetArch::X8664WithAslr => {
                // x86-64: typical user-space is 0x000000000000 to 0x7fffffffffff
                // but LowHighMem mappings extend beyond that
                (0u64, 0x0000_7fff_ffff_ffffu64, X86_ASAN_MAX_SHADOW_SIZE_64)
            }
            X86AsanTargetArch::I386 | X86AsanTargetArch::X32 => {
                // i386: typical user-space is 0x00000000 - 0xffffffff (minus kernel)
                (0u64, 0xffff_ffffu64, 0x2000_0000u64) // 512 MB shadow
            }
        };

        Self {
            shadow_offset,
            arch,
            shadow_allocated: false,
            shadow_base: 0,
            shadow_size,
            app_region_start: app_start,
            app_region_end: app_end,
            shadow_buffer: Vec::new(),
        }
    }

    /// Create a shadow map for x86-64 (most common).
    pub fn x86_64() -> Self {
        Self::new(X86AsanTargetArch::X8664)
    }

    /// Create a shadow map for i386.
    pub fn i386() -> Self {
        Self::new(X86AsanTargetArch::I386)
    }

    /// Create a shadow map with ASLR shadow offset for x86-64.
    pub fn x86_64_aslr() -> Self {
        Self::new(X86AsanTargetArch::X8664WithAslr)
    }

    /// Allocate shadow memory.
    ///
    /// In a real implementation, this would mmap with MAP_NORESERVE.
    /// Here we simulate with a Vec<u8> sized for the address space.
    pub fn allocate_shadow(&mut self, max_app_address: u64) -> u64 {
        let shadow_end = self.app_to_shadow(max_app_address);
        let required = shadow_end + 1;
        let actual = required.min(self.shadow_size) as usize;

        self.shadow_buffer = vec![ADDRESSABLE as u8; actual];
        self.shadow_base = self.shadow_offset; // simulate mmap return
        self.shadow_allocated = true;
        self.shadow_base
    }

    /// Deallocate shadow memory.
    pub fn deallocate_shadow(&mut self) {
        self.shadow_buffer.clear();
        self.shadow_allocated = false;
    }

    /// Map application address to shadow address.
    #[inline]
    pub fn app_to_shadow(&self, addr: u64) -> u64 {
        (addr >> X86_ASAN_SHADOW_SCALE) + self.shadow_offset
    }

    /// Map shadow address back to the base of the application granule.
    #[inline]
    pub fn shadow_to_app(&self, shadow_addr: u64) -> u64 {
        (shadow_addr - self.shadow_offset) << X86_ASAN_SHADOW_SCALE
    }

    /// Get the shadow byte for an application address.
    #[inline]
    pub fn get_shadow(&self, addr: u64) -> i8 {
        let saddr = self.app_to_shadow(addr);
        let idx = (saddr - self.shadow_offset) as usize;
        if idx < self.shadow_buffer.len() {
            self.shadow_buffer[idx] as i8
        } else {
            // Out of bounds: simulate high shadow gap
            HIGH_SHADOW_GAP
        }
    }

    /// Set the shadow byte for an application address.
    #[inline]
    pub fn set_shadow(&mut self, addr: u64, value: i8) {
        let saddr = self.app_to_shadow(addr);
        let idx = (saddr - self.shadow_offset) as usize;
        if idx < self.shadow_buffer.len() {
            self.shadow_buffer[idx] = value as u8;
        }
    }

    /// Poison a memory range by setting shadow bytes.
    pub fn poison_range(&mut self, start: u64, size: u64, value: i8) {
        let shadow_start = self.app_to_shadow(start);
        let shadow_end = self.app_to_shadow(start + size - 1);
        for sa in shadow_start..=shadow_end {
            let idx = (sa - self.shadow_offset) as usize;
            if idx < self.shadow_buffer.len() {
                self.shadow_buffer[idx] = value as u8;
            }
        }
    }

    /// Unpoison (mark addressable) a memory range.
    pub fn unpoison_range(&mut self, start: u64, size: u64) {
        self.poison_range(start, size, ADDRESSABLE);
    }

    /// Set partial addressability for a range (e.g. for a variable that
    /// doesn't fill its shadow granule).
    pub fn set_partial_range(&mut self, start: u64, size: u64) {
        let end = start + size;
        let shadow_start = self.app_to_shadow(start);
        let shadow_end = self.app_to_shadow(end.wrapping_sub(1));

        for sa in shadow_start..=shadow_end {
            let ga_start = self.shadow_to_app(sa);
            let ga_end = ga_start + X86_ASAN_SHADOW_GRANULARITY;

            let first_addr = start.max(ga_start);
            let last_addr = (end - 1).min(ga_end - 1);

            if first_addr <= last_addr {
                let addr_bytes = (last_addr - first_addr + 1) as i8;
                let offset = (first_addr - ga_start) as i8;
                let value = if offset == 0 {
                    addr_bytes
                } else if offset + addr_bytes >= X86_ASAN_SHADOW_GRANULARITY as i8 {
                    PARTIAL7 // mark fully accessible within this granule
                } else {
                    // Partially accessible starting from a non-zero offset
                    offset + addr_bytes
                };

                let idx = (sa - self.shadow_offset) as usize;
                if idx < self.shadow_buffer.len() {
                    self.shadow_buffer[idx] = value as u8;
                }
            }
        }
    }

    /// Check a memory access against the shadow.
    /// Returns Ok(()) if addressable, Err(description) if poisoned.
    pub fn check_access(
        &self,
        addr: u64,
        size: u64,
        is_write: bool,
    ) -> Result<(), String> {
        let shadow = self.get_shadow(addr);

        if shadow == ADDRESSABLE {
            return Ok(());
        }

        if shadow >= 1 && shadow <= 7 {
            // Partially addressable: verify the access fits within
            // the addressable portion of this granule.
            let offset_in_granule = addr & X86_ASAN_SHADOW_MASK;
            if offset_in_granule + size <= shadow as u64 {
                return Ok(());
            }
        }

        Err(describe(shadow).to_string())
    }

    /// Check an 8-byte aligned load (fast path).
    #[inline]
    pub fn check_8byte_load(&self, addr: u64) -> Result<(), String> {
        if addr & X86_ASAN_SHADOW_MASK == 0 {
            let shadow = self.get_shadow(addr);
            if shadow == ADDRESSABLE {
                return Ok(());
            }
            if shadow == PARTIAL7 {
                // 7 bytes addressable — check first byte of next granule too
                let next_shadow = self.get_shadow(addr + 7);
                if next_shadow >= 1 {
                    return Ok(());
                }
            }
            Err(describe(shadow).to_string())
        } else {
            // Unaligned: fall back to precise check
            self.check_access(addr, 8, false)
        }
    }

    /// Check an 8-byte aligned store (fast path).
    #[inline]
    pub fn check_8byte_store(&self, addr: u64) -> Result<(), String> {
        // Same logic as load
        self.check_8byte_load(addr)
    }

    /// Check a 16-byte (SSE/AVX) aligned load.
    #[inline]
    pub fn check_16byte_load(&self, addr: u64) -> Result<(), String> {
        // For 16-byte access, check two adjacent 8-byte granules.
        self.check_8byte_load(addr)?;
        self.check_8byte_load(addr + 8)
    }

    /// Check a 16-byte (SSE/AVX) aligned store.
    #[inline]
    pub fn check_16byte_store(&self, addr: u64) -> Result<(), String> {
        self.check_16byte_load(addr)
    }

    /// Bulk poison: mark an entire contiguous range with a given shadow value.
    pub fn bulk_poison(&mut self, start: u64, size: u64, value: i8) {
        if size == 0 {
            return;
        }
        self.poison_range(start, size, value);
    }

    /// Bulk unpoison: mark an entire contiguous range as addressable.
    pub fn bulk_unpoison(&mut self, start: u64, size: u64) {
        self.bulk_poison(start, size, ADDRESSABLE);
    }

    /// Get the shadow region size occupied by a given application range.
    pub fn shadow_region_size(&self, app_size: u64) -> u64 {
        (app_size + X86_ASAN_SHADOW_GRANULARITY - 1) >> X86_ASAN_SHADOW_SCALE
    }

    /// Returns the number of distinct shadow granules in a memory range.
    pub fn granule_count(&self, start: u64, size: u64) -> u64 {
        let shadow_start = self.app_to_shadow(start);
        let shadow_end = self.app_to_shadow(start + size);
        shadow_end - shadow_start
    }

    /// Check whether an address is in the shadow gap (unaddressable).
    pub fn is_shadow_gap(&self, addr: u64) -> bool {
        let shadow = self.get_shadow(addr);
        shadow == SHADOW_GAP || shadow == HIGH_SHADOW_GAP || shadow == INVALID
    }

    /// Scan the shadow for any poisoned regions (used for testing/validation).
    pub fn find_poisoned_regions(&self) -> Vec<(u64, u64, i8)> {
        let mut regions = Vec::new();
        let mut i = 0usize;
        while i < self.shadow_buffer.len() {
            let val = self.shadow_buffer[i] as i8;
            if val < 0 {
                let start = i;
                while i < self.shadow_buffer.len() && self.shadow_buffer[i] as i8 == val
                {
                    i += 1;
                }
                let app_start = self.shadow_to_app(self.shadow_offset + start as u64);
                let app_end = self.shadow_to_app(self.shadow_offset + i as u64);
                regions.push((app_start, app_end - app_start, val));
            } else {
                i += 1;
            }
        }
        regions
    }

    /// Reset all shadow memory to addressable.
    pub fn reset(&mut self) {
        for b in self.shadow_buffer.iter_mut() {
            *b = ADDRESSABLE as u8;
        }
    }
}

impl Default for X86ASanShadowMap {
    fn default() -> Self {
        Self::x86_64()
    }
}

// ============================================================================
// X86ASanStackFrame — stack variable instrumentation with redzones
// ============================================================================

/// Descriptor for a single stack variable protected by ASan.
#[derive(Debug, Clone)]
pub struct X86ASanStackVar {
    /// Human-readable variable name.
    pub name: String,
    /// Offset from the frame base pointer (negative = below RBP).
    pub frame_offset: i64,
    /// Size of the variable in bytes.
    pub size: u64,
    /// Required alignment.
    pub alignment: u64,
    /// Size of the left redzone (before the variable).
    pub left_redzone_size: u64,
    /// Size of the right redzone (after the variable).
    pub right_redzone_size: u64,
    /// Whether this variable should be poisoned on scope exit.
    pub use_after_scope: bool,
    /// Whether this variable uses the fake stack (use-after-return).
    pub use_after_return: bool,
    /// Shadow value for the left redzone.
    pub left_shadow: i8,
    /// Shadow value for the right redzone.
    pub right_shadow: i8,
    /// The middle redzone shadow value (for padding between variables).
    pub mid_shadow: i8,
}

impl X86ASanStackVar {
    /// Create a new stack variable descriptor.
    pub fn new(name: &str, frame_offset: i64, size: u64, alignment: u64) -> Self {
        let rz = X86_ASAN_STACK_REDZONE_SIZE.max(alignment).min(X86_ASAN_MAX_STACK_REDZONE_SIZE);
        Self {
            name: name.to_string(),
            frame_offset,
            size,
            alignment,
            left_redzone_size: rz,
            right_redzone_size: rz,
            use_after_scope: false,
            use_after_return: false,
            left_shadow: STACK_LEFT_REDZONE,
            right_shadow: STACK_RIGHT_REDZONE,
            mid_shadow: STACK_MID_REDZONE,
        }
    }

    /// Total memory needed including both redzones.
    pub fn total_size(&self) -> u64 {
        self.left_redzone_size + self.size + self.right_redzone_size
    }

    /// The start address of the variable region (after left redzone).
    pub fn var_start(&self) -> i64 {
        self.frame_offset + self.left_redzone_size as i64
    }

    /// The end address (exclusive) of the variable region.
    pub fn var_end(&self) -> i64 {
        self.var_start() + self.size as i64
    }

    /// Enable use-after-scope detection for this variable.
    pub fn with_use_after_scope(mut self) -> Self {
        self.use_after_scope = true;
        self
    }

    /// Enable use-after-return detection (fake stack) for this variable.
    pub fn with_use_after_return(mut self) -> Self {
        self.use_after_return = true;
        self
    }
}

/// A fully instrumented stack frame with all variable redzones.
#[derive(Debug, Clone)]
pub struct X86ASanStackFrame {
    /// All stack variables in this frame.
    pub variables: Vec<X86ASanStackVar>,
    /// Total stack frame size including all redzones.
    pub total_frame_size: u64,
    /// Number of variables with use-after-scope enabled.
    pub uas_count: usize,
    /// Number of variables with use-after-return enabled.
    pub uar_count: usize,
    /// Whether this frame uses the fake stack.
    pub uses_fake_stack: bool,
    /// Frame descriptor magic for runtime identification.
    pub frame_descriptor_magic: u64,
    /// Offset of the frame descriptor relative to RBP.
    pub frame_descriptor_offset: i64,
}

impl X86ASanStackFrame {
    /// Create an empty instrumented stack frame.
    pub fn new() -> Self {
        Self {
            variables: Vec::new(),
            total_frame_size: 0,
            uas_count: 0,
            uar_count: 0,
            uses_fake_stack: false,
            frame_descriptor_magic: 0x41B58AB3,
            frame_descriptor_offset: -8,
        }
    }

    /// Add a variable to the frame, computing its layout.
    pub fn add_variable(&mut self, mut var: X86ASanStackVar) {
        if var.use_after_scope {
            self.uas_count += 1;
        }
        if var.use_after_return {
            self.uar_count += 1;
            self.uses_fake_stack = true;
        }

        // Align the variable position
        let aligned_offset = self
            .total_frame_size
            .max(var.left_redzone_size)
            .next_multiple_of(var.alignment);

        var.frame_offset = -(aligned_offset as i64);
        self.total_frame_size = aligned_offset + var.total_size();
        self.variables.push(var);
    }

    /// Compute all shadow regions that need to be poisoned/unpoisoned
    /// for this stack frame. Returns (poison_regions, unpoison_regions).
    pub fn compute_shadow_operations(
        &self,
        frame_base: u64,
    ) -> (Vec<(u64, u64, i8)>, Vec<(u64, u64)>) {
        let mut poison = Vec::new();
        let mut unpoison = Vec::new();

        // The frame grows downward from frame_base
        let frame_low = frame_base - self.total_frame_size;

        for var in &self.variables {
            let var_base = (frame_base as i64 + var.frame_offset) as u64;

            // Left redzone
            let lrz_start = (frame_base as i64 + var.frame_offset - var.left_redzone_size as i64)
                as u64;
            if lrz_start >= frame_low {
                poison.push((lrz_start, var.left_redzone_size, var.left_shadow));
            }

            // Variable itself: unpoison
            unpoison.push((var_base, var.size));

            // Right redzone
            let rrz_start = var_base + var.size;
            poison.push((rrz_start, var.right_redzone_size, var.right_shadow));
        }

        (poison, unpoison)
    }

    /// Apply the shadow operations to a shadow map.
    pub fn apply_shadow(
        &self,
        shadow: &mut X86ASanShadowMap,
        frame_base: u64,
    ) {
        let (poison_regions, unpoison_regions) =
            self.compute_shadow_operations(frame_base);

        for (start, size, value) in &poison_regions {
            shadow.poison_range(*start, *size, *value);
        }
        for (start, size) in &unpoison_regions {
            shadow.unpoison_range(*start, *size);
        }
    }

    /// Poison all variables in this frame (frame exit).
    pub fn poison_all_on_exit(
        &self,
        shadow: &mut X86ASanShadowMap,
        frame_base: u64,
    ) {
        for var in &self.variables {
            let var_base = (frame_base as i64 + var.frame_offset) as u64;
            let poison_val = if var.use_after_scope {
                STACK_USE_AFTER_SCOPE
            } else {
                STACK_MID_REDZONE
            };
            shadow.poison_range(var_base, var.size, poison_val);
        }
    }

    /// Format a debug string describing the frame layout.
    pub fn format_layout(&self) -> String {
        let mut s = format!(
            "Stack frame: {} vars, {} bytes total\n",
            self.variables.len(),
            self.total_frame_size
        );
        for var in &self.variables {
            s.push_str(&format!(
                "  {:>24} offset={:>+6} size={:>6} rz=[{:>3},{:>3}]{} {}\n",
                var.name,
                var.frame_offset,
                var.size,
                var.left_redzone_size,
                var.right_redzone_size,
                if var.use_after_scope { " [uas]" } else { "" },
                if var.use_after_return {
                    " [uar]"
                } else {
                    ""
                },
            ));
        }
        s
    }
}

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

// ============================================================================
// X86ASanFakeStack — use-after-return detection
// ============================================================================

/// A single entry in the fake stack for a function call.
#[derive(Debug, Clone)]
pub struct X86ASanFakeStackEntry {
    /// Function name whose frame is on the fake stack.
    pub function_name: String,
    /// Base address of the fake frame in the fake stack region.
    pub frame_base: u64,
    /// Size of the frame (including redzones).
    pub frame_size: u64,
    /// Depth of this entry (nesting level).
    pub depth: usize,
    /// Timestamp when this entry was created.
    pub creation_time: u64,
    /// Whether the entry is currently active.
    pub is_active: bool,
    /// The original stack frame layout.
    pub stack_frame: X86ASanStackFrame,
    /// The original real stack frame base.
    pub real_frame_base: u64,
}

/// FakeStack — a separately allocated memory region where stack frames
/// are copied to enable use-after-return detection.
///
/// When a function returns, instead of deallocating its stack frame
/// (which would be reused by the next call), the frame is left poisoned
/// on the real stack and an active copy is held in the fake stack.
/// Accesses through dangling pointers to the original frame are caught.
#[derive(Debug)]
pub struct X86ASanFakeStack {
    /// All entries currently tracked.
    pub entries: VecDeque<X86ASanFakeStackEntry>,
    /// Maximum number of entries before eviction.
    pub max_entries: usize,
    /// Current fake stack depth.
    pub depth: usize,
    /// The fake stack memory region base.
    pub region_base: u64,
    /// The fake stack memory region size.
    pub region_size: u64,
    /// Next available offset within the fake stack region.
    pub next_offset: u64,
    /// Monotonically increasing timestamp for LRU eviction.
    timestamp: u64,
    /// Total frames ever pushed.
    total_pushes: u64,
    /// Total frames evicted from the fake stack.
    total_evictions: u64,
}

impl X86ASanFakeStack {
    /// Create a new fake stack with a given region and maximum entries.
    pub fn new(region_base: u64, region_size: u64, max_entries: usize) -> Self {
        Self {
            entries: VecDeque::with_capacity(max_entries),
            max_entries,
            depth: 0,
            region_base,
            region_size,
            next_offset: 0,
            timestamp: 0,
            total_pushes: 0,
            total_evictions: 0,
        }
    }

    /// Create with default sizing (1 MB fake stack, 256 entries).
    pub fn default_sized() -> Self {
        Self::new(
            0, // will be allocated
            X86_ASAN_FAKE_STACK_MIN_SIZE,
            X86_ASAN_FAKE_STACK_MAX_ENTRIES,
        )
    }

    /// Reset the fake stack (e.g. after reallocation).
    pub fn reset(&mut self, new_base: u64) {
        self.entries.clear();
        self.depth = 0;
        self.region_base = new_base;
        self.next_offset = 0;
    }

    /// Push a new frame onto the fake stack.
    /// Returns the fake frame base address, or 0 if allocation failed.
    pub fn push(
        &mut self,
        function_name: &str,
        real_frame_base: u64,
        stack_frame: &X86ASanStackFrame,
    ) -> u64 {
        self.timestamp += 1;

        let frame_size = stack_frame.total_frame_size;

        // Evict old entries if we're over capacity
        while self.entries.len() >= self.max_entries {
            self.evict_one();
        }

        // Allocate space in the fake stack region (circular/fragmented
        // allocation).
        let frame_base = if self.next_offset + frame_size <= self.region_size {
            let base = self.region_base + self.next_offset;
            self.next_offset += frame_size;
            base
        } else {
            // Wrap around or fail: try evicting entries and retrying,
            // or allocate from beginning.
            self.next_offset = 0;
            if frame_size > self.region_size {
                // Frame too large for fake stack
                return 0;
            }
            // Evict entries that are at the beginning
            while !self.entries.is_empty()
                && self.entries.front().unwrap().frame_base
                    < self.region_base + frame_size
            {
                self.entries.pop_front();
            }
            self.region_base + self.next_offset
        };

        self.depth += 1;
        self.total_pushes += 1;

        let entry = X86ASanFakeStackEntry {
            function_name: function_name.to_string(),
            frame_base,
            frame_size,
            depth: self.depth,
            creation_time: self.timestamp,
            is_active: true,
            stack_frame: stack_frame.clone(),
            real_frame_base,
        };

        self.entries.push_back(entry);
        frame_base
    }

    /// Pop a frame from the fake stack (function returns).
    pub fn pop(
        &mut self,
        shadow: &mut X86ASanShadowMap,
        function_name: &str,
    ) -> Option<X86ASanFakeStackEntry> {
        if let Some(pos) = self
            .entries
            .iter()
            .rposition(|e| e.is_active && e.function_name == function_name)
        {
            let mut entry = self.entries.remove(pos).unwrap();
            entry.is_active = false;
            self.depth = self.depth.saturating_sub(1);

            // Poison the fake stack copy to catch use-after-return
            shadow.poison_range(
                entry.frame_base,
                entry.frame_size,
                STACK_UAR_REDZONE,
            );

            // Also poison the original real frame
            entry.stack_frame.poison_all_on_exit(shadow, entry.real_frame_base);

            Some(entry)
        } else {
            None
        }
    }

    /// Check if an access to a given address could be use-after-return.
    /// Returns Some(entry) if the address falls within a freed fake entry.
    pub fn check_use_after_return(&self, addr: u64) -> Option<&X86ASanFakeStackEntry> {
        self.entries
            .iter()
            .rev()
            .find(|e| !e.is_active && addr >= e.frame_base && addr < e.frame_base + e.frame_size)
    }

    /// Evict the least-recently-used entry.
    fn evict_one(&mut self) {
        if let Some(entry) = self.entries.pop_front() {
            self.total_evictions += 1;
            // Mark space as reclaimable
            if self.next_offset >= entry.frame_base - self.region_base + entry.frame_size {
                // This space was already advanced past
            }
        }
    }

    /// Number of active entries.
    pub fn active_count(&self) -> usize {
        self.entries.iter().filter(|e| e.is_active).count()
    }

    /// Total pushes since creation.
    pub fn total_pushes(&self) -> u64 {
        self.total_pushes
    }

    /// Total evictions since creation.
    pub fn total_evictions(&self) -> u64 {
        self.total_evictions
    }

    /// Get an iterator over all entries (active and inactive).
    pub fn all_entries(&self) -> impl Iterator<Item = &X86ASanFakeStackEntry> {
        self.entries.iter()
    }
}

impl Default for X86ASanFakeStack {
    fn default() -> Self {
        Self::default_sized()
    }
}

// ============================================================================
// X86ASanScopeTracker — use-after-scope detection
// ============================================================================

/// Tracks which stack variables are currently in scope.
/// When a variable exits scope, its memory is poisoned.
#[derive(Debug, Clone)]
pub struct X86ASanScopeTracker {
    /// Set of active variable IDs (by name).
    active_vars: HashMap<String, usize>,
    /// Variable to scope depth mapping.
    var_depth: HashMap<String, usize>,
    /// Current lexical scope depth.
    scope_depth: usize,
    /// Counter for generating unique variable IDs.
    next_var_id: usize,
    /// Stack frames currently tracked.
    tracked_frames: HashMap<String, X86ASanStackFrame>,
    /// Name of the current function being tracked.
    current_function: String,
}

impl X86ASanScopeTracker {
    pub fn new() -> Self {
        Self {
            active_vars: HashMap::new(),
            var_depth: HashMap::new(),
            scope_depth: 0,
            next_var_id: 0,
            tracked_frames: HashMap::new(),
            current_function: String::new(),
        }
    }

    /// Enter the scope of a function.
    pub fn enter_function(&mut self, name: &str) {
        self.current_function = name.to_string();
        self.scope_depth = 0;
        self.active_vars.clear();
        self.var_depth.clear();
    }

    /// Leave the current function scope.
    pub fn leave_function(&mut self) {
        self.active_vars.clear();
        self.var_depth.clear();
        self.scope_depth = 0;
    }

    /// Enter a new lexical scope (e.g. compound statement).
    pub fn enter_scope(&mut self) {
        self.scope_depth += 1;
    }

    /// Exit the current lexical scope.
    /// Returns the list of variables that went out of scope and should
    /// be poisoned.
    pub fn exit_scope(&mut self) -> Vec<String> {
        let mut poisoned = Vec::new();

        // All variables at this depth go out of scope
        let vars_to_remove: Vec<String> = self
            .var_depth
            .iter()
            .filter(|(_, d)| **d == self.scope_depth)
            .map(|(n, _)| n.clone())
            .collect();

        for var_name in &vars_to_remove {
            self.active_vars.remove(var_name);
            self.var_depth.remove(var_name);
            poisoned.push(var_name.clone());
        }

        self.scope_depth = self.scope_depth.saturating_sub(1);
        poisoned
    }

    /// Register a stack variable in the current scope.
    pub fn register_var(&mut self, name: &str) -> usize {
        let id = self.next_var_id;
        self.next_var_id += 1;
        self.active_vars.insert(name.to_string(), id);
        self.var_depth.insert(name.to_string(), self.scope_depth);
        id
    }

    /// Check if a variable is currently in scope.
    pub fn is_in_scope(&self, name: &str) -> bool {
        self.active_vars.contains_key(name)
    }

    /// Get the variable ID for a name.
    pub fn var_id(&self, name: &str) -> Option<usize> {
        self.active_vars.get(name).copied()
    }

    /// Number of active (in-scope) variables.
    pub fn active_count(&self) -> usize {
        self.active_vars.len()
    }

    /// Get the current scope depth.
    pub fn current_depth(&self) -> usize {
        self.scope_depth
    }

    /// Record a stack frame layout for scope tracking.
    pub fn track_frame(&mut self, name: &str, frame: X86ASanStackFrame) {
        self.tracked_frames.insert(name.to_string(), frame);
    }
}

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

// ============================================================================
// X86ASanGlobalInstrumentation — global variable redzones & ODR detection
// ============================================================================

/// Protection descriptor for a single global variable.
#[derive(Debug, Clone)]
pub struct X86ASanGlobalProtection {
    /// The global variable's name.
    pub name: String,
    /// Size of the global in bytes.
    pub size: u64,
    /// Required alignment.
    pub alignment: u64,
    /// Left redzone size.
    pub left_redzone_size: u64,
    /// Right redzone size.
    pub right_redzone_size: u64,
    /// Whether this global has been instrumented.
    pub instrumented: bool,
    /// Whether ODR-violation checking is enabled.
    pub odr_check: bool,
    /// The ODR indicator variable address (if ODR check enabled).
    pub odr_indicator: Option<u64>,
    /// Hash of the global's definition for ODR comparison.
    pub odr_hash: Option<u64>,
    /// Module name where the global is defined.
    pub module_name: Option<String>,
    /// Source file where the global is defined.
    pub source_file: Option<String>,
    /// Source line number.
    pub source_line: Option<u32>,
}

impl X86ASanGlobalProtection {
    /// Create protection metadata for a global variable.
    pub fn new(name: &str, size: u64, alignment: u64) -> Self {
        let rz = X86_ASAN_GLOBAL_REDZONE_SIZE.max(alignment).next_multiple_of(32);
        Self {
            name: name.to_string(),
            size,
            alignment,
            left_redzone_size: rz,
            right_redzone_size: rz,
            instrumented: false,
            odr_check: false,
            odr_indicator: None,
            odr_hash: None,
            module_name: None,
            source_file: None,
            source_line: None,
        }
    }

    /// Total padded size including redzones.
    pub fn padded_size(&self) -> u64 {
        self.left_redzone_size + self.size + self.right_redzone_size
    }

    /// Enable ODR checking for this global.
    pub fn with_odr_check(mut self, hash: u64, indicator: u64) -> Self {
        self.odr_check = true;
        self.odr_hash = Some(hash);
        self.odr_indicator = Some(indicator);
        self
    }

    /// Add source location info.
    pub fn with_source(mut self, file: &str, line: u32) -> Self {
        self.source_file = Some(file.to_string());
        self.source_line = Some(line);
        self
    }

    /// Add module name.
    pub fn with_module(mut self, module: &str) -> Self {
        self.module_name = Some(module.to_string());
        self
    }

    /// Compute the shadow regions for this global.
    pub fn compute_shadow_regions(
        &self,
        base_addr: u64,
    ) -> Vec<(u64, u64, i8)> {
        let mut regions = Vec::new();

        // Left redzone
        if self.left_redzone_size > 0 {
            regions.push((base_addr, self.left_redzone_size, GLOBAL_REDZONE));
        }

        // Right redzone
        let right_start = base_addr + self.left_redzone_size + self.size;
        if self.right_redzone_size > 0 {
            regions.push((right_start, self.right_redzone_size, GLOBAL_REDZONE));
        }

        // ODR indicator
        if let Some(odr_addr) = self.odr_indicator {
            regions.push((odr_addr, 1, ODR_VIOLATION));
        }

        // The global itself is addressable (no poison)
        // regions with ADDRESSABLE are handled separately during unpoison

        regions
    }
}

/// Collection of all instrumented globals.
#[derive(Debug, Clone)]
pub struct X86ASanGlobalInstrumentation {
    /// All instrumented globals.
    pub globals: Vec<X86ASanGlobalProtection>,
    /// Map from name to index for fast lookup.
    name_index: HashMap<String, usize>,
    /// Map from address to index.
    addr_index: BTreeMap<u64, usize>,
    /// Total redzone bytes added.
    pub total_redzone_bytes: u64,
    /// ODR violation detector state.
    pub odr_detector: X86ASanODRViolationDetector,
}

impl X86ASanGlobalInstrumentation {
    pub fn new() -> Self {
        Self {
            globals: Vec::new(),
            name_index: HashMap::new(),
            addr_index: BTreeMap::new(),
            total_redzone_bytes: 0,
            odr_detector: X86ASanODRViolationDetector::new(),
        }
    }

    /// Add a global variable for instrumentation.
    pub fn add_global(&mut self, global: X86ASanGlobalProtection, addr: u64) {
        let idx = self.globals.len();
        self.name_index.insert(global.name.clone(), idx);
        self.addr_index.insert(addr, idx);
        self.total_redzone_bytes += global.left_redzone_size + global.right_redzone_size;
        self.globals.push(global);
    }

    /// Apply global instrumentation to a shadow map.
    pub fn apply_to_shadow(
        &self,
        shadow: &mut X86ASanShadowMap,
        base_addrs: &[(u64, &str)],
    ) {
        for (addr, name) in base_addrs {
            if let Some(idx) = self.name_index.get(*name) {
                let g = &self.globals[*idx];
                let base = *addr;

                // Poison redzones
                shadow.poison_range(base, g.left_redzone_size, GLOBAL_REDZONE);
                let right_start = base + g.left_redzone_size + g.size;
                shadow.poison_range(right_start, g.right_redzone_size, GLOBAL_REDZONE);

                // Unpoison the global itself
                let var_start = base + g.left_redzone_size;
                shadow.unpoison_range(var_start, g.size);

                // Check ODR indicator
                if let Some(odr_addr) = g.odr_indicator {
                    let val = shadow.get_shadow(odr_addr);
                    if val == ODR_VIOLATION {
                        // Already set by another TU; ODR violation!
                        self.odr_detector.report_violation(name);
                    }
                    shadow.set_shadow(odr_addr, ODR_VIOLATION);
                }
            }
        }
    }

    /// Look up a global by name.
    pub fn by_name(&self, name: &str) -> Option<&X86ASanGlobalProtection> {
        self.name_index.get(name).map(|&idx| &self.globals[idx])
    }

    /// Look up a global by address (binary search).
    pub fn by_address(&self, addr: u64) -> Option<&X86ASanGlobalProtection> {
        // Find the global whose base+left_redzone is <= addr < base+left_redzone+size
        self.globals.iter().find(|g| {
            // Each global address was registered; need the actual base
            false // simplified — actual lookup needs addr mapping
        })
        .or_else(|| None)
    }

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

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

// ============================================================================
// X86ASanODRViolationDetector — ODR (One Definition Rule) checking
// ============================================================================

/// Detects ODR violations by comparing hashes of global variable
/// definitions across translation units.
#[derive(Debug, Clone)]
pub struct X86ASanODRViolationDetector {
    /// Map from global name to the first seen hash.
    pub global_hashes: HashMap<String, u64>,
    /// Set of global names that have ODR violations.
    pub violations: HashSet<String>,
    /// Metadata for each global's first definition.
    pub first_definition: HashMap<String, (String, u32, u64)>,
}

impl X86ASanODRViolationDetector {
    pub fn new() -> Self {
        Self {
            global_hashes: HashMap::new(),
            violations: HashSet::new(),
            first_definition: HashMap::new(),
        }
    }

    /// Register a global definition. Returns true if an ODR violation
    /// is detected (hash mismatch with a previously seen definition).
    pub fn register_global(
        &mut self,
        name: &str,
        hash: u64,
        file: &str,
        line: u32,
        size: u64,
    ) -> bool {
        if let Some(&existing_hash) = self.global_hashes.get(name) {
            if existing_hash != hash {
                // ODR violation: two TUs disagree on the type/size of
                // this global.
                self.violations.insert(name.to_string());
                return true;
            }
            // Same hash: consistent definition, no violation
            false
        } else {
            // First time seeing this global
            self.global_hashes.insert(name.to_string(), hash);
            self.first_definition
                .insert(name.to_string(), (file.to_string(), line, size));
            false
        }
    }

    /// Compute a content-based hash for a global variable definition.
    /// In practice this would use a hash of the type signature + size.
    pub fn compute_hash(name: &str, type_name: &str, size: u64) -> u64 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut hasher = DefaultHasher::new();
        name.hash(&mut hasher);
        type_name.hash(&mut hasher);
        size.hash(&mut hasher);
        hasher.finish()
    }

    /// Report a violation (used when shadow memory detects it).
    pub fn report_violation(&self, name: &str) {
        // Mark as violated in the detector state
        // The actual logging happens in X86ASanErrorReporter
    }

    /// Check if a global has a known ODR violation.
    pub fn has_violation(&self, name: &str) -> bool {
        self.violations.contains(name)
    }

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

    /// Get a formatted report of all ODR violations.
    pub fn format_violations(&self) -> String {
        let mut report = String::new();
        report.push_str("=== ODR Violation Report ===\n");
        for name in &self.violations {
            report.push_str(&format!("  ODR Violation: {}\n", name));
            if let Some((file, line, size)) = self.first_definition.get(name) {
                report.push_str(&format!(
                    "    First definition: {} ({} bytes, line {})\n",
                    file, size, line
                ));
            }
        }
        report.push_str(&format!(
            "Total ODR violations: {}\n",
            self.violations.len()
        ));
        report
    }
}

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

// ============================================================================
// X86ASanContainerOverflow — container overflow detection
// ============================================================================

/// Detects overflow within heap-allocated containers (e.g. std::vector
/// internal buffer). Uses intra-object redzones.
#[derive(Debug, Clone)]
pub struct X86ASanContainerOverflowDetector {
    /// Whether container overflow detection is enabled.
    pub enabled: bool,
    /// Intra-object redzone size.
    pub intra_object_redzone_size: u64,
    /// Minimum container size to instrument.
    pub min_container_size: u64,
    /// Tracked container allocations.
    containers: HashMap<u64, String>,
}

impl X86ASanContainerOverflowDetector {
    pub fn new() -> Self {
        Self {
            enabled: true,
            intra_object_redzone_size: 16, // 2 shadow granules
            min_container_size: 32,
            containers: HashMap::new(),
        }
    }

    /// Instrument a container allocation by adding intra-object redzones.
    pub fn instrument_container(
        &mut self,
        shadow: &mut X86ASanShadowMap,
        addr: u64,
        object_size: u64,
        container_name: &str,
    ) {
        if !self.enabled || object_size < self.min_container_size {
            return;
        }

        // Place an intra-object redzone at the end of the container's
        // nominal capacity region, so writes past the logical end
        // are caught even if they stay within the allocated block.
        let intra_rz_start = addr + object_size - self.intra_object_redzone_size;

        shadow.poison_range(
            intra_rz_start,
            self.intra_object_redzone_size,
            INTRA_OBJECT_REDZONE,
        );

        self.containers
            .insert(addr, container_name.to_string());
    }

    /// Check if an access is an intra-object overflow (hit the intra-object
    /// redzone within a container allocation).
    pub fn is_intra_object_overflow(&self, shadow: &X86ASanShadowMap, addr: u64) -> bool {
        let sv = shadow.get_shadow(addr);
        sv == INTRA_OBJECT_REDZONE
    }

    /// Remove container tracking.
    pub fn remove_container(&mut self, addr: u64) {
        self.containers.remove(&addr);
    }

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

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

// ============================================================================
// X86ASanTLS — thread-local storage for ASan runtime
// ============================================================================

/// Thread-local state for ASan.
#[derive(Debug)]
pub struct X86ASanTLS {
    /// Thread-local quarantine cache for recently freed blocks.
    pub quarantine_cache: VecDeque<(u64, u64, u64)>, // (addr, size, timestamp)
    /// Thread-local allocation count.
    pub alloc_count: u64,
    /// Thread-local free count.
    pub free_count: u64,
    /// Thread-local total allocated bytes.
    pub total_allocated: u64,
    /// Thread-local total freed bytes.
    pub total_freed: u64,
    /// Whether this thread has ASan activated.
    pub activated: bool,
    /// Thread name for diagnostics.
    pub thread_name: Option<String>,
}

impl X86ASanTLS {
    pub fn new() -> Self {
        Self {
            quarantine_cache: VecDeque::new(),
            alloc_count: 0,
            free_count: 0,
            total_allocated: 0,
            total_freed: 0,
            activated: false,
            thread_name: None,
        }
    }

    /// Add a freed block to the thread-local quarantine.
    pub fn add_to_quarantine(&mut self, addr: u64, size: u64) {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis() as u64;

        self.quarantine_cache.push_back((addr, size, now));

        // Enforce per-thread quarantine size limit
        let mut total: u64 = self.quarantine_cache.iter().map(|(_, s, _)| s).sum();
        while total > X86_ASAN_THREAD_QUARANTINE_SIZE {
            if let Some((addr, _, _)) = self.quarantine_cache.pop_front() {
                total = self.quarantine_cache.iter().map(|(_, s, _)| s).sum();
            } else {
                break;
            }
        }
    }

    /// Flush the thread-local quarantine to the global quarantine.
    pub fn flush_quarantine(&mut self) -> Vec<(u64, u64)> {
        self.quarantine_cache
            .drain(..)
            .map(|(a, s, _)| (a, s))
            .collect()
    }

    /// Check if an address is in the thread-local quarantine (UAF
    /// detection).
    pub fn is_quarantined(&self, addr: u64, size: u64) -> bool {
        self.quarantine_cache
            .iter()
            .any(|(qa, qs, _)| *qa <= addr && addr + size <= *qa + *qs)
    }
}

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

// ============================================================================
// X86ASanErrorReport — structured error reporting
// ============================================================================

/// The type of ASan error detected.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum X86ASanErrorType {
    HeapBufferOverflow,
    StackBufferOverflow,
    GlobalBufferOverflow,
    HeapUseAfterFree,
    StackUseAfterReturn,
    StackUseAfterScope,
    UseAfterPoison,
    DoubleFree,
    InvalidFree,
    AllocDeallocMismatch,
    MemoryLeak,
    ODRViolation,
    ContainerOverflow,
    ShadowGapAccess,
    NullDereference,
    WildPointerAccess,
    BadFree,
    CallocOverflow,
    ReallocInvalid,
    MemsetParamOverlap,
    MemcpyParamOverlap,
    StrcatParamOverlap,
    StrcpyParamOverlap,
    StrncatParamOverlap,
    StrncpyParamOverlap,
    MemmoveParamOverlap,
}

impl fmt::Display for X86ASanErrorType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            X86ASanErrorType::HeapBufferOverflow => "heap-buffer-overflow",
            X86ASanErrorType::StackBufferOverflow => "stack-buffer-overflow",
            X86ASanErrorType::GlobalBufferOverflow => "global-buffer-overflow",
            X86ASanErrorType::HeapUseAfterFree => "heap-use-after-free",
            X86ASanErrorType::StackUseAfterReturn => "stack-use-after-return",
            X86ASanErrorType::StackUseAfterScope => "stack-use-after-scope",
            X86ASanErrorType::UseAfterPoison => "use-after-poison",
            X86ASanErrorType::DoubleFree => "double-free",
            X86ASanErrorType::InvalidFree => "invalid-free",
            X86ASanErrorType::AllocDeallocMismatch => "alloc-dealloc-mismatch",
            X86ASanErrorType::MemoryLeak => "memory-leak",
            X86ASanErrorType::ODRViolation => "odr-violation",
            X86ASanErrorType::ContainerOverflow => "container-overflow",
            X86ASanErrorType::ShadowGapAccess => "shadow-gap-access",
            X86ASanErrorType::NullDereference => "null-dereference",
            X86ASanErrorType::WildPointerAccess => "wild-pointer-access",
            X86ASanErrorType::BadFree => "bad-free",
            X86ASanErrorType::CallocOverflow => "calloc-overflow",
            X86ASanErrorType::ReallocInvalid => "realloc-invalid-argument",
            X86ASanErrorType::MemsetParamOverlap => "memset-param-overlap",
            X86ASanErrorType::MemcpyParamOverlap => "memcpy-param-overlap",
            X86ASanErrorType::StrcatParamOverlap => "strcat-param-overlap",
            X86ASanErrorType::StrcpyParamOverlap => "strcpy-param-overlap",
            X86ASanErrorType::StrncatParamOverlap => "strncat-param-overlap",
            X86ASanErrorType::StrncpyParamOverlap => "strncpy-param-overlap",
            X86ASanErrorType::MemmoveParamOverlap => "memmove-param-overlap",
        };
        write!(f, "{}", s)
    }
}

/// An access type descriptor for error reports.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86ASanAccessType {
    Read,
    Write,
    Free,
    Alloc,
}

impl fmt::Display for X86ASanAccessType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            X86ASanAccessType::Read => write!(f, "READ"),
            X86ASanAccessType::Write => write!(f, "WRITE"),
            X86ASanAccessType::Free => write!(f, "FREE"),
            X86ASanAccessType::Alloc => write!(f, "ALLOC"),
        }
    }
}

/// A single stack frame entry in a stack trace.
#[derive(Debug, Clone)]
pub struct X86ASanStackFrameEntry {
    /// Function name (if known).
    pub function: Option<String>,
    /// Source file (if known).
    pub file: Option<String>,
    /// Source line number (if known).
    pub line: Option<u32>,
    /// Column number (if known).
    pub column: Option<u32>,
    /// Module name (e.g. DSO or executable name).
    pub module: Option<String>,
    /// Offset into the module.
    pub module_offset: u64,
    /// Instruction pointer address.
    pub ip: u64,
    /// Base pointer address.
    pub bp: u64,
    /// Whether this frame is symbolized.
    pub symbolized: bool,
}

impl X86ASanStackFrameEntry {
    pub fn new(ip: u64, bp: u64) -> Self {
        Self {
            function: None,
            file: None,
            line: None,
            column: None,
            module: None,
            module_offset: ip,
            ip,
            bp,
            symbolized: false,
        }
    }

    pub fn format(&self) -> String {
        if self.symbolized {
            format!(
                "    #0 0x{:x} in {} {}:{}:{}",
                self.ip,
                self.function.as_deref().unwrap_or("??"),
                self.file.as_deref().unwrap_or("??"),
                self.line.unwrap_or(0),
                self.column.unwrap_or(0),
            )
        } else {
            format!(
                "    #0 0x{:x} ({}+0x{:x})",
                self.ip,
                self.module.as_deref().unwrap_or("??"),
                self.module_offset,
            )
        }
    }
}

/// A complete ASan error report.
#[derive(Debug, Clone)]
pub struct X86ASanErrorReport {
    /// The type of error.
    pub error_type: X86ASanErrorType,
    /// The faulting address.
    pub address: u64,
    /// Size of the access that triggered the error.
    pub access_size: u64,
    /// The type of access (read, write, free).
    pub access_type: X86ASanAccessType,
    /// The shadow byte value at the fault address.
    pub shadow_value: i8,
    /// Human-readable description of the shadow value.
    pub shadow_description: String,
    /// The stack trace at the point of error.
    pub stack_trace: Vec<X86ASanStackFrameEntry>,
    /// The stack trace at allocation time (for UAF errors).
    pub allocation_trace: Option<Vec<X86ASanStackFrameEntry>>,
    /// The stack trace at deallocation time (for UAF errors).
    pub deallocation_trace: Option<Vec<X86ASanStackFrameEntry>>,
    /// Thread ID.
    pub thread_id: u64,
    /// Thread name.
    pub thread_name: Option<String>,
    /// Whether the program can continue after this error.
    pub is_recoverable: bool,
    /// Timestamp of the error.
    pub timestamp: u64,
    /// Additional description text.
    pub description: Option<String>,
}

impl X86ASanErrorReport {
    pub fn new(
        error_type: X86ASanErrorType,
        address: u64,
        access_size: u64,
        access_type: X86ASanAccessType,
        shadow_value: i8,
    ) -> Self {
        Self {
            error_type,
            address,
            access_size,
            access_type,
            shadow_value,
            shadow_description: describe(shadow_value).to_string(),
            stack_trace: Vec::new(),
            allocation_trace: None,
            deallocation_trace: None,
            thread_id: 0,
            thread_name: None,
            is_recoverable: true,
            timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
            description: None,
        }
    }

    /// Format a human-readable error report.
    pub fn format_report(&self) -> String {
        let mut report = String::new();
        let line = "=".repeat(60);

        report.push_str(&line);
        report.push('\n');
        report.push_str(&format!(
            "=={}== ERROR: AddressSanitizer: {} on address 0x{:016x} at pc 0x{:016x}\n",
            self.thread_id,
            self.error_type,
            self.address,
            self.stack_trace
                .first()
                .map(|f| f.ip)
                .unwrap_or(0),
        ));

        report.push_str(&format!(
            "{} of size {} at 0x{:016x} thread T{}\n",
            self.access_type, self.access_size, self.address, self.thread_id,
        ));

        if let Some(ref desc) = self.description {
            report.push_str(&format!("    {}\n", desc));
        }

        // Shadow description
        report.push_str(&format!(
            "Address 0x{:016x} is located in the {} region ({})\n",
            self.address, self.shadow_description, describe(self.shadow_value),
        ));

        // Stack trace at error
        report.push_str("STACK TRACE at error:\n");
        for frame in &self.stack_trace {
            report.push_str(&frame.format());
            report.push('\n');
        }

        // Allocation trace (for UAF)
        if let Some(ref alloc_trace) = self.allocation_trace {
            report.push_str("STACK TRACE at allocation:\n");
            for frame in alloc_trace {
                report.push_str(&frame.format());
                report.push('\n');
            }
        }

        // Deallocation trace (for UAF)
        if let Some(ref free_trace) = self.deallocation_trace {
            report.push_str("STACK TRACE at deallocation:\n");
            for frame in free_trace {
                report.push_str(&frame.format());
                report.push('\n');
            }
        }

        report.push_str(&format!(
            "Shadow byte legend (one shadow byte represents {} application bytes):\n",
            X86_ASAN_SHADOW_GRANULARITY
        ));
        report.push_str(
            "  Addressable:            0\n  Partially addressable:  1-7\n",
        );
        report.push_str(
            "  Heap left redzone:      fa\n  Heap right redzone:     fb\n",
        );
        report.push_str(
            "  Stack left redzone:     f1\n  Stack mid redzone:      f2\n  Stack right redzone:    f3\n",
        );
        report.push_str(
            "  Stack use-after-return: f5\n  Stack use-after-scope:  f8\n",
        );
        report.push_str(
            "  Global redzone:         f9\n  Freed heap region:      fd\n",
        );
        report.push_str("  Container overflow:     fc\n");

        if self.is_recoverable {
            report.push_str("\n[NOTE] The program can continue.\n");
        } else {
            report.push_str("\n[FATAL] Aborting.\n");
        }

        report.push_str(&line);
        report
    }

    /// Get a short one-line summary.
    pub fn summary(&self) -> String {
        format!(
            "{} on address 0x{:016x} ({})",
            self.error_type, self.address, self.shadow_description,
        )
    }
}

// ============================================================================
// X86ASanStackTraceCollector — stack trace collection and symbolization
// ============================================================================

/// Collects and symbolizes stack traces for ASan error reports.
#[derive(Debug)]
pub struct X86ASanStackTraceCollector {
    /// Whether to use fast frame-pointer-based unwinding.
    pub fast_unwind: bool,
    /// Maximum number of frames to collect.
    pub max_depth: usize,
    /// Whether to symbolize stack traces.
    pub symbolize: bool,
    /// Path to an external symbolizer tool.
    pub external_symbolizer_path: Option<String>,
    /// Cached symbol table for function name lookups.
    symbol_table: HashMap<u64, String>,
    /// Cached source location info.
    source_cache: HashMap<u64, (String, u32, u32)>,
    /// Module name for symbol lookup.
    module_name: Option<String>,
}

impl X86ASanStackTraceCollector {
    pub fn new() -> Self {
        Self {
            fast_unwind: true,
            max_depth: X86_ASAN_MAX_STACK_DEPTH,
            symbolize: true,
            external_symbolizer_path: None,
            symbol_table: HashMap::new(),
            source_cache: HashMap::new(),
            module_name: None,
        }
    }

    /// Set the module name for symbol lookup.
    pub fn set_module(&mut self, name: &str) {
        self.module_name = Some(name.to_string());
    }

    /// Register a symbol in the symbol table.
    pub fn register_symbol(
        &mut self,
        addr: u64,
        name: &str,
        file: Option<&str>,
        line: Option<u32>,
        column: Option<u32>,
    ) {
        self.symbol_table.insert(addr, name.to_string());
        if let (Some(f), Some(l), Some(c)) = (file, line, column) {
            self.source_cache.insert(addr, (f.to_string(), l, c));
        }
    }

    /// Capture a stack trace from the current execution context.
    pub fn capture_stack_trace(&self, ip: u64, bp: u64, sp: u64) -> Vec<X86ASanStackFrameEntry> {
        let mut frames = Vec::new();
        frames.push(X86ASanStackFrameEntry::new(ip, bp));

        if self.fast_unwind {
            self.fast_unwind_frames(bp, sp, &mut frames);
        }

        // Symbolize frames
        if self.symbolize {
            for frame in &mut frames {
                self.symbolize_frame(frame);
            }
        }

        frames
    }

    /// Fast frame-pointer-based stack unwinding.
    fn fast_unwind_frames(
        &self,
        start_bp: u64,
        sp: u64,
        frames: &mut Vec<X86ASanStackFrameEntry>,
    ) {
        let mut current_bp = start_bp;

        for _depth in 0..self.max_depth {
            if current_bp == 0 || current_bp < sp {
                break;
            }

            // Read [rbp]: saved rbp (caller's frame pointer)
            // Read [rbp+8]: return address
            // In real ASan, these reads must happen with shadow checks disabled.
            // Here we simulate by reading from "memory" — the BP chain.

            // For simulation, we push a placeholder entry.
            // In real code, this would dereference the frame pointer chain.
            let caller_bp = current_bp; // simplified
            let return_addr = current_bp + 8; // simulated

            if caller_bp <= current_bp {
                // Frame pointer chain is non-monotonic; stop unwinding.
                break;
            }

            frames.push(X86ASanStackFrameEntry::new(return_addr, caller_bp));
            current_bp = caller_bp;

            if frames.len() >= self.max_depth {
                break;
            }
        }
    }

    /// Symbolize a single stack frame entry.
    fn symbolize_frame(&self, frame: &mut X86ASanStackFrameEntry) {
        // Look up in symbol table
        if let Some(name) = self.symbol_table.get(&frame.ip) {
            frame.function = Some(name.clone());
            frame.symbolized = true;
        }

        // Look up source location
        if let Some((file, line, col)) = self.source_cache.get(&frame.ip) {
            frame.file = Some(file.clone());
            frame.line = Some(*line);
            frame.column = Some(*col);
        }

        if let Some(ref module) = self.module_name {
            frame.module = Some(module.clone());
        }
    }

    /// Try to symbolize using an external tool (e.g. llvm-symbolizer).
    pub fn external_symbolize(&self, ip: u64) -> Option<(String, String, u32, u32)> {
        if let Some(ref path) = self.external_symbolizer_path {
            // In production, this would run the external tool
            // For now, return cached info
            if let Some(name) = self.symbol_table.get(&ip) {
                if let Some((file, line, col)) = self.source_cache.get(&ip) {
                    return Some((name.clone(), file.clone(), *line, *col));
                }
            }
        }
        None
    }

    /// Compute a hash of a stack trace for error deduplication.
    pub fn hash_stack_trace(frames: &[X86ASanStackFrameEntry]) -> u64 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut hasher = DefaultHasher::new();
        for frame in frames.iter().take(8) {
            frame.ip.hash(&mut hasher);
            frame.module_offset.hash(&mut hasher);
        }
        hasher.finish()
    }

    /// Check if two stack traces are equivalent (for dedup).
    pub fn equivalent(a: &[X86ASanStackFrameEntry], b: &[X86ASanStackFrameEntry]) -> bool {
        if a.len() < 3 || b.len() < 3 {
            return false;
        }
        // Compare first 3 frames
        for i in 0..3.min(a.len()).min(b.len()) {
            if a[i].ip != b[i].ip {
                return false;
            }
        }
        true
    }
}

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

// ============================================================================
// X86ASanErrorSuppression — error suppression from file
// ============================================================================

/// Parsed suppression rule.
#[derive(Debug, Clone)]
pub struct X86ASanSuppressionRule {
    /// The pattern to match against the stack trace.
    pub pattern: String,
    /// The error type this suppression applies to.
    pub error_type: Option<X86ASanErrorType>,
    /// Whether this is a regex pattern.
    pub is_regex: bool,
    /// The line number where this rule was defined.
    pub source_line: usize,
}

impl X86ASanSuppressionRule {
    pub fn new(pattern: &str, error_type: Option<X86ASanErrorType>) -> Self {
        Self {
            pattern: pattern.to_string(),
            error_type,
            is_regex: false,
            source_line: 0,
        }
    }

    /// Check if this rule matches a given error report.
    pub fn matches(
        &self,
        report: &X86ASanErrorReport,
    ) -> bool {
        if let Some(et) = &self.error_type {
            if *et != report.error_type {
                return false;
            }
        }

        // Check if any stack frame function name matches the pattern
        for frame in &report.stack_trace {
            if let Some(ref func) = frame.function {
                if func.contains(&self.pattern) {
                    return true;
                }
            }
        }

        // Check allocation/free traces too
        for trace in [&report.allocation_trace, &report.deallocation_trace] {
            if let Some(frames) = trace {
                for frame in frames {
                    if let Some(ref func) = frame.function {
                        if func.contains(&self.pattern) {
                            return true;
                        }
                    }
                }
            }
        }

        false
    }
}

/// ASan error suppression system (reads ASAN_OPTIONS=suppressions=file).
#[derive(Debug, Clone)]
pub struct X86ASanErrorSuppression {
    /// All active suppression rules.
    pub rules: Vec<X86ASanSuppressionRule>,
    /// Whether suppressions are enabled.
    pub enabled: bool,
    /// Number of errors suppressed.
    pub suppressed_count: u64,
}

impl X86ASanErrorSuppression {
    pub fn new() -> Self {
        Self {
            rules: Vec::new(),
            enabled: false,
            suppressed_count: 0,
        }
    }

    /// Load suppressions from a file.
    pub fn load_from_file(&mut self, path: &str) -> std::io::Result<usize> {
        let content = std::fs::read_to_string(path)?;
        self.parse_suppressions(&content);
        self.enabled = true;
        Ok(self.rules.len())
    }

    /// Parse suppression rules from a string.
    pub fn parse_suppressions(&mut self, content: &str) {
        let mut current_type: Option<X86ASanErrorType> = None;
        let mut line_num = 0usize;

        for line in content.lines() {
            line_num += 1;
            let trimmed = line.trim();

            if trimmed.is_empty() || trimmed.starts_with('#') {
                continue;
            }

            if trimmed.ends_with(':') {
                // Section header: error type
                let header = trimmed.trim_end_matches(':');
                current_type = match header {
                    "heap-buffer-overflow" => Some(X86ASanErrorType::HeapBufferOverflow),
                    "stack-buffer-overflow" => Some(X86ASanErrorType::StackBufferOverflow),
                    "global-buffer-overflow" => Some(X86ASanErrorType::GlobalBufferOverflow),
                    "heap-use-after-free" => Some(X86ASanErrorType::HeapUseAfterFree),
                    "stack-use-after-return" => Some(X86ASanErrorType::StackUseAfterReturn),
                    "stack-use-after-scope" => Some(X86ASanErrorType::StackUseAfterScope),
                    "use-after-poison" => Some(X86ASanErrorType::UseAfterPoison),
                    "double-free" => Some(X86ASanErrorType::DoubleFree),
                    "invalid-free" => Some(X86ASanErrorType::InvalidFree),
                    "alloc-dealloc-mismatch" => {
                        Some(X86ASanErrorType::AllocDeallocMismatch)
                    }
                    "memory-leak" => Some(X86ASanErrorType::MemoryLeak),
                    "odr-violation" => Some(X86ASanErrorType::ODRViolation),
                    "container-overflow" => Some(X86ASanErrorType::ContainerOverflow),
                    _ => None,
                };
            } else if trimmed.starts_with("fun:") {
                // Function name pattern
                let pattern = &trimmed[4..];
                let mut rule = X86ASanSuppressionRule::new(pattern, current_type);
                rule.source_line = line_num;
                self.rules.push(rule);
            } else if trimmed.starts_with("interceptor_via_fun:") {
                let pattern = &trimmed[21..];
                let mut rule = X86ASanSuppressionRule::new(pattern, current_type);
                rule.source_line = line_num;
                self.rules.push(rule);
            }
        }
    }

    /// Check if a report should be suppressed.
    pub fn should_suppress(&mut self, report: &X86ASanErrorReport) -> bool {
        if !self.enabled || self.rules.is_empty() {
            return false;
        }

        for rule in &self.rules {
            if rule.matches(report) {
                self.suppressed_count += 1;
                return true;
            }
        }
        false
    }
}

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

// ============================================================================
// X86ASanAllocator — custom allocator with quarantine and redzone padding
// ============================================================================

/// Metadata stored alongside each ASan allocation.
#[derive(Debug, Clone)]
pub struct X86ASanAllocMeta {
    /// Unique allocation ID.
    pub id: u64,
    /// User pointer (after redzones).
    pub user_ptr: u64,
    /// Total allocation size (including redzones + metadata).
    pub total_size: u64,
    /// User-requested size.
    pub requested_size: u64,
    /// Whether the allocation has been freed.
    pub is_freed: bool,
    /// Stack trace at allocation time.
    pub alloc_stack: Vec<X86ASanStackFrameEntry>,
    /// Stack trace at free time.
    pub free_stack: Option<Vec<X86ASanStackFrameEntry>>,
    /// Thread ID that performed the allocation.
    pub alloc_thread_id: u64,
    /// Thread ID that performed the free.
    pub free_thread_id: Option<u64>,
    /// Whether this is a container allocation.
    pub is_container: bool,
    /// The allocation kind for mismatch detection.
    pub alloc_kind: X86ASanAllocKind,
}

/// Allocation kind for detecting malloc/free mismatches.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86ASanAllocKind {
    Malloc,
    Calloc,
    Realloc,
    Memalign,
    AlignedAlloc,
    PosixMemalign,
    Reallocarray,
    Valloc,
    Pvalloc,
    Custom,
}

impl X86ASanAllocKind {
    pub fn as_str(&self) -> &'static str {
        match self {
            X86ASanAllocKind::Malloc => "malloc",
            X86ASanAllocKind::Calloc => "calloc",
            X86ASanAllocKind::Realloc => "realloc",
            X86ASanAllocKind::Memalign => "memalign",
            X86ASanAllocKind::AlignedAlloc => "aligned_alloc",
            X86ASanAllocKind::PosixMemalign => "posix_memalign",
            X86ASanAllocKind::Reallocarray => "reallocarray",
            X86ASanAllocKind::Valloc => "valloc",
            X86ASanAllocKind::Pvalloc => "pvalloc",
            X86ASanAllocKind::Custom => "custom",
        }
    }
}

/// The ASan custom allocator.
///
/// This allocator wraps every allocation with redzones and metadata,
/// and maintains a quarantine for use-after-free detection.
#[derive(Debug)]
pub struct X86ASanAllocator {
    /// All active (non-freed) allocations.
    pub allocations: HashMap<u64, X86ASanAllocMeta>,
    /// Global quarantine: freed blocks held for UAF detection.
    pub quarantine: VecDeque<X86ASanAllocMeta>,
    /// Maximum quarantine size in bytes.
    pub quarantine_max_size: u64,
    /// Total bytes ever allocated (cumulative).
    pub total_allocated: u64,
    /// Total bytes ever freed (cumulative).
    pub total_freed: u64,
    /// Current bytes allocated.
    pub current_bytes: u64,
    /// Current peak bytes.
    pub peak_bytes: u64,
    /// Number of active allocations.
    pub allocation_count: u64,
    /// Monotonically increasing allocation ID.
    next_alloc_id: AtomicU64,
    /// Shadow memory reference for poisoning.
    shadow: Option<*mut X86ASanShadowMap>,
    /// Stack trace collector for recording allocation stacks.
    stack_collector: Option<*mut X86ASanStackTraceCollector>,
    /// Secondary allocator for large allocations.
    secondary_alloc_big_threshold: u64,
}

/// Thread-local quarantine batch.
#[derive(Debug)]
pub struct X86ASanThreadQuarantineBatch {
    /// Blocks in this batch.
    blocks: Vec<(u64, u64, X86ASanAllocMeta)>,
    /// Total size of blocks in this batch.
    total_size: u64,
    /// Maximum batch size.
    max_size: u64,
}

impl X86ASanThreadQuarantineBatch {
    pub fn new(max_size: u64) -> Self {
        Self {
            blocks: Vec::new(),
            total_size: 0,
            max_size,
        }
    }

    pub fn add(&mut self, addr: u64, size: u64, meta: X86ASanAllocMeta) {
        self.total_size += size;
        self.blocks.push((addr, size, meta));
    }

    pub fn flush(&mut self) -> Vec<(u64, u64, X86ASanAllocMeta)> {
        self.total_size = 0;
        std::mem::take(&mut self.blocks)
    }

    pub fn is_full(&self) -> bool {
        self.total_size >= self.max_size
    }
}

impl X86ASanAllocator {
    /// Create a new ASan allocator.
    pub fn new() -> Self {
        Self {
            allocations: HashMap::new(),
            quarantine: VecDeque::new(),
            quarantine_max_size: X86_ASAN_QUARANTINE_MAX_SIZE,
            total_allocated: 0,
            total_freed: 0,
            current_bytes: 0,
            peak_bytes: 0,
            allocation_count: 0,
            next_alloc_id: AtomicU64::new(1),
            shadow: None,
            stack_collector: None,
            secondary_alloc_big_threshold: 1024 * 1024, // 1 MB
        }
    }

    /// Attach a shadow memory reference for poisoning/unpoisoning.
    pub fn attach_shadow(&mut self, shadow: &mut X86ASanShadowMap) {
        self.shadow = Some(shadow as *mut X86ASanShadowMap);
    }

    /// Attach a stack trace collector.
    pub fn attach_stack_collector(
        &mut self,
        collector: &mut X86ASanStackTraceCollector,
    ) {
        self.stack_collector = Some(collector as *mut X86ASanStackTraceCollector);
    }

    /// Allocate memory with redzone padding (simulated).
    pub fn alloc(
        &mut self,
        size: u64,
        alignment: u64,
        kind: X86ASanAllocKind,
    ) -> (u64, u64) {
        let total = self.compute_allocation_size(size, alignment);
        let id = self.next_alloc_id.fetch_add(1, Ordering::Relaxed);

        // Simulate memory allocation — in production this would mmap
        let user_ptr = id * 0x10000 + 0x6000_0000_0000; // fake address

        let meta = X86ASanAllocMeta {
            id,
            user_ptr,
            total_size: total,
            requested_size: size,
            is_freed: false,
            alloc_stack: Vec::new(), // would capture stack trace
            free_stack: None,
            alloc_thread_id: 0,
            free_thread_id: None,
            is_container: false,
            alloc_kind: kind,
        };

        // Poison the redzones
        if let Some(shadow_ptr) = self.shadow {
            unsafe {
                let shadow = &mut *shadow_ptr;
                let left_rz = X86_ASAN_HEAP_REDZONE_SIZE;
                let right_rz = total - left_rz - size;

                // Left redzone
                shadow.poison_range(user_ptr - left_rz, left_rz, HEAP_LEFT_REDZONE);
                // Right redzone
                shadow.poison_range(
                    user_ptr + size,
                    right_rz,
                    HEAP_RIGHT_REDZONE,
                );
                // The user portion: unpoison
                shadow.unpoison_range(user_ptr, size);
            }
        }

        self.allocations.insert(user_ptr, meta);
        self.total_allocated += size;
        self.current_bytes += size;
        self.allocation_count += 1;
        if self.current_bytes > self.peak_bytes {
            self.peak_bytes = self.current_bytes;
        }

        (user_ptr, size)
    }

    /// Free a previously allocated block.
    pub fn free(
        &mut self,
        ptr: u64,
        expected_kind: Option<X86ASanAllocKind>,
    ) -> Result<(), X86ASanErrorType> {
        if let Some(mut meta) = self.allocations.remove(&ptr) {
            if meta.is_freed {
                return Err(X86ASanErrorType::DoubleFree);
            }

            // Check alloc/dealloc mismatch
            if let Some(expected) = expected_kind {
                if meta.alloc_kind != expected {
                    return Err(X86ASanErrorType::AllocDeallocMismatch);
                }
            }

            meta.is_freed = true;
            meta.free_thread_id = Some(0); // current thread

            // Poison the freed memory
            if let Some(shadow_ptr) = self.shadow {
                unsafe {
                    let shadow = &mut *shadow_ptr;
                    shadow.poison_range(ptr, meta.requested_size, FREED);
                }
            }

            self.total_freed += meta.requested_size;
            self.current_bytes -= meta.requested_size;
            self.allocation_count -= 1;

            // Add to quarantine
            self.quarantine.push_back(meta);

            // Drain quarantine if over limit
            self.drain_quarantine();

            Ok(())
        } else {
            Err(X86ASanErrorType::InvalidFree)
        }
    }

    /// Reallocate a block.
    pub fn realloc(
        &mut self,
        old_ptr: u64,
        new_size: u64,
        alignment: u64,
    ) -> Result<(u64, u64), X86ASanErrorType> {
        if old_ptr == 0 {
            return Ok(self.alloc(new_size, alignment, X86ASanAllocKind::Realloc));
        }

        if new_size == 0 {
            self.free(old_ptr, None)?;
            return Ok((0, 0));
        }

        // Get old metadata
        if let Some(old_meta) = self.allocations.get(&old_ptr) {
            let old_requested = old_meta.requested_size;
            let old_is_freed = old_meta.is_freed;

            if old_is_freed {
                return Err(X86ASanErrorType::HeapUseAfterFree);
            }

            // Allocate new block
            let (new_ptr, actual_new_size) =
                self.alloc(new_size, alignment, X86ASanAllocKind::Realloc);

            // Copy old data (simulated; in production, memcpy with shadow
            // checks temporarily disabled)
            let copy_size = old_requested.min(new_size);

            // Free old block
            self.free(old_ptr, None)?;

            Ok((new_ptr, actual_new_size))
        } else {
            Err(X86ASanErrorType::InvalidFree)
        }
    }

    /// Reallocarray (calloc + realloc).
    pub fn reallocarray(
        &mut self,
        old_ptr: u64,
        nmemb: u64,
        size: u64,
        alignment: u64,
    ) -> Result<(u64, u64), X86ASanErrorType> {
        // Check for overflow in nmemb * size
        let total = nmemb.checked_mul(size).ok_or(X86ASanErrorType::CallocOverflow)?;
        self.realloc(old_ptr, total, alignment)
    }

    /// Calloc: allocate and zero memory.
    pub fn calloc(
        &mut self,
        nmemb: u64,
        size: u64,
        alignment: u64,
    ) -> Result<(u64, u64), X86ASanErrorType> {
        let total = nmemb.checked_mul(size).ok_or(X86ASanErrorType::CallocOverflow)?;
        let (ptr, actual) = self.alloc(total, alignment, X86ASanAllocKind::Calloc);
        // Zero the memory (simulated)
        if let Some(shadow_ptr) = self.shadow {
            unsafe {
                let shadow = &mut *shadow_ptr;
                shadow.unpoison_range(ptr, total);
            }
        }
        Ok((ptr, actual))
    }

    /// Aligned allocation with a specific alignment.
    pub fn memalign(
        &mut self,
        alignment: u64,
        size: u64,
    ) -> (u64, u64) {
        // memalign requires alignment >= sizeof(void*)
        let actual_align = alignment.max(16);
        self.alloc(size, actual_align, X86ASanAllocKind::Memalign)
    }

    /// aligned_alloc (C11): size must be multiple of alignment.
    pub fn aligned_alloc(
        &mut self,
        alignment: u64,
        size: u64,
    ) -> Result<(u64, u64), &'static str> {
        if size % alignment != 0 {
            return Err("size not multiple of alignment");
        }
        if alignment < std::mem::size_of::<*const u8>() as u64 {
            return Err("alignment too small");
        }
        Ok(self.alloc(size, alignment, X86ASanAllocKind::AlignedAlloc))
    }

    /// posix_memalign.
    pub fn posix_memalign(
        &mut self,
        alignment: u64,
        size: u64,
    ) -> (u64, u64) {
        self.alloc(size, alignment, X86ASanAllocKind::PosixMemalign)
    }

    /// Compute the total allocation size including redzones.
    fn compute_allocation_size(&self, size: u64, alignment: u64) -> u64 {
        let rz = X86_ASAN_HEAP_REDZONE_SIZE.max(alignment);
        let total = rz + size + rz;

        // Align to 16 bytes (2 shadow granules)
        total.next_multiple_of(16)
    }

    /// Drain old entries from the quarantine.
    fn drain_quarantine(&mut self) {
        while self.quarantine_size() > self.quarantine_max_size {
            if let Some(meta) = self.quarantine.pop_front() {
                // Recycle the memory (make available for reuse)
                // In production: munmap or return to allocator
                if let Some(shadow_ptr) = self.shadow {
                    unsafe {
                        let shadow = &mut *shadow_ptr;
                        // Unpoison now that it's been recycled
                        shadow.unpoison_range(
                            meta.user_ptr,
                            meta.requested_size,
                        );
                    }
                }
            } else {
                break;
            }
        }
    }

    /// Current total quarantine size in bytes.
    fn quarantine_size(&self) -> u64 {
        self.quarantine
            .iter()
            .map(|m| m.total_size)
            .sum()
    }

    /// Check if a pointer is to a quarantined (freed) block.
    pub fn is_quarantined(&self, ptr: u64) -> Option<&X86ASanAllocMeta> {
        self.quarantine.iter().find(|m| {
            ptr >= m.user_ptr && ptr < m.user_ptr + m.requested_size
        })
    }

    /// Report active leaks.
    pub fn detect_leaks(&self) -> Vec<&X86ASanAllocMeta> {
        self.allocations
            .values()
            .filter(|m| !m.is_freed)
            .collect()
    }

    /// Get statistics about the allocator.
    pub fn stats(&self) -> X86ASanAllocStats {
        X86ASanAllocStats {
            total_allocated: self.total_allocated,
            total_freed: self.total_freed,
            current_bytes: self.current_bytes,
            peak_bytes: self.peak_bytes,
            allocation_count: self.allocation_count,
            quarantine_size: self.quarantine_size(),
            quarantine_entries: self.quarantine.len() as u64,
            large_allocs_secondary: 0,
        }
    }
}

/// Allocator statistics.
#[derive(Debug, Clone)]
pub struct X86ASanAllocStats {
    pub total_allocated: u64,
    pub total_freed: u64,
    pub current_bytes: u64,
    pub peak_bytes: u64,
    pub allocation_count: u64,
    pub quarantine_size: u64,
    pub quarantine_entries: u64,
    pub large_allocs_secondary: u64,
}

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

// ============================================================================
// X86ASanFull — Complete ASan runtime for X86
// ============================================================================

/// The complete AddressSanitizer runtime for X86 targets.
///
/// Orchestrates shadow memory, stack/global/heap instrumentation,
/// error reporting, and the custom allocator.
#[derive(Debug)]
pub struct X86ASanFull {
    /// Shadow memory mapping.
    pub shadow: X86ASanShadowMap,
    /// The custom allocator with quarantine.
    pub allocator: X86ASanAllocator,
    /// Stack trace collector and symbolizer.
    pub stack_trace: X86ASanStackTraceCollector,
    /// Error suppression rules.
    pub suppression: X86ASanErrorSuppression,
    /// Fake stack for use-after-return detection.
    pub fake_stack: X86ASanFakeStack,
    /// Scope tracker for use-after-scope detection.
    pub scope_tracker: X86ASanScopeTracker,
    /// Global variable instrumentation.
    pub global_instr: X86ASanGlobalInstrumentation,
    /// Container overflow detector.
    pub container_overflow: X86ASanContainerOverflowDetector,
    /// Stack frame currently being set up.
    pub current_frame: Option<X86ASanStackFrame>,
    /// All collected error reports.
    pub error_reports: Vec<X86ASanErrorReport>,
    /// Number of errors suppressed.
    pub errors_suppressed: u64,
    /// Runtime flags.
    pub flags: X86ASanRuntimeFlags,
    /// Whether the runtime is activated.
    pub activated: bool,
    /// Whether to halt on the first error.
    pub halt_on_error: bool,
    /// Deduplication cache (hash -> timestamp).
    dedup_cache: HashMap<u64, u64>,
    /// TLS state for the main thread.
    tls: X86ASanTLS,
    /// Total reports generated.
    total_reports: u64,
}

/// Runtime configurable flags.
#[derive(Debug, Clone)]
pub struct X86ASanRuntimeFlags {
    /// Whether to detect stack buffer overflow.
    pub detect_stack_overflow: bool,
    /// Whether to detect use-after-free.
    pub detect_use_after_free: bool,
    /// Whether to detect use-after-return.
    pub detect_use_after_return: bool,
    /// Whether to detect use-after-scope.
    pub detect_use_after_scope: bool,
    /// Whether to detect container overflow.
    pub detect_container_overflow: bool,
    /// Whether to detect ODR violations.
    pub detect_odr_violation: bool,
    /// Whether to detect leaks at exit.
    pub detect_leaks: bool,
    /// Whether to detect initialization order bugs.
    pub detect_init_order: bool,
    /// Whether to poison stack memory.
    pub poison_stack: bool,
    /// Whether to poison heap memory.
    pub poison_heap: bool,
    /// Whether to poison global memory.
    pub poison_globals: bool,
    /// Maximum redzone size for stack variables.
    pub max_redzone_size: u64,
    /// Whether to print verbose error messages.
    pub verbose: bool,
    /// Whether to print command-line arguments.
    pub print_cmdline: bool,
    /// Maximum stack trace depth.
    pub stack_trace_depth: usize,
    /// Whether to check printf format strings.
    pub check_printf: bool,
    /// Whether to check memset/memcpy parameter overlaps.
    pub check_memcpy_overlap: bool,
    /// Whether malloc_context_size is non-zero.
    pub store_malloc_context: bool,
    /// Maximum quarantine size in MB.
    pub quarantine_size_mb: u64,
    /// Whether to use the fake stack.
    pub use_fake_stack: bool,
    /// Whether to enable coverage instrumentation.
    pub coverage: bool,
    /// Whether to use the fast unwinder.
    pub fast_unwind: bool,
    /// Whether to replace the default allocator.
    pub replace_allocator: bool,
    /// Allocator may return null (rather than abort on OOM).
    pub allocator_may_return_null: bool,
    /// Sleep between error reports (in seconds).
    pub sleep_before_dying: u64,
}

impl Default for X86ASanRuntimeFlags {
    fn default() -> Self {
        Self {
            detect_stack_overflow: true,
            detect_use_after_free: true,
            detect_use_after_return: true,
            detect_use_after_scope: true,
            detect_container_overflow: true,
            detect_odr_violation: true,
            detect_leaks: true,
            detect_init_order: false,
            poison_stack: true,
            poison_heap: true,
            poison_globals: true,
            max_redzone_size: X86_ASAN_MAX_STACK_REDZONE_SIZE,
            verbose: false,
            print_cmdline: false,
            stack_trace_depth: X86_ASAN_MAX_STACK_DEPTH,
            check_printf: true,
            check_memcpy_overlap: true,
            store_malloc_context: true,
            quarantine_size_mb: 256,
            use_fake_stack: true,
            coverage: false,
            fast_unwind: true,
            replace_allocator: true,
            allocator_may_return_null: false,
            sleep_before_dying: 0,
        }
    }
}

impl X86ASanFull {
    /// Create a new, uninitialized ASan runtime for x86-64.
    pub fn new() -> Self {
        let mut shadow = X86ASanShadowMap::x86_64();
        shadow.allocate_shadow(0x7f_ffff_ffff);

        let mut trace = X86ASanStackTraceCollector::new();
        trace.fast_unwind = true;

        Self {
            shadow,
            allocator: X86ASanAllocator::new(),
            stack_trace: trace,
            suppression: X86ASanErrorSuppression::new(),
            fake_stack: X86ASanFakeStack::default_sized(),
            scope_tracker: X86ASanScopeTracker::new(),
            global_instr: X86ASanGlobalInstrumentation::new(),
            container_overflow: X86ASanContainerOverflowDetector::new(),
            current_frame: None,
            error_reports: Vec::new(),
            errors_suppressed: 0,
            flags: X86ASanRuntimeFlags::default(),
            activated: false,
            halt_on_error: false,
            dedup_cache: HashMap::new(),
            tls: X86ASanTLS::new(),
            total_reports: 0,
        }
    }

    /// Create for i386 (32-bit).
    pub fn new_i386() -> Self {
        let mut shadow = X86ASanShadowMap::i386();
        shadow.allocate_shadow(0xFFFF_FFFF);

        Self {
            shadow,
            ..Self::new()
        }
    }

    /// Activate the ASan runtime.
    pub fn activate(&mut self) {
        self.activated = true;
        self.allocator.attach_shadow(&mut self.shadow);
        self.allocator
            .attach_stack_collector(&mut self.stack_trace);
    }

    /// Deactivate the ASan runtime.
    pub fn deactivate(&mut self) {
        self.activated = false;
    }

    /// Check a memory access against shadow memory.
    /// Called by instrumented code before each load/store.
    pub fn check_memory_access(
        &mut self,
        addr: u64,
        size: u64,
        is_write: bool,
    ) -> Result<(), X86ASanErrorReport> {
        if !self.activated {
            return Ok(());
        }

        // Check shadow
        match self.shadow.check_access(addr, size, is_write) {
            Ok(()) => Ok(()),
            Err(desc) => {
                let sv = self.shadow.get_shadow(addr);
                let error_type = self.classify_error(sv);
                let access_type = if is_write {
                    X86ASanAccessType::Write
                } else {
                    X86ASanAccessType::Read
                };

                let mut report = X86ASanErrorReport::new(
                    error_type,
                    addr,
                    size,
                    access_type,
                    sv,
                );

                // Capture stack trace
                report.stack_trace = self.stack_trace.capture_stack_trace(
                    addr, // simulated IP
                    0,    // simulated BP
                    0,    // simulated SP
                );

                // Check UAF
                if sv == FREED || sv == QUARANTINE {
                    if let Some(meta) = self.allocator.is_quarantined(addr) {
                        report.allocation_trace =
                            Some(meta.alloc_stack.clone());
                        report.deallocation_trace = meta.free_stack.clone();
                    }
                }

                // Check UAR
                if sv == STACK_UAR_REDZONE {
                    if let Some(entry) =
                        self.fake_stack.check_use_after_return(addr)
                    {
                        report.description = Some(format!(
                            "Address points to a stack frame of function '{}' \
                         which has returned",
                            entry.function_name,
                        ));
                    }
                }

                // Check use-after-scope
                if sv == STACK_USE_AFTER_SCOPE {
                    report.description = Some(
                        "Address points to a stack variable that has \
                     gone out of lexical scope"
                            .to_string(),
                    );
                }

                Err(report)
            }
        }
    }

    /// Fast check for 8-byte aligned loads.
    pub fn check_load_8(&mut self, addr: u64) -> Result<(), X86ASanErrorReport> {
        self.check_memory_access(addr, 8, false)
    }

    /// Fast check for 8-byte aligned stores.
    pub fn check_store_8(&mut self, addr: u64) -> Result<(), X86ASanErrorReport> {
        self.check_memory_access(addr, 8, true)
    }

    /// Check a 16-byte load (SSE/AVX).
    pub fn check_load_16(&mut self, addr: u64) -> Result<(), X86ASanErrorReport> {
        self.check_memory_access(addr, 16, false)
    }

    /// Check a 16-byte store (SSE/AVX).
    pub fn check_store_16(&mut self, addr: u64) -> Result<(), X86ASanErrorReport> {
        self.check_memory_access(addr, 16, true)
    }

    /// Check a 32-byte load (AVX).
    pub fn check_load_32(&mut self, addr: u64) -> Result<(), X86ASanErrorReport> {
        self.check_memory_access(addr, 32, false)
    }

    /// Check a 32-byte store (AVX).
    pub fn check_store_32(&mut self, addr: u64) -> Result<(), X86ASanErrorReport> {
        self.check_memory_access(addr, 32, true)
    }

    /// Check an N-byte access with explicit access type.
    pub fn check_access_n(
        &mut self,
        addr: u64,
        n: u64,
        access_type: X86ASanAccessType,
    ) -> Result<(), X86ASanErrorReport> {
        match access_type {
            X86ASanAccessType::Read | X86ASanAccessType::Alloc => {
                self.check_memory_access(addr, n, false)
            }
            X86ASanAccessType::Write => self.check_memory_access(addr, n, true),
            X86ASanAccessType::Free => {
                let sv = self.shadow.get_shadow(addr);
                if sv == FREED {
                    return Err(X86ASanErrorReport::new(
                        X86ASanErrorType::DoubleFree,
                        addr,
                        n,
                        X86ASanAccessType::Free,
                        sv,
                    ));
                }
                Ok(())
            }
        }
    }

    /// Classify the shadow value into an error type.
    fn classify_error(&self, shadow_value: i8) -> X86ASanErrorType {
        match shadow_value {
            HEAP_LEFT_REDZONE | HEAP_RIGHT_REDZONE => {
                X86ASanErrorType::HeapBufferOverflow
            }
            STACK_LEFT_REDZONE
            | STACK_MID_REDZONE
            | STACK_RIGHT_REDZONE => {
                X86ASanErrorType::StackBufferOverflow
            }
            STACK_UAR_REDZONE => X86ASanErrorType::StackUseAfterReturn,
            GLOBAL_REDZONE => X86ASanErrorType::GlobalBufferOverflow,
            INTRA_OBJECT_REDZONE => X86ASanErrorType::ContainerOverflow,
            FREED | QUARANTINE => X86ASanErrorType::HeapUseAfterFree,
            STACK_USE_AFTER_SCOPE => X86ASanErrorType::StackUseAfterScope,
            ODR_VIOLATION => X86ASanErrorType::ODRViolation,
            USER_POISON => X86ASanErrorType::UseAfterPoison,
            SHADOW_GAP | HIGH_SHADOW_GAP => X86ASanErrorType::ShadowGapAccess,
            INVALID => X86ASanErrorType::WildPointerAccess,
            _ => X86ASanErrorType::WildPointerAccess,
        }
    }

    /// Report an error through the full reporting pipeline.
    pub fn report_error(
        &mut self,
        report: X86ASanErrorReport,
    ) {
        // Suppression check
        if self.suppression.should_suppress(&report) {
            self.errors_suppressed += 1;
            return;
        }

        // Deduplication
        let hash = X86ASanStackTraceCollector::hash_stack_trace(
            &report.stack_trace,
        );
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        if let Some(&last_time) = self.dedup_cache.get(&hash) {
            if now - last_time < X86_ASAN_REPORT_DEDUP_WINDOW {
                // Duplicate within window; skip
                return;
            }
        }
        self.dedup_cache.insert(hash, now);

        // Rate limiting
        if self.total_reports >= X86_ASAN_MAX_REPORTS {
            if self.total_reports == X86_ASAN_MAX_REPORTS {
                eprintln!(
                    "==ASAN: Too many errors reported ({}). \
                 Further reports will be suppressed.",
                    X86_ASAN_MAX_REPORTS
                );
            }
            self.total_reports += 1;
            return;
        }

        self.total_reports += 1;
        self.error_reports.push(report.clone());

        // Print the report
        if self.flags.verbose {
            eprintln!("{}", report.format_report());
        }

        // Halt on error if configured
        if self.halt_on_error {
            eprintln!("==ASAN: HALTING ON ERROR ==");
            std::process::abort();
        }
    }

    /// Begin instrumenting a stack frame.
    pub fn begin_stack_frame(&mut self) {
        self.current_frame = Some(X86ASanStackFrame::new());
    }

    /// Add a stack variable to the current frame.
    pub fn add_stack_variable(
        &mut self,
        name: &str,
        size: u64,
        alignment: u64,
    ) {
        if let Some(ref mut frame) = self.current_frame {
            let var = X86ASanStackVar::new(name, 0, size, alignment)
                .with_use_after_scope(self.flags.detect_use_after_scope);
            frame.add_variable(var);
        }
    }

    /// Finish instrumenting a stack frame and apply shadow operations.
    pub fn finish_stack_frame(
        &mut self,
        frame_base: u64,
    ) -> Option<X86ASanStackFrame> {
        if let Some(frame) = self.current_frame.take() {
            frame.apply_shadow(&mut self.shadow, frame_base);
            Some(frame)
        } else {
            None
        }
    }

    /// Push the current stack frame onto the fake stack (for UAR detection).
    pub fn push_fake_stack(
        &mut self,
        function_name: &str,
        frame_base: u64,
    ) -> Option<u64> {
        if let Some(ref frame) = self.current_frame {
            let fake_base = self.fake_stack.push(function_name, frame_base, frame);
            Some(fake_base)
        } else {
            None
        }
    }

    /// Pop a frame from the fake stack (function returns).
    pub fn pop_fake_stack(&mut self, function_name: &str) {
        self.fake_stack.pop(&mut self.shadow, function_name);
    }

    /// Register a global variable for instrumentation.
    pub fn register_global(
        &mut self,
        name: &str,
        addr: u64,
        size: u64,
        alignment: u64,
    ) {
        let global = X86ASanGlobalProtection::new(name, size, alignment);
        self.global_instr.add_global(global, addr);
    }

    /// Apply all global variable instrumentations.
    pub fn apply_global_instrumentation(
        &mut self,
        base_addrs: &[(u64, &str)],
    ) {
        self.global_instr
            .apply_to_shadow(&mut self.shadow, base_addrs);
    }

    /// Instrument a container allocation.
    pub fn instrument_container(
        &mut self,
        addr: u64,
        object_size: u64,
        name: &str,
    ) {
        self.container_overflow
            .instrument_container(&mut self.shadow, addr, object_size, name);
    }

    /// Enter a function scope (for use-after-scope tracking).
    pub fn enter_function(&mut self, name: &str) {
        self.scope_tracker.enter_function(name);
    }

    /// Leave a function scope.
    pub fn leave_function(&mut self) {
        self.scope_tracker.leave_function();
    }

    /// Enter a lexical scope.
    pub fn enter_scope(&mut self) {
        self.scope_tracker.enter_scope();
    }

    /// Exit a lexical scope and poison out-of-scope variables.
    pub fn exit_scope(&mut self, frame_base: u64) {
        let poisoned = self.scope_tracker.exit_scope();
        if let Some(ref frame) = self.current_frame {
            for var_name in &poisoned {
                if let Some(var) =
                    frame.variables.iter().find(|v| &v.name == var_name)
                {
                    let addr =
                        (frame_base as i64 + var.frame_offset) as u64;
                    self.shadow
                        .poison_range(addr, var.size, STACK_USE_AFTER_SCOPE);
                }
            }
        }
    }

    /// Register a stack variable for scope tracking.
    pub fn register_stack_var(&mut self, name: &str) {
        self.scope_tracker.register_var(name);
    }

    /// Perform a leak check at process exit.
    pub fn leak_check(&self) -> Vec<X86ASanErrorReport> {
        if !self.flags.detect_leaks {
            return Vec::new();
        }

        let leaks = self.allocator.detect_leaks();
        let mut reports = Vec::new();

        for meta in leaks {
            let report = X86ASanErrorReport::new(
                X86ASanErrorType::MemoryLeak,
                meta.user_ptr,
                meta.requested_size,
                X86ASanAccessType::Alloc,
                ADDRESSABLE,
            );
            reports.push(report);
        }

        reports
    }

    /// Print leak summary.
    pub fn print_leak_summary(&self) {
        let leaks = self.allocator.detect_leaks();
        if leaks.is_empty() {
            println!("==ASAN: No memory leaks detected.");
            return;
        }

        println!(
            "==ASAN: {} memory leak(s) detected:",
            leaks.len()
        );
        for meta in leaks {
            println!(
                "  - {} bytes at 0x{:016x} (allocated as {})",
                meta.requested_size,
                meta.user_ptr,
                meta.alloc_kind.as_str(),
            );
        }
    }

    /// Collect runtime statistics.
    pub fn stats(&self) -> X86ASanFullStats {
        X86ASanFullStats {
            shadow_allocated: self.shadow.shadow_allocated,
            total_allocations: self.allocator.total_allocated,
            current_bytes: self.allocator.current_bytes,
            peak_bytes: self.allocator.peak_bytes,
            quarantine_size: self.allocator.quarantine_size(),
            fake_stack_entries: self.fake_stack.active_count(),
            global_count: self.global_instr.count(),
            container_count: self.container_overflow.tracked_count(),
            error_reports: self.error_reports.len() as u64,
            errors_suppressed: self.errors_suppressed,
            total_reports: self.total_reports,
            activated: self.activated,
        }
    }

    /// Reset all state (useful for testing).
    pub fn reset(&mut self) {
        self.shadow.reset();
        self.allocator = X86ASanAllocator::new();
        self.allocator.attach_shadow(&mut self.shadow);
        self.allocator
            .attach_stack_collector(&mut self.stack_trace);
        self.fake_stack = X86ASanFakeStack::default_sized();
        self.scope_tracker = X86ASanScopeTracker::new();
        self.current_frame = None;
        self.error_reports.clear();
        self.errors_suppressed = 0;
        self.total_reports = 0;
        self.dedup_cache.clear();
    }

    /// Load suppressions from a file.
    pub fn load_suppressions(&mut self, path: &str) -> std::io::Result<usize> {
        self.suppression.load_from_file(path)
    }

    /// Poison a memory range (user-requested).
    pub fn poison_memory_region(&mut self, addr: u64, size: u64) {
        self.shadow.poison_range(addr, size, USER_POISON);
    }

    /// Unpoison a memory range (user-requested).
    pub fn unpoison_memory_region(&mut self, addr: u64, size: u64) {
        self.shadow.unpoison_range(addr, size);
    }

    /// Check if an address is poisoned.
    pub fn is_poisoned(&self, addr: u64) -> bool {
        is_poisoned(self.shadow.get_shadow(addr))
    }
}

/// Full ASan runtime statistics.
#[derive(Debug, Clone)]
pub struct X86ASanFullStats {
    pub shadow_allocated: bool,
    pub total_allocations: u64,
    pub current_bytes: u64,
    pub peak_bytes: u64,
    pub quarantine_size: u64,
    pub fake_stack_entries: usize,
    pub global_count: usize,
    pub container_count: usize,
    pub error_reports: u64,
    pub errors_suppressed: u64,
    pub total_reports: u64,
    pub activated: bool,
}

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

// ============================================================================
// X86HWASanRuntime — Hardware-assisted AddressSanitizer for X86
// ============================================================================

/// Hardware-assisted AddressSanitizer (HWASan) for X86.
///
/// On AArch64, HWASan uses Top-Byte-Ignore (TBI) for tag-based memory
/// access checks. On X86, since TBI is not available, we emulate it
/// using explicit tag manipulation in software.
///
/// Each 16-byte granule of memory gets an 8-bit tag. Pointers carry
/// a matching tag in their top byte (or in a separate metadata field
/// for X86). Before each memory access, the pointer's tag is checked
/// against the memory's tag.
#[derive(Debug)]
pub struct X86HWASanRuntime {
    /// Whether HWASan is enabled.
    pub enabled: bool,
    /// Whether to tag stack variables.
    pub tag_stack: bool,
    /// Whether to tag heap allocations.
    pub tag_heap: bool,
    /// Whether to tag global variables.
    pub tag_globals: bool,
    /// Whether short granule tagging is enabled.
    pub use_short_granules: bool,
    /// Whether to use MTE (Memory Tagging Extension) if available.
    pub use_mte: bool,
    /// Whether to halt on tag mismatch.
    pub halt_on_error: bool,
    /// Whether to print stack traces.
    pub print_stacktrace: bool,
    /// Random seed for tag generation.
    pub random_seed: u64,
    /// Whether running in kernel mode.
    pub kernel_mode: bool,
    /// Tag generator.
    pub tag_generator: X86HWASanTagGenerator,
    /// Memory tag table: maps addresses to tags.
    pub memory_tags: X86HWASanMemoryTagTable,
    /// Stack tagging manager.
    pub stack_tags: X86HWASanStackTagging,
    /// Heap tagging manager.
    pub heap_tags: X86HWASanHeapTagging,
    /// Global tagging manager.
    pub global_tags: X86HWASanGlobalTagging,
    /// MTE support probing result.
    pub mte_available: bool,
    /// MTE sync mode.
    pub mte_sync: bool,
    /// Kernel HWASan stubs.
    pub kernel: X86HWASanKernel,
    /// Tag mismatch reports.
    pub mismatch_reports: Vec<X86HWASanTagMismatchReport>,
    /// Whether the runtime has been initialized.
    pub initialized: bool,
}

impl X86HWASanRuntime {
    /// Create a new HWASan runtime.
    pub fn new() -> Self {
        Self {
            enabled: false,
            tag_stack: true,
            tag_heap: true,
            tag_globals: true,
            use_short_granules: true,
            use_mte: false,
            halt_on_error: false,
            print_stacktrace: true,
            random_seed: 0,
            kernel_mode: false,
            tag_generator: X86HWASanTagGenerator::new(0),
            memory_tags: X86HWASanMemoryTagTable::new(),
            stack_tags: X86HWASanStackTagging::new(),
            heap_tags: X86HWASanHeapTagging::new(),
            global_tags: X86HWASanGlobalTagging::new(),
            mte_available: false,
            mte_sync: false,
            kernel: X86HWASanKernel::new(),
            mismatch_reports: Vec::new(),
            initialized: false,
        }
    }

    /// Initialize the HWASan runtime.
    pub fn init(&mut self, seed: u64) {
        self.tag_generator = X86HWASanTagGenerator::new(seed);
        self.mte_available = self.probe_mte();
        self.initialized = true;
    }

    /// Probe whether MTE (Memory Tagging Extension) is available.
    pub fn probe_mte(&self) -> bool {
        // On X86, MTE is never available natively.
        // This is a stub that can be overridden for testing.
        self.use_mte && cfg!(target_feature = "mte") // never true on X86
    }

    /// Generate a new random tag.
    pub fn generate_tag(&mut self) -> u8 {
        self.tag_generator.generate_tag()
    }

    /// Allocate a specific tag.
    pub fn allocate_tag(&mut self) -> u8 {
        self.tag_generator.allocate_tag()
    }

    /// Free a tag (return to pool).
    pub fn free_tag(&mut self, tag: u8) {
        self.tag_generator.free_tag(tag);
    }

    /// Tag a memory address with a given tag.
    pub fn tag_pointer(ptr: u64, tag: u8) -> u64 {
        X86HWASanTaggedPtr::create(ptr, tag).raw()
    }

    /// Extract the tag from a tagged pointer.
    pub fn extract_tag(ptr: u64) -> u8 {
        X86HWASanTaggedPtr::get_tag(ptr)
    }

    /// Strip the tag, returning the untagged address.
    pub fn strip_tag(ptr: u64) -> u64 {
        X86HWASanTaggedPtr::strip_tag(ptr)
    }

    /// Check a memory access against the tag.
    /// Returns Ok(()) if tags match, Err(report) on mismatch.
    pub fn check_memory_access(
        &mut self,
        ptr: u64,
        size: u64,
        is_write: bool,
    ) -> Result<(), X86HWASanTagMismatchReport> {
        if !self.enabled || !self.initialized {
            return Ok(());
        }

        let ptr_tag = X86HWASanTaggedPtr::get_tag(ptr);
        let untagged = X86HWASanTaggedPtr::strip_tag(ptr);

        // Check all granules touched by this access
        let start_granule = untagged / X86_HWASAN_GRANULE_SIZE;
        let end_granule = (untagged + size - 1) / X86_HWASAN_GRANULE_SIZE;

        for granule in start_granule..=end_granule {
            let granule_addr = granule * X86_HWASAN_GRANULE_SIZE;

            if let Some(mem_tag) = self.memory_tags.get_tag(granule_addr) {
                if mem_tag != ptr_tag {
                    let report = X86HWASanTagMismatchReport::new(
                        ptr,
                        granule_addr,
                        ptr_tag,
                        mem_tag,
                        size,
                        is_write,
                    );
                    return Err(report);
                }
            }
        }

        Ok(())
    }

    /// Check a tagged heap access.
    pub fn check_heap_access(
        &mut self,
        ptr: u64,
        size: u64,
        is_write: bool,
    ) -> Result<(), X86HWASanTagMismatchReport> {
        self.heap_tags.check_access(
            &self.memory_tags,
            ptr,
            size,
            is_write,
        )
    }

    /// Tag a heap allocation and return the tagged pointer.
    pub fn tag_heap_allocation(
        &mut self,
        ptr: u64,
        size: u64,
    ) -> u64 {
        self.heap_tags.tag_allocation(ptr, size)
    }

    /// Tag a stack variable and return the tagged pointer.
    pub fn tag_stack_variable(
        &mut self,
        ptr: u64,
        size: u64,
    ) -> u64 {
        self.stack_tags.tag_variable(ptr, size)
    }

    /// Tag a global variable.
    pub fn tag_global(&mut self, name: &str, ptr: u64, size: u64) -> u64 {
        self.global_tags.tag_global(name, ptr, size)
    }

    /// Handle a tag mismatch report.
    pub fn handle_mismatch(&mut self, report: X86HWASanTagMismatchReport) {
        self.mismatch_reports.push(report.clone());
        if self.print_stacktrace {
            eprintln!("{}", report.format());
        }
        if self.halt_on_error {
            std::process::abort();
        }
    }

    /// Compute the shadow address for a given application address.
    pub fn shadow_address(addr: u64) -> u64 {
        if addr >= 0xffff_0000_0000_0000 {
            // Kernel address
            (addr >> X86_HWASAN_KERNEL_SHADOW_SCALE) + X86_HWASAN_KERNEL_SHADOW_OFFSET
        } else {
            // User address
            (addr >> 4) + 0x8000_0000_0000
        }
    }

    /// Collect statistics.
    pub fn stats(&self) -> X86HWASanStats {
        X86HWASanStats {
            tags_generated: self.tag_generator.tags_issued,
            heap_allocs_tagged: self.heap_tags.tag_count,
            stack_vars_tagged: self.stack_tags.tag_count,
            globals_tagged: self.global_tags.tag_count,
            short_granules: self.memory_tags.short_granule_count,
            mismatches: self.mismatch_reports.len() as u64,
            initialized: self.initialized,
        }
    }
}

/// HWASan statistics.
#[derive(Debug, Clone)]
pub struct X86HWASanStats {
    pub tags_generated: u64,
    pub heap_allocs_tagged: u64,
    pub stack_vars_tagged: u64,
    pub globals_tagged: u64,
    pub short_granules: u64,
    pub mismatches: u64,
    pub initialized: bool,
}

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

// ============================================================================
// X86HWASanTagGenerator — random tag generation
// ============================================================================

/// Generates random 8-bit tags for memory tagging.
#[derive(Debug)]
pub struct X86HWASanTagGenerator {
    /// Seed for the pseudo-random number generator.
    pub seed: u64,
    /// LCG state.
    lcg_state: u64,
    /// Available tags (pool).
    tag_pool: VecDeque<u8>,
    /// Tags currently in use.
    used_tags: HashSet<u8>,
    /// Total tags ever issued.
    pub tags_issued: u64,
}

impl X86HWASanTagGenerator {
    /// Create a new tag generator with a given seed.
    pub fn new(seed: u64) -> Self {
        let actual_seed = if seed == 0 {
            // Use time-based seed if none provided
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos() as u64
        } else {
            seed
        };

        let mut gen = Self {
            seed: actual_seed,
            lcg_state: actual_seed,
            tag_pool: VecDeque::new(),
            used_tags: HashSet::new(),
            tags_issued: 0,
        };

        // Pre-populate tag pool with all valid tags (1-254)
        for t in 1..=X86_HWASAN_MAX_TAG {
            gen.tag_pool.push_back(t);
        }

        gen
    }

    /// Generate a random tag (pseudo-random).
    pub fn generate_tag(&mut self) -> u8 {
        self.tags_issued += 1;
        // LCG: state = (state * 6364136223846793005 + 1442695040888963407) mod 2^64
        self.lcg_state = self
            .lcg_state
            .wrapping_mul(6364136223846793005u64)
            .wrapping_add(1442695040888963407u64);

        let tag = (self.lcg_state % 254) as u8 + 1;
        tag.min(X86_HWASAN_MAX_TAG).max(1)
    }

    /// Allocate a tag from the pool.
    pub fn allocate_tag(&mut self) -> u8 {
        if let Some(tag) = self.tag_pool.pop_front() {
            self.used_tags.insert(tag);
            self.tags_issued += 1;
            tag
        } else {
            // Pool exhausted; fall back to random generation
            self.generate_tag()
        }
    }

    /// Return a tag to the pool.
    pub fn free_tag(&mut self, tag: u8) {
        if tag > 0 && tag <= X86_HWASAN_MAX_TAG {
            self.used_tags.remove(&tag);
            self.tag_pool.push_back(tag);
        }
    }

    /// Get the number of available tags in the pool.
    pub fn available_tags(&self) -> usize {
        self.tag_pool.len()
    }
}

// ============================================================================
// X86HWASanTaggedPtr — tagged pointer operations
// ============================================================================

/// Operations on HWASan-tagged pointers.
pub struct X86HWASanTaggedPtr;

impl X86HWASanTaggedPtr {
    /// Create a tagged pointer from an address and tag.
    #[inline]
    pub fn create(addr: u64, tag: u8) -> Self {
        let tagged = (addr & X86_HWASAN_ADDR_MASK)
            | ((tag as u64) << X86_HWASAN_TAG_SHIFT);
        // Return value through raw() call pattern — we use static methods
        std::mem::forget(tagged);
        Self
    }

    /// Get the tag from a raw tagged pointer value.
    #[inline]
    pub fn get_tag(ptr: u64) -> u8 {
        ((ptr >> X86_HWASAN_TAG_SHIFT) & X86_HWASAN_TAG_MASK) as u8
    }

    /// Strip the tag from a raw tagged pointer value.
    #[inline]
    pub fn strip_tag(ptr: u64) -> u64 {
        ptr & X86_HWASAN_ADDR_MASK
    }

    /// Check if a pointer has a non-zero tag.
    #[inline]
    pub fn is_tagged(ptr: u64) -> bool {
        Self::get_tag(ptr) != 0
    }

    /// Compare two tagged pointers' tags.
    #[inline]
    pub fn tags_match(a: u64, b: u64) -> bool {
        Self::get_tag(a) == Self::get_tag(b)
    }

    /// Return the raw tagged pointer value.
    pub fn raw(&self) -> u64 {
        // Placeholder — actual tagged value is computed in create
        0
    }

    /// Sign a pointer with a PAC-like signature (for kernel mode).
    pub fn sign_pointer(ptr: u64, modifier: u64) -> u64 {
        // Simple XOR-based "signature" (not cryptographically secure)
        ptr ^ modifier
    }
}

// ============================================================================
// X86HWASanMemoryTagTable — memory tag lookup
// ============================================================================

/// Stores and retrieves memory tags for each 16-byte granule.
#[derive(Debug)]
pub struct X86HWASanMemoryTagTable {
    /// Map from granule address to tag value.
    pub tags: HashMap<u64, u8>,
    /// Allocation trace IDs (for diagnostics).
    pub alloc_trace_ids: HashMap<u64, u64>,
    /// Free trace IDs.
    pub free_trace_ids: HashMap<u64, u64>,
    /// Short granule tags for sub-16-byte allocations.
    pub short_granules: HashMap<u64, u8>,
    /// Whether short granule support is enabled.
    pub use_short_granules: bool,
    /// Count of short granules.
    pub short_granule_count: u64,
}

impl X86HWASanMemoryTagTable {
    pub fn new() -> Self {
        Self {
            tags: HashMap::new(),
            alloc_trace_ids: HashMap::new(),
            free_trace_ids: HashMap::new(),
            short_granules: HashMap::new(),
            use_short_granules: true,
            short_granule_count: 0,
        }
    }

    /// Set the memory tag for a granule address.
    pub fn set_tag(&mut self, addr: u64, tag: u8) {
        let granule = addr & !(X86_HWASAN_GRANULE_SIZE - 1);
        self.tags.insert(granule, tag);
    }

    /// Set tags for a range of memory.
    pub fn set_tags_range(
        &mut self,
        addr: u64,
        size: u64,
        tag: u8,
    ) {
        let start = addr & !(X86_HWASAN_GRANULE_SIZE - 1);
        let end = (addr + size + X86_HWASAN_GRANULE_SIZE - 1)
            & !(X86_HWASAN_GRANULE_SIZE - 1);

        let mut granule = start;
        while granule < end {
            self.tags.insert(granule, tag);
            granule += X86_HWASAN_GRANULE_SIZE;
        }
    }

    /// Set short granule tags for a sub-16-byte allocation.
    pub fn set_short_granule_tags(
        &mut self,
        addr: u64,
        size: u64,
        tag: u8,
    ) {
        if !self.use_short_granules {
            return;
        }

        let granule = addr & !(X86_HWASAN_GRANULE_SIZE - 1);
        let offset = (addr & (X86_HWASAN_GRANULE_SIZE - 1)) as u8;

        // Encode: top nibble = size, bottom nibble = tag nibble
        let short_encoding =
            ((size.min(15) as u8) << 4) | (tag & 0x0F);

        self.short_granules.insert(granule, short_encoding);
        self.short_granule_count += 1;
    }

    /// Get the memory tag at a given address.
    pub fn get_tag(&self, addr: u64) -> Option<u8> {
        let granule = addr & !(X86_HWASAN_GRANULE_SIZE - 1);
        self.tags.get(&granule).copied()
    }

    /// Check if a short granule access is valid.
    pub fn check_short_granule(
        &self,
        addr: u64,
        size: u64,
    ) -> Option<bool> {
        if !self.use_short_granules {
            return None;
        }

        let granule = addr & !(X86_HWASAN_GRANULE_SIZE - 1);

        if let Some(&encoding) = self.short_granules.get(&granule) {
            let alloc_size = (encoding >> 4) as u64;
            let offset = addr & (X86_HWASAN_GRANULE_SIZE - 1);
            if offset + size <= alloc_size {
                return Some(true);
            } else {
                return Some(false); // overflow!
            }
        }

        None
    }

    /// Set the allocation trace ID for a granule.
    pub fn set_alloc_trace(&mut self, addr: u64, trace_id: u64) {
        let granule = addr & !(X86_HWASAN_GRANULE_SIZE - 1);
        self.alloc_trace_ids.insert(granule, trace_id);
    }

    /// Set the free trace ID for a granule.
    pub fn set_free_trace(&mut self, addr: u64, trace_id: u64) {
        let granule = addr & !(X86_HWASAN_GRANULE_SIZE - 1);
        self.free_trace_ids.insert(granule, trace_id);
    }

    /// Get the allocation trace ID.
    pub fn get_alloc_trace(&self, addr: u64) -> Option<u64> {
        let granule = addr & !(X86_HWASAN_GRANULE_SIZE - 1);
        self.alloc_trace_ids.get(&granule).copied()
    }

    /// Get the free trace ID.
    pub fn get_free_trace(&self, addr: u64) -> Option<u64> {
        let granule = addr & !(X86_HWASAN_GRANULE_SIZE - 1);
        self.free_trace_ids.get(&granule).copied()
    }

    /// Clear all tags for a range.
    pub fn clear_range(&mut self, addr: u64, size: u64) {
        let start = addr & !(X86_HWASAN_GRANULE_SIZE - 1);
        let end = (addr + size + X86_HWASAN_GRANULE_SIZE - 1)
            & !(X86_HWASAN_GRANULE_SIZE - 1);

        let mut granule = start;
        while granule < end {
            self.tags.remove(&granule);
            self.alloc_trace_ids.remove(&granule);
            self.free_trace_ids.remove(&granule);
            self.short_granules.remove(&granule);
            granule += X86_HWASAN_GRANULE_SIZE;
        }
    }
}

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

// ============================================================================
// X86HWASanStackTagging — stack variable tagging
// ============================================================================

/// Manages tagging of stack variables.
#[derive(Debug)]
pub struct X86HWASanStackTagging {
    /// Per-frame base tag.
    pub frame_base_tag: u8,
    /// Whether stack tagging is enabled.
    pub enabled: bool,
    /// Map from frame pointer to assigned tags.
    frame_tags: HashMap<u64, Vec<u8>>,
    /// Number of tagged variables.
    pub tag_count: u64,
}

impl X86HWASanStackTagging {
    pub fn new() -> Self {
        Self {
            frame_base_tag: 0,
            enabled: true,
            frame_tags: HashMap::new(),
            tag_count: 0,
        }
    }

    /// Generate a random base tag for a new stack frame.
    pub fn begin_frame(&mut self, tag_gen: &mut X86HWASanTagGenerator) -> u8 {
        self.frame_base_tag = tag_gen.generate_tag();
        self.frame_tags.clear();
        self.frame_base_tag
    }

    /// Tag a single stack variable and return the tagged pointer.
    pub fn tag_variable(&mut self, ptr: u64, size: u64) -> u64 {
        if !self.enabled {
            return ptr;
        }

        // Derive a per-variable tag from the frame base tag
        let var_tag = self.frame_base_tag.wrapping_add(self.tag_count as u8);
        let granule_tag = if var_tag == 0 { 1 } else { var_tag };

        self.tag_count += 1;

        X86HWASanTaggedPtr::create(ptr, granule_tag).raw()
    }

    /// Check a stack access.
    pub fn check_access(
        &self,
        tags: &X86HWASanMemoryTagTable,
        ptr: u64,
        size: u64,
        is_write: bool,
    ) -> Result<(), X86HWASanTagMismatchReport> {
        let ptr_tag = X86HWASanTaggedPtr::get_tag(ptr);
        let untagged = X86HWASanTaggedPtr::strip_tag(ptr);

        if let Some(mem_tag) = tags.get_tag(untagged) {
            if mem_tag != ptr_tag && mem_tag != 0 {
                return Err(X86HWASanTagMismatchReport::new(
                    ptr, untagged, ptr_tag, mem_tag, size, is_write,
                ));
            }
        }

        Ok(())
    }
}

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

// ============================================================================
// X86HWASanHeapTagging — heap allocation tagging
// ============================================================================

/// Manages tagging of heap allocations.
#[derive(Debug)]
pub struct X86HWASanHeapTagging {
    /// Whether heap tagging is enabled.
    pub enabled: bool,
    /// Map from allocation address to tag.
    alloc_tags: HashMap<u64, u8>,
    /// Number of tagged allocations.
    pub tag_count: u64,
}

impl X86HWASanHeapTagging {
    pub fn new() -> Self {
        Self {
            enabled: true,
            alloc_tags: HashMap::new(),
            tag_count: 0,
        }
    }

    /// Tag a heap allocation with a random tag.
    pub fn tag_allocation(
        &mut self,
        ptr: u64,
        size: u64,
    ) -> u64 {
        if !self.enabled {
            return ptr;
        }

        // Generate tag
        let tag = (self.tag_count as u8).wrapping_mul(17).wrapping_add(1);
        self.tag_count += 1;

        self.alloc_tags.insert(ptr, tag);

        X86HWASanTaggedPtr::create(ptr, tag).raw()
    }

    /// Check a heap access.
    pub fn check_access(
        &self,
        tags: &X86HWASanMemoryTagTable,
        ptr: u64,
        size: u64,
        is_write: bool,
    ) -> Result<(), X86HWASanTagMismatchReport> {
        let ptr_tag = X86HWASanTaggedPtr::get_tag(ptr);
        let untagged = X86HWASanTaggedPtr::strip_tag(ptr);

        if let Some(&alloc_tag) = self.alloc_tags.get(&untagged) {
            if alloc_tag != ptr_tag {
                return Err(X86HWASanTagMismatchReport::new(
                    ptr, untagged, ptr_tag, alloc_tag, size, is_write,
                ));
            }
        } else if let Some(mem_tag) = tags.get_tag(untagged) {
            if mem_tag != ptr_tag && mem_tag != 0 {
                return Err(X86HWASanTagMismatchReport::new(
                    ptr, untagged, ptr_tag, mem_tag, size, is_write,
                ));
            }
        }

        Ok(())
    }
}

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

// ============================================================================
// X86HWASanGlobalTagging — global variable tagging
// ============================================================================

/// Manages tagging of global variables.
#[derive(Debug)]
pub struct X86HWASanGlobalTagging {
    /// Whether global tagging is enabled.
    pub enabled: bool,
    /// Map from global name to tag.
    global_tags: HashMap<String, u8>,
    /// Map from address to tag.
    addr_tags: HashMap<u64, u8>,
    /// Number of tagged globals.
    pub tag_count: u64,
}

impl X86HWASanGlobalTagging {
    pub fn new() -> Self {
        Self {
            enabled: true,
            global_tags: HashMap::new(),
            addr_tags: HashMap::new(),
            tag_count: 0,
        }
    }

    /// Register and tag a global variable.
    pub fn tag_global(&mut self, name: &str, ptr: u64, size: u64) -> u64 {
        if !self.enabled {
            return ptr;
        }

        let tag = (self.tag_count as u8).wrapping_mul(7).wrapping_add(3);
        self.tag_count += 1;

        self.global_tags.insert(name.to_string(), tag);
        self.addr_tags.insert(ptr, tag);

        X86HWASanTaggedPtr::create(ptr, tag).raw()
    }

    /// Get the tag for a named global.
    pub fn get_global_tag(&self, name: &str) -> Option<u8> {
        self.global_tags.get(name).copied()
    }
}

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

// ============================================================================
// X86HWASanTagMismatchReport — tag mismatch diagnostics
// ============================================================================

/// A report for a tag mismatch detected by HWASan.
#[derive(Debug, Clone)]
pub struct X86HWASanTagMismatchReport {
    /// The faulting address.
    pub address: u64,
    /// The granule base address.
    pub granule_address: u64,
    /// The tag in the pointer.
    pub pointer_tag: u8,
    /// The tag in memory.
    pub memory_tag: u8,
    /// Size of the access.
    pub access_size: u64,
    /// Whether the access was a write.
    pub is_write: bool,
    /// Allocation trace ID.
    pub alloc_trace_id: Option<u64>,
    /// Free trace ID (for UAF detection).
    pub free_trace_id: Option<u64>,
    /// Whether this is likely a use-after-free.
    pub likely_uaf: bool,
    /// Whether this is likely a buffer overflow.
    pub likely_buffer_overflow: bool,
}

impl X86HWASanTagMismatchReport {
    pub fn new(
        ptr: u64,
        granule: u64,
        ptr_tag: u8,
        mem_tag: u8,
        size: u64,
        is_write: bool,
    ) -> Self {
        let likely_uaf = mem_tag == 0xFE || mem_tag == 0xFD;
        Self {
            address: ptr,
            granule_address: granule,
            pointer_tag: ptr_tag,
            memory_tag: mem_tag,
            access_size: size,
            is_write,
            alloc_trace_id: None,
            free_trace_id: None,
            likely_uaf,
            likely_buffer_overflow: !likely_uaf && mem_tag != 0,
        }
    }

    /// Format a human-readable report.
    pub fn format(&self) -> String {
        let sep = "=".repeat(58);
        let mut r = String::new();

        r.push_str(&sep);
        r.push('\n');
        r.push_str("==HWASAN== ERROR: HWAddressSanitizer: tag-mismatch on address");
        r.push('\n');
        r.push_str(&format!(
            "{} of size {} at 0x{:016x} tags: {:02x}/{:02x} (ptr/mem)\n",
            if self.is_write { "WRITE" } else { "READ" },
            self.access_size,
            self.address,
            self.pointer_tag,
            self.memory_tag,
        ));

        if self.likely_uaf {
            r.push_str("  Likely use-after-free detected.\n");
        } else if self.likely_buffer_overflow {
            r.push_str("  Likely buffer overflow detected.\n");
        }

        r.push_str(&format!(
            "  Pointer tag: 0x{:02x}, Memory tag: 0x{:02x}\n",
            self.pointer_tag, self.memory_tag,
        ));

        if let Some(tid) = self.alloc_trace_id {
            r.push_str(&format!("  Allocation trace id: {}\n", tid));
        }
        if let Some(tid) = self.free_trace_id {
            r.push_str(&format!("  Free trace id: {}\n", tid));
        }

        r.push_str("  HWASan: tag mismatch on memory access\n");
        r.push_str(&sep);
        r
    }

    /// Short summary.
    pub fn summary(&self) -> String {
        format!(
            "tag-mismatch at 0x{:016x}: ptr_tag=0x{:02x} mem_tag=0x{:02x} size={}",
            self.address, self.pointer_tag, self.memory_tag, self.access_size,
        )
    }
}

// ============================================================================
// X86HWASanKernel — kernel-mode HWASan stubs
// ============================================================================

/// Kernel-mode HWASan support (stubs for X86).
///
/// In Linux kernel HWASan, the kernel's virtual address space has its
/// own shadow region, slab allocators are tagged, and stack frames get
/// random tags.
#[derive(Debug)]
pub struct X86HWASanKernel {
    /// Whether kernel HWASan is enabled.
    pub enabled: bool,
    /// Kernel shadow offset.
    pub shadow_offset: u64,
    /// Kernel shadow scale.
    pub shadow_scale: u8,
    /// Tag slab allocations.
    pub tag_slab: bool,
    /// Tag page allocations.
    pub tag_page_alloc: bool,
    /// Tag vmalloc allocations.
    pub tag_vmalloc: bool,
    /// Tag kernel stacks.
    pub tag_stack: bool,
    /// Tag kernel globals.
    pub tag_globals: bool,
    /// Kernel-specific tag counter.
    kernel_tag_counter: u64,
}

impl X86HWASanKernel {
    pub fn new() -> Self {
        Self {
            enabled: false,
            shadow_offset: X86_HWASAN_KERNEL_SHADOW_OFFSET,
            shadow_scale: X86_HWASAN_KERNEL_SHADOW_SCALE,
            tag_slab: true,
            tag_page_alloc: true,
            tag_vmalloc: true,
            tag_stack: true,
            tag_globals: true,
            kernel_tag_counter: 0,
        }
    }

    /// Convert a kernel virtual address to a shadow address.
    pub fn virt_to_shadow(&self, vaddr: u64) -> u64 {
        (vaddr >> self.shadow_scale) + self.shadow_offset
    }

    /// Tag a slab allocation.
    pub fn tag_slab_allocation(
        &mut self,
        ptr: u64,
        size: u64,
    ) -> u64 {
        if !self.enabled || !self.tag_slab {
            return ptr;
        }
        self.kernel_tag_counter += 1;
        let tag = ((self.kernel_tag_counter * 13 + 7) % 254 + 1) as u8;
        X86HWASanTaggedPtr::create(ptr, tag).raw()
    }

    /// Check a kernel memory access.
    pub fn check_kernel_access(
        &self,
        tags: &X86HWASanMemoryTagTable,
        ptr: u64,
        size: u64,
    ) -> Result<(), X86HWASanTagMismatchReport> {
        let ptr_tag = X86HWASanTaggedPtr::get_tag(ptr);
        let untagged = X86HWASanTaggedPtr::strip_tag(ptr);

        // Kernel addresses have distinct tag handling
        if untagged < 0xffff_0000_0000_0000 {
            // Not a kernel address; skip
            return Ok(());
        }

        if let Some(mem_tag) = tags.get_tag(untagged) {
            if mem_tag != ptr_tag {
                return Err(X86HWASanTagMismatchReport::new(
                    ptr, untagged, ptr_tag, mem_tag, size, false,
                ));
            }
        }

        Ok(())
    }

    /// Page-align an address downward.
    pub fn page_align_down(addr: u64, page_size: u64) -> u64 {
        addr & !(page_size - 1)
    }

    /// Page-align an address upward.
    pub fn page_align_up(addr: u64, page_size: u64) -> u64 {
        (addr + page_size - 1) & !(page_size - 1)
    }

    /// Initialize kernel HWASan at boot time.
    pub fn init_boot(&mut self) {
        self.enabled = true;
        self.kernel_tag_counter = 0;
    }
}

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

// ============================================================================
// X86ASanFullOrchestrator — high-level orchestration of ASan+HWASan
// ============================================================================

/// Unified orchestrator that manages both ASan and HWASan runtimes.
#[derive(Debug)]
pub struct X86ASanFullOrchestrator {
    /// The ASan runtime.
    pub asan: X86ASanFull,
    /// The HWASan runtime.
    pub hwasan: X86HWASanRuntime,
    /// Common flags.
    pub flags: X86ASanRuntimeFlags,
    /// Which sanitizers are active.
    pub active: X86ActiveSanitizers,
}

/// Bitflags for active sanitizers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct X86ActiveSanitizers {
    pub asan: bool,
    pub hwasan: bool,
    pub ubsan: bool,
    pub tsan: bool,
    pub msan: bool,
    pub lsan: bool,
    pub dfsan: bool,
}

impl Default for X86ActiveSanitizers {
    fn default() -> Self {
        Self {
            asan: false,
            hwasan: false,
            ubsan: false,
            tsan: false,
            msan: false,
            lsan: false,
            dfsan: false,
        }
    }
}

impl X86ASanFullOrchestrator {
    pub fn new() -> Self {
        Self {
            asan: X86ASanFull::new(),
            hwasan: X86HWASanRuntime::new(),
            flags: X86ASanRuntimeFlags::default(),
            active: X86ActiveSanitizers {
                asan: true,
                ..Default::default()
            },
        }
    }

    /// Activate both ASan and HWASan.
    pub fn activate_all(&mut self) {
        self.asan.activate();
        self.hwasan.enabled = true;
        self.hwasan.init(42);
        self.active.asan = true;
        self.active.hwasan = true;
    }

    /// Deactivate all sanitizers.
    pub fn deactivate_all(&mut self) {
        self.asan.deactivate();
        self.hwasan.enabled = false;
        self.active.asan = false;
        self.active.hwasan = false;
    }

    /// Check a memory access against all active sanitizers.
    pub fn check_memory_access(
        &mut self,
        addr: u64,
        size: u64,
        is_write: bool,
    ) -> Vec<String> {
        let mut errors = Vec::new();

        if self.active.asan {
            if let Err(report) =
                self.asan.check_memory_access(addr, size, is_write)
            {
                errors.push(report.summary());
            }
        }

        if self.active.hwasan {
            if let Err(report) =
                self.hwasan.check_memory_access(addr, size, is_write)
            {
                errors.push(report.summary());
            }
        }

        errors
    }

    /// Perform a leak check.
    pub fn leak_check(&self) -> Vec<X86ASanErrorReport> {
        if self.active.asan {
            self.asan.leak_check()
        } else {
            Vec::new()
        }
    }

    /// Print leak summary.
    pub fn print_leak_summary(&self) {
        self.asan.print_leak_summary();
    }

    /// Allocate memory through the ASan allocator.
    pub fn sanitizer_malloc(&mut self, size: u64) -> (u64, u64) {
        if self.active.asan {
            self.asan
                .allocator
                .alloc(size, 16, X86ASanAllocKind::Malloc)
        } else {
            (0, 0) // fallback to system malloc
        }
    }

    /// Free memory through the ASan allocator.
    pub fn sanitizer_free(&mut self, ptr: u64) -> Result<(), X86ASanErrorType> {
        if self.active.asan {
            self.asan.allocator.free(ptr, None)
        } else {
            Ok(())
        }
    }

    /// Reallocate memory.
    pub fn sanitizer_realloc(
        &mut self,
        old_ptr: u64,
        new_size: u64,
    ) -> Result<(u64, u64), X86ASanErrorType> {
        if self.active.asan {
            self.asan.allocator.realloc(old_ptr, new_size, 16)
        } else {
            Ok((0, 0))
        }
    }

    /// Collect all statistics.
    pub fn full_stats(&self) -> X86ASanFullOrchestratorStats {
        X86ASanFullOrchestratorStats {
            asan_stats: self.asan.stats(),
            hwasan_stats: self.hwasan.stats(),
            active_sanitizers: self.active,
        }
    }
}

/// Combined orchestrator statistics.
#[derive(Debug, Clone)]
pub struct X86ASanFullOrchestratorStats {
    pub asan_stats: X86ASanFullStats,
    pub hwasan_stats: X86HWASanStats,
    pub active_sanitizers: X86ActiveSanitizers,
}

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

// ============================================================================
// X86ASanInstrumentationEmitter — inline asm emission for checks
// ============================================================================

/// Emits inline assembly for ASan load/store checks on X86.
///
/// In production compiler-rt, the check is emitted as:
/// ```asm
///   mov  rax, [ptr]
///   shr  rax, 3
///   cmp  byte [rax + shadow_offset], 0
///   jne  __asan_report_loadN
/// ```
pub struct X86ASanInstrumentationEmitter {
    /// Shadow offset for address computation.
    pub shadow_offset: u64,
    /// Whether to emit nop sleds for alignment.
    pub emit_nops: bool,
    /// Whether to use 64-bit or 32-bit mode.
    pub is_64bit: bool,
}

impl X86ASanInstrumentationEmitter {
    pub fn new(shadow_offset: u64, is_64bit: bool) -> Self {
        Self {
            shadow_offset,
            emit_nops: false,
            is_64bit,
        }
    }

    /// Emit a load check for an N-byte aligned access.
    /// Returns the size of emitted code in bytes.
    pub fn emit_load_check(&self, addr_reg: &str, size: u8) -> usize {
        // mov rax, [addr_reg]    — 3 bytes
        // shr rax, 3             — 4 bytes
        // cmp byte [rax+offset], 0 — 7 bytes
        // jne error_handler      — 6 bytes
        // Total: ~20 bytes (x86-64)
        20
    }

    /// Emit a store check for an N-byte aligned access.
    pub fn emit_store_check(&self, addr_reg: &str, size: u8) -> usize {
        // Same sequence as load
        self.emit_load_check(addr_reg, size)
    }

    /// Emit a 1-byte access check (precise offset within granule).
    pub fn emit_byte_check(&self, addr_reg: &str) -> usize {
        // Additional masking for byte-level offset
        // mov rax, [addr_reg]
        // shr rax, 3
        // add rax, offset
        // movsx ebx, byte [rax]
        // test bl, bl
        // js  error_handler         (jump if negative = poisoned)
        // jns +0x....(skip)
        // But also check: if bl != 0 and offset_in_granule >= bl → error
        32
    }

    /// Emit the prologue for a function with stack instrumentation.
    pub fn emit_stack_prologue(&self, _frame_size: u64) -> String {
        // Poison the entire stack frame initially
        // Then unpoison each variable
        String::from("// __asan_stack_malloc_N prologue")
    }

    /// Emit the epilogue: poison stack variables on exit.
    pub fn emit_stack_epilogue(&self, _frame_size: u64) -> String {
        String::from("// __asan_stack_free_N epilogue")
    }

    /// Emit a call to the ASan runtime error handler.
    pub fn emit_error_handler_call(&self, access_type: &str, size: u8) -> String {
        format!(
            "call __asan_report_{}{}",
            access_type,
            if size == 1 { "1".into() }
            else if size == 2 { "2".into() }
            else if size == 4 { "4".into() }
            else if size == 8 { "8".into() }
            else if size == 16 { "16".into() }
            else { format!("n_{}", size) }
        )
    }

    /// Emit the entire instrumentation sequence as a string.
    pub fn emit_full_sequence(&self, base_reg: &str, size: u8, is_store: bool) -> String {
        let mut seq = String::new();
        let access = if is_store { "store" } else { "load" };

        // Compute shadow address
        seq.push_str(&format!("    mov rax, {}\n", base_reg));
        seq.push_str("    shr rax, 3\n");
        seq.push_str(&format!(
            "    cmp byte ptr [rax + 0x{:x}], 0\n",
            self.shadow_offset
        ));
        seq.push_str("    jne .Lerror\n");
        seq.push_str("    jmp .Lok\n");
        seq.push_str(".Lerror:\n");
        seq.push_str(&format!(
            "    call __asan_report_{}{}\n",
            access, size
        ));
        seq.push_str(".Lok:\n");
        seq
    }
}

// ============================================================================
// X86ASanPageManager — shadow memory page-level operations
// ============================================================================

/// Manages shadow memory at page granularity.
///
/// Shadow memory is typically mmap'd with MAP_NORESERVE, meaning
/// physical pages are allocated on first access. This reduces the
/// virtual memory overhead of the shadow region.
#[derive(Debug)]
pub struct X86ASanPageManager {
    /// Page size (typically 4096).
    pub page_size: u64,
    /// Number of shadow pages in the working set.
    pub resident_pages: u64,
    /// Maximum resident pages (for limiting RSS).
    pub max_resident_pages: u64,
    /// Track which shadow pages are currently mapped.
    page_table: HashMap<u64, bool>,
    /// Page access timestamps for LRU eviction.
    page_timestamps: HashMap<u64, u64>,
    /// Monotonically increasing clock for LRU.
    clock: u64,
}

impl X86ASanPageManager {
    pub fn new(page_size: u64, max_pages: u64) -> Self {
        Self {
            page_size,
            resident_pages: 0,
            max_resident_pages: max_pages,
            page_table: HashMap::new(),
            page_timestamps: HashMap::new(),
            clock: 0,
        }
    }

    /// Default page manager (4KB pages, 65536 max resident).
    pub fn default_pages() -> Self {
        Self::new(4096, 65536)
    }

    /// Map a shadow page for the given application address.
    pub fn map_shadow_page(&mut self, app_addr: u64, shadow: &X86ASanShadowMap) -> bool {
        let shadow_addr = shadow.app_to_shadow(app_addr);
        let page_base = shadow_addr & !(self.page_size - 1);

        if self.page_table.contains_key(&page_base) {
            // Already mapped; just update timestamp
            self.clock += 1;
            self.page_timestamps.insert(page_base, self.clock);
            return true;
        }

        // Check if we need to evict
        if self.resident_pages >= self.max_resident_pages {
            self.evict_lru();
        }

        // Simulate mmap
        self.page_table.insert(page_base, true);
        self.clock += 1;
        self.page_timestamps.insert(page_base, self.clock);
        self.resident_pages += 1;
        true
    }

    /// Unmap a shadow page.
    pub fn unmap_shadow_page(&mut self, app_addr: u64, shadow: &X86ASanShadowMap) {
        let shadow_addr = shadow.app_to_shadow(app_addr);
        let page_base = shadow_addr & !(self.page_size - 1);

        self.page_table.remove(&page_base);
        self.page_timestamps.remove(&page_base);
        self.resident_pages = self.resident_pages.saturating_sub(1);
    }

    /// Check if a shadow page is mapped.
    pub fn is_mapped(&self, app_addr: u64, shadow: &X86ASanShadowMap) -> bool {
        let shadow_addr = shadow.app_to_shadow(app_addr);
        let page_base = shadow_addr & !(self.page_size - 1);
        self.page_table.contains_key(&page_base)
    }

    /// Evict the least-recently-used page.
    fn evict_lru(&mut self) {
        if let Some((&page, _)) = self
            .page_timestamps
            .iter()
            .min_by_key(|(_, &ts)| ts)
        {
            self.page_table.remove(&page);
            self.page_timestamps.remove(&page);
            self.resident_pages = self.resident_pages.saturating_sub(1);
        }
    }

    /// Pre-fault a range of shadow pages (make them resident).
    pub fn prefault_range(
        &mut self,
        start: u64,
        size: u64,
        shadow: &X86ASanShadowMap,
    ) {
        let end = start + size;
        let mut addr = start & !(self.page_size - 1);
        while addr < end {
            self.map_shadow_page(addr, shadow);
            addr += self.page_size;
        }
    }
}

impl Default for X86ASanPageManager {
    fn default() -> Self {
        Self::default_pages()
    }
}

// ============================================================================
// X86ASanLeakScanner — mark-and-sweep leak detection
// ============================================================================

/// Implements mark-and-sweep leak detection by scanning the stack,
/// registers, and global variables for potential root pointers.
#[derive(Debug)]
pub struct X86ASanLeakScanner {
    /// The root set: addresses known to be reachable.
    pub root_set: HashSet<u64>,
    /// Allocations that have been marked as reachable.
    pub reachable: HashSet<u64>,
    /// Allocations classified as directly lost.
    pub directly_lost: Vec<(u64, u64)>,
    /// Allocations classified as indirectly lost.
    pub indirectly_lost: Vec<(u64, u64)>,
    /// Whether the scanner is active.
    pub active: bool,
    /// Maximum stack depth for root scanning.
    pub max_stack_scan_depth: u64,
}

impl X86ASanLeakScanner {
    pub fn new() -> Self {
        Self {
            root_set: HashSet::new(),
            reachable: HashSet::new(),
            directly_lost: Vec::new(),
            indirectly_lost: Vec::new(),
            active: false,
            max_stack_scan_depth: 64 * 1024, // 64 KB
        }
    }

    /// Register a known root pointer (e.g. a global variable address).
    pub fn add_root(&mut self, addr: u64) {
        self.root_set.insert(addr);
    }

    /// Clear all registered roots.
    pub fn clear_roots(&mut self) {
        self.root_set.clear();
        self.reachable.clear();
        self.directly_lost.clear();
        self.indirectly_lost.clear();
    }

    /// Scan for leaks given the set of all active allocations.
    pub fn detect_leaks(
        &mut self,
        allocations: &HashMap<u64, X86ASanAllocMeta>,
        shadow: &X86ASanShadowMap,
    ) -> (Vec<(u64, u64)>, Vec<(u64, u64)>) {
        if !self.active {
            return (Vec::new(), Vec::new());
        }

        // Phase 1: Mark all reachable allocations from root set
        self.mark_reachable(allocations);

        // Phase 2: Classify unreachable allocations
        let mut directly = Vec::new();
        let mut indirectly = Vec::new();

        for (&addr, meta) in allocations {
            if meta.is_freed {
                continue;
            }
            if self.reachable.contains(&addr) {
                continue;
            }

            // Check if any other reachable allocation points to this one
            if self.is_indirectly_reachable(addr, allocations) {
                indirectly.push((addr, meta.requested_size));
            } else {
                directly.push((addr, meta.requested_size));
            }
        }

        self.directly_lost = directly.clone();
        self.indirectly_lost = indirectly.clone();

        (directly, indirectly)
    }

    /// Mark all allocations reachable from the root set.
    fn mark_reachable(&mut self, allocations: &HashMap<u64, X86ASanAllocMeta>) {
        self.reachable.clear();

        // BFS from each root
        let mut worklist: VecDeque<u64> = self.root_set.iter().copied().collect();

        while let Some(ptr) = worklist.pop_front() {
            // Check if ptr points inside any allocation
            for (&alloc_addr, meta) in allocations {
                if meta.is_freed {
                    continue;
                }
                if ptr >= alloc_addr && ptr < alloc_addr + meta.requested_size {
                    if self.reachable.insert(alloc_addr) {
                        // Newly reached — scan its contents for more pointers
                        worklist.push_back(alloc_addr);
                    }
                }
            }
        }
    }

    /// Check if an allocation is reachable indirectly.
    fn is_indirectly_reachable(
        &self,
        addr: u64,
        allocations: &HashMap<u64, X86ASanAllocMeta>,
    ) -> bool {
        // An allocation is indirectly reachable if a reachable allocation
        // contains a pointer to it.
        for &reachable_addr in &self.reachable {
            if let Some(meta) = allocations.get(&reachable_addr) {
                // In a real implementation, we'd scan the memory contents
                // of the reachable block for pointers.
                // Here we simulate: if reachable block could contain ptr
                // to addr, it's indirectly reachable.
                let _ = meta;
                let _ = addr;
            }
        }
        false
    }

    /// Print a leak summary.
    pub fn print_summary(&self) -> String {
        let mut report = String::new();
        report.push_str("=== LeakSanitizer Report ===\n");

        if self.directly_lost.is_empty() && self.indirectly_lost.is_empty() {
            report.push_str("No leaks detected.\n");
            return report;
        }

        let direct_bytes: u64 = self.directly_lost.iter().map(|(_, s)| s).sum();
        let indirect_bytes: u64 = self.indirectly_lost.iter().map(|(_, s)| s).sum();

        report.push_str(&format!(
            "Directly lost: {} allocations, {} bytes\n",
            self.directly_lost.len(),
            direct_bytes,
        ));
        report.push_str(&format!(
            "Indirectly lost: {} allocations, {} bytes\n",
            self.indirectly_lost.len(),
            indirect_bytes,
        ));
        report.push_str(&format!(
            "Total lost: {} bytes\n",
            direct_bytes + indirect_bytes,
        ));

        for (ptr, size) in &self.directly_lost {
            report.push_str(&format!(
                "  Direct leak of {} bytes at 0x{:016x}\n",
                size, ptr,
            ));
        }

        report
    }

    /// Returns true if the scanner has detected leaks.
    pub fn has_leaks(&self) -> bool {
        !self.directly_lost.is_empty() || !self.indirectly_lost.is_empty()
    }
}

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

// ============================================================================
// X86ASanLibcInterceptors — common libc function interception
// ============================================================================

/// Interception wrappers for common libc functions that ASan checks.
///
/// These replace the standard libc functions to add bounds checks.
#[derive(Debug)]
pub struct X86ASanLibcInterceptors {
    /// Whether string interception is enabled.
    pub string_interception: bool,
    /// Whether memory copy interception is enabled.
    pub memory_interception: bool,
    /// Whether to check for overlapping regions.
    pub check_overlap: bool,
}

impl X86ASanLibcInterceptors {
    pub fn new() -> Self {
        Self {
            string_interception: true,
            memory_interception: true,
            check_overlap: true,
        }
    }

    /// Intercepted memcpy with ASan checks.
    pub fn asan_memcpy(
        &self,
        dst: u64,
        src: u64,
        n: u64,
        shadow: &mut X86ASanShadowMap,
    ) -> Result<(), X86ASanErrorReport> {
        // Check source
        if let Err(e) = shadow.check_access(src, n, false) {
            return Err(X86ASanErrorReport::new(
                X86ASanErrorType::MemcpyParamOverlap,
                src,
                n,
                X86ASanAccessType::Read,
                shadow.get_shadow(src),
            ));
        }

        // Check destination
        if let Err(e) = shadow.check_access(dst, n, true) {
            return Err(X86ASanErrorReport::new(
                X86ASanErrorType::MemcpyParamOverlap,
                dst,
                n,
                X86ASanAccessType::Write,
                shadow.get_shadow(dst),
            ));
        }

        // Check overlap
        if self.check_overlap {
            let src_end = src + n;
            let dst_end = dst + n;
            if (dst >= src && dst < src_end) || (dst_end > src && dst_end <= src_end) {
                return Err(X86ASanErrorReport::new(
                    X86ASanErrorType::MemcpyParamOverlap,
                    dst,
                    n,
                    X86ASanAccessType::Write,
                    USER_POISON,
                ));
            }
        }

        // Simulate copy: update shadow for destination
        shadow.unpoison_range(dst, n);

        Ok(())
    }

    /// Intercepted memset with ASan checks.
    pub fn asan_memset(
        &self,
        dst: u64,
        _value: u8,
        n: u64,
        shadow: &mut X86ASanShadowMap,
    ) -> Result<(), X86ASanErrorReport> {
        // Check destination is addressable
        if let Err(e) = shadow.check_access(dst, n, true) {
            return Err(X86ASanErrorReport::new(
                X86ASanErrorType::MemsetParamOverlap,
                dst,
                n,
                X86ASanAccessType::Write,
                shadow.get_shadow(dst),
            ));
        }

        Ok(())
    }

    /// Intercepted strcpy.
    pub fn asan_strcpy(
        &self,
        dst: u64,
        src: u64,
        shadow: &mut X86ASanShadowMap,
    ) -> Result<(), X86ASanErrorReport> {
        // Compute string length from shadow or just check bounds
        // Scan src until a null byte or poisoned memory
        let mut offset: u64 = 0;
        let max_check = 4096; // arbitrary limit

        while offset < max_check {
            if let Err(e) = shadow.check_access(src + offset, 1, false) {
                return Err(X86ASanErrorReport::new(
                    X86ASanErrorType::StrcpyParamOverlap,
                    src + offset,
                    1,
                    X86ASanAccessType::Read,
                    shadow.get_shadow(src + offset),
                ));
            }
            if let Err(e) = shadow.check_access(dst + offset, 1, true) {
                return Err(X86ASanErrorReport::new(
                    X86ASanErrorType::StrcpyParamOverlap,
                    dst + offset,
                    1,
                    X86ASanAccessType::Write,
                    shadow.get_shadow(dst + offset),
                ));
            }

            // Check for null terminator (simulated)
            let sv = shadow.get_shadow(src + offset);
            if sv == ADDRESSABLE {
                // In real code, we'd read the byte
                // For simulation, assume termination after some bytes
                if offset > 100 {
                    break;
                }
            }
            offset += 1;
        }

        Ok(())
    }

    /// Intercepted strlen.
    pub fn asan_strlen(
        &self,
        src: u64,
        shadow: &X86ASanShadowMap,
    ) -> Result<u64, X86ASanErrorReport> {
        let mut offset: u64 = 0;
        let max_check = 8192;

        while offset < max_check {
            if let Err(e) = shadow.check_access(src + offset, 1, false) {
                return Err(X86ASanErrorReport::new(
                    X86ASanErrorType::WildPointerAccess,
                    src + offset,
                    1,
                    X86ASanAccessType::Read,
                    shadow.get_shadow(src + offset),
                ));
            }

            if offset > 256 {
                // Simulated null byte found
                return Ok(offset);
            }
            offset += 1;
        }

        Ok(offset)
    }

    /// Intercepted strnlen.
    pub fn asan_strnlen(
        &self,
        src: u64,
        maxlen: u64,
        shadow: &X86ASanShadowMap,
    ) -> Result<u64, X86ASanErrorReport> {
        let mut offset: u64 = 0;

        while offset < maxlen {
            if let Err(e) = shadow.check_access(src + offset, 1, false) {
                return Err(X86ASanErrorReport::new(
                    X86ASanErrorType::WildPointerAccess,
                    src + offset,
                    1,
                    X86ASanAccessType::Read,
                    shadow.get_shadow(src + offset),
                ));
            }
            offset += 1;
            if offset > 256 {
                return Ok(offset.min(maxlen));
            }
        }

        Ok(maxlen)
    }
}

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

// ============================================================================
// X86ASanDWARFSymbolizer — DWARF-based symbolization
// ============================================================================

/// Symbolizes stack traces using DWARF debug information.
#[derive(Debug)]
pub struct X86ASanDWARFSymbolizer {
    /// DWARF compilation units mapped by address range.
    pub units: Vec<X86ASanDwarfUnit>,
    /// Subprogram DIEs mapped by address.
    pub subprograms: BTreeMap<u64, X86ASanDwarfSubprogram>,
    /// Line number information.
    pub line_table: Vec<X86ASanDwarfLineEntry>,
    /// Whether DWARF symbolization is available.
    pub available: bool,
}

/// A DWARF compilation unit.
#[derive(Debug, Clone)]
pub struct X86ASanDwarfUnit {
    /// Name of the source file.
    pub name: String,
    /// Compilation directory.
    pub comp_dir: Option<String>,
    /// Low PC of the unit.
    pub low_pc: u64,
    /// High PC of the unit.
    pub high_pc: u64,
    /// Offset into .debug_info.
    pub debug_info_offset: u64,
}

/// A DWARF subprogram (function) descriptor.
#[derive(Debug, Clone)]
pub struct X86ASanDwarfSubprogram {
    /// Function name.
    pub name: String,
    /// Low PC of the function.
    pub low_pc: u64,
    /// High PC of the function.
    pub high_pc: u64,
    /// Source file index.
    pub file_index: u64,
    /// Line number declaration.
    pub decl_line: u64,
}

/// A DWARF line table entry.
#[derive(Debug, Clone)]
pub struct X86ASanDwarfLineEntry {
    /// Program counter.
    pub address: u64,
    /// Source file index.
    pub file_index: u64,
    /// Line number.
    pub line: u64,
    /// Column number.
    pub column: u64,
}

impl X86ASanDWARFSymbolizer {
    pub fn new() -> Self {
        Self {
            units: Vec::new(),
            subprograms: BTreeMap::new(),
            line_table: Vec::new(),
            available: false,
        }
    }

    /// Load DWARF info from an ELF file section (simulated).
    pub fn load_from_elf(&mut self, _debug_info: &[u8], _debug_line: &[u8]) {
        // In production, parse .debug_info and .debug_line sections.
        // This stub sets up the symbolizer as available for testing.
        self.available = true;
    }

    /// Symbolize an instruction pointer: find function name and source
    /// location.
    pub fn symbolize(
        &self,
        ip: u64,
    ) -> Option<(String, String, u32, u32)> {
        if !self.available {
            return None;
        }

        // Find the subprogram containing this IP
        let func_name = self.subprograms
            .range(..=ip)
            .next_back()
            .and_then(|(low_pc, sub)| {
                if ip < sub.high_pc {
                    Some(sub.name.clone())
                } else {
                    None
                }
            })
            .unwrap_or_else(|| "??".to_string());

        // Find the source file
        let file_name = self.units
            .first()
            .map(|u| u.name.clone())
            .unwrap_or_else(|| "??".to_string());

        // Find the line entry
        let (line, col) = self.line_table
            .iter()
            .find(|entry| entry.address == ip)
            .map(|entry| (entry.line as u32, entry.column as u32))
            .unwrap_or((0, 0));

        Some((func_name, file_name, line, col))
    }

    /// Add a known subprogram for testing.
    pub fn add_subprogram(&mut self, name: &str, low_pc: u64, high_pc: u64) {
        self.subprograms.insert(
            low_pc,
            X86ASanDwarfSubprogram {
                name: name.to_string(),
                low_pc,
                high_pc,
                file_index: 1,
                decl_line: 0,
            },
        );
    }

    /// Add a line entry for testing.
    pub fn add_line_entry(&mut self, address: u64, line: u64, column: u64) {
        self.line_table.push(X86ASanDwarfLineEntry {
            address,
            file_index: 1,
            line,
            column,
        });
    }
}

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

// ============================================================================
// X86HWASanMTESupport — Memory Tagging Extension probing & emulation
// ============================================================================

/// Probes for and optionally emulates ARM MTE (Memory Tagging Extension)
/// on X86 targets. Since X86 does not have native MTE, this provides
/// software-based tag checking with MTE-compatible API.
#[derive(Debug)]
pub struct X86HWASanMTESupport {
    /// Whether MTE is available (always false on X86).
    pub available: bool,
    /// Sync mode: check tags synchronously on each access.
    pub sync_mode: bool,
    /// Async mode: check tags asynchronously (via fault).
    pub async_mode: bool,
    /// Tag checking granularity (16 bytes for MTE).
    pub granule_size: u64,
    /// Number of tag-check faults handled.
    pub tag_faults: u64,
}

impl X86HWASanMTESupport {
    pub fn new() -> Self {
        Self {
            available: false, // Never available on X86
            sync_mode: false,
            async_mode: false,
            granule_size: X86_HWASAN_GRANULE_SIZE,
            tag_faults: 0,
        }
    }

    /// Probe for MTE availability (always false on X86).
    pub fn probe(&self) -> bool {
        // On AArch64, this would check ID_AA64PFR1_EL1.MTE bits.
        // On X86, MTE is never available.
        false
    }

    /// Emit MTE-like tag check intrinsics for inline checks.
    pub fn emit_tag_check(&self, ptr: u64, expected_tag: u8) -> Result<(), &'static str> {
        let actual_tag = (ptr >> 56) as u8;
        if actual_tag != expected_tag {
            self.record_tag_fault();
            Err("tag mismatch")
        } else {
            Ok(())
        }
    }

    /// Record a tag fault for statistics.
    fn record_tag_fault(&self) {
        // In real MTE, this would be a synchronous exception.
        // Incrementing the counter here for simulation.
    }

    /// Set the tag allocation tag for a granule (simulated STG instruction).
    pub fn set_allocation_tag(&self, addr: u64, tag: u8, table: &mut X86HWASanMemoryTagTable) {
        table.set_tag(addr, tag);
    }

    /// Load the allocation tag for a granule (simulated LDG instruction).
    pub fn load_allocation_tag(&self, addr: u64, table: &X86HWASanMemoryTagTable) -> Option<u8> {
        table.get_tag(addr)
    }

    /// Increment tag by a given value with exclusion (IRG-like).
    pub fn insert_random_tag(&self, ptr: u64, exclude: u8) -> u64 {
        // Generate a random tag excluding the given value.
        // On AArch64, IRG does this in hardware.
        let mut tag = (ptr.wrapping_mul(0x9E3779B97F4A7C15) >> 56) as u8;
        if tag == 0 || tag == exclude {
            tag = tag.wrapping_add(1);
        }
        if tag == 0 || tag == exclude {
            tag = tag.wrapping_add(1);
        }
        (ptr & X86_HWASAN_ADDR_MASK) | ((tag as u64) << 56)
    }
}

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

// ============================================================================
// X86HWASanColorMap — color-based visual tag representation
// ============================================================================

/// Maps HWASan tags to human-readable colors for diagnostics.
/// Makes tag mismatches easier to understand in reports.
#[derive(Debug, Clone)]
pub struct X86HWASanColorMap {
    /// Map from tag value to color name.
    pub colors: HashMap<u8, String>,
    /// Map from color name to tag value.
    pub tags: HashMap<String, u8>,
}

impl X86HWASanColorMap {
    pub fn new() -> Self {
        let mut colors = HashMap::new();
        let mut tags = HashMap::new();

        // Pre-assign colors to common tag values
        let color_names = [
            "red", "green", "blue", "yellow", "magenta", "cyan",
            "orange", "purple", "lime", "teal", "pink", "brown",
            "navy", "maroon", "olive", "coral", "gold", "silver",
            "violet", "indigo",
        ];

        for (i, name) in color_names.iter().enumerate() {
            let tag = (i as u8) + 1;
            colors.insert(tag, name.to_string());
            tags.insert(name.to_string(), tag);
        }

        Self { colors, tags }
    }

    /// Get the color name for a tag.
    pub fn color_for_tag(&self, tag: u8) -> &str {
        self.colors
            .get(&tag)
            .map(|s| s.as_str())
            .unwrap_or("unknown")
    }

    /// Get the tag for a color name.
    pub fn tag_for_color(&self, color: &str) -> Option<u8> {
        self.tags.get(color).copied()
    }

    /// Format a report with color names for readability.
    pub fn format_tag_report(&self, ptr_tag: u8, mem_tag: u8) -> String {
        format!(
            "tag mismatch: ptr has '{}' (0x{:02x}), mem has '{}' (0x{:02x})",
            self.color_for_tag(ptr_tag),
            ptr_tag,
            self.color_for_tag(mem_tag),
            mem_tag,
        )
    }
}

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

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

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

    // ------------------------------------------------------------------
    // ASan shadow byte tests
    // ------------------------------------------------------------------

    #[test]
    fn test_shadow_byte_constants() {
        assert_eq!(ADDRESSABLE, 0);
        assert_eq!(PARTIAL1, 1);
        assert_eq!(PARTIAL7, 7);
        assert_eq!(HEAP_LEFT_REDZONE, -1);
        assert_eq!(FREED, -9);
        assert_eq!(STACK_USE_AFTER_SCOPE, -10);
    }

    #[test]
    fn test_shadow_byte_is_addressable() {
        assert!(is_addressable(0));
        assert!(is_addressable(1));
        assert!(is_addressable(7));
        assert!(!is_addressable(-1));
        assert!(!is_addressable(FREED));
    }

    #[test]
    fn test_shadow_byte_is_poisoned() {
        assert!(!is_poisoned(0));
        assert!(!is_poisoned(7));
        assert!(is_poisoned(HEAP_LEFT_REDZONE));
        assert!(is_poisoned(FREED));
    }

    #[test]
    fn test_shadow_byte_addr_bytes() {
        assert_eq!(addr_bytes(0), 8);
        assert_eq!(addr_bytes(1), 1);
        assert_eq!(addr_bytes(7), 7);
        assert_eq!(addr_bytes(-1), 0);
    }

    #[test]
    fn test_shadow_byte_describe() {
        assert_eq!(describe(0), "addressable");
        assert_eq!(describe(HEAP_LEFT_REDZONE), "heap left redzone");
        assert_eq!(describe(FREED), "freed (heap-use-after-free)");
        assert_eq!(describe(STACK_USE_AFTER_SCOPE), "stack-use-after-scope");
    }

    #[test]
    fn test_shadow_byte_error_category() {
        assert_eq!(error_category(HEAP_LEFT_REDZONE), "heap-buffer-overflow");
        assert_eq!(error_category(STACK_LEFT_REDZONE), "stack-buffer-overflow");
        assert_eq!(error_category(FREED), "heap-use-after-free");
        assert_eq!(error_category(STACK_USE_AFTER_SCOPE), "stack-use-after-scope");
    }

    // ------------------------------------------------------------------
    // ASan shadow map tests
    // ------------------------------------------------------------------

    #[test]
    fn test_shadow_map_x86_64_creation() {
        let map = X86ASanShadowMap::x86_64();
        assert_eq!(map.shadow_offset, X86_ASAN_SHADOW_OFFSET_64_DEFAULT);
        assert_eq!(map.arch, X86AsanTargetArch::X8664);
    }

    #[test]
    fn test_shadow_map_i386_creation() {
        let map = X86ASanShadowMap::i386();
        assert_eq!(map.shadow_offset, X86_ASAN_SHADOW_OFFSET_32);
        assert_eq!(map.arch, X86AsanTargetArch::I386);
    }

    #[test]
    fn test_shadow_map_app_to_shadow() {
        let map = X86ASanShadowMap::x86_64();
        let addr: u64 = 0x1000;
        let expected = (addr >> 3) + X86_ASAN_SHADOW_OFFSET_64_DEFAULT;
        assert_eq!(map.app_to_shadow(addr), expected);
    }

    #[test]
    fn test_shadow_map_shadow_to_app() {
        let map = X86ASanShadowMap::x86_64();
        let app: u64 = 0x1000;
        let shadow = map.app_to_shadow(app);
        let back = map.shadow_to_app(shadow);
        assert_eq!(back, app & !X86_ASAN_SHADOW_MASK);
    }

    #[test]
    fn test_shadow_map_allocate() {
        let mut map = X86ASanShadowMap::x86_64();
        assert!(!map.shadow_allocated);
        map.allocate_shadow(0x100000);
        assert!(map.shadow_allocated);
        assert!(!map.shadow_buffer.is_empty());
    }

    #[test]
    fn test_shadow_map_set_get() {
        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x20000);

        let addr: u64 = 0x1000;
        assert_eq!(map.get_shadow(addr), ADDRESSABLE);

        map.set_shadow(addr, HEAP_LEFT_REDZONE);
        assert_eq!(map.get_shadow(addr), HEAP_LEFT_REDZONE);

        map.set_shadow(addr, ADDRESSABLE);
        assert_eq!(map.get_shadow(addr), ADDRESSABLE);
    }

    #[test]
    fn test_shadow_map_poison_range() {
        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x20000);

        let addr: u64 = 0x1000;
        map.poison_range(addr, 32, FREED);

        // Check each shadow granule in the range
        for offset in (0..32).step_by(8) {
            assert_eq!(map.get_shadow(addr + offset), FREED);
        }

        // Check adjacent range is still clean
        assert_eq!(map.get_shadow(addr + 40), ADDRESSABLE);
    }

    #[test]
    fn test_shadow_map_unpoison_range() {
        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x20000);

        let addr: u64 = 0x1000;
        map.poison_range(addr, 32, FREED);
        map.unpoison_range(addr, 16);

        assert_eq!(map.get_shadow(addr), ADDRESSABLE);
        assert_eq!(map.get_shadow(addr + 8), ADDRESSABLE);
        assert_eq!(map.get_shadow(addr + 16), FREED);
    }

    #[test]
    fn test_shadow_map_check_access_addressable() {
        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x20000);

        assert!(map.check_access(0x100, 8, false).is_ok());
    }

    #[test]
    fn test_shadow_map_check_access_poisoned() {
        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x20000);

        map.set_shadow(0x100, HEAP_RIGHT_REDZONE);
        assert!(map.check_access(0x100, 8, false).is_err());
    }

    #[test]
    fn test_shadow_map_check_access_partial_ok() {
        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x20000);

        map.set_shadow(0x100, PARTIAL4);
        // Access 4 bytes at offset 0 should be OK
        assert!(map.check_access(0x100, 4, false).is_ok());
    }

    #[test]
    fn test_shadow_map_check_access_partial_fail() {
        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x20000);

        map.set_shadow(0x100, PARTIAL4);
        // Access 5 bytes at offset 0 should fail
        assert!(map.check_access(0x100, 5, false).is_err());
    }

    #[test]
    fn test_shadow_map_check_8byte_load() {
        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x20000);

        // Aligned 8-byte access to addressable memory
        assert!(map.check_8byte_load(0x100).is_ok());

        // Aligned 8-byte access to poisoned memory
        map.set_shadow(0x100, HEAP_LEFT_REDZONE);
        assert!(map.check_8byte_load(0x100).is_err());
    }

    #[test]
    fn test_shadow_map_check_16byte() {
        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x20000);

        assert!(map.check_16byte_load(0x100).is_ok());

        map.set_shadow(0x108, HEAP_RIGHT_REDZONE);
        assert!(map.check_16byte_load(0x100).is_err()); // second half
    }

    #[test]
    fn test_shadow_map_reset() {
        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x20000);

        map.poison_range(0x100, 64, FREED);
        assert_eq!(map.get_shadow(0x100), FREED);

        map.reset();
        assert_eq!(map.get_shadow(0x100), ADDRESSABLE);
    }

    #[test]
    fn test_shadow_map_find_poisoned_regions() {
        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x20000);

        map.poison_range(0x1000, 32, FREED);
        map.poison_range(0x2000, 16, HEAP_LEFT_REDZONE);

        let regions = map.find_poisoned_regions();
        assert!(!regions.is_empty());

        // Should find at least the freed region
        let freed_regions: Vec<_> = regions.iter().filter(|(_, _, v)| *v == FREED).collect();
        assert!(!freed_regions.is_empty());
    }

    #[test]
    fn test_shadow_map_set_partial_range() {
        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x20000);

        // Set 12 bytes starting at address 0x1004 (offset 4 in granule)
        map.set_partial_range(0x1004, 12);

        // First granule (0x1000): offset 4, size up to 4 within this granule
        assert!(map.get_shadow(0x1000) >= 4);
    }

    // ------------------------------------------------------------------
    // ASan stack frame tests
    // ------------------------------------------------------------------

    #[test]
    fn test_stack_var_creation() {
        let var = X86ASanStackVar::new("buf", -64, 32, 8);
        assert_eq!(var.name, "buf");
        assert_eq!(var.size, 32);
        assert_eq!(var.alignment, 8);
        assert!(var.left_redzone_size >= X86_ASAN_MIN_REDZONE_SIZE);
        assert!(var.right_redzone_size >= X86_ASAN_MIN_REDZONE_SIZE);
    }

    #[test]
    fn test_stack_var_total_size() {
        let var = X86ASanStackVar::new("buf", -64, 32, 8);
        let total = var.total_size();
        assert_eq!(total, var.left_redzone_size + 32 + var.right_redzone_size);
    }

    #[test]
    fn test_stack_var_with_use_after_scope() {
        let var = X86ASanStackVar::new("buf", -64, 32, 8).with_use_after_scope();
        assert!(var.use_after_scope);
    }

    #[test]
    fn test_stack_var_with_use_after_return() {
        let var = X86ASanStackVar::new("buf", -64, 32, 8).with_use_after_return();
        assert!(var.use_after_return);
    }

    #[test]
    fn test_stack_frame_add_variable() {
        let mut frame = X86ASanStackFrame::new();
        assert_eq!(frame.variables.len(), 0);

        let var = X86ASanStackVar::new("buf", -64, 32, 8);
        frame.add_variable(var);
        assert_eq!(frame.variables.len(), 1);
        assert!(frame.total_frame_size > 0);
    }

    #[test]
    fn test_stack_frame_add_multiple_variables() {
        let mut frame = X86ASanStackFrame::new();

        frame.add_variable(X86ASanStackVar::new("a", -64, 16, 8));
        frame.add_variable(X86ASanStackVar::new("b", -128, 32, 16));
        frame.add_variable(X86ASanStackVar::new("c", -256, 64, 32));

        assert_eq!(frame.variables.len(), 3);
        assert!(frame.total_frame_size >= 16 + 32 + 64 + 6 * 32); // sizes + redzones
    }

    #[test]
    fn test_stack_frame_compute_shadow_operations() {
        let mut frame = X86ASanStackFrame::new();
        frame.add_variable(X86ASanStackVar::new("x", -64, 32, 8));

        let (poison, unpoison) = frame.compute_shadow_operations(0x7fff0000);
        assert!(!poison.is_empty()); // should have redzone poison regions
        assert!(!unpoison.is_empty()); // should have variable unpoison regions
    }

    #[test]
    fn test_stack_frame_poison_all_on_exit() {
        let mut frame = X86ASanStackFrame::new();
        frame.add_variable(
            X86ASanStackVar::new("x", -64, 32, 8).with_use_after_scope(),
        );

        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x20000);

        frame.poison_all_on_exit(&mut map, 0x1000);

        // Variable region should now be poisoned
        // (exact offset depends on frame layout)
        assert!(frame.variables.len() > 0);
    }

    #[test]
    fn test_stack_frame_format_layout() {
        let mut frame = X86ASanStackFrame::new();
        frame.add_variable(X86ASanStackVar::new("buf", -64, 32, 8));
        let layout = frame.format_layout();
        assert!(layout.contains("buf"));
        assert!(layout.contains("vars"));
    }

    // ------------------------------------------------------------------
    // Fake stack tests
    // ------------------------------------------------------------------

    #[test]
    fn test_fake_stack_default() {
        let fs = X86ASanFakeStack::default_sized();
        assert_eq!(fs.max_entries, X86_ASAN_FAKE_STACK_MAX_ENTRIES);
        assert_eq!(fs.depth, 0);
    }

    #[test]
    fn test_fake_stack_push_pop() {
        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x20000);

        let mut fs = X86ASanFakeStack::default_sized();

        let mut frame = X86ASanStackFrame::new();
        frame.add_variable(X86ASanStackVar::new("x", -64, 32, 8));

        let fake_base = fs.push("test_fn", 0x7fff0000, &frame);
        assert!(fake_base > 0);

        let entry = fs.pop(&mut map, "test_fn");
        assert!(entry.is_some());
        assert!(!entry.unwrap().is_active);
    }

    #[test]
    fn test_fake_stack_check_use_after_return() {
        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x20000);

        let mut fs = X86ASanFakeStack::default_sized();

        let mut frame = X86ASanStackFrame::new();
        frame.add_variable(X86ASanStackVar::new("y", -64, 64, 8));

        let fake_base = fs.push("uar_fn", 0x7fff0000, &frame);
        fs.pop(&mut map, "uar_fn");

        // Access to the freed fake frame
        let result = fs.check_use_after_return(fake_base + 8);
        assert!(result.is_some());
        assert_eq!(result.unwrap().function_name, "uar_fn");
    }

    #[test]
    fn test_fake_stack_eviction() {
        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x20000);

        let mut fs = X86ASanFakeStack::new(0, 1024 * 1024, 5);

        let frame = X86ASanStackFrame::new();

        for i in 0..10 {
            fs.push(&format!("fn{}", i), 0x7fff0000, &frame);
        }

        // Should not exceed max_entries
        assert!(fs.active_count() <= 5);
    }

    // ------------------------------------------------------------------
    // Scope tracker tests
    // ------------------------------------------------------------------

    #[test]
    fn test_scope_tracker_enter_leave() {
        let mut st = X86ASanScopeTracker::new();
        assert_eq!(st.current_depth(), 0);

        st.enter_scope();
        assert_eq!(st.current_depth(), 1);

        st.enter_scope();
        assert_eq!(st.current_depth(), 2);

        st.exit_scope();
        assert_eq!(st.current_depth(), 1);

        st.exit_scope();
        assert_eq!(st.current_depth(), 0);
    }

    #[test]
    fn test_scope_tracker_register_var() {
        let mut st = X86ASanScopeTracker::new();
        st.enter_function("test");

        st.enter_scope();
        let id = st.register_var("x");
        assert!(st.is_in_scope("x"));

        st.exit_scope();
        assert!(!st.is_in_scope("x"));
    }

    #[test]
    fn test_scope_tracker_nested_scopes() {
        let mut st = X86ASanScopeTracker::new();
        st.enter_function("nested");

        st.enter_scope();
        st.register_var("outer");
        assert!(st.is_in_scope("outer"));

        st.enter_scope();
        st.register_var("inner");
        assert!(st.is_in_scope("outer"));
        assert!(st.is_in_scope("inner"));

        // Exit inner scope
        let went_out = st.exit_scope();
        assert!(went_out.contains(&"inner".to_string()));
        assert!(!st.is_in_scope("inner"));
        assert!(st.is_in_scope("outer"));

        // Exit outer scope
        let went_out = st.exit_scope();
        assert!(went_out.contains(&"outer".to_string()));
        assert!(!st.is_in_scope("outer"));
    }

    // ------------------------------------------------------------------
    // Global instrumentation tests
    // ------------------------------------------------------------------

    #[test]
    fn test_global_protection_creation() {
        let gp = X86ASanGlobalProtection::new("my_global", 128, 32);
        assert_eq!(gp.name, "my_global");
        assert_eq!(gp.size, 128);
        assert!(gp.left_redzone_size >= X86_ASAN_GLOBAL_REDZONE_SIZE);
        assert!(gp.right_redzone_size >= X86_ASAN_GLOBAL_REDZONE_SIZE);
    }

    #[test]
    fn test_global_protection_padded_size() {
        let gp = X86ASanGlobalProtection::new("g", 128, 32);
        let padded = gp.padded_size();
        assert_eq!(padded, gp.left_redzone_size + 128 + gp.right_redzone_size);
    }

    #[test]
    fn test_global_instrumentation_add() {
        let mut gi = X86ASanGlobalInstrumentation::new();
        let gp = X86ASanGlobalProtection::new("g", 128, 32);
        gi.add_global(gp, 0x600000);
        assert_eq!(gi.count(), 1);
    }

    #[test]
    fn test_global_protection_with_odr_check() {
        let gp = X86ASanGlobalProtection::new("g", 128, 32)
            .with_odr_check(0xDEADBEEF, 0x1000);
        assert!(gp.odr_check);
        assert_eq!(gp.odr_hash, Some(0xDEADBEEF));
        assert_eq!(gp.odr_indicator, Some(0x1000));
    }

    // ------------------------------------------------------------------
    // ODR violation detector tests
    // ------------------------------------------------------------------

    #[test]
    fn test_odr_detector_consistent() {
        let mut odr = X86ASanODRViolationDetector::new();

        // First registration
        let violated = odr.register_global("global_x", 0xABCD, "a.cc", 10, 64);
        assert!(!violated);

        // Same hash: no violation
        let violated = odr.register_global("global_x", 0xABCD, "b.cc", 20, 64);
        assert!(!violated);
    }

    #[test]
    fn test_odr_detector_violation() {
        let mut odr = X86ASanODRViolationDetector::new();

        odr.register_global("global_y", 0x1111, "a.cc", 10, 64);
        let violated = odr.register_global("global_y", 0x2222, "b.cc", 20, 128);

        assert!(violated);
        assert!(odr.has_violation("global_y"));
        assert_eq!(odr.violation_count(), 1);
    }

    #[test]
    fn test_odr_compute_hash() {
        let h1 = X86ASanODRViolationDetector::compute_hash("foo", "int", 4);
        let h2 = X86ASanODRViolationDetector::compute_hash("foo", "int", 4);
        let h3 = X86ASanODRViolationDetector::compute_hash("foo", "long", 8);

        assert_eq!(h1, h2); // same
        assert_ne!(h1, h3); // different type/size
    }

    // ------------------------------------------------------------------
    // Container overflow tests
    // ------------------------------------------------------------------

    #[test]
    fn test_container_overflow_default() {
        let cod = X86ASanContainerOverflowDetector::new();
        assert!(cod.enabled);
        assert_eq!(cod.min_container_size, 32);
    }

    #[test]
    fn test_container_overflow_instrument() {
        let mut cod = X86ASanContainerOverflowDetector::new();
        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x20000);

        cod.instrument_container(&mut map, 0x1000, 128, "std::vector<int>");

        // Check that the intra-object redzone is poisoned
        let rz_addr = 0x1000 + 128 - cod.intra_object_redzone_size;
        assert!(cod.is_intra_object_overflow(&map, rz_addr));

        // The beginning should not be poisoned as container overflow
        assert!(!cod.is_intra_object_overflow(&map, 0x1000));
    }

    // ------------------------------------------------------------------
    // Allocator tests
    // ------------------------------------------------------------------

    #[test]
    fn test_allocator_creation() {
        let alloc = X86ASanAllocator::new();
        assert_eq!(alloc.allocation_count, 0);
        assert_eq!(alloc.current_bytes, 0);
    }

    #[test]
    fn test_allocator_alloc() {
        let mut alloc = X86ASanAllocator::new();
        let (ptr, size) = alloc.alloc(128, 16, X86ASanAllocKind::Malloc);
        assert!(ptr > 0);
        assert_eq!(size, 128);
        assert_eq!(alloc.allocation_count, 1);
        assert_eq!(alloc.current_bytes, 128);
    }

    #[test]
    fn test_allocator_alloc_free() {
        let mut alloc = X86ASanAllocator::new();
        let (ptr, _) = alloc.alloc(256, 16, X86ASanAllocKind::Malloc);
        assert_eq!(alloc.allocation_count, 1);

        let result = alloc.free(ptr, None);
        assert!(result.is_ok());
        assert_eq!(alloc.allocation_count, 0);
    }

    #[test]
    fn test_allocator_double_free() {
        let mut alloc = X86ASanAllocator::new();
        let (ptr, _) = alloc.alloc(64, 8, X86ASanAllocKind::Malloc);

        alloc.free(ptr, None).unwrap();
        let result = alloc.free(ptr, None);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), X86ASanErrorType::DoubleFree);
    }

    #[test]
    fn test_allocator_invalid_free() {
        let mut alloc = X86ASanAllocator::new();
        let result = alloc.free(0xDEADBEEF, None);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), X86ASanErrorType::InvalidFree);
    }

    #[test]
    fn test_allocator_mismatch_free() {
        let mut alloc = X86ASanAllocator::new();
        let (ptr, _) = alloc.alloc(128, 16, X86ASanAllocKind::Malloc);

        let result = alloc.free(ptr, Some(X86ASanAllocKind::Calloc));
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), X86ASanErrorType::AllocDeallocMismatch);
    }

    #[test]
    fn test_allocator_calloc() {
        let mut alloc = X86ASanAllocator::new();
        let result = alloc.calloc(10, 8, 16);
        assert!(result.is_ok());
        let (ptr, size) = result.unwrap();
        assert_eq!(size, 80);
        assert!(ptr > 0);
    }

    #[test]
    fn test_allocator_calloc_overflow() {
        let mut alloc = X86ASanAllocator::new();
        // nmemb * size would overflow u64
        let result = alloc.calloc(u64::MAX, 2, 16);
        assert!(result.is_err());
    }

    #[test]
    fn test_allocator_realloc() {
        let mut alloc = X86ASanAllocator::new();
        let (old_ptr, _) = alloc.alloc(64, 8, X86ASanAllocKind::Malloc);

        let result = alloc.realloc(old_ptr, 128, 16);
        assert!(result.is_ok());
        let (new_ptr, new_size) = result.unwrap();
        assert_eq!(new_size, 128);
        assert!(new_ptr != old_ptr); // may differ in simulated allocator
    }

    #[test]
    fn test_allocator_realloc_to_zero() {
        let mut alloc = X86ASanAllocator::new();
        let (old_ptr, _) = alloc.alloc(64, 8, X86ASanAllocKind::Malloc);

        let result = alloc.realloc(old_ptr, 0, 16);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), (0, 0));
        assert_eq!(alloc.allocation_count, 0);
    }

    #[test]
    fn test_allocator_realloc_null() {
        let mut alloc = X86ASanAllocator::new();
        let result = alloc.realloc(0, 128, 16);
        assert!(result.is_ok());
        assert_eq!(alloc.allocation_count, 1);
    }

    #[test]
    fn test_allocator_memalign() {
        let mut alloc = X86ASanAllocator::new();
        let (ptr, _) = alloc.memalign(64, 256);
        assert!(ptr > 0);
    }

    #[test]
    fn test_allocator_aligned_alloc() {
        let mut alloc = X86ASanAllocator::new();
        // size 64 is multiple of alignment 16
        let result = alloc.aligned_alloc(16, 64);
        assert!(result.is_ok());
    }

    #[test]
    fn test_allocator_aligned_alloc_not_multiple() {
        let mut alloc = X86ASanAllocator::new();
        let result = alloc.aligned_alloc(16, 63);
        assert!(result.is_err());
    }

    #[test]
    fn test_allocator_quarantine() {
        let mut alloc = X86ASanAllocator::new();
        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x20000);
        alloc.attach_shadow(&mut map);

        let (ptr, _) = alloc.alloc(256, 16, X86ASanAllocKind::Malloc);
        alloc.free(ptr, None).unwrap();

        // Freed block should be in quarantine
        assert!(alloc.is_quarantined(ptr).is_some());
    }

    #[test]
    fn test_allocator_detect_leaks() {
        let mut alloc = X86ASanAllocator::new();

        let (ptr1, _) = alloc.alloc(100, 8, X86ASanAllocKind::Malloc);
        let (ptr2, _) = alloc.alloc(200, 8, X86ASanAllocKind::Malloc);
        alloc.free(ptr2, None).unwrap();

        let leaks = alloc.detect_leaks();
        assert_eq!(leaks.len(), 1); // ptr1 is still allocated
    }

    #[test]
    fn test_allocator_stats() {
        let mut alloc = X86ASanAllocator::new();

        alloc.alloc(100, 8, X86ASanAllocKind::Malloc);
        alloc.alloc(200, 8, X86ASanAllocKind::Calloc);

        let stats = alloc.stats();
        assert_eq!(stats.allocation_count, 2);
        assert_eq!(stats.current_bytes, 300);
    }

    #[test]
    fn test_alloc_kind_as_str() {
        assert_eq!(X86ASanAllocKind::Malloc.as_str(), "malloc");
        assert_eq!(X86ASanAllocKind::Calloc.as_str(), "calloc");
        assert_eq!(X86ASanAllocKind::Realloc.as_str(), "realloc");
        assert_eq!(X86ASanAllocKind::AlignedAlloc.as_str(), "aligned_alloc");
    }

    // ------------------------------------------------------------------
    // Stack trace tests
    // ------------------------------------------------------------------

    #[test]
    fn test_stack_frame_entry_new() {
        let entry = X86ASanStackFrameEntry::new(0x400100, 0x7fff0000);
        assert_eq!(entry.ip, 0x400100);
        assert_eq!(entry.bp, 0x7fff0000);
        assert!(!entry.symbolized);
    }

    #[test]
    fn test_stack_frame_entry_format() {
        let entry = X86ASanStackFrameEntry::new(0x400123, 0x7fff0000);
        let formatted = entry.format();
        assert!(formatted.contains("0x400123"));
    }

    #[test]
    fn test_stack_trace_collector_creation() {
        let sc = X86ASanStackTraceCollector::new();
        assert!(sc.fast_unwind);
        assert_eq!(sc.max_depth, X86_ASAN_MAX_STACK_DEPTH);
        assert!(sc.symbolize);
    }

    #[test]
    fn test_stack_trace_capture() {
        let collector = X86ASanStackTraceCollector::new();
        let frames = collector.capture_stack_trace(0x400200, 0x7fff0000, 0x7ffeff00);

        // Should at least have the first IPC frame
        assert!(!frames.is_empty());
        assert_eq!(frames[0].ip, 0x400200);
    }

    #[test]
    fn test_stack_trace_register_symbol() {
        let mut collector = X86ASanStackTraceCollector::new();
        collector.register_symbol(
            0x400300,
            "my_function",
            Some("main.cc"),
            Some(42),
            Some(10),
        );

        let frames = collector.capture_stack_trace(0x400300, 0x7fff0000, 0x7ffeff00);
        let frame = &frames[0];
        assert_eq!(frame.function, Some("my_function".to_string()));
        assert!(frame.symbolized);
    }

    #[test]
    fn test_stack_trace_hash() {
        let a = vec![
            X86ASanStackFrameEntry::new(0x400100, 0x7fff0000),
            X86ASanStackFrameEntry::new(0x400200, 0x7ffff000),
        ];
        let b = vec![
            X86ASanStackFrameEntry::new(0x400100, 0x7fff0000),
            X86ASanStackFrameEntry::new(0x400200, 0x7ffff000),
        ];
        let c = vec![
            X86ASanStackFrameEntry::new(0x400999, 0x7fff0000),
        ];

        assert_eq!(
            X86ASanStackTraceCollector::hash_stack_trace(&a),
            X86ASanStackTraceCollector::hash_stack_trace(&b)
        );
        assert_ne!(
            X86ASanStackTraceCollector::hash_stack_trace(&a),
            X86ASanStackTraceCollector::hash_stack_trace(&c)
        );
    }

    // ------------------------------------------------------------------
    // Error report tests
    // ------------------------------------------------------------------

    #[test]
    fn test_error_report_new() {
        let report = X86ASanErrorReport::new(
            X86ASanErrorType::HeapBufferOverflow,
            0x1000,
            8,
            X86ASanAccessType::Write,
            HEAP_RIGHT_REDZONE,
        );
        assert_eq!(report.error_type, X86ASanErrorType::HeapBufferOverflow);
        assert_eq!(report.address, 0x1000);
        assert_eq!(report.access_size, 8);
        assert!(!report.is_recoverable || report.is_recoverable); // default
    }

    #[test]
    fn test_error_report_format() {
        let report = X86ASanErrorReport::new(
            X86ASanErrorType::HeapUseAfterFree,
            0x1000,
            4,
            X86ASanAccessType::Read,
            FREED,
        );
        let formatted = report.format_report();
        assert!(formatted.contains("heap-use-after-free"));
        assert!(formatted.contains("0x0000000000001000"));
        assert!(formatted.contains("READ"));
    }

    #[test]
    fn test_error_report_summary() {
        let report = X86ASanErrorReport::new(
            X86ASanErrorType::StackBufferOverflow,
            0x2000,
            8,
            X86ASanAccessType::Write,
            STACK_RIGHT_REDZONE,
        );
        let summary = report.summary();
        assert!(summary.contains("stack-buffer-overflow"));
        assert!(summary.contains("0x2000"));
    }

    #[test]
    fn test_error_type_display() {
        assert_eq!(
            format!("{}", X86ASanErrorType::HeapBufferOverflow),
            "heap-buffer-overflow"
        );
        assert_eq!(
            format!("{}", X86ASanErrorType::DoubleFree),
            "double-free"
        );
        assert_eq!(
            format!("{}", X86ASanErrorType::MemoryLeak),
            "memory-leak"
        );
    }

    #[test]
    fn test_access_type_display() {
        assert_eq!(format!("{}", X86ASanAccessType::Read), "READ");
        assert_eq!(format!("{}", X86ASanAccessType::Write), "WRITE");
        assert_eq!(format!("{}", X86ASanAccessType::Free), "FREE");
    }

    // ------------------------------------------------------------------
    // Error suppression tests
    // ------------------------------------------------------------------

    #[test]
    fn test_suppression_parse_empty() {
        let mut supp = X86ASanErrorSuppression::new();
        supp.parse_suppressions("");
        assert!(supp.rules.is_empty());
    }

    #[test]
    fn test_suppression_parse_function() {
        let mut supp = X86ASanErrorSuppression::new();
        let input = "heap-buffer-overflow:\nfun:bad_function\n";
        supp.parse_suppressions(input);

        assert_eq!(supp.rules.len(), 1);
        assert_eq!(supp.rules[0].pattern, "bad_function");
        assert_eq!(
            supp.rules[0].error_type,
            Some(X86ASanErrorType::HeapBufferOverflow)
        );
    }

    #[test]
    fn test_suppression_matches() {
        let mut supp = X86ASanErrorSuppression::new();
        supp.parse_suppressions("fun:vulnerable_fn\n");
        supp.enabled = true;

        let mut report = X86ASanErrorReport::new(
            X86ASanErrorType::HeapBufferOverflow,
            0x1000,
            8,
            X86ASanAccessType::Write,
            HEAP_RIGHT_REDZONE,
        );

        // No stack traces — no match
        assert!(!supp.should_suppress(&report));

        // Add a matching frame
        let mut frame = X86ASanStackFrameEntry::new(0x400100, 0x7fff0000);
        frame.function = Some("vulnerable_fn".to_string());
        report.stack_trace.push(frame);

        assert!(supp.should_suppress(&report));
        assert_eq!(supp.suppressed_count, 1);
    }

    // ------------------------------------------------------------------
    // X86ASanFull tests
    // ------------------------------------------------------------------

    #[test]
    fn test_asan_full_new() {
        let asan = X86ASanFull::new();
        assert!(!asan.activated);
        assert!(asan.shadow.shadow_allocated);
        assert!(asan.error_reports.is_empty());
    }

    #[test]
    fn test_asan_full_i386() {
        let asan = X86ASanFull::new_i386();
        assert_eq!(asan.shadow.arch, X86AsanTargetArch::I386);
        assert_eq!(asan.shadow.shadow_offset, X86_ASAN_SHADOW_OFFSET_32);
    }

    #[test]
    fn test_asan_full_activate_deactivate() {
        let mut asan = X86ASanFull::new();
        assert!(!asan.activated);

        asan.activate();
        assert!(asan.activated);

        asan.deactivate();
        assert!(!asan.activated);
    }

    #[test]
    fn test_asan_full_check_memory_access_clean() {
        let mut asan = X86ASanFull::new();
        asan.activate();

        // Access to clean memory should succeed
        let result = asan.check_memory_access(0x1000, 8, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_asan_full_check_memory_access_poisoned() {
        let mut asan = X86ASanFull::new();
        asan.activate();

        // Poison some memory
        asan.shadow.poison_range(0x1000, 32, FREED);

        // Access to poisoned memory should fail
        let result = asan.check_memory_access(0x1000, 8, false);
        assert!(result.is_err());

        let report = result.unwrap_err();
        assert_eq!(report.error_type, X86ASanErrorType::HeapUseAfterFree);
    }

    #[test]
    fn test_asan_full_deactivated_no_check() {
        let mut asan = X86ASanFull::new();
        // Not activated

        asan.shadow.poison_range(0x1000, 32, FREED);

        // Access should pass because ASan is deactivated
        let result = asan.check_memory_access(0x1000, 8, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_asan_full_stack_frame() {
        let mut asan = X86ASanFull::new();
        asan.activate();

        asan.begin_stack_frame();
        asan.add_stack_variable("buf", 128, 32);
        asan.add_stack_variable("idx", 8, 8);

        let frame = asan.finish_stack_frame(0x7fff0000);
        assert!(frame.is_some());
        assert_eq!(frame.unwrap().variables.len(), 2);
    }

    #[test]
    fn test_asan_full_fake_stack_push_pop() {
        let mut asan = X86ASanFull::new();
        asan.activate();

        asan.begin_stack_frame();
        asan.add_stack_variable("local", 64, 8);

        let fake_base = asan.push_fake_stack("my_func", 0x7fff0000);
        assert!(fake_base.is_some());

        asan.pop_fake_stack("my_func");
        // After pop, the fake frame should be poisoned
    }

    #[test]
    fn test_asan_full_register_global() {
        let mut asan = X86ASanFull::new();
        asan.activate();

        asan.register_global("important_global", 0x600000, 256, 32);
        assert_eq!(asan.global_instr.count(), 1);
    }

    #[test]
    fn test_asan_full_scope_tracking() {
        let mut asan = X86ASanFull::new();
        asan.activate();

        asan.enter_function("test_scope");
        asan.enter_scope();
        asan.register_stack_var("x");

        // x should be in scope
        assert!(asan.scope_tracker.is_in_scope("x"));

        asan.exit_scope(0x7fff0000);
        // x should now be out of scope
        assert!(!asan.scope_tracker.is_in_scope("x"));
    }

    #[test]
    fn test_asan_full_leak_check() {
        let mut asan = X86ASanFull::new();
        asan.activate();

        // Allocate without freeing
        asan.allocator.alloc(128, 16, X86ASanAllocKind::Malloc);

        let leaks = asan.leak_check();
        assert!(!leaks.is_empty());
        assert_eq!(leaks[0].error_type, X86ASanErrorType::MemoryLeak);
    }

    #[test]
    fn test_asan_full_poison_unpoison_memory() {
        let mut asan = X86ASanFull::new();
        asan.activate();

        let addr: u64 = 0x5000;
        assert!(!asan.is_poisoned(addr));

        asan.poison_memory_region(addr, 64);
        assert!(asan.is_poisoned(addr));

        asan.unpoison_memory_region(addr, 64);
        assert!(!asan.is_poisoned(addr));
    }

    #[test]
    fn test_asan_full_reset() {
        let mut asan = X86ASanFull::new();
        asan.activate();

        asan.shadow.poison_range(0x1000, 64, FREED);
        asan.allocator.alloc(128, 16, X86ASanAllocKind::Malloc);

        asan.reset();

        assert!(asan.error_reports.is_empty());
        assert!(asan.allocator.detect_leaks().is_empty());
        // Shadow should be clean
        assert_eq!(asan.shadow.get_shadow(0x1000), ADDRESSABLE);
    }

    #[test]
    fn test_asan_full_stats() {
        let mut asan = X86ASanFull::new();
        asan.activate();

        asan.allocator.alloc(256, 16, X86ASanAllocKind::Malloc);

        let stats = asan.stats();
        assert!(stats.shadow_allocated);
        assert!(stats.total_allocations > 0);
    }

    #[test]
    fn test_asan_full_classify_error() {
        let asan = X86ASanFull::new();
        assert_eq!(
            asan.classify_error(HEAP_LEFT_REDZONE),
            X86ASanErrorType::HeapBufferOverflow
        );
        assert_eq!(
            asan.classify_error(STACK_LEFT_REDZONE),
            X86ASanErrorType::StackBufferOverflow
        );
        assert_eq!(
            asan.classify_error(FREED),
            X86ASanErrorType::HeapUseAfterFree
        );
        assert_eq!(
            asan.classify_error(GLOBAL_REDZONE),
            X86ASanErrorType::GlobalBufferOverflow
        );
        assert_eq!(
            asan.classify_error(STACK_UAR_REDZONE),
            X86ASanErrorType::StackUseAfterReturn
        );
        assert_eq!(
            asan.classify_error(STACK_USE_AFTER_SCOPE),
            X86ASanErrorType::StackUseAfterScope
        );
    }

    #[test]
    fn test_asan_full_report_error() {
        let mut asan = X86ASanFull::new();
        asan.activate();
        asan.halt_on_error = false;

        let report = X86ASanErrorReport::new(
            X86ASanErrorType::HeapBufferOverflow,
            0x1000,
            8,
            X86ASanAccessType::Write,
            HEAP_RIGHT_REDZONE,
        );

        asan.report_error(report);
        assert_eq!(asan.error_reports.len(), 1);
    }

    #[test]
    fn test_asan_full_report_deduplication() {
        let mut asan = X86ASanFull::new();
        asan.activate();

        let mut report1 = X86ASanErrorReport::new(
            X86ASanErrorType::HeapBufferOverflow,
            0x1000,
            8,
            X86ASanAccessType::Write,
            HEAP_RIGHT_REDZONE,
        );
        report1.stack_trace = vec![X86ASanStackFrameEntry::new(0x400100, 0x7fff0000)];

        let mut report2 = report1.clone(); // same stack trace

        asan.report_error(report1);
        assert_eq!(asan.error_reports.len(), 1);

        asan.report_error(report2);
        // Should be deduplicated — still 1
        assert_eq!(asan.error_reports.len(), 1);
    }

    #[test]
    fn test_asan_full_load_suppressions_empty() {
        let mut asan = X86ASanFull::new();
        // Loading non-existent file should fail
        let result = asan.load_suppressions("/nonexistent/path");
        assert!(result.is_err());
    }

    // ------------------------------------------------------------------
    // HWASan tag generator tests
    // ------------------------------------------------------------------

    #[test]
    fn test_hwasan_tag_generator_new() {
        let gen = X86HWASanTagGenerator::new(42);
        assert_eq!(gen.seed, 42);
    }

    #[test]
    fn test_hwasan_tag_generator_generate_tag() {
        let mut gen = X86HWASanTagGenerator::new(12345);
        let tag = gen.generate_tag();
        assert!(tag >= 1);
        assert!(tag <= X86_HWASAN_MAX_TAG);
    }

    #[test]
    fn test_hwasan_tag_generator_unique_tags() {
        let mut gen = X86HWASanTagGenerator::new(67890);
        let mut seen = HashSet::new();

        for _ in 0..50 {
            let tag = gen.generate_tag();
            seen.insert(tag);
        }

        // With 50 tags, we should have many unique ones (at least 20)
        assert!(seen.len() >= 20);
    }

    #[test]
    fn test_hwasan_tag_generator_no_zero_tag() {
        let mut gen = X86HWASanTagGenerator::new(11111);
        for _ in 0..100 {
            let tag = gen.generate_tag();
            assert_ne!(tag, 0, "Tag generator should never produce tag 0");
        }
    }

    #[test]
    fn test_hwasan_tag_generator_allocate_free() {
        let mut gen = X86HWASanTagGenerator::new(22222);
        let initial = gen.available_tags();

        let tag = gen.allocate_tag();
        assert!(gen.available_tags() < initial);

        gen.free_tag(tag);
        assert_eq!(gen.available_tags(), initial);
    }

    // ------------------------------------------------------------------
    // HWASan tagged pointer tests
    // ------------------------------------------------------------------

    #[test]
    fn test_hwasan_tagged_ptr_get_tag() {
        let addr: u64 = 0x7fff00001000;
        let tag: u8 = 42;
        let tagged = (addr & X86_HWASAN_ADDR_MASK) | ((tag as u64) << X86_HWASAN_TAG_SHIFT);

        assert_eq!(X86HWASanTaggedPtr::get_tag(tagged), 42);
    }

    #[test]
    fn test_hwasan_tagged_ptr_strip_tag() {
        let addr: u64 = 0x7fff00001000;
        let tagged = (addr & X86_HWASAN_ADDR_MASK) | (0xABu64 << X86_HWASAN_TAG_SHIFT);

        assert_eq!(X86HWASanTaggedPtr::strip_tag(tagged), addr);
    }

    #[test]
    fn test_hwasan_tagged_ptr_is_tagged() {
        let addr: u64 = 0x7fff00001000;
        let tagged = (addr & X86_HWASAN_ADDR_MASK) | (0x42u64 << X86_HWASAN_TAG_SHIFT);

        assert!(X86HWASanTaggedPtr::is_tagged(tagged));
        assert!(!X86HWASanTaggedPtr::is_tagged(addr));
    }

    #[test]
    fn test_hwasan_tagged_ptr_tags_match() {
        let tag_a = 0x10;
        let tag_b = 0x10;
        let tag_c = 0x20;

        let ptr_a = (0x1000u64 & X86_HWASAN_ADDR_MASK) | ((tag_a as u64) << X86_HWASAN_TAG_SHIFT);
        let ptr_b = (0x2000u64 & X86_HWASAN_ADDR_MASK) | ((tag_b as u64) << X86_HWASAN_TAG_SHIFT);
        let ptr_c = (0x3000u64 & X86_HWASAN_ADDR_MASK) | ((tag_c as u64) << X86_HWASAN_TAG_SHIFT);

        assert!(X86HWASanTaggedPtr::tags_match(ptr_a, ptr_b));
        assert!(!X86HWASanTaggedPtr::tags_match(ptr_a, ptr_c));
    }

    // ------------------------------------------------------------------
    // HWASan memory tag table tests
    // ------------------------------------------------------------------

    #[test]
    fn test_hwasan_memory_tag_table_set_get() {
        let mut table = X86HWASanMemoryTagTable::new();
        let addr: u64 = 0x1000;

        table.set_tag(addr, 42);
        assert_eq!(table.get_tag(addr), Some(42));

        // Check nearby granule
        assert_eq!(table.get_tag(addr + X86_HWASAN_GRANULE_SIZE), None);
    }

    #[test]
    fn test_hwasan_memory_tag_table_neighbor() {
        let mut table = X86HWASanMemoryTagTable::new();

        table.set_tag(0x1000, 1);
        table.set_tag(0x1010, 2); // adjacent granule (16 bytes apart)

        assert_eq!(table.get_tag(0x1000), Some(1));
        assert_eq!(table.get_tag(0x1010), Some(2));
        assert_eq!(table.get_tag(0x1008), Some(1)); // within first granule
    }

    #[test]
    fn test_hwasan_memory_tag_table_range() {
        let mut table = X86HWASanMemoryTagTable::new();

        table.set_tags_range(0x1000, 64, 7);

        // All granules in 64-byte range should be tagged
        for offset in (0..64).step_by(16) {
            assert_eq!(table.get_tag(0x1000 + offset), Some(7));
        }

        // Just outside
        assert_eq!(table.get_tag(0x1000 + 64), None);
    }

    #[test]
    fn test_hwasan_memory_tag_table_clear_range() {
        let mut table = X86HWASanMemoryTagTable::new();

        table.set_tags_range(0x1000, 64, 7);
        table.clear_range(0x1000, 32);

        // First 32 bytes cleared
        assert_eq!(table.get_tag(0x1000), None);
        assert_eq!(table.get_tag(0x1010), None);

        // Next 32 bytes still tagged
        assert_eq!(table.get_tag(0x1020), Some(7));
    }

    #[test]
    fn test_hwasan_memory_tag_table_trace_ids() {
        let mut table = X86HWASanMemoryTagTable::new();

        table.set_alloc_trace(0x1000, 100);
        table.set_free_trace(0x1000, 200);

        assert_eq!(table.get_alloc_trace(0x1000), Some(100));
        assert_eq!(table.get_free_trace(0x1000), Some(200));
    }

    #[test]
    fn test_hwasan_memory_tag_table_short_granules() {
        let mut table = X86HWASanMemoryTagTable::new();

        table.set_short_granule_tags(0x1000, 7, 3);
        assert_eq!(table.short_granule_count, 1);

        // Access 5 bytes (within short granule)
        let result = table.check_short_granule(0x1000, 5);
        assert_eq!(result, Some(true));

        // Access 8 bytes (exceeds short granule)
        let result = table.check_short_granule(0x1000, 8);
        assert_eq!(result, Some(false));
    }

    // ------------------------------------------------------------------
    // HWASan stack/heap/global tagging tests
    // ------------------------------------------------------------------

    #[test]
    fn test_hwasan_stack_tagging_begin_frame() {
        let mut st = X86HWASanStackTagging::new();
        let mut gen = X86HWASanTagGenerator::new(42);

        let tag = st.begin_frame(&mut gen);
        assert!(tag >= 1 && tag <= X86_HWASAN_MAX_TAG);
    }

    #[test]
    fn test_hwasan_stack_tagging_tag_variable() {
        let mut st = X86HWASanStackTagging::new();
        let mut gen = X86HWASanTagGenerator::new(42);

        st.begin_frame(&mut gen);
        let tagged = st.tag_variable(0x7fff0000, 32);

        let extracted = X86HWASanTaggedPtr::get_tag(tagged);
        assert!(extracted != 0);
    }

    #[test]
    fn test_hwasan_heap_tagging() {
        let mut ht = X86HWASanHeapTagging::new();

        let tagged = ht.tag_allocation(0x600000, 128);
        let tag = X86HWASanTaggedPtr::get_tag(tagged);
        assert!(tag != 0);

        // Check that the allocation tag is stored
        assert!(ht.alloc_tags.contains_key(&0x600000));
    }

    #[test]
    fn test_hwasan_heap_tagging_disabled() {
        let mut ht = X86HWASanHeapTagging::new();
        ht.enabled = false;

        let tagged = ht.tag_allocation(0x600000, 128);
        assert_eq!(tagged, 0x600000); // unchanged
    }

    #[test]
    fn test_hwasan_global_tagging() {
        let mut gt = X86HWASanGlobalTagging::new();

        let tagged = gt.tag_global("my_global_var", 0x700000, 256);
        let tag = X86HWASanTaggedPtr::get_tag(tagged);
        assert!(tag != 0);

        assert_eq!(gt.get_global_tag("my_global_var"), Some(tag));
    }

    // ------------------------------------------------------------------
    // HWASan tag mismatch report tests
    // ------------------------------------------------------------------

    #[test]
    fn test_hwasan_tag_mismatch_report_new() {
        let report = X86HWASanTagMismatchReport::new(
            0x7fff00001000,
            0x7fff00001000,
            0x42,
            0x99,
            8,
            true,
        );

        assert_eq!(report.pointer_tag, 0x42);
        assert_eq!(report.memory_tag, 0x99);
        assert!(report.is_write);
        assert!(report.likely_buffer_overflow);
    }

    #[test]
    fn test_hwasan_tag_mismatch_report_uaf() {
        // UAF tags: 0xFE or 0xFD
        let report = X86HWASanTagMismatchReport::new(
            0x7fff00001000,
            0x7fff00001000,
            0x10,
            0xFE,
            4,
            false,
        );

        assert!(report.likely_uaf);
    }

    #[test]
    fn test_hwasan_tag_mismatch_report_format() {
        let report = X86HWASanTagMismatchReport::new(
            0x7fff00001000,
            0x7fff00001000,
            0xAB,
            0xCD,
            4,
            true,
        );

        let formatted = report.format();
        assert!(formatted.contains("tag-mismatch"));
        assert!(formatted.contains("WRITE"));
        assert!(formatted.contains("ab/cd"));
    }

    #[test]
    fn test_hwasan_tag_mismatch_report_summary() {
        let report = X86HWASanTagMismatchReport::new(
            0x7fff00001000,
            0x7fff00001000,
            1,
            2,
            8,
            false,
        );
        let summary = report.summary();
        assert!(summary.contains("tag-mismatch"));
        assert!(summary.contains("0x01"));
        assert!(summary.contains("0x02"));
    }

    // ------------------------------------------------------------------
    // HWASan runtime tests
    // ------------------------------------------------------------------

    #[test]
    fn test_hwasan_runtime_new() {
        let rt = X86HWASanRuntime::new();
        assert!(!rt.enabled);
        assert!(!rt.initialized);
        assert!(rt.tag_stack);
        assert!(rt.tag_heap);
    }

    #[test]
    fn test_hwasan_runtime_init() {
        let mut rt = X86HWASanRuntime::new();
        rt.init(12345);
        assert!(rt.initialized);
        assert_eq!(rt.tag_generator.seed, 12345);
    }

    #[test]
    fn test_hwasan_runtime_generate_tag() {
        let mut rt = X86HWASanRuntime::new();
        rt.init(42);

        let tag = rt.generate_tag();
        assert!(tag >= 1 && tag <= X86_HWASAN_MAX_TAG);
    }

    #[test]
    fn test_hwasan_runtime_tag_pointer() {
        let mut rt = X86HWASanRuntime::new();
        rt.init(42);

        let tagged = rt.tag_pointer(0x1000, 0xAB);
        let extracted = rt.extract_tag(tagged);
        assert_eq!(extracted, 0xAB);

        let stripped = rt.strip_tag(tagged);
        assert_eq!(stripped, 0x1000);
    }

    #[test]
    fn test_hwasan_runtime_probe_mte() {
        let mut rt = X86HWASanRuntime::new();
        rt.use_mte = true;
        // On X86, MTE probe should always return false
        assert!(!rt.probe_mte());
    }

    #[test]
    fn test_hwasan_runtime_shadow_address() {
        let user_addr: u64 = 0x7fff00001000;
        let kernel_addr: u64 = 0xffffff0000001000;

        let user_shadow = X86HWASanRuntime::shadow_address(user_addr);
        let kernel_shadow = X86HWASanRuntime::shadow_address(kernel_addr);

        // Kernel shadow should use the kernel shadow offset
        assert!(kernel_shadow > X86_HWASAN_KERNEL_SHADOW_OFFSET);
        // User shadow should be within user range
        assert!(user_shadow < X86_HWASAN_KERNEL_SHADOW_OFFSET);
    }

    #[test]
    fn test_hwasan_runtime_check_disabled() {
        let mut rt = X86HWASanRuntime::new();
        rt.init(42);
        // rt.enabled is false, so checks should pass
        let result = rt.check_memory_access(0x1000, 8, true);
        assert!(result.is_ok());
    }

    #[test]
    fn test_hwasan_runtime_stats() {
        let mut rt = X86HWASanRuntime::new();
        rt.init(42);

        let stats = rt.stats();
        assert!(!stats.initialized || stats.initialized); // init sets it
        assert_eq!(stats.mismatches, 0);
    }

    // ------------------------------------------------------------------
    // HWASan kernel tests
    // ------------------------------------------------------------------

    #[test]
    fn test_hwasan_kernel_new() {
        let k = X86HWASanKernel::new();
        assert!(!k.enabled);
        assert_eq!(k.shadow_offset, X86_HWASAN_KERNEL_SHADOW_OFFSET);
    }

    #[test]
    fn test_hwasan_kernel_virt_to_shadow() {
        let k = X86HWASanKernel::new();
        let vaddr: u64 = 0xffff888000000000;
        let shadow = k.virt_to_shadow(vaddr);
        let expected = (vaddr >> X86_HWASAN_KERNEL_SHADOW_SCALE)
            + X86_HWASAN_KERNEL_SHADOW_OFFSET;
        assert_eq!(shadow, expected);
    }

    #[test]
    fn test_hwasan_kernel_slab_tagging() {
        let mut k = X86HWASanKernel::new();
        k.enabled = true;
        k.tag_slab = true;

        let tagged = k.tag_slab_allocation(0xffff888000001000, 64);
        let tag = X86HWASanTaggedPtr::get_tag(tagged);
        assert!(tag != 0);
    }

    #[test]
    fn test_hwasan_kernel_disabled_tagging() {
        let k = X86HWASanKernel::new();
        // Not enabled
        let tagged = k.tag_slab_allocation(0xffff888000001000, 64);
        assert_eq!(tagged, 0xffff888000001000); // unchanged
    }

    #[test]
    fn test_hwasan_kernel_page_align() {
        let page_size: u64 = 4096;

        assert_eq!(
            X86HWASanKernel::page_align_down(0x12345, page_size),
            0x12000
        );
        assert_eq!(
            X86HWASanKernel::page_align_down(0x12000, page_size),
            0x12000
        );

        assert_eq!(
            X86HWASanKernel::page_align_up(0x12345, page_size),
            0x13000
        );
        assert_eq!(
            X86HWASanKernel::page_align_up(0x12000, page_size),
            0x12000
        );
    }

    #[test]
    fn test_hwasan_kernel_init_boot() {
        let mut k = X86HWASanKernel::new();
        assert!(!k.enabled);

        k.init_boot();
        assert!(k.enabled);
    }

    // ------------------------------------------------------------------
    // Orchestrator tests
    // ------------------------------------------------------------------

    #[test]
    fn test_orchestrator_new() {
        let orch = X86ASanFullOrchestrator::new();
        assert!(orch.active.asan);
        assert!(!orch.active.hwasan);
    }

    #[test]
    fn test_orchestrator_activate_all() {
        let mut orch = X86ASanFullOrchestrator::new();
        orch.activate_all();

        assert!(orch.active.asan);
        assert!(orch.active.hwasan);
        assert!(orch.asan.activated);
        assert!(orch.hwasan.enabled);
    }

    #[test]
    fn test_orchestrator_deactivate_all() {
        let mut orch = X86ASanFullOrchestrator::new();
        orch.activate_all();
        orch.deactivate_all();

        assert!(!orch.active.asan);
        assert!(!orch.active.hwasan);
        assert!(!orch.asan.activated);
        assert!(!orch.hwasan.enabled);
    }

    #[test]
    fn test_orchestrator_check_memory() {
        let mut orch = X86ASanFullOrchestrator::new();
        orch.activate_all();

        // Access to addressable memory
        let errors = orch.check_memory_access(0x10000, 8, false);
        assert!(errors.is_empty());
    }

    #[test]
    fn test_orchestrator_malloc_free() {
        let mut orch = X86ASanFullOrchestrator::new();
        orch.activate_all();

        let (ptr, size) = orch.sanitizer_malloc(128);
        assert!(ptr > 0);
        assert_eq!(size, 128);

        let result = orch.sanitizer_free(ptr);
        assert!(result.is_ok());
    }

    #[test]
    fn test_orchestrator_full_stats() {
        let mut orch = X86ASanFullOrchestrator::new();
        orch.activate_all();

        orch.sanitizer_malloc(256);

        let stats = orch.full_stats();
        assert!(stats.asan_stats.total_allocations > 0);
        assert!(stats.active_sanitizers.asan);
    }

    // ------------------------------------------------------------------
    // Shadow map cross-architecture tests
    // ------------------------------------------------------------------

    #[test]
    fn test_target_arch_from_pointer_width() {
        assert_eq!(
            X86AsanTargetArch::from_pointer_width(64),
            X86AsanTargetArch::X8664
        );
        assert_eq!(
            X86AsanTargetArch::from_pointer_width(32),
            X86AsanTargetArch::I386
        );
    }

    #[test]
    fn test_shadow_map_x86_64_aslr() {
        let map = X86ASanShadowMap::x86_64_aslr();
        assert_eq!(map.shadow_offset, X86_ASAN_SHADOW_OFFSET_64_ASLR);
    }

    // ------------------------------------------------------------------
    // Thread-local storage tests
    // ------------------------------------------------------------------

    #[test]
    fn test_tls_new() {
        let tls = X86ASanTLS::new();
        assert!(!tls.activated);
        assert_eq!(tls.alloc_count, 0);
        assert!(tls.quarantine_cache.is_empty());
    }

    #[test]
    fn test_tls_add_to_quarantine() {
        let mut tls = X86ASanTLS::new();
        tls.add_to_quarantine(0x1000, 32);
        assert!(!tls.quarantine_cache.is_empty());
    }

    #[test]
    fn test_tls_is_quarantined() {
        let mut tls = X86ASanTLS::new();
        tls.add_to_quarantine(0x1000, 64);

        assert!(tls.is_quarantined(0x1000, 8));
        assert!(tls.is_quarantined(0x1030, 4));
        assert!(!tls.is_quarantined(0x2000, 8));
    }

    #[test]
    fn test_tls_flush_quarantine() {
        let mut tls = X86ASanTLS::new();
        tls.add_to_quarantine(0x1000, 32);
        tls.add_to_quarantine(0x2000, 64);

        let flushed = tls.flush_quarantine();
        assert_eq!(flushed.len(), 2);
        assert!(tls.quarantine_cache.is_empty());
    }

    // ------------------------------------------------------------------
    // Thread quarantine batch tests
    // ------------------------------------------------------------------

    #[test]
    fn test_quarantine_batch_new() {
        let batch = X86ASanThreadQuarantineBatch::new(1024);
        assert_eq!(batch.total_size, 0);
        assert!(!batch.is_full());
    }

    #[test]
    fn test_quarantine_batch_add() {
        let mut batch = X86ASanThreadQuarantineBatch::new(1024);
        let meta = X86ASanAllocMeta {
            id: 1,
            user_ptr: 0x1000,
            total_size: 64,
            requested_size: 32,
            is_freed: true,
            alloc_stack: Vec::new(),
            free_stack: None,
            alloc_thread_id: 0,
            free_thread_id: None,
            is_container: false,
            alloc_kind: X86ASanAllocKind::Malloc,
        };

        batch.add(0x1000, 32, meta);
        assert_eq!(batch.total_size, 32);
    }

    #[test]
    fn test_quarantine_batch_flush() {
        let mut batch = X86ASanThreadQuarantineBatch::new(1024);

        let meta = X86ASanAllocMeta {
            id: 1,
            user_ptr: 0x1000,
            total_size: 64,
            requested_size: 32,
            is_freed: true,
            alloc_stack: Vec::new(),
            free_stack: None,
            alloc_thread_id: 0,
            free_thread_id: None,
            is_container: false,
            alloc_kind: X86ASanAllocKind::Malloc,
        };

        batch.add(0x1000, 32, meta);

        let flushed = batch.flush();
        assert_eq!(flushed.len(), 1);
        assert_eq!(batch.total_size, 0);
    }

    // ------------------------------------------------------------------
    // Constant validation tests
    // ------------------------------------------------------------------

    #[test]
    fn test_asan_shadow_scale_constant() {
        assert_eq!(X86_ASAN_SHADOW_SCALE, 3);
    }

    #[test]
    fn test_asan_shadow_granularity_constant() {
        assert_eq!(X86_ASAN_SHADOW_GRANULARITY, 8);
    }

    #[test]
    fn test_asan_shadow_mask_constant() {
        assert_eq!(X86_ASAN_SHADOW_MASK, 7);
    }

    #[test]
    fn test_hwasan_granule_size_constant() {
        assert_eq!(X86_HWASAN_GRANULE_SIZE, 16);
    }

    #[test]
    fn test_hwasan_tag_mask_constant() {
        assert_eq!(X86_HWASAN_TAG_MASK, 0xFF);
    }

    #[test]
    fn test_hwasan_addr_mask_constant() {
        // The address mask should be 0x00FF_FFFF_FFFF_FFFF
        assert_eq!(X86_HWASAN_ADDR_MASK, (1u64 << 56) - 1);
    }

    // ------------------------------------------------------------------
    // Integration-style tests
    // ------------------------------------------------------------------

    #[test]
    fn test_full_asan_workflow() {
        let mut asan = X86ASanFull::new();
        asan.activate();

        // 1. Allocate some memory
        let (ptr, size) = asan.allocator.alloc(256, 16, X86ASanAllocKind::Malloc);
        assert!(ptr > 0);
        assert_eq!(size, 256);

        // 2. Write to it (should be OK)
        assert!(asan.check_memory_access(ptr, 8, true).is_ok());

        // 3. Free it
        asan.allocator.free(ptr, None).unwrap();

        // 4. Try to read freed memory (should report UAF)
        let result = asan.check_memory_access(ptr, 8, false);
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().error_type,
            X86ASanErrorType::HeapUseAfterFree
        );

        // 5. Try to free again (double free)
        let result = asan.allocator.free(ptr, None);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), X86ASanErrorType::DoubleFree);
    }

    #[test]
    fn test_full_stack_instrumentation_workflow() {
        let mut asan = X86ASanFull::new();
        asan.activate();

        // 1. Set up a stack frame
        asan.begin_stack_frame();
        asan.add_stack_variable("buffer", 64, 16);
        asan.add_stack_variable("index", 4, 4);

        // 2. Push to fake stack
        let fake_base =
            asan.push_fake_stack("process_data", 0x7fff0000);
        assert!(fake_base.is_some());

        // 3. Finish frame
        let frame = asan.finish_stack_frame(0x7fff0000);
        assert!(frame.is_some());

        // 4. Pop fake stack (simulating return)
        asan.pop_fake_stack("process_data");

        // 5. Check use-after-return
        let fake_addr = fake_base.unwrap() + 16;
        asan.shadow.set_shadow(fake_addr, STACK_UAR_REDZONE);

        let result = asan.check_memory_access(fake_addr, 8, false);
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().error_type,
            X86ASanErrorType::StackUseAfterReturn
        );
    }

    #[test]
    fn test_full_global_odr_workflow() {
        let mut asan = X86ASanFull::new();
        asan.activate();

        // Register a global with ODR checking
        let hash = X86ASanODRViolationDetector::compute_hash(
            "config", "struct Config", 128,
        );

        let gp = X86ASanGlobalProtection::new("config", 128, 32)
            .with_odr_check(hash, 0x700000);

        asan.global_instr.add_global(gp, 0x600000);

        // Register same global with different hash (simulating ODR violation
        // from another TU)
        let different_hash = 0xDEADBEEF;
        let violated = asan.global_instr.odr_detector.register_global(
            "config",
            different_hash,
            "other.cc",
            42,
            64,
        );

        assert!(violated);
        assert!(asan.global_instr.odr_detector.has_violation("config"));
    }

    #[test]
    fn test_full_hwasan_workflow() {
        let mut rt = X86HWASanRuntime::new();
        rt.init(12345);
        rt.enabled = true;

        // 1. Tag a heap allocation
        let tagged = rt.tag_pointer(0x600000, 0x42);
        assert_eq!(rt.extract_tag(tagged), 0x42);

        // 2. Set memory tags
        rt.memory_tags.set_tag(0x600000, 0x42); // matching

        // 3. Check access (should match)
        let result = rt.check_memory_access(tagged, 8, false);
        assert!(result.is_ok());

        // 4. Change memory tag (simulating UAF or corruption)
        rt.memory_tags.set_tag(0x600000, 0x99);

        // 5. Check access again (should mismatch)
        let result = rt.check_memory_access(tagged, 8, false);
        assert!(result.is_err());

        let report = result.unwrap_err();
        assert_eq!(report.pointer_tag, 0x42);
        assert_eq!(report.memory_tag, 0x99);
    }

    #[test]
    fn test_combined_asan_hwasan_workflow() {
        let mut orch = X86ASanFullOrchestrator::new();
        orch.activate_all();

        // Allocate through ASan
        let (ptr, _) = orch.sanitizer_malloc(128);

        // Access through ASan (should be OK)
        let errors = orch.check_memory_access(ptr, 8, true);
        assert!(errors.is_empty());

        // Free
        orch.sanitizer_free(ptr).unwrap();

        // Access after free (should error)
        let errors = orch.check_memory_access(ptr, 4, false);
        assert!(!errors.is_empty());

        // Leak check
        let leaks = orch.leak_check();
        // Only leaked allocations (none in this test because we freed)
        let leaked_count = leaks.len();
        // Allocator may have some internal state, but our alloc&free should
        // result in 0 leaks for that specific block
    }

    // ------------------------------------------------------------------
    // Edge case tests
    // ------------------------------------------------------------------

    #[test]
    fn test_shadow_map_zero_address() {
        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x20000);

        // Address 0 is valid in ASan but typically poisoned as a redzone
        map.set_shadow(0, HEAP_LEFT_REDZONE);
        assert!(map.check_access(0, 1, false).is_err());
    }

    #[test]
    fn test_shadow_map_large_address() {
        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x7fff_ffff_ffff);

        // Large address near top of user space
        let addr: u64 = 0x7fff_ffff_fff0;
        map.set_shadow(addr, ADDRESSABLE);
        assert_eq!(map.get_shadow(addr), ADDRESSABLE);
    }

    #[test]
    fn test_allocator_zero_size() {
        let mut alloc = X86ASanAllocator::new();
        // malloc(0) is implementation-defined but should not crash
        let (ptr, size) = alloc.alloc(0, 8, X86ASanAllocKind::Malloc);
        assert_eq!(size, 0);
    }

    #[test]
    fn test_error_report_with_allocation_trace() {
        let report = X86ASanErrorReport::new(
            X86ASanErrorType::HeapUseAfterFree,
            0x1000,
            8,
            X86ASanAccessType::Read,
            FREED,
        );
        let formatted = report.format_report();
        // Should not crash even with empty traces
        assert!(!formatted.is_empty());
    }

    #[test]
    fn test_suppression_comment_lines() {
        let mut supp = X86ASanErrorSuppression::new();
        supp.parse_suppressions("# This is a comment\nfun:real_fn\n");
        assert_eq!(supp.rules.len(), 1);
        assert_eq!(supp.rules[0].pattern, "real_fn");
    }

    #[test]
    fn test_multiple_allocs_and_frees() {
        let mut alloc = X86ASanAllocator::new();

        let ptrs: Vec<u64> = (0..10)
            .map(|_| alloc.alloc(64, 8, X86ASanAllocKind::Malloc).0)
            .collect();

        assert_eq!(alloc.allocation_count, 10);

        for &ptr in &ptrs[..5] {
            alloc.free(ptr, None).unwrap();
        }

        assert_eq!(alloc.allocation_count, 5);
    }

    #[test]
    fn test_tag_generator_deterministic() {
        let mut gen1 = X86HWASanTagGenerator::new(42);
        let mut gen2 = X86HWASanTagGenerator::new(42);

        for _ in 0..10 {
            assert_eq!(gen1.generate_tag(), gen2.generate_tag());
        }
    }

    #[test]
    fn test_hwasan_check_all_granules() {
        let mut table = X86HWASanMemoryTagTable::new();
        let mut rt = X86HWASanRuntime::new();
        rt.init(42);
        rt.enabled = true;

        // Set tags for 3 adjacent granules
        table.set_tag(0x1000, 7);
        table.set_tag(0x1010, 7);
        table.set_tag(0x1020, 7);

        rt.memory_tags = table;

        // Access spanning 2 granules (should match on both)
        let tagged = rt.tag_pointer(0x1008, 7);
        let result = rt.check_memory_access(tagged, 16, true);
        assert!(result.is_ok());

        // Access with wrong tag
        let tagged = rt.tag_pointer(0x1008, 9); // wrong tag
        let result = rt.check_memory_access(tagged, 16, true);
        assert!(result.is_err());
    }

    // ------------------------------------------------------------------
    // Stress / bulk operation tests
    // ------------------------------------------------------------------

    #[test]
    fn test_bulk_poison_unpoison() {
        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x100000);

        // Bulk poison a large range
        map.bulk_poison(0x10000, 65536, FREED);

        // Verify sampling
        for addr in (0x10000..0x20000).step_by(256) {
            assert_eq!(map.get_shadow(addr), FREED);
        }

        // Bulk unpoison
        map.bulk_unpoison(0x10000, 65536);

        // Verify
        assert_eq!(map.get_shadow(0x10000), ADDRESSABLE);
        assert_eq!(map.get_shadow(0x15000), ADDRESSABLE);
    }

    #[test]
    fn test_many_stack_variables() {
        let mut frame = X86ASanStackFrame::new();

        for i in 0..100 {
            frame.add_variable(X86ASanStackVar::new(
                &format!("var_{}", i),
                32,
                8,
            ));
        }

        assert_eq!(frame.variables.len(), 100);
        assert!(frame.total_frame_size > 100 * (32 + 2 * X86_ASAN_STACK_REDZONE_SIZE));
    }

    #[test]
    fn test_many_globals() {
        let mut gi = X86ASanGlobalInstrumentation::new();

        for i in 0..200 {
            let gp = X86ASanGlobalProtection::new(&format!("g_{}", i), 64, 16);
            gi.add_global(gp, 0x600000 + i * 128);
        }

        assert_eq!(gi.count(), 200);
    }

    #[test]
    fn test_many_fake_stack_entries() {
        let mut map = X86ASanShadowMap::x86_64();
        map.allocate_shadow(0x20000);

        let mut fs = X86ASanFakeStack::new(0, 10 * 1024 * 1024, 64);

        let frame = X86ASanStackFrame::new();

        for i in 0..100 {
            fs.push(&format!("fn_{}", i), 0x7fff0000 + i * 0x1000, &frame);
        }

        // Should cap at max_entries
        assert!(fs.active_count() <= 64);
    }

    #[test]
    fn test_hwasan_many_tags() {
        let mut gen = X86HWASanTagGenerator::new(1);

        let mut seen = HashSet::new();
        for _ in 0..254 {
            let tag = gen.generate_tag();
            seen.insert(tag);
        }

        // Should cover most of the valid tag range
        assert!(seen.len() > 200);
    }
} // end mod tests