memscope-rs 0.2.3

A memory tracking library for Rust applications.
Documentation
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
//! Enhanced memory tracking for unsafe Rust and FFI operations
//!
//!
//! This module extends the basic memory tracking to handle:
//! - Unsafe Rust memory operations (std::alloc::alloc, raw pointers)
//! - FFI memory operations (malloc, free from C libraries)
//! - Cross-boundary memory transfers
//! - Safety violation detection

use crate::analysis::ffi_function_resolver::{get_global_ffi_resolver, ResolvedFfiFunction};
use crate::capture::types::{AllocationInfo, TrackingError, TrackingResult};
use crate::core::{get_global_call_stack_normalizer, CallStackRef};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};

/// Enhanced allocation source tracking
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AllocationSource {
    /// Safe Rust allocation (through normal allocator)
    RustSafe,
    /// Unsafe Rust allocation with location info
    UnsafeRust {
        /// Location of the unsafe block in source code
        unsafe_block_location: String,
        /// Call stack at the time of allocation
        call_stack: CallStackRef,
        /// Risk assessment for this unsafe operation
        risk_assessment: RiskAssessment,
    },
    /// FFI allocation from C library
    FfiC {
        /// Resolved FFI function information
        resolved_function: ResolvedFfiFunction,
        /// Call stack at the time of allocation
        call_stack: CallStackRef,
        /// LibC hook information
        libc_hook_info: LibCHookInfo,
    },
    /// Cross-boundary memory transfer
    CrossBoundary {
        /// Source allocation context
        from: Box<AllocationSource>,
        /// Destination allocation context
        to: Box<AllocationSource>,
        /// Timestamp when transfer occurred
        transfer_timestamp: u128,
        /// Transfer metadata
        transfer_metadata: TransferMetadata,
    },
}

/// Stack frame information for call stack tracking
#[derive(Debug, Clone, Serialize, Deserialize, Hash, PartialEq, Eq)]
pub struct StackFrame {
    /// Name of the function in this stack frame
    pub function_name: String,
    /// Source file name if available
    pub file_name: Option<String>,
    /// Line number in the source file if available
    pub line_number: Option<u32>,
    /// Whether this frame is in an unsafe block
    pub is_unsafe: bool,
}

/// Safety violation types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SafetyViolation {
    /// Double free detected
    DoubleFree {
        /// Call stack from the first free operation
        first_free_stack: CallStackRef,
        /// Call stack from the second free operation
        second_free_stack: CallStackRef,
        /// Timestamp when the double free was detected
        timestamp: u128,
    },
    /// Invalid free (pointer not in allocation table)
    InvalidFree {
        /// The pointer that was attempted to be freed
        attempted_pointer: usize,
        /// Call stack at the time of invalid free
        stack: CallStackRef,
        /// Timestamp when the invalid free was attempted
        timestamp: u128,
    },
    /// Potential memory leak
    PotentialLeak {
        /// Call stack from the original allocation
        allocation_stack: CallStackRef,
        /// Timestamp when the allocation occurred
        allocation_timestamp: u128,
        /// Timestamp when the leak was detected
        leak_detection_timestamp: u128,
    },
    /// Cross-boundary risk
    CrossBoundaryRisk {
        /// Risk level of the cross-boundary operation
        risk_level: RiskLevel,
        /// Description of the risk
        description: String,
        /// Call stack at the time of risk detection
        stack: CallStackRef,
    },
}

/// Risk levels for safety violations
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum RiskLevel {
    /// Low risk - minor issues that are unlikely to cause problems
    Low,
    /// Medium risk - issues that could potentially cause problems
    Medium,
    /// High risk - serious issues that are likely to cause problems
    High,
    /// Critical risk - severe issues that will almost certainly cause problems
    Critical,
}

/// Comprehensive risk assessment for unsafe operations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RiskAssessment {
    /// Overall risk level
    pub risk_level: RiskLevel,
    /// Specific risk factors identified
    pub risk_factors: Vec<RiskFactor>,
    /// Suggested mitigation strategies
    pub mitigation_suggestions: Vec<String>,
    /// Confidence score of the assessment (0.0 to 1.0)
    pub confidence_score: f64,
    /// Timestamp when assessment was performed
    pub assessment_timestamp: u128,
}

/// Individual risk factor in an assessment
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RiskFactor {
    /// Type of risk factor
    pub factor_type: RiskFactorType,
    /// Severity score (0.0 to 10.0)
    pub severity: f64,
    /// Human-readable description
    pub description: String,
    /// Source location where risk was detected
    pub source_location: Option<String>,
}

/// Types of risk factors that can be detected
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RiskFactorType {
    /// Raw pointer dereference without bounds checking
    RawPointerDeref,
    /// Manual memory management (alloc/dealloc)
    ManualMemoryManagement,
    /// Memory transfer across language boundaries
    CrossBoundaryTransfer,
    /// Unchecked type casting
    UncheckedCast,
    /// Potential lifetime violation
    LifetimeViolation,
    /// Use after free potential
    UseAfterFree,
    /// Buffer overflow potential
    BufferOverflow,
    /// Data race potential
    DataRace,
}

/// Information about LibC function hooks
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LibCHookInfo {
    /// Method used to hook the function
    pub hook_method: HookMethod,
    /// Original function that was hooked
    pub original_function: String,
    /// Timestamp when hook was installed
    pub hook_timestamp: u128,
    /// Metadata about the allocation
    pub allocation_metadata: AllocationMetadata,
    /// Performance impact of the hook
    pub hook_overhead_ns: Option<u64>,
}

/// Methods for hooking LibC functions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum HookMethod {
    /// LD_PRELOAD mechanism (Linux/macOS)
    LdPreload,
    /// Dynamic linker interposition
    DynamicLinker,
    /// Static function interposition
    StaticInterposition,
    /// Runtime patching
    RuntimePatching,
}

/// Metadata about memory allocations from LibC
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AllocationMetadata {
    /// Size requested by the caller
    pub requested_size: usize,
    /// Actual size allocated (may be larger due to alignment)
    pub actual_size: usize,
    /// Memory alignment used
    pub alignment: usize,
    /// Information about the allocator used
    pub allocator_info: String,
    /// Memory protection flags if available
    pub protection_flags: Option<MemoryProtectionFlags>,
}

/// Memory protection flags
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryProtectionFlags {
    /// Memory is readable
    pub readable: bool,
    /// Memory is writable
    pub writable: bool,
    /// Memory is executable
    pub executable: bool,
    /// Memory is shared
    pub shared: bool,
}

/// Memory "passport" for tracking cross-boundary transfers
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryPassport {
    /// Unique identifier for this memory passport
    pub passport_id: String,
    /// Original allocation context
    pub origin: AllocationOrigin,
    /// Journey of the memory through different contexts
    pub journey: Vec<PassportStamp>,
    /// Current ownership information
    pub current_owner: OwnershipInfo,
    /// Validity status of the passport
    pub validity_status: ValidityStatus,
    /// Security clearance level
    pub security_clearance: SecurityClearance,
}

/// Information about where memory was originally allocated
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AllocationOrigin {
    /// Context where allocation occurred (Rust/FFI)
    pub context: String,
    /// Function that performed the allocation
    pub allocator_function: String,
    /// Timestamp of original allocation
    pub timestamp: u128,
    /// Call stack at allocation time
    pub call_stack: CallStackRef,
}

/// A stamp in the memory passport journey
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PassportStamp {
    /// Timestamp of this checkpoint
    pub timestamp: u128,
    /// Location/context of the checkpoint
    pub location: String,
    /// Operation performed at this checkpoint
    pub operation: String,
    /// Authority that validated this checkpoint
    pub authority: String,
    /// Cryptographic hash for verification
    pub verification_hash: String,
}

/// Current ownership information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OwnershipInfo {
    /// Current owner context (Rust/FFI)
    pub owner_context: String,
    /// Function/module that owns the memory
    pub owner_function: String,
    /// Ownership transfer timestamp
    pub transfer_timestamp: u128,
    /// Expected lifetime of ownership
    pub expected_lifetime: Option<u128>,
}

/// Validity status of a memory passport
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ValidityStatus {
    /// Passport is valid and memory is safe to use
    Valid,
    /// Passport is expired (memory may be freed)
    Expired,
    /// Passport is revoked (memory is definitely freed)
    Revoked,
    /// Passport validity is unknown/suspicious
    Suspicious,
}

/// Security clearance levels for memory operations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SecurityClearance {
    /// Public memory, safe for all operations
    Public,
    /// Restricted memory, limited operations allowed
    Restricted,
    /// Confidential memory, special handling required
    Confidential,
    /// Secret memory, maximum security required
    Secret,
}

/// Metadata for cross-boundary transfers
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransferMetadata {
    /// Reason for the transfer
    pub transfer_reason: String,
    /// Expected return context (if any)
    pub expected_return: Option<String>,
    /// Transfer validation method used
    pub validation_method: ValidationMethod,
    /// Performance impact of the transfer
    pub transfer_overhead_ns: Option<u64>,
}

/// Methods for validating cross-boundary transfers
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ValidationMethod {
    /// No validation performed
    None,
    /// Basic pointer validation
    PointerCheck,
    /// Size and bounds validation
    BoundsCheck,
    /// Full memory integrity check
    IntegrityCheck,
    /// Cryptographic validation
    CryptographicCheck,
}

/// Enhanced allocation info with unsafe/FFI tracking
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnhancedAllocationInfo {
    /// Base allocation info
    pub base: AllocationInfo,
    /// Source of the allocation
    pub source: AllocationSource,
    /// Call stack at allocation time
    pub call_stack: CallStackRef,
    /// Cross-boundary events
    pub cross_boundary_events: Vec<BoundaryEvent>,
    /// Safety violations detected
    pub safety_violations: Vec<SafetyViolation>,
    /// Whether this allocation is currently being tracked by FFI
    pub ffi_tracked: bool,
    /// Memory passport for cross-boundary tracking
    pub memory_passport: Option<MemoryPassport>,
    /// Ownership transfer history
    pub ownership_history: Option<Vec<OwnershipTransferEvent>>,
}

/// Cross-boundary memory event
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BoundaryEvent {
    /// Type of boundary crossing event
    pub event_type: BoundaryEventType,
    /// Timestamp when the event occurred
    pub timestamp: u128,
    /// Context where the crossing originated
    pub from_context: String,
    /// Context where the crossing ended
    pub to_context: String,
    /// Call stack at the time of crossing
    pub stack: CallStackRef,
}

/// Types of boundary events
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum BoundaryEventType {
    /// Memory allocated in Rust, passed to FFI
    RustToFfi,
    /// Memory allocated in FFI, passed to Rust
    FfiToRust,
    /// Memory ownership transferred
    OwnershipTransfer,
    /// Memory shared between contexts
    SharedAccess,
}

/// Comprehensive analysis of a boundary event
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BoundaryEventAnalysis {
    /// Unique identifier for this event analysis
    pub event_id: String,
    /// Memory pointer involved in the event
    pub ptr: usize,
    /// Type of boundary event
    pub event_type: BoundaryEventType,
    /// Source context
    pub from_context: String,
    /// Destination context
    pub to_context: String,
    /// Size of memory being transferred
    pub transfer_size: usize,
    /// Timestamp of the event
    pub timestamp: u128,
    /// Risk assessment for this event
    pub risk_assessment: BoundaryRiskAssessment,
    /// Ownership chain history
    pub ownership_chain: Vec<OwnershipRecord>,
    /// Security implications
    pub security_implications: Vec<SecurityImplication>,
    /// Performance impact analysis
    pub performance_impact: PerformanceImpact,
    /// Recommended mitigation strategies
    pub mitigation_recommendations: Vec<String>,
}

/// Risk assessment for boundary transfers
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BoundaryRiskAssessment {
    /// Overall risk level
    pub overall_risk_level: RiskLevel,
    /// Numerical risk score (0.0 to 100.0)
    pub risk_score: f64,
    /// Individual risk factors
    pub risk_factors: Vec<BoundaryRiskFactor>,
    /// Confidence in the assessment (0.0 to 1.0)
    pub confidence_score: f64,
    /// When the assessment was performed
    pub assessment_timestamp: u128,
}

/// Individual risk factor for boundary transfers
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BoundaryRiskFactor {
    /// Type of risk factor
    pub factor_type: BoundaryRiskFactorType,
    /// Severity score (0.0 to 10.0)
    pub severity: f64,
    /// Human-readable description
    pub description: String,
    /// Suggested mitigation
    pub mitigation: String,
}

/// Types of boundary risk factors
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum BoundaryRiskFactorType {
    /// Transfer from Rust to foreign code
    RustToForeignTransfer,
    /// Transfer from foreign code to Rust
    ForeignToRustTransfer,
    /// Ownership transfer across boundaries
    OwnershipTransfer,
    /// Shared access across boundaries
    SharedAccess,
    /// Large memory transfer
    LargeTransfer,
    /// Frequent boundary crossings
    FrequentTransfers,
    /// Unvalidated data transfer
    UnvalidatedTransfer,
    /// Privilege boundary crossing
    PrivilegeBoundary,
}

/// Ownership transfer event
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OwnershipTransferEvent {
    /// Unique identifier for this transfer
    pub transfer_id: String,
    /// Memory pointer being transferred
    pub ptr: usize,
    /// Source context
    pub from_context: String,
    /// Destination context
    pub to_context: String,
    /// When the transfer occurred
    pub transfer_timestamp: u128,
    /// Reason for the transfer
    pub transfer_reason: String,
    /// Validation status of the transfer
    pub validation_status: OwnershipValidationStatus,
}

/// Status of ownership validation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum OwnershipValidationStatus {
    /// Transfer is valid and safe
    Valid,
    /// Transfer is pending validation
    Pending,
    /// Transfer has validation warnings
    Warning,
    /// Transfer is invalid or unsafe
    Invalid,
    /// Transfer validation failed
    Failed,
}

/// Record in the ownership chain
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OwnershipRecord {
    /// Context that owns the memory
    pub context: String,
    /// When ownership was acquired
    pub timestamp: u128,
    /// Reason for ownership transfer
    pub transfer_reason: String,
    /// Validation status
    pub validation_status: OwnershipValidationStatus,
}

/// Security implication of boundary crossing
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityImplication {
    /// Type of security implication
    pub implication_type: SecurityImplicationType,
    /// Severity level
    pub severity: RiskLevel,
    /// Description of the implication
    pub description: String,
    /// Potential impact
    pub potential_impact: String,
    /// Recommended action
    pub recommended_action: String,
}

/// Types of security implications
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SecurityImplicationType {
    /// Potential privilege escalation
    PrivilegeEscalation,
    /// Data exposure risk
    DataExposure,
    /// Code injection risk
    InjectionRisk,
    /// Buffer overflow risk
    BufferOverflow,
    /// Use after free risk
    UseAfterFree,
    /// Race condition risk
    RaceCondition,
    /// Information disclosure
    InformationDisclosure,
}

/// Performance impact analysis
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceImpact {
    /// Overall impact level
    pub impact_level: PerformanceImpactLevel,
    /// Estimated overhead in nanoseconds
    pub estimated_overhead_ns: u64,
    /// Memory overhead in bytes
    pub memory_overhead_bytes: usize,
    /// CPU overhead percentage
    pub cpu_overhead_percent: f64,
    /// Performance optimization recommendations
    pub recommendations: Vec<String>,
}

/// Levels of performance impact
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PerformanceImpactLevel {
    /// Minimal performance impact
    Low,
    /// Moderate performance impact
    Medium,
    /// Significant performance impact
    High,
    /// Critical performance impact
    Critical,
}

/// Statistics for boundary events
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BoundaryEventStatistics {
    /// Total number of boundary events
    pub total_events: usize,
    /// Events grouped by type
    pub events_by_type: std::collections::HashMap<String, usize>,
    /// Risk level distribution
    pub risk_distribution: std::collections::HashMap<String, usize>,
    /// Average transfer size
    pub average_transfer_size: f64,
    /// Total volume of data transferred
    pub total_transfer_volume: usize,
    /// Most active contexts (context name, event count)
    pub most_active_contexts: Vec<(String, usize)>,
    /// Number of security incidents detected
    pub security_incidents: usize,
    /// Number of performance issues detected
    pub performance_issues: usize,
    /// When the statistics were generated
    pub analysis_timestamp: u128,
}

/// Enhanced memory tracker for unsafe/FFI operations
pub struct UnsafeFFITracker {
    /// Enhanced allocations with source tracking
    enhanced_allocations: Mutex<HashMap<usize, EnhancedAllocationInfo>>,
    /// Freed pointers (for double-free detection)
    freed_pointers: Mutex<HashMap<usize, (CallStackRef, u128)>>,
    /// Safety violations log
    violations: Mutex<Vec<SafetyViolation>>,
    /// C library tracking registry
    c_libraries: Mutex<HashMap<String, CLibraryInfo>>,
    /// Enhanced LibC hook registry
    libc_hooks: Mutex<HashMap<String, EnhancedLibCHookInfo>>,
    /// Memory passport registry
    memory_passports: Mutex<HashMap<usize, MemoryPassport>>,
}

impl UnsafeFFITracker {
    /// Create a new enhanced tracker
    pub fn new() -> Self {
        Self {
            enhanced_allocations: Mutex::new(HashMap::new()),
            freed_pointers: Mutex::new(HashMap::new()),
            violations: Mutex::new(Vec::new()),
            c_libraries: Mutex::new(HashMap::new()),
            libc_hooks: Mutex::new(HashMap::new()),
            memory_passports: Mutex::new(HashMap::new()),
        }
    }

    /// Create a default risk assessment for unsafe operations
    fn create_default_unsafe_risk_assessment(&self, unsafe_location: &str) -> RiskAssessment {
        let current_time = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();

        let risk_factors = vec![RiskFactor {
            factor_type: RiskFactorType::ManualMemoryManagement,
            severity: 5.0,
            description: "Manual memory management in unsafe block".to_string(),
            source_location: Some(unsafe_location.to_string()),
        }];

        RiskAssessment {
            risk_level: RiskLevel::Medium,
            risk_factors,
            mitigation_suggestions: vec![
                "Ensure proper memory cleanup".to_string(),
                "Use RAII patterns where possible".to_string(),
            ],
            confidence_score: 0.7,
            assessment_timestamp: current_time,
        }
    }

    /// Create a default LibC hook info for FFI operations
    fn create_default_libc_hook_info(&self, function_name: &str, size: usize) -> LibCHookInfo {
        let current_time = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();

        LibCHookInfo {
            hook_method: HookMethod::DynamicLinker,
            original_function: function_name.to_string(),
            hook_timestamp: current_time,
            allocation_metadata: AllocationMetadata {
                requested_size: size,
                actual_size: size,
                alignment: 8, // Default alignment
                allocator_info: "libc malloc".to_string(),
                protection_flags: Some(MemoryProtectionFlags {
                    readable: true,
                    writable: true,
                    executable: false,
                    shared: false,
                }),
            },
            hook_overhead_ns: Some(100), // Estimated overhead
        }
    }

    /// Create a memory passport for cross-boundary tracking
    fn create_memory_passport(&self, ptr: usize, origin_context: &str) -> MemoryPassport {
        let current_time = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();

        MemoryPassport {
            passport_id: format!("passport_{ptr:x}_{current_time}"),
            origin: AllocationOrigin {
                context: origin_context.to_string(),
                allocator_function: "unknown".to_string(),
                timestamp: current_time,
                call_stack: {
                    let normalizer = get_global_call_stack_normalizer();
                    let empty_frames = vec![];
                    let id = normalizer.normalize_call_stack(&empty_frames).unwrap_or(0);
                    CallStackRef::new(id, Some(0))
                },
            },
            journey: Vec::new(),
            current_owner: OwnershipInfo {
                owner_context: origin_context.to_string(),
                owner_function: "unknown".to_string(),
                transfer_timestamp: current_time,
                expected_lifetime: None,
            },
            validity_status: ValidityStatus::Valid,
            security_clearance: SecurityClearance::Public,
        }
    }

    /// Track an unsafe Rust allocation
    pub fn track_unsafe_allocation(
        &self,
        ptr: usize,
        size: usize,
        unsafe_location: String,
    ) -> TrackingResult<()> {
        let call_stack = self.capture_call_stack()?;
        let base_allocation = AllocationInfo::new(ptr, size);
        let risk_assessment = self.create_default_unsafe_risk_assessment(&unsafe_location);

        let enhanced = EnhancedAllocationInfo {
            base: base_allocation,
            source: AllocationSource::UnsafeRust {
                unsafe_block_location: unsafe_location,
                call_stack: call_stack.clone(),
                risk_assessment,
            },
            call_stack,
            cross_boundary_events: Vec::new(),
            safety_violations: Vec::new(),
            ffi_tracked: false,
            memory_passport: None,
            ownership_history: None,
        };

        if let Ok(mut allocations) = self.enhanced_allocations.lock() {
            allocations.insert(ptr, enhanced);
            tracing::info!("Tracked unsafe allocation at {:x} (size: {})", ptr, size);
        }

        Ok(())
    }

    /// Track an FFI allocation
    pub fn track_ffi_allocation(
        &self,
        ptr: usize,
        size: usize,
        library_name: String,
        function_name: String,
    ) -> TrackingResult<()> {
        let call_stack = self.capture_call_stack()?;
        let base_allocation = AllocationInfo::new(ptr, size);
        let libc_hook_info = self.create_default_libc_hook_info(&function_name, size);

        // Resolve FFI function information
        let resolver = get_global_ffi_resolver();
        let resolved_function = resolver
            .resolve_function(&function_name, Some(&library_name))
            .unwrap_or_else(|_| {
                tracing::warn!(
                    "Failed to resolve FFI function: {}::{}",
                    library_name,
                    function_name
                );
                // Create fallback resolution
                ResolvedFfiFunction {
                    library_name: library_name.clone(),
                    function_name: function_name.clone(),
                    signature: None,
                    category: crate::analysis::FfiFunctionCategory::Unknown,
                    risk_level: crate::analysis::FfiRiskLevel::Medium,
                    metadata: std::collections::HashMap::new(),
                }
            });

        let enhanced = EnhancedAllocationInfo {
            base: base_allocation,
            source: AllocationSource::FfiC {
                resolved_function,
                call_stack: call_stack.clone(),
                libc_hook_info,
            },
            call_stack,
            cross_boundary_events: Vec::new(),
            safety_violations: Vec::new(),
            ffi_tracked: true,
            memory_passport: None,
            ownership_history: None,
        };

        if let Ok(mut allocations) = self.enhanced_allocations.lock() {
            allocations.insert(ptr, enhanced);
            tracing::info!("Tracked FFI allocation at {:x} (size: {})", ptr, size);
        }

        Ok(())
    }

    /// Track a deallocation with safety checks
    pub fn track_enhanced_deallocation(&self, ptr: usize) -> TrackingResult<()> {
        let call_stack = self.capture_call_stack()?;
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis();

        // Check for double free
        if let Ok(freed) = self.freed_pointers.lock() {
            if let Some((first_free_stack, _first_timestamp)) = freed.get(&ptr) {
                let violation = SafetyViolation::DoubleFree {
                    first_free_stack: first_free_stack.clone(),
                    second_free_stack: call_stack.clone(),
                    timestamp,
                };

                if let Ok(mut violations) = self.violations.lock() {
                    violations.push(violation);
                }

                tracing::error!("Double free detected at {:x}", ptr);
                return Err(TrackingError::MemoryCorruption(
                    "Memory corruption detected".to_string(),
                ));
            }
        }

        // Check if allocation exists
        if let Ok(mut allocations) = self.enhanced_allocations.lock() {
            if let Some(mut allocation) = allocations.remove(&ptr) {
                allocation.base.mark_deallocated();

                // Record in freed pointers
                if let Ok(mut freed) = self.freed_pointers.lock() {
                    freed.insert(ptr, (call_stack, timestamp));
                }

                tracing::info!("Tracked enhanced deallocation at {:x}", ptr);
            } else {
                // Invalid free
                let violation = SafetyViolation::InvalidFree {
                    attempted_pointer: ptr,
                    stack: call_stack,
                    timestamp,
                };

                if let Ok(mut violations) = self.violations.lock() {
                    violations.push(violation);
                }

                tracing::error!("Invalid free detected at {:x}", ptr);
                return Err(TrackingError::InvalidPointer(format!(
                    "Invalid pointer: 0x{ptr:x}"
                )));
            }
        }

        Ok(())
    }

    /// Record a cross-boundary event
    pub fn record_boundary_event(
        &self,
        ptr: usize,
        event_type: BoundaryEventType,
        from_context: String,
        to_context: String,
    ) -> TrackingResult<()> {
        let call_stack = self.capture_call_stack()?;
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis();

        let event = BoundaryEvent {
            event_type,
            timestamp,
            from_context,
            to_context,
            stack: call_stack,
        };

        if let Ok(mut allocations) = self.enhanced_allocations.lock() {
            if let Some(allocation) = allocations.get_mut(&ptr) {
                allocation.cross_boundary_events.push(event);
                tracing::info!("Recorded boundary event for {:x}", ptr);
            }
        }

        Ok(())
    }

    /// Create or update memory passport for cross-boundary tracking
    pub fn create_or_update_passport(
        &self,
        ptr: usize,
        operation: &str,
        context: &str,
    ) -> TrackingResult<()> {
        if let Ok(mut allocations) = self.enhanced_allocations.lock() {
            if let Some(allocation) = allocations.get_mut(&ptr) {
                let current_time = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_nanos();

                if allocation.memory_passport.is_none() {
                    allocation.memory_passport = Some(self.create_memory_passport(ptr, context));
                }

                if let Some(passport) = &mut allocation.memory_passport {
                    let stamp = PassportStamp {
                        timestamp: current_time,
                        location: context.to_string(),
                        operation: operation.to_string(),
                        authority: "UnsafeFFITracker".to_string(),
                        verification_hash: format!("{:x}", ptr ^ current_time as usize),
                    };
                    passport.journey.push(stamp);
                }
            }
        }

        Ok(())
    }

    /// Update ownership information for a memory allocation
    pub fn update_ownership(
        &self,
        ptr: usize,
        new_owner_context: String,
        new_owner_function: String,
    ) -> TrackingResult<()> {
        if let Ok(mut allocations) = self.enhanced_allocations.lock() {
            if let Some(allocation) = allocations.get_mut(&ptr) {
                let current_time = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_nanos();

                if let Some(passport) = &mut allocation.memory_passport {
                    passport.current_owner = OwnershipInfo {
                        owner_context: new_owner_context,
                        owner_function: new_owner_function,
                        transfer_timestamp: current_time,
                        expected_lifetime: None,
                    };
                }
            }
        }

        Ok(())
    }

    /// Validate memory passport integrity
    pub fn validate_passport(&self, ptr: usize) -> TrackingResult<bool> {
        if let Ok(allocations) = self.enhanced_allocations.lock() {
            if let Some(allocation) = allocations.get(&ptr) {
                if let Some(passport) = &allocation.memory_passport {
                    // Basic validation: check if passport is not expired or revoked
                    match passport.validity_status {
                        ValidityStatus::Valid => Ok(true),
                        ValidityStatus::Expired
                        | ValidityStatus::Revoked
                        | ValidityStatus::Suspicious => Ok(false),
                    }
                } else {
                    Ok(false) // No passport means not validated
                }
            } else {
                Ok(false) // Allocation not found
            }
        } else {
            Err(TrackingError::LockError(
                "Failed to acquire allocations lock".to_string(),
            ))
        }
    }

    /// Get all safety violations
    pub fn get_safety_violations(&self) -> TrackingResult<Vec<SafetyViolation>> {
        self.violations
            .lock()
            .map(|v| v.clone())
            .map_err(|e| TrackingError::LockError(e.to_string()))
    }

    /// Get enhanced allocations
    pub fn get_enhanced_allocations(&self) -> TrackingResult<Vec<EnhancedAllocationInfo>> {
        self.enhanced_allocations
            .lock()
            .map(|allocations| allocations.values().cloned().collect())
            .map_err(|e| TrackingError::LockError(e.to_string()))
    }

    /// Capture current call stack and normalize it
    fn capture_call_stack(&self) -> TrackingResult<CallStackRef> {
        // In a real implementation, this would use backtrace crate
        // For now, return a simplified stack
        let frames = vec![StackFrame {
            function_name: "current_function".to_string(),
            file_name: Some("src/unsafe_ffi_tracker.rs".to_string()),
            line_number: Some(42),
            is_unsafe: true,
        }];

        let normalizer = get_global_call_stack_normalizer();
        // Manual error handling to convert between old and new TrackingError types
        let id = match normalizer.normalize_call_stack(&frames) {
            Ok(id) => id,
            Err(e) => {
                return Err(TrackingError::AnalysisError(format!(
                    "Failed to normalize call stack: {}",
                    e
                )))
            }
        };
        Ok(CallStackRef::new(id, Some(frames.len())))
    }

    /// Detect potential memory leaks
    pub fn detect_leaks(&self, threshold_ms: u128) -> TrackingResult<Vec<SafetyViolation>> {
        let current_time = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis();

        let mut leaks = Vec::new();

        if let Ok(allocations) = self.enhanced_allocations.lock() {
            for allocation in allocations.values() {
                let alloc_time = allocation.base.timestamp_alloc as u128;
                let age = current_time.saturating_sub(alloc_time);
                if age > threshold_ms && allocation.base.is_active() {
                    leaks.push(SafetyViolation::PotentialLeak {
                        allocation_stack: allocation.call_stack.clone(),
                        allocation_timestamp: allocation.base.timestamp_alloc as u128,
                        leak_detection_timestamp: current_time,
                    });
                }
            }
        }

        Ok(leaks)
    }
}

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

/// Global instance of the enhanced tracker
static GLOBAL_UNSAFE_FFI_TRACKER: std::sync::OnceLock<std::sync::Arc<UnsafeFFITracker>> =
    std::sync::OnceLock::new();

/// Get the global unsafe/FFI tracker instance
pub fn get_global_unsafe_ffi_tracker() -> std::sync::Arc<UnsafeFFITracker> {
    GLOBAL_UNSAFE_FFI_TRACKER
        .get_or_init(|| std::sync::Arc::new(UnsafeFFITracker::new()))
        .clone()
}

/// Macro for tracking unsafe allocations
#[macro_export]
macro_rules! track_unsafe_alloc {
    ($ptr:expr, $size:expr) => {{
        let tracker = $crate::unsafe_ffi_tracker::get_global_unsafe_ffi_tracker();
        let location = format!("{}:{}:{}", file!(), line!(), column!());
        let _ = tracker.track_unsafe_allocation($ptr as usize, $size, location);
    }};
}

/// Macro for tracking FFI allocations
#[macro_export]
macro_rules! track_ffi_alloc {
    ($ptr:expr, $size:expr, $lib:expr, $func:expr) => {{
        let tracker = $crate::unsafe_ffi_tracker::get_global_unsafe_ffi_tracker();
        let _ =
            tracker.track_ffi_allocation($ptr as usize, $size, $lib.to_string(), $func.to_string());
    }};
}

/// Statistics for unsafe and FFI operations
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UnsafeFFIStats {
    /// Total number of unsafe operations
    pub total_operations: usize,
    /// Number of unsafe blocks encountered
    pub unsafe_blocks: usize,
    /// Number of FFI calls made
    pub ffi_calls: usize,
    /// Number of raw pointer operations
    pub raw_pointer_operations: usize,
    /// Number of memory violations detected
    pub memory_violations: usize,
    /// Overall risk score (0.0 to 10.0)
    pub risk_score: f64,
    /// List of unsafe operations
    pub operations: Vec<UnsafeOperation>,
}

/// Represents a single unsafe operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnsafeOperation {
    /// Type of operation
    pub operation_type: UnsafeOperationType,
    /// Location in source code
    pub location: String,
    /// Risk level of this operation
    pub risk_level: RiskLevel,
    /// Timestamp when operation occurred
    pub timestamp: u128,
    /// Description of the operation
    pub description: String,
}

/// Types of unsafe operations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum UnsafeOperationType {
    /// Raw pointer dereference operation
    RawPointerDeref,
    /// Foreign Function Interface call
    FfiCall,
    /// Unsafe block execution
    UnsafeBlock,
    /// Memory safety violation detected
    MemoryViolation,
    /// Memory transfer across safety boundaries
    CrossBoundaryTransfer,
}

/// C Library information for detailed tracking
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CLibraryInfo {
    /// Name of the C library
    pub library_name: String,
    /// Version of the library if available
    pub library_version: Option<String>,
    /// Path to the library file
    pub library_path: Option<String>,
    /// Functions from this library that have been called
    pub functions_called: HashMap<String, CFunctionInfo>,
    /// Total number of allocations from this library
    pub total_allocations: usize,
    /// Total bytes allocated from this library
    pub total_bytes_allocated: usize,
    /// Library load timestamp
    pub load_timestamp: u128,
    /// Library metadata
    pub metadata: LibraryMetadata,
}

/// Information about a specific C function
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CFunctionInfo {
    /// Function name
    pub function_name: String,
    /// Function signature if available
    pub function_signature: Option<String>,
    /// Number of times this function has been called
    pub call_count: usize,
    /// Total bytes allocated by this function
    pub bytes_allocated: usize,
    /// Average allocation size
    pub average_allocation_size: f64,
    /// Risk assessment for this function
    pub risk_assessment: RiskAssessment,
    /// Performance metrics
    pub performance_metrics: FunctionPerformanceMetrics,
    /// First call timestamp
    pub first_call_timestamp: u128,
    /// Last call timestamp
    pub last_call_timestamp: u128,
}

/// Performance metrics for C functions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FunctionPerformanceMetrics {
    /// Average execution time in nanoseconds
    pub avg_execution_time_ns: u64,
    /// Minimum execution time in nanoseconds
    pub min_execution_time_ns: u64,
    /// Maximum execution time in nanoseconds
    pub max_execution_time_ns: u64,
    /// Total execution time in nanoseconds
    pub total_execution_time_ns: u64,
    /// Memory overhead introduced by tracking
    pub tracking_overhead_ns: u64,
}

/// Library metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LibraryMetadata {
    /// Architecture (x86_64, arm64, etc.)
    pub architecture: String,
    /// Operating system
    pub operating_system: String,
    /// Compiler used to build the library
    pub compiler_info: Option<String>,
    /// Debug symbols available
    pub has_debug_symbols: bool,
    /// Security features enabled
    pub security_features: Vec<String>,
}

/// Enhanced LibC hook information with detailed tracking
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnhancedLibCHookInfo {
    /// Base hook information
    pub base_info: LibCHookInfo,
    /// Detailed function tracking
    pub function_tracking: CFunctionInfo,
    /// Hook installation details
    pub installation_details: HookInstallationDetails,
    /// Runtime behavior analysis
    pub runtime_analysis: RuntimeBehaviorAnalysis,
    /// Security analysis
    pub security_analysis: SecurityAnalysis,
}

/// Details about hook installation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HookInstallationDetails {
    /// Method used to install the hook
    pub installation_method: HookInstallationMethod,
    /// Success status of installation
    pub installation_success: bool,
    /// Error message if installation failed
    pub installation_error: Option<String>,
    /// Timestamp of installation attempt
    pub installation_timestamp: u128,
    /// Process ID where hook was installed
    pub process_id: u32,
    /// Thread ID where hook was installed
    pub thread_id: u64,
}

/// Methods for installing hooks
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum HookInstallationMethod {
    /// Preload library method
    Preload,
    /// Runtime symbol interposition
    SymbolInterposition,
    /// Binary patching
    BinaryPatching,
    /// Debugger-based hooking
    DebuggerHook,
    /// Kernel-level hooking
    KernelHook,
}

/// Runtime behavior analysis for hooked functions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RuntimeBehaviorAnalysis {
    /// Memory access patterns
    pub memory_patterns: Vec<MemoryAccessPattern>,
    /// Allocation size distribution
    pub size_distribution: SizeDistribution,
    /// Temporal patterns
    pub temporal_patterns: TemporalPatterns,
    /// Error patterns
    pub error_patterns: Vec<ErrorPattern>,
}

/// Memory access pattern analysis
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryAccessPattern {
    /// Pattern type
    pub pattern_type: MemoryPatternType,
    /// Frequency of this pattern
    pub frequency: usize,
    /// Average size involved in this pattern
    pub average_size: usize,
    /// Risk level associated with this pattern
    pub risk_level: RiskLevel,
}

/// Types of memory access patterns
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MemoryPatternType {
    /// Sequential allocation pattern
    Sequential,
    /// Random allocation pattern
    Random,
    /// Bulk allocation pattern
    Bulk,
    /// Fragmented allocation pattern
    Fragmented,
    /// Reallocation pattern
    Reallocation,
}

/// Size distribution analysis
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SizeDistribution {
    /// Small allocations (< 1KB)
    pub small_allocations: usize,
    /// Medium allocations (1KB - 1MB)
    pub medium_allocations: usize,
    /// Large allocations (> 1MB)
    pub large_allocations: usize,
    /// Average allocation size
    pub average_size: f64,
    /// Standard deviation of sizes
    pub size_std_dev: f64,
}

/// Temporal patterns in allocations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemporalPatterns {
    /// Allocation rate (allocations per second)
    pub allocation_rate: f64,
    /// Peak allocation periods
    pub peak_periods: Vec<PeakPeriod>,
    /// Allocation bursts detected
    pub burst_count: usize,
    /// Average time between allocations
    pub avg_time_between_allocs_ms: f64,
}

/// Peak allocation period
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PeakPeriod {
    /// Start timestamp of peak
    pub start_timestamp: u128,
    /// End timestamp of peak
    pub end_timestamp: u128,
    /// Number of allocations during peak
    pub allocation_count: usize,
    /// Total bytes allocated during peak
    pub bytes_allocated: usize,
}

/// Error pattern analysis
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorPattern {
    /// Type of error
    pub error_type: ErrorType,
    /// Frequency of this error
    pub frequency: usize,
    /// Context where error occurs
    pub context: String,
    /// Suggested mitigation
    pub mitigation: String,
}

/// Types of errors that can be detected
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ErrorType {
    /// Allocation failure
    AllocationFailure,
    /// Invalid free
    InvalidFree,
    /// Double free
    DoubleFree,
    /// Memory leak
    MemoryLeak,
    /// Buffer overflow
    BufferOverflow,
    /// Use after free
    UseAfterFree,
}

/// Security analysis for hooked functions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityAnalysis {
    /// Security vulnerabilities detected
    pub vulnerabilities: Vec<SecurityVulnerability>,
    /// Security score (0.0 to 10.0)
    pub security_score: f64,
    /// Recommended security measures
    pub recommendations: Vec<String>,
    /// Compliance status
    pub compliance_status: ComplianceStatus,
}

/// Security vulnerability information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityVulnerability {
    /// Type of vulnerability
    pub vulnerability_type: VulnerabilityType,
    /// Severity level
    pub severity: RiskLevel,
    /// Description of the vulnerability
    pub description: String,
    /// Location where vulnerability was detected
    pub location: String,
    /// Potential impact
    pub potential_impact: String,
    /// Remediation steps
    pub remediation: Vec<String>,
}

/// Types of security vulnerabilities
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum VulnerabilityType {
    /// Buffer overflow vulnerability
    BufferOverflow,
    /// Use after free vulnerability
    UseAfterFree,
    /// Double free vulnerability
    DoubleFree,
    /// Memory leak vulnerability
    MemoryLeak,
    /// Integer overflow vulnerability
    IntegerOverflow,
    /// Format string vulnerability
    FormatString,
    /// Race condition vulnerability
    RaceCondition,
}

/// Compliance status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplianceStatus {
    /// Memory safety compliance
    pub memory_safety: bool,
    /// Thread safety compliance
    pub thread_safety: bool,
    /// API usage compliance
    pub api_usage: bool,
    /// Security best practices compliance
    pub security_practices: bool,
    /// Overall compliance score
    pub overall_score: f64,
}

impl UnsafeFFITracker {
    /// Register a C library for tracking
    pub fn register_c_library(
        &self,
        library_name: String,
        library_path: Option<String>,
        library_version: Option<String>,
    ) -> TrackingResult<()> {
        let current_time = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();

        let library_info = CLibraryInfo {
            library_name: library_name.clone(),
            library_version,
            library_path,
            functions_called: HashMap::new(),
            total_allocations: 0,
            total_bytes_allocated: 0,
            load_timestamp: current_time,
            metadata: LibraryMetadata {
                architecture: std::env::consts::ARCH.to_string(),
                operating_system: std::env::consts::OS.to_string(),
                compiler_info: None,
                has_debug_symbols: false,
                security_features: Vec::new(),
            },
        };

        if let Ok(mut libraries) = self.c_libraries.lock() {
            libraries.insert(library_name.clone(), library_info);
            tracing::info!("Registered C library: {}", library_name);
        }

        Ok(())
    }

    /// Track a C function call with detailed information
    pub fn track_c_function_call(
        &self,
        library_name: &str,
        function_name: &str,
        allocation_size: usize,
        execution_time_ns: u64,
    ) -> TrackingResult<()> {
        let current_time = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();

        if let Ok(mut libraries) = self.c_libraries.lock() {
            let library = libraries
                .entry(library_name.to_string())
                .or_insert_with(|| CLibraryInfo {
                    library_name: library_name.to_string(),
                    library_version: None,
                    library_path: None,
                    functions_called: HashMap::new(),
                    total_allocations: 0,
                    total_bytes_allocated: 0,
                    load_timestamp: current_time,
                    metadata: LibraryMetadata {
                        architecture: std::env::consts::ARCH.to_string(),
                        operating_system: std::env::consts::OS.to_string(),
                        compiler_info: None,
                        has_debug_symbols: false,
                        security_features: Vec::new(),
                    },
                });

            // Update library statistics
            library.total_allocations += 1;
            library.total_bytes_allocated += allocation_size;

            // Update or create function information
            let function_info = library
                .functions_called
                .entry(function_name.to_string())
                .or_insert_with(|| CFunctionInfo {
                    function_name: function_name.to_string(),
                    function_signature: None,
                    call_count: 0,
                    bytes_allocated: 0,
                    average_allocation_size: 0.0,
                    risk_assessment: RiskAssessment {
                        risk_level: RiskLevel::Low,
                        risk_factors: Vec::new(),
                        mitigation_suggestions: Vec::new(),
                        confidence_score: 0.5,
                        assessment_timestamp: current_time,
                    },
                    performance_metrics: FunctionPerformanceMetrics {
                        avg_execution_time_ns: 0,
                        min_execution_time_ns: u64::MAX,
                        max_execution_time_ns: 0,
                        total_execution_time_ns: 0,
                        tracking_overhead_ns: 0,
                    },
                    first_call_timestamp: current_time,
                    last_call_timestamp: current_time,
                });

            // Update function statistics
            function_info.call_count += 1;
            function_info.bytes_allocated += allocation_size;
            function_info.average_allocation_size =
                function_info.bytes_allocated as f64 / function_info.call_count as f64;
            function_info.last_call_timestamp = current_time;

            // Update performance metrics
            let metrics = &mut function_info.performance_metrics;
            metrics.total_execution_time_ns += execution_time_ns;
            metrics.avg_execution_time_ns =
                metrics.total_execution_time_ns / function_info.call_count as u64;
            metrics.min_execution_time_ns = metrics.min_execution_time_ns.min(execution_time_ns);
            metrics.max_execution_time_ns = metrics.max_execution_time_ns.max(execution_time_ns);

            tracing::debug!(
                "Tracked C function call: {}::{} (size: {}, time: {}ns)",
                library_name,
                function_name,
                allocation_size,
                execution_time_ns
            );
        }

        Ok(())
    }

    /// Install an enhanced LibC hook
    pub fn install_enhanced_libc_hook(
        &self,
        function_name: String,
        hook_method: HookInstallationMethod,
    ) -> TrackingResult<()> {
        let current_time = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();

        let installation_details = HookInstallationDetails {
            installation_method: hook_method,
            installation_success: true, // Assume success for now
            installation_error: None,
            installation_timestamp: current_time,
            process_id: std::process::id(),
            thread_id: 0, // Would need platform-specific code to get thread ID
        };

        let enhanced_hook = EnhancedLibCHookInfo {
            base_info: LibCHookInfo {
                hook_method: HookMethod::DynamicLinker,
                original_function: function_name.clone(),
                hook_timestamp: current_time,
                allocation_metadata: AllocationMetadata {
                    requested_size: 0,
                    actual_size: 0,
                    alignment: 8,
                    allocator_info: format!("hooked_{function_name}"),
                    protection_flags: Some(MemoryProtectionFlags {
                        readable: true,
                        writable: true,
                        executable: false,
                        shared: false,
                    }),
                },
                hook_overhead_ns: Some(50),
            },
            function_tracking: CFunctionInfo {
                function_name: function_name.clone(),
                function_signature: None,
                call_count: 0,
                bytes_allocated: 0,
                average_allocation_size: 0.0,
                risk_assessment: RiskAssessment {
                    risk_level: RiskLevel::Medium,
                    risk_factors: Vec::new(),
                    mitigation_suggestions: vec![
                        "Monitor for memory leaks".to_string(),
                        "Validate all pointer operations".to_string(),
                    ],
                    confidence_score: 0.7,
                    assessment_timestamp: current_time,
                },
                performance_metrics: FunctionPerformanceMetrics {
                    avg_execution_time_ns: 0,
                    min_execution_time_ns: u64::MAX,
                    max_execution_time_ns: 0,
                    total_execution_time_ns: 0,
                    tracking_overhead_ns: 50,
                },
                first_call_timestamp: current_time,
                last_call_timestamp: current_time,
            },
            installation_details,
            runtime_analysis: RuntimeBehaviorAnalysis {
                memory_patterns: Vec::new(),
                size_distribution: SizeDistribution {
                    small_allocations: 0,
                    medium_allocations: 0,
                    large_allocations: 0,
                    average_size: 0.0,
                    size_std_dev: 0.0,
                },
                temporal_patterns: TemporalPatterns {
                    allocation_rate: 0.0,
                    peak_periods: Vec::new(),
                    burst_count: 0,
                    avg_time_between_allocs_ms: 0.0,
                },
                error_patterns: Vec::new(),
            },
            security_analysis: SecurityAnalysis {
                vulnerabilities: Vec::new(),
                security_score: 5.0,
                recommendations: vec![
                    "Enable memory protection".to_string(),
                    "Use safe allocation patterns".to_string(),
                ],
                compliance_status: ComplianceStatus {
                    memory_safety: false,
                    thread_safety: false,
                    api_usage: true,
                    security_practices: false,
                    overall_score: 0.25,
                },
            },
        };

        if let Ok(mut hooks) = self.libc_hooks.lock() {
            hooks.insert(function_name.clone(), enhanced_hook);
            tracing::info!("Installed enhanced LibC hook for: {}", function_name);
        }

        Ok(())
    }

    /// Create and register a memory passport for cross-boundary tracking
    pub fn create_and_register_passport(
        &self,
        ptr: usize,
        origin_context: &str,
        security_clearance: SecurityClearance,
    ) -> TrackingResult<String> {
        let passport = self.create_memory_passport(ptr, origin_context);
        let passport_id = passport.passport_id.clone();

        // Set the security clearance
        let mut passport = passport;
        passport.security_clearance = security_clearance;

        if let Ok(mut passports) = self.memory_passports.lock() {
            passports.insert(ptr, passport);
            tracing::info!("Created memory passport {} for ptr {:x}", passport_id, ptr);
        }

        Ok(passport_id)
    }

    /// Update memory passport with new stamp
    pub fn stamp_passport(
        &self,
        ptr: usize,
        operation: &str,
        location: &str,
        authority: &str,
    ) -> TrackingResult<()> {
        let current_time = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();

        if let Ok(mut passports) = self.memory_passports.lock() {
            if let Some(passport) = passports.get_mut(&ptr) {
                let stamp = PassportStamp {
                    timestamp: current_time,
                    location: location.to_string(),
                    operation: operation.to_string(),
                    authority: authority.to_string(),
                    verification_hash: format!("{:x}", ptr ^ current_time as usize),
                };

                passport.journey.push(stamp);
                tracing::debug!("Stamped passport for ptr {:x}: {}", ptr, operation);
            } else {
                return Err(TrackingError::InvalidPointer(format!(
                    "No passport found for pointer: 0x{ptr:x}",
                )));
            }
        }

        Ok(())
    }

    /// Transfer memory passport ownership
    pub fn transfer_passport_ownership(
        &self,
        ptr: usize,
        new_owner_context: &str,
        new_owner_function: &str,
    ) -> TrackingResult<()> {
        let current_time = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();

        if let Ok(mut passports) = self.memory_passports.lock() {
            if let Some(passport) = passports.get_mut(&ptr) {
                passport.current_owner = OwnershipInfo {
                    owner_context: new_owner_context.to_string(),
                    owner_function: new_owner_function.to_string(),
                    transfer_timestamp: current_time,
                    expected_lifetime: None,
                };

                // Add a stamp for the ownership transfer
                let stamp = PassportStamp {
                    timestamp: current_time,
                    location: new_owner_context.to_string(),
                    operation: "ownership_transfer".to_string(),
                    authority: "UnsafeFFITracker".to_string(),
                    verification_hash: format!("{:x}", ptr ^ current_time as usize),
                };

                passport.journey.push(stamp);
                tracing::info!(
                    "Transferred passport ownership for ptr {:x} to {}::{}",
                    ptr,
                    new_owner_context,
                    new_owner_function
                );
            } else {
                return Err(TrackingError::InvalidPointer(format!(
                    "No passport found for pointer: 0x{ptr:x}",
                )));
            }
        }

        Ok(())
    }

    /// Revoke a memory passport (when memory is freed)
    pub fn revoke_passport(&self, ptr: usize, reason: &str) -> TrackingResult<()> {
        if let Ok(mut passports) = self.memory_passports.lock() {
            if let Some(passport) = passports.get_mut(&ptr) {
                passport.validity_status = ValidityStatus::Revoked;

                // Add a final stamp
                let current_time = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_nanos();

                let stamp = PassportStamp {
                    timestamp: current_time,
                    location: "memory_freed".to_string(),
                    operation: format!("revoked: {reason}"),
                    authority: "UnsafeFFITracker".to_string(),
                    verification_hash: format!("{:x}", ptr ^ current_time as usize),
                };

                passport.journey.push(stamp);
                tracing::info!("Revoked passport for ptr {ptr:x}: {reason}");
            }
        }

        Ok(())
    }

    /// Get C library statistics
    pub fn get_c_library_stats(&self) -> TrackingResult<HashMap<String, CLibraryInfo>> {
        self.c_libraries
            .lock()
            .map(|libs| libs.clone())
            .map_err(|e| TrackingError::LockError(e.to_string()))
    }

    /// Get LibC hook information
    pub fn get_libc_hook_info(&self) -> TrackingResult<HashMap<String, EnhancedLibCHookInfo>> {
        self.libc_hooks
            .lock()
            .map(|hooks| hooks.clone())
            .map_err(|e| TrackingError::LockError(e.to_string()))
    }

    /// Get memory passport information
    pub fn get_memory_passports(&self) -> TrackingResult<HashMap<usize, MemoryPassport>> {
        self.memory_passports
            .lock()
            .map(|passports| passports.clone())
            .map_err(|e| TrackingError::LockError(e.to_string()))
    }

    /// Analyze cross-boundary risks with detailed assessment
    pub fn analyze_cross_boundary_risks(&self) -> TrackingResult<Vec<SafetyViolation>> {
        let mut risks = Vec::new();

        if let Ok(passports) = self.memory_passports.lock() {
            for (ptr, passport) in passports.iter() {
                // Check for suspicious passport activity
                if passport.journey.len() > 10 {
                    risks.push(SafetyViolation::CrossBoundaryRisk {
                        risk_level: RiskLevel::Medium,
                        description: format!(
                            "Memory at {ptr:x} has crossed boundaries {} times",
                            passport.journey.len()
                        ),
                        stack: {
                            let normalizer = get_global_call_stack_normalizer();
                            let empty_frames = vec![];
                            let id = normalizer.normalize_call_stack(&empty_frames).unwrap_or(0);
                            CallStackRef::new(id, Some(0))
                        },
                    });
                }

                // Check for expired passports
                if matches!(passport.validity_status, ValidityStatus::Expired) {
                    risks.push(SafetyViolation::CrossBoundaryRisk {
                        risk_level: RiskLevel::High,
                        description: format!("Expired passport detected for memory at {ptr:x}"),
                        stack: {
                            let normalizer = get_global_call_stack_normalizer();
                            let empty_frames = vec![];
                            let id = normalizer.normalize_call_stack(&empty_frames).unwrap_or(0);
                            CallStackRef::new(id, Some(0))
                        },
                    });
                }
            }
        }

        Ok(risks)
    }

    /// Process boundary events with comprehensive analysis
    pub fn process_boundary_event(
        &self,
        ptr: usize,
        event_type: BoundaryEventType,
        from_context: &str,
        to_context: &str,
        transfer_size: usize,
    ) -> TrackingResult<BoundaryEventAnalysis> {
        let current_time = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();

        // Record the boundary event
        self.record_boundary_event(
            ptr,
            event_type.clone(),
            from_context.to_string(),
            to_context.to_string(),
        )?;

        // Analyze the risk level for this specific transfer
        let risk_analysis = self.assess_boundary_transfer_risk(
            ptr,
            &event_type,
            from_context,
            to_context,
            transfer_size,
        )?;

        // Update ownership tracking
        self.track_ownership_transfer(ptr, from_context, to_context)?;

        // Create comprehensive analysis
        let analysis = BoundaryEventAnalysis {
            event_id: format!("boundary_{ptr}_{current_time}"),
            ptr,
            event_type: event_type.clone(),
            from_context: from_context.to_string(),
            to_context: to_context.to_string(),
            transfer_size,
            timestamp: current_time,
            risk_assessment: risk_analysis.clone(),
            ownership_chain: self.get_ownership_chain(ptr)?,
            security_implications: self.analyze_security_implications(
                ptr,
                from_context,
                to_context,
            )?,
            performance_impact: self.estimate_performance_impact(&event_type, transfer_size),
            mitigation_recommendations: self.generate_mitigation_recommendations(&risk_analysis),
        };

        Ok(analysis)
    }

    /// Assess risk level for boundary transfers
    fn assess_boundary_transfer_risk(
        &self,
        ptr: usize,
        event_type: &BoundaryEventType,
        _from_context: &str,
        _to_context: &str,
        transfer_size: usize,
    ) -> TrackingResult<BoundaryRiskAssessment> {
        let mut risk_factors = Vec::new();
        let mut risk_score = 0.0;

        // Analyze transfer direction risk
        match event_type {
            BoundaryEventType::RustToFfi => {
                risk_factors.push(BoundaryRiskFactor {
                    factor_type: BoundaryRiskFactorType::RustToForeignTransfer,
                    severity: 6.0,
                    description: "Memory allocated in Rust being passed to foreign code"
                        .to_string(),
                    mitigation: "Ensure foreign code doesn't free Rust-allocated memory"
                        .to_string(),
                });
                risk_score += 6.0;
            }
            BoundaryEventType::FfiToRust => {
                risk_factors.push(BoundaryRiskFactor {
                    factor_type: BoundaryRiskFactorType::ForeignToRustTransfer,
                    severity: 7.0,
                    description: "Foreign-allocated memory being passed to Rust".to_string(),
                    mitigation: "Validate memory layout and lifetime guarantees".to_string(),
                });
                risk_score += 7.0;
            }
            BoundaryEventType::OwnershipTransfer => {
                risk_factors.push(BoundaryRiskFactor {
                    factor_type: BoundaryRiskFactorType::OwnershipTransfer,
                    severity: 8.0,
                    description: "Memory ownership being transferred across language boundary"
                        .to_string(),
                    mitigation: "Clearly document ownership transfer and cleanup responsibilities"
                        .to_string(),
                });
                risk_score += 8.0;
            }
            BoundaryEventType::SharedAccess => {
                risk_factors.push(BoundaryRiskFactor {
                    factor_type: BoundaryRiskFactorType::SharedAccess,
                    severity: 5.0,
                    description: "Memory being shared between Rust and foreign code".to_string(),
                    mitigation: "Implement proper synchronization mechanisms".to_string(),
                });
                risk_score += 5.0;
            }
        }

        // Analyze transfer size risk
        if transfer_size > 1024 * 1024 {
            risk_factors.push(BoundaryRiskFactor {
                factor_type: BoundaryRiskFactorType::LargeTransfer,
                severity: 4.0,
                description: format!("Large memory transfer: {transfer_size} bytes"),
                mitigation: "Consider streaming or chunked transfer for large data".to_string(),
            });
            risk_score += 4.0;
        }

        // Check for frequent transfers (potential performance issue)
        if let Ok(allocations) = self.enhanced_allocations.lock() {
            if let Some(allocation) = allocations.get(&ptr) {
                if allocation.cross_boundary_events.len() > 5 {
                    risk_factors.push(BoundaryRiskFactor {
                        factor_type: BoundaryRiskFactorType::FrequentTransfers,
                        severity: 3.0,
                        description: format!(
                            "Memory has crossed boundaries {} times",
                            allocation.cross_boundary_events.len()
                        ),
                        mitigation: "Consider reducing boundary crossings or caching".to_string(),
                    });
                    risk_score += 3.0;
                }
            }
        }

        // Determine overall risk level
        let risk_level = if risk_score >= 15.0 {
            RiskLevel::Critical
        } else if risk_score >= 10.0 {
            RiskLevel::High
        } else if risk_score >= 5.0 {
            RiskLevel::Medium
        } else {
            RiskLevel::Low
        };

        Ok(BoundaryRiskAssessment {
            overall_risk_level: risk_level,
            risk_score,
            risk_factors,
            confidence_score: 0.8, // High confidence in boundary risk assessment
            assessment_timestamp: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos(),
        })
    }

    /// Track ownership transfer across boundaries
    fn track_ownership_transfer(
        &self,
        ptr: usize,
        from_context: &str,
        to_context: &str,
    ) -> TrackingResult<()> {
        let current_time = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();

        // Update memory passport ownership
        if let Ok(mut passports) = self.memory_passports.lock() {
            if let Some(passport) = passports.get_mut(&ptr) {
                // Record the ownership transfer in the journey
                let stamp = PassportStamp {
                    timestamp: current_time,
                    location: to_context.to_string(),
                    operation: format!("ownership_transfer_from_{from_context}"),
                    authority: "BoundaryEventProcessor".to_string(),
                    verification_hash: format!("{:x}", ptr ^ current_time as usize),
                };
                passport.journey.push(stamp);

                // Update current owner
                passport.current_owner = OwnershipInfo {
                    owner_context: to_context.to_string(),
                    owner_function: "unknown".to_string(),
                    transfer_timestamp: current_time,
                    expected_lifetime: None,
                };
            }
        }

        // Update allocation tracking
        if let Ok(mut allocations) = self.enhanced_allocations.lock() {
            if let Some(allocation) = allocations.get_mut(&ptr) {
                // Add ownership transfer event
                let ownership_event = OwnershipTransferEvent {
                    transfer_id: format!("transfer_{ptr}_{current_time}"),
                    ptr,
                    from_context: from_context.to_string(),
                    to_context: to_context.to_string(),
                    transfer_timestamp: current_time,
                    transfer_reason: "boundary_crossing".to_string(),
                    validation_status: OwnershipValidationStatus::Pending,
                };

                // Store in allocation's ownership history
                if allocation.ownership_history.is_none() {
                    allocation.ownership_history = Some(Vec::new());
                }
                if let Some(ref mut history) = allocation.ownership_history {
                    history.push(ownership_event);
                }
            }
        }

        Ok(())
    }

    /// Get ownership chain for a memory allocation
    fn get_ownership_chain(&self, ptr: usize) -> TrackingResult<Vec<OwnershipRecord>> {
        let mut chain = Vec::new();

        if let Ok(allocations) = self.enhanced_allocations.lock() {
            if let Some(allocation) = allocations.get(&ptr) {
                if let Some(ref history) = allocation.ownership_history {
                    for transfer in history {
                        chain.push(OwnershipRecord {
                            context: transfer.to_context.clone(),
                            timestamp: transfer.transfer_timestamp,
                            transfer_reason: transfer.transfer_reason.clone(),
                            validation_status: transfer.validation_status.clone(),
                        });
                    }
                }
            }
        }

        Ok(chain)
    }

    /// Analyze security implications of boundary crossing
    fn analyze_security_implications(
        &self,
        _ptr: usize,
        from_context: &str,
        to_context: &str,
    ) -> TrackingResult<Vec<SecurityImplication>> {
        let mut implications = Vec::new();

        // Check for privilege escalation
        if from_context.contains("user") && to_context.contains("system") {
            implications.push(SecurityImplication {
                implication_type: SecurityImplicationType::PrivilegeEscalation,
                severity: RiskLevel::High,
                description: "Memory transfer from user context to system context".to_string(),
                potential_impact: "Potential privilege escalation vulnerability".to_string(),
                recommended_action: "Validate and sanitize all data before system context access"
                    .to_string(),
            });
        }

        // Check for data exposure
        if from_context.contains("secure") || to_context.contains("secure") {
            implications.push(SecurityImplication {
                implication_type: SecurityImplicationType::DataExposure,
                severity: RiskLevel::Medium,
                description: "Memory transfer involving secure context".to_string(),
                potential_impact: "Potential sensitive data exposure".to_string(),
                recommended_action: "Ensure proper data sanitization and access controls"
                    .to_string(),
            });
        }

        // Check for injection attacks
        if to_context.contains("interpreter") || to_context.contains("eval") {
            implications.push(SecurityImplication {
                implication_type: SecurityImplicationType::InjectionRisk,
                severity: RiskLevel::Critical,
                description: "Memory transfer to code interpretation context".to_string(),
                potential_impact: "Potential code injection vulnerability".to_string(),
                recommended_action: "Validate and sanitize all input data before interpretation"
                    .to_string(),
            });
        }

        Ok(implications)
    }

    /// Estimate performance impact of boundary crossing
    fn estimate_performance_impact(
        &self,
        event_type: &BoundaryEventType,
        transfer_size: usize,
    ) -> PerformanceImpact {
        let base_overhead_ns = match event_type {
            BoundaryEventType::RustToFfi => 100,
            BoundaryEventType::FfiToRust => 150,
            BoundaryEventType::OwnershipTransfer => 200,
            BoundaryEventType::SharedAccess => 50,
        };

        let size_overhead_ns = (transfer_size / 1024) as u64 * 10; // 10ns per KB
        let total_overhead_ns = base_overhead_ns + size_overhead_ns;

        let impact_level = if total_overhead_ns > 10000 {
            PerformanceImpactLevel::High
        } else if total_overhead_ns > 1000 {
            PerformanceImpactLevel::Medium
        } else {
            PerformanceImpactLevel::Low
        };

        PerformanceImpact {
            impact_level,
            estimated_overhead_ns: total_overhead_ns,
            memory_overhead_bytes: transfer_size / 10, // Assume 10% memory overhead
            cpu_overhead_percent: if total_overhead_ns > 5000 { 5.0 } else { 1.0 },
            recommendations: vec![
                "Consider batching small transfers".to_string(),
                "Use memory mapping for large transfers".to_string(),
                "Implement caching for frequently accessed data".to_string(),
            ],
        }
    }

    /// Generate mitigation recommendations based on risk assessment
    fn generate_mitigation_recommendations(
        &self,
        risk_assessment: &BoundaryRiskAssessment,
    ) -> Vec<String> {
        let mut recommendations = Vec::new();

        match risk_assessment.overall_risk_level {
            RiskLevel::Critical => {
                recommendations
                    .push("URGENT: Review and redesign boundary crossing strategy".to_string());
                recommendations.push("Implement comprehensive input validation".to_string());
                recommendations.push("Add runtime safety checks".to_string());
                recommendations
                    .push("Consider using safer alternatives to raw pointers".to_string());
            }
            RiskLevel::High => {
                recommendations.push("Implement additional safety checks".to_string());
                recommendations.push("Add comprehensive logging and monitoring".to_string());
                recommendations.push("Review memory ownership patterns".to_string());
            }
            RiskLevel::Medium => {
                recommendations.push("Monitor boundary crossing frequency".to_string());
                recommendations.push("Consider performance optimizations".to_string());
                recommendations.push("Document ownership transfer clearly".to_string());
            }
            RiskLevel::Low => {
                recommendations.push("Continue current practices".to_string());
                recommendations.push("Periodic review recommended".to_string());
            }
        }

        // Add specific recommendations based on risk factors
        for factor in &risk_assessment.risk_factors {
            recommendations.push(factor.mitigation.clone());
        }

        recommendations.dedup();
        recommendations
    }

    /// Get comprehensive boundary event statistics
    pub fn get_boundary_event_statistics(&self) -> TrackingResult<BoundaryEventStatistics> {
        let mut stats = BoundaryEventStatistics {
            total_events: 0,
            events_by_type: std::collections::HashMap::new(),
            risk_distribution: std::collections::HashMap::new(),
            average_transfer_size: 0.0,
            total_transfer_volume: 0,
            most_active_contexts: Vec::new(),
            security_incidents: 0,
            performance_issues: 0,
            analysis_timestamp: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos(),
        };

        if let Ok(allocations) = self.enhanced_allocations.lock() {
            let mut context_activity: std::collections::HashMap<String, usize> =
                std::collections::HashMap::new();
            let mut total_size = 0usize;
            let mut event_count = 0usize;

            for allocation in allocations.values() {
                for event in &allocation.cross_boundary_events {
                    stats.total_events += 1;
                    event_count += 1;

                    // Count by event type
                    *stats
                        .events_by_type
                        .entry(format!("{:?}", event.event_type))
                        .or_insert(0) += 1;

                    // Track context activity
                    *context_activity
                        .entry(event.from_context.clone())
                        .or_insert(0) += 1;
                    *context_activity
                        .entry(event.to_context.clone())
                        .or_insert(0) += 1;

                    // Estimate transfer size (would need actual size tracking)
                    let estimated_size = allocation.base.size;
                    total_size += estimated_size;
                }
            }

            if event_count > 0 {
                stats.average_transfer_size = total_size as f64 / event_count as f64;
            }
            stats.total_transfer_volume = total_size;

            // Get most active contexts
            let mut context_vec: Vec<_> = context_activity.into_iter().collect();
            context_vec.sort_by_key(|b| std::cmp::Reverse(b.1));
            stats.most_active_contexts = context_vec.into_iter().take(10).collect();
        }

        Ok(stats)
    }

    /// Get statistics for unsafe and FFI operations
    pub fn get_stats(&self) -> UnsafeFFIStats {
        let allocations = self
            .enhanced_allocations
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let violations = self
            .violations
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());

        let mut stats = UnsafeFFIStats::default();

        // Count different types of operations
        for allocation in allocations.values() {
            match &allocation.source {
                AllocationSource::UnsafeRust { .. } => {
                    stats.unsafe_blocks += 1;
                    stats.total_operations += 1;
                }
                AllocationSource::FfiC { .. } => {
                    stats.ffi_calls += 1;
                    stats.total_operations += 1;
                }
                AllocationSource::CrossBoundary { .. } => {
                    stats.total_operations += 1;
                }
                _ => {}
            }

            // Count safety violations
            stats.memory_violations += allocation.safety_violations.len();
        }

        // Add violations from the violations log
        stats.memory_violations += violations.len();

        // Calculate risk score (simplified)
        stats.risk_score = if stats.total_operations > 0 {
            let base_risk = (stats.unsafe_blocks as f64 * 1.0)
                + (stats.ffi_calls as f64 * 2.0)
                + (stats.memory_violations as f64 * 5.0);
            (base_risk / stats.total_operations as f64).min(10.0)
        } else {
            0.0
        };

        // Create operation list (simplified)
        for allocation in allocations.values() {
            let (op_type, risk_level, description) = match &allocation.source {
                AllocationSource::UnsafeRust {
                    unsafe_block_location,
                    ..
                } => (
                    UnsafeOperationType::UnsafeBlock,
                    RiskLevel::Medium,
                    format!("Unsafe block at {unsafe_block_location}"),
                ),
                AllocationSource::FfiC {
                    resolved_function, ..
                } => (
                    UnsafeOperationType::FfiCall,
                    RiskLevel::High,
                    format!(
                        "FFI call to {}::{}",
                        resolved_function.library_name, resolved_function.function_name
                    ),
                ),
                AllocationSource::CrossBoundary { .. } => (
                    UnsafeOperationType::CrossBoundaryTransfer,
                    RiskLevel::Medium,
                    "Cross-boundary memory transfer".to_string(),
                ),
                _ => continue,
            };

            stats.operations.push(UnsafeOperation {
                operation_type: op_type,
                location: "unknown".to_string(), // Could be enhanced with actual location
                risk_level,
                timestamp: allocation.base.timestamp_alloc as u128,
                description,
            });
        }

        // Limit operations to avoid huge JSON
        stats.operations.truncate(50);

        stats
    }

    /// Integrate with SafetyAnalyzer for enhanced reporting
    pub fn integrate_with_safety_analyzer(
        &self,
        safety_analyzer: &crate::analysis::SafetyAnalyzer,
    ) -> TrackingResult<()> {
        // Get current violations
        let violations = if let Ok(violations) = self.violations.lock() {
            violations.clone()
        } else {
            return Err(TrackingError::LockContention(
                "Failed to lock violations".to_string(),
            ));
        };

        // Get current allocations
        let allocations: Vec<AllocationInfo> =
            if let Ok(enhanced_allocations) = self.enhanced_allocations.lock() {
                enhanced_allocations
                    .values()
                    .map(|ea| ea.base.clone())
                    .collect()
            } else {
                return Err(TrackingError::LockContention(
                    "Failed to lock allocations".to_string(),
                ));
            };

        // Generate unsafe reports for each violation
        for violation in &violations {
            let source = match violation {
                SafetyViolation::DoubleFree { .. } => crate::analysis::UnsafeSource::RawPointer {
                    operation: "double_free".to_string(),
                    location: "memory_violation".to_string(),
                },
                SafetyViolation::InvalidFree {
                    attempted_pointer, ..
                } => crate::analysis::UnsafeSource::RawPointer {
                    operation: "invalid_free".to_string(),
                    location: format!("0x{attempted_pointer:x}"),
                },
                SafetyViolation::PotentialLeak { .. } => {
                    crate::analysis::UnsafeSource::RawPointer {
                        operation: "potential_leak".to_string(),
                        location: "memory_leak".to_string(),
                    }
                }
                SafetyViolation::CrossBoundaryRisk { description, .. } => {
                    crate::analysis::UnsafeSource::FfiFunction {
                        library: "unknown".to_string(),
                        function: "cross_boundary".to_string(),
                        call_site: description.clone(),
                    }
                }
            };

            let _report_id =
                safety_analyzer.generate_unsafe_report(source, &allocations, &violations)?;
        }

        tracing::info!(
            "🔗 Integrated {} violations with SafetyAnalyzer",
            violations.len()
        );
        Ok(())
    }

    /// Integrate with MemoryPassportTracker for FFI boundary tracking
    pub fn integrate_with_passport_tracker(
        &self,
        passport_tracker: &crate::analysis::MemoryPassportTracker,
    ) -> TrackingResult<()> {
        if let Ok(enhanced_allocations) = self.enhanced_allocations.lock() {
            for (ptr, allocation) in enhanced_allocations.iter() {
                // Create passports for FFI allocations
                if allocation.ffi_tracked {
                    // Use type inference if type_name is not available
                    let type_name = allocation.base.type_name.clone();
                    let _passport_id = if type_name.is_none()
                        || type_name
                            .as_ref()
                            .is_none_or(|t| t == "unknown" || t.is_empty())
                    {
                        // Use inference-based passport creation
                        passport_tracker.create_passport_with_inference(
                            *ptr,
                            allocation.base.size,
                            None,
                            "ffi_integration".to_string(),
                            allocation.base.var_name.clone(),
                        )?
                    } else {
                        passport_tracker.create_passport(
                            *ptr,
                            allocation.base.size,
                            "ffi_integration".to_string(),
                            type_name,
                            allocation.base.var_name.clone(),
                        )?
                    };

                    // Record boundary events
                    for event in &allocation.cross_boundary_events {
                        let event_type = match event.event_type {
                            BoundaryEventType::RustToFfi => {
                                crate::analysis::PassportEventType::HandoverToFfi
                            }
                            BoundaryEventType::FfiToRust => {
                                crate::analysis::PassportEventType::ReclaimedByRust
                            }
                            BoundaryEventType::OwnershipTransfer => {
                                crate::analysis::PassportEventType::OwnershipTransfer
                            }
                            BoundaryEventType::SharedAccess => {
                                crate::analysis::PassportEventType::BoundaryAccess
                            }
                        };

                        passport_tracker.record_passport_event(
                            *ptr,
                            event_type,
                            event.to_context.clone(),
                            std::collections::HashMap::new(),
                        )?;
                    }
                }
            }
        }

        tracing::info!("🔗 Integrated FFI allocations with MemoryPassportTracker");
        Ok(())
    }

    /// Perform comprehensive safety analysis using integrated components
    pub fn perform_comprehensive_safety_analysis(
        &self,
    ) -> TrackingResult<crate::analysis::ComprehensiveSafetyReport> {
        // Initialize integrated components
        let safety_analyzer = crate::analysis::SafetyAnalyzer::default();
        let passport_tracker = crate::analysis::get_global_passport_tracker();

        // Integrate with components
        self.integrate_with_safety_analyzer(&safety_analyzer)?;
        self.integrate_with_passport_tracker(&passport_tracker)?;

        // Detect leaks at shutdown
        let leak_detection = passport_tracker.detect_leaks_at_shutdown();

        // Get reports and statistics
        let unsafe_reports = safety_analyzer.get_unsafe_reports();
        let memory_passports = passport_tracker.get_all_passports();
        let safety_stats = safety_analyzer.get_stats();
        let passport_stats = passport_tracker.get_stats();

        let report = crate::analysis::ComprehensiveSafetyReport {
            unsafe_reports,
            memory_passports,
            leak_detection,
            safety_stats,
            passport_stats,
            analysis_timestamp: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
        };

        tracing::info!("📊 Generated comprehensive safety analysis report");
        Ok(report)
    }
}

/// Comprehensive safety analysis report
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ComprehensiveSafetyReport {
    /// All unsafe operation reports
    pub unsafe_reports: std::collections::HashMap<String, crate::analysis::UnsafeReport>,
    /// All memory passports
    pub memory_passports: std::collections::HashMap<usize, crate::analysis::MemoryPassport>,
    /// Leak detection results
    pub leak_detection: crate::analysis::LeakDetectionResult,
    /// Safety analysis statistics
    pub safety_stats: crate::analysis::SafetyAnalysisStats,
    /// Passport tracker statistics
    pub passport_stats: crate::analysis::PassportTrackerStats,
    /// Analysis timestamp
    pub analysis_timestamp: u64,
}

/// Global unsafe/FFI tracker instance
static GLOBAL_UNSAFE_TRACKER: OnceLock<Arc<UnsafeFFITracker>> = OnceLock::new();

/// Get the global unsafe/FFI tracker instance
pub fn get_global_unsafe_tracker() -> Option<Arc<UnsafeFFITracker>> {
    GLOBAL_UNSAFE_TRACKER.get().cloned()
}

/// Initialize the global unsafe/FFI tracker
pub fn init_global_unsafe_tracker() -> Arc<UnsafeFFITracker> {
    GLOBAL_UNSAFE_TRACKER
        .get_or_init(|| Arc::new(UnsafeFFITracker::new()))
        .clone()
}

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

    /// Helper function to create a test tracker
    fn create_test_tracker() -> UnsafeFFITracker {
        UnsafeFFITracker::new()
    }

    #[test]
    fn test_unsafe_ffi_tracker_creation() {
        let tracker = create_test_tracker();

        // Verify initial state
        assert!(tracker
            .get_enhanced_allocations()
            .expect("Should get enhanced allocations")
            .is_empty());
        assert!(tracker
            .get_safety_violations()
            .expect("Should get safety violations")
            .is_empty());
        assert!(tracker
            .get_c_library_stats()
            .expect("Should get C library stats")
            .is_empty());
    }

    #[test]
    fn test_unsafe_ffi_tracker_default() {
        let tracker = UnsafeFFITracker::default();

        // Verify default state
        assert!(tracker
            .get_enhanced_allocations()
            .expect("Should get enhanced allocations after reset")
            .is_empty());
        assert!(tracker
            .get_safety_violations()
            .expect("Should get safety violations after reset")
            .is_empty());
    }

    #[test]
    fn test_track_unsafe_allocation() {
        let tracker = create_test_tracker();
        let ptr = 0x1000;
        let size = 1024;
        let location = "test_file.rs:42:10".to_string();

        let result = tracker.track_unsafe_allocation(ptr, size, location.clone());
        assert!(result.is_ok());

        // Verify allocation was tracked
        let allocations = tracker.get_enhanced_allocations().unwrap();
        assert_eq!(allocations.len(), 1);

        let allocation = &allocations[0];
        assert_eq!(allocation.base.ptr, ptr);
        assert_eq!(allocation.base.size, size);

        // Verify it's marked as unsafe
        match &allocation.source {
            AllocationSource::UnsafeRust {
                unsafe_block_location,
                ..
            } => {
                assert_eq!(unsafe_block_location, &location);
            }
            _ => panic!("Expected UnsafeRust allocation source"),
        }
    }

    #[test]
    fn test_track_ffi_allocation() {
        let tracker = create_test_tracker();
        let ptr = 0x2000;
        let size = 512;
        let library_name = "libc".to_string();
        let function_name = "malloc".to_string();

        let result =
            tracker.track_ffi_allocation(ptr, size, library_name.clone(), function_name.clone());
        assert!(result.is_ok());

        // Verify allocation was tracked
        let allocations = tracker.get_enhanced_allocations().unwrap();
        assert_eq!(allocations.len(), 1);

        let allocation = &allocations[0];
        assert_eq!(allocation.base.ptr, ptr);
        assert_eq!(allocation.base.size, size);
        assert!(allocation.ffi_tracked);

        // Verify it's marked as FFI
        match &allocation.source {
            AllocationSource::FfiC {
                resolved_function, ..
            } => {
                assert_eq!(resolved_function.library_name, library_name);
                assert_eq!(resolved_function.function_name, function_name);
            }
            _ => panic!("Expected FfiC allocation source"),
        }
    }

    #[test]
    fn test_track_enhanced_deallocation_valid() {
        let tracker = create_test_tracker();
        let ptr = 0x3000;
        let size = 256;

        // First track an allocation
        tracker
            .track_unsafe_allocation(ptr, size, "test_location".to_string())
            .unwrap();

        // Then deallocate it
        let result = tracker.track_enhanced_deallocation(ptr);
        assert!(result.is_ok());

        // Verify allocation was removed
        let allocations = tracker.get_enhanced_allocations().unwrap();
        assert!(allocations.is_empty());
    }

    #[test]
    fn test_track_enhanced_deallocation_invalid_free() {
        let tracker = create_test_tracker();
        let ptr = 0x4000;

        // Try to free a pointer that was never allocated
        let result = tracker.track_enhanced_deallocation(ptr);
        assert!(result.is_err());

        // Verify violation was recorded
        let violations = tracker.get_safety_violations().unwrap();
        assert_eq!(violations.len(), 1);

        match &violations[0] {
            SafetyViolation::InvalidFree {
                attempted_pointer, ..
            } => {
                assert_eq!(*attempted_pointer, ptr);
            }
            _ => panic!("Expected InvalidFree violation"),
        }
    }

    #[test]
    fn test_track_enhanced_deallocation_double_free() {
        let tracker = create_test_tracker();
        let ptr = 0x5000;
        let size = 128;

        // Track allocation
        tracker
            .track_unsafe_allocation(ptr, size, "test_location".to_string())
            .unwrap();

        // First deallocation (should succeed)
        let result1 = tracker.track_enhanced_deallocation(ptr);
        assert!(result1.is_ok());

        // Second deallocation (should fail with double free)
        let result2 = tracker.track_enhanced_deallocation(ptr);
        assert!(result2.is_err());

        // Verify double free violation was recorded
        let violations = tracker.get_safety_violations().unwrap();
        assert_eq!(violations.len(), 1);

        match &violations[0] {
            SafetyViolation::DoubleFree { .. } => {
                // Expected
            }
            _ => panic!("Expected DoubleFree violation"),
        }
    }

    #[test]
    fn test_record_boundary_event() {
        let tracker = create_test_tracker();
        let ptr = 0x6000;
        let size = 1024;

        // Track allocation first
        tracker
            .track_unsafe_allocation(ptr, size, "test_location".to_string())
            .unwrap();

        // Record boundary event
        let result = tracker.record_boundary_event(
            ptr,
            BoundaryEventType::RustToFfi,
            "rust_context".to_string(),
            "ffi_context".to_string(),
        );
        assert!(result.is_ok());

        // Verify event was recorded
        let allocations = tracker.get_enhanced_allocations().unwrap();
        assert_eq!(allocations.len(), 1);

        let allocation = &allocations[0];
        assert_eq!(allocation.cross_boundary_events.len(), 1);

        let event = &allocation.cross_boundary_events[0];
        assert!(matches!(event.event_type, BoundaryEventType::RustToFfi));
        assert_eq!(event.from_context, "rust_context");
        assert_eq!(event.to_context, "ffi_context");
    }

    #[test]
    fn test_register_c_library() {
        let tracker = create_test_tracker();
        let library_name = "test_lib".to_string();
        let library_path = Some("/usr/lib/libtest.so".to_string());
        let library_version = Some("1.0.0".to_string());

        let result = tracker.register_c_library(
            library_name.clone(),
            library_path.clone(),
            library_version.clone(),
        );
        assert!(result.is_ok());

        // Verify library was registered
        let libraries = tracker.get_c_library_stats().unwrap();
        assert_eq!(libraries.len(), 1);

        let library = libraries.get(&library_name).unwrap();
        assert_eq!(library.library_name, library_name);
        assert_eq!(library.library_path, library_path);
        assert_eq!(library.library_version, library_version);
        assert_eq!(library.total_allocations, 0);
        assert_eq!(library.total_bytes_allocated, 0);
    }

    #[test]
    fn test_track_c_function_call() {
        let tracker = create_test_tracker();
        let library_name = "libc";
        let function_name = "malloc";
        let allocation_size = 1024;
        let execution_time_ns = 500;

        let result = tracker.track_c_function_call(
            library_name,
            function_name,
            allocation_size,
            execution_time_ns,
        );
        assert!(result.is_ok());

        // Verify function call was tracked
        let libraries = tracker.get_c_library_stats().unwrap();
        assert_eq!(libraries.len(), 1);

        let library = libraries.get(library_name).unwrap();
        assert_eq!(library.total_allocations, 1);
        assert_eq!(library.total_bytes_allocated, allocation_size);

        let function = library.functions_called.get(function_name).unwrap();
        assert_eq!(function.call_count, 1);
        assert_eq!(function.bytes_allocated, allocation_size);
        assert_eq!(function.average_allocation_size, allocation_size as f64);
        assert_eq!(
            function.performance_metrics.avg_execution_time_ns,
            execution_time_ns
        );
    }

    #[test]
    fn test_install_enhanced_libc_hook() {
        let tracker = create_test_tracker();
        let function_name = "malloc".to_string();
        let hook_method = HookInstallationMethod::Preload;

        let result = tracker.install_enhanced_libc_hook(function_name.clone(), hook_method);
        assert!(result.is_ok());

        // Verify hook was installed
        let hooks = tracker.get_libc_hook_info().unwrap();
        assert_eq!(hooks.len(), 1);

        let hook = hooks.get(&function_name).unwrap();
        assert_eq!(hook.base_info.original_function, function_name);
        assert!(matches!(
            hook.installation_details.installation_method,
            HookInstallationMethod::Preload
        ));
        assert!(hook.installation_details.installation_success);
    }

    #[test]
    fn test_create_and_register_passport() {
        let tracker = create_test_tracker();
        let ptr = 0x7000;
        let origin_context = "rust_main";
        let security_clearance = SecurityClearance::Public;

        let result = tracker.create_and_register_passport(ptr, origin_context, security_clearance);
        assert!(result.is_ok());

        let passport_id = result.unwrap();
        assert!(!passport_id.is_empty());

        // Verify passport was created
        let passports = tracker.get_memory_passports().unwrap();
        assert_eq!(passports.len(), 1);

        let passport = passports.get(&ptr).unwrap();
        assert_eq!(passport.passport_id, passport_id);
        assert_eq!(passport.origin.context, origin_context);
        assert!(matches!(
            passport.security_clearance,
            SecurityClearance::Public
        ));
        assert!(matches!(passport.validity_status, ValidityStatus::Valid));
    }

    #[test]
    fn test_stamp_passport() {
        let tracker = create_test_tracker();
        let ptr = 0x8000;

        // Create passport first
        tracker
            .create_and_register_passport(ptr, "rust_main", SecurityClearance::Public)
            .unwrap();

        // Stamp the passport
        let result =
            tracker.stamp_passport(ptr, "memory_access", "ffi_boundary", "UnsafeFFITracker");
        assert!(result.is_ok());

        // Verify stamp was added
        let passports = tracker.get_memory_passports().unwrap();
        let passport = passports.get(&ptr).unwrap();
        assert_eq!(passport.journey.len(), 1);

        let stamp = &passport.journey[0];
        assert_eq!(stamp.operation, "memory_access");
        assert_eq!(stamp.location, "ffi_boundary");
        assert_eq!(stamp.authority, "UnsafeFFITracker");
    }

    #[test]
    fn test_transfer_passport_ownership() {
        let tracker = create_test_tracker();
        let ptr = 0x9000;

        // Create passport first
        tracker
            .create_and_register_passport(ptr, "rust_main", SecurityClearance::Public)
            .unwrap();

        // Transfer ownership
        let result = tracker.transfer_passport_ownership(ptr, "ffi_context", "malloc");
        assert!(result.is_ok());

        // Verify ownership was transferred
        let passports = tracker.get_memory_passports().unwrap();
        let passport = passports.get(&ptr).unwrap();
        assert_eq!(passport.current_owner.owner_context, "ffi_context");
        assert_eq!(passport.current_owner.owner_function, "malloc");

        // Verify transfer was recorded in journey
        assert_eq!(passport.journey.len(), 1);
        assert_eq!(passport.journey[0].operation, "ownership_transfer");
    }

    #[test]
    fn test_revoke_passport() {
        let tracker = create_test_tracker();
        let ptr = 0xa000;

        // Create passport first
        tracker
            .create_and_register_passport(ptr, "rust_main", SecurityClearance::Public)
            .unwrap();

        // Revoke passport
        let result = tracker.revoke_passport(ptr, "memory_freed");
        assert!(result.is_ok());

        // Verify passport was revoked
        let passports = tracker.get_memory_passports().unwrap();
        let passport = passports.get(&ptr).unwrap();
        assert!(matches!(passport.validity_status, ValidityStatus::Revoked));

        // Verify revocation was recorded in journey
        assert_eq!(passport.journey.len(), 1);
        assert!(passport.journey[0].operation.contains("revoked"));
    }

    #[test]
    fn test_validate_passport() {
        let tracker = create_test_tracker();
        let ptr = 0xb000;

        // Track allocation first to make validation work properly
        tracker
            .track_unsafe_allocation(ptr, 1024, "test_location".to_string())
            .unwrap();

        // Create passport for the allocation
        tracker
            .create_or_update_passport(ptr, "create", "rust_main")
            .unwrap();

        // Validate passport
        let result = tracker.validate_passport(ptr);
        assert!(result.is_ok());
        let is_valid = result.unwrap();
        assert!(is_valid);

        // Verify passport was created and is valid in enhanced_allocations
        let allocations = tracker.get_enhanced_allocations().unwrap();
        assert_eq!(allocations.len(), 1);
        let allocation = &allocations[0];
        assert!(allocation.memory_passport.is_some());
        let passport = allocation.memory_passport.as_ref().unwrap();
        assert!(matches!(passport.validity_status, ValidityStatus::Valid));

        // Test validation with non-existent pointer
        let result = tracker.validate_passport(0xdead);
        assert!(result.is_ok());
        assert!(!result.unwrap()); // Should return false for non-existent allocation

        // Test passport functionality with memory_passports registry
        let ptr2 = 0xc000;
        tracker
            .create_and_register_passport(ptr2, "rust_main", SecurityClearance::Public)
            .unwrap();

        // Verify passport was created in memory_passports
        let passports = tracker.get_memory_passports().unwrap();
        assert_eq!(passports.len(), 1);
        let passport = passports.get(&ptr2).unwrap();
        assert!(matches!(passport.validity_status, ValidityStatus::Valid));

        // Revoke passport in memory_passports
        tracker.revoke_passport(ptr2, "test_revocation").unwrap();
        let passports = tracker.get_memory_passports().unwrap();
        let passport = passports.get(&ptr2).unwrap();
        assert!(matches!(passport.validity_status, ValidityStatus::Revoked));
    }

    #[test]
    fn test_detect_leaks() {
        let tracker = create_test_tracker();
        let ptr = 0xc000;
        let size = 1024;

        // Track allocation
        tracker
            .track_unsafe_allocation(ptr, size, "test_location".to_string())
            .unwrap();

        // Wait a bit to ensure allocation age exceeds threshold
        std::thread::sleep(std::time::Duration::from_millis(10));

        // Detect leaks with very low threshold (should detect the allocation)
        let result = tracker.detect_leaks(1); // 1ms threshold
        assert!(result.is_ok());

        let leaks = result.unwrap();
        // The leak detection might not always detect leaks immediately due to timing
        // So we check if we have leaks or if the allocation is still active
        if !leaks.is_empty() {
            match &leaks[0] {
                SafetyViolation::PotentialLeak { .. } => {
                    // Expected
                }
                _ => panic!("Expected PotentialLeak violation"),
            }
        } else {
            // If no leaks detected, verify allocation is still active
            let allocations = tracker.get_enhanced_allocations().unwrap();
            assert_eq!(allocations.len(), 1);
            assert!(allocations[0].base.is_active());
        }
    }

    #[test]
    fn test_analyze_cross_boundary_risks() {
        let tracker = create_test_tracker();
        let ptr = 0xd000;

        // Create passport with many boundary crossings
        tracker
            .create_and_register_passport(ptr, "rust_main", SecurityClearance::Public)
            .unwrap();

        // Add many stamps to simulate frequent boundary crossings
        for i in 0..15 {
            tracker
                .stamp_passport(ptr, &format!("operation_{i}"), "boundary", "test")
                .unwrap();
        }

        // Analyze risks
        let result = tracker.analyze_cross_boundary_risks();
        assert!(result.is_ok());

        let risks = result.unwrap();
        assert!(!risks.is_empty());

        // Should detect frequent boundary crossings
        let has_boundary_risk = risks
            .iter()
            .any(|risk| matches!(risk, SafetyViolation::CrossBoundaryRisk { .. }));
        assert!(has_boundary_risk);
    }

    #[test]
    fn test_get_stats() {
        let tracker = create_test_tracker();

        // Track some operations
        tracker
            .track_unsafe_allocation(0x1000, 1024, "unsafe_block".to_string())
            .unwrap();
        tracker
            .track_ffi_allocation(0x2000, 512, "libc".to_string(), "malloc".to_string())
            .unwrap();

        // Get stats
        let stats = tracker.get_stats();

        assert_eq!(stats.total_operations, 2);
        assert_eq!(stats.unsafe_blocks, 1);
        assert_eq!(stats.ffi_calls, 1);
        assert_eq!(stats.memory_violations, 0);
        assert!(stats.risk_score > 0.0);
        assert_eq!(stats.operations.len(), 2);
    }

    #[test]
    fn test_boundary_event_statistics() {
        let tracker = create_test_tracker();
        let ptr = 0xe000;

        // Track allocation and boundary events
        tracker
            .track_unsafe_allocation(ptr, 1024, "test_location".to_string())
            .unwrap();
        tracker
            .record_boundary_event(
                ptr,
                BoundaryEventType::RustToFfi,
                "rust".to_string(),
                "ffi".to_string(),
            )
            .unwrap();
        tracker
            .record_boundary_event(
                ptr,
                BoundaryEventType::FfiToRust,
                "ffi".to_string(),
                "rust".to_string(),
            )
            .unwrap();

        // Get statistics
        let result = tracker.get_boundary_event_statistics();
        assert!(result.is_ok());

        let stats = result.unwrap();
        assert_eq!(stats.total_events, 2);
        assert!(stats.events_by_type.contains_key("RustToFfi"));
        assert!(stats.events_by_type.contains_key("FfiToRust"));
        assert!(stats.average_transfer_size > 0.0);
        assert!(stats.total_transfer_volume > 0);
    }

    #[test]
    fn test_risk_level_serialization() {
        let risk_levels = vec![
            RiskLevel::Low,
            RiskLevel::Medium,
            RiskLevel::High,
            RiskLevel::Critical,
        ];

        for risk_level in risk_levels {
            let serialized = serde_json::to_string(&risk_level).expect("Failed to serialize");
            let _deserialized: RiskLevel =
                serde_json::from_str(&serialized).expect("Failed to deserialize");
        }
    }

    #[test]
    fn test_boundary_event_type_serialization() {
        let event_types = vec![
            BoundaryEventType::RustToFfi,
            BoundaryEventType::FfiToRust,
            BoundaryEventType::OwnershipTransfer,
            BoundaryEventType::SharedAccess,
        ];

        for event_type in event_types {
            let serialized = serde_json::to_string(&event_type).expect("Failed to serialize");
            let _deserialized: BoundaryEventType =
                serde_json::from_str(&serialized).expect("Failed to deserialize");
        }
    }

    #[test]
    fn test_security_clearance_serialization() {
        let clearances = vec![
            SecurityClearance::Public,
            SecurityClearance::Restricted,
            SecurityClearance::Confidential,
            SecurityClearance::Secret,
        ];

        for clearance in clearances {
            let serialized = serde_json::to_string(&clearance).expect("Failed to serialize");
            let _deserialized: SecurityClearance =
                serde_json::from_str(&serialized).expect("Failed to deserialize");
        }
    }

    #[test]
    fn test_global_tracker_initialization() {
        let tracker1 = init_global_unsafe_tracker();
        let tracker2 = init_global_unsafe_tracker();

        // Should return the same instance
        assert!(Arc::ptr_eq(&tracker1, &tracker2));
    }

    #[test]
    fn test_memory_protection_flags() {
        let flags = MemoryProtectionFlags {
            readable: true,
            writable: true,
            executable: false,
            shared: false,
        };

        assert!(flags.readable);
        assert!(flags.writable);
        assert!(!flags.executable);
        assert!(!flags.shared);
    }

    #[test]
    fn test_allocation_metadata() {
        let metadata = AllocationMetadata {
            requested_size: 1024,
            actual_size: 1024,
            alignment: 8,
            allocator_info: "test_allocator".to_string(),
            protection_flags: Some(MemoryProtectionFlags {
                readable: true,
                writable: true,
                executable: false,
                shared: false,
            }),
        };

        assert_eq!(metadata.requested_size, 1024);
        assert_eq!(metadata.actual_size, 1024);
        assert_eq!(metadata.alignment, 8);
        assert!(metadata.protection_flags.is_some());
    }

    #[test]
    fn test_comprehensive_workflow() {
        let tracker = create_test_tracker();

        // Register a C library
        tracker
            .register_c_library(
                "test_lib".to_string(),
                Some("/lib/libtest.so".to_string()),
                Some("1.0".to_string()),
            )
            .unwrap();

        // Track various allocations
        let ptr1 = 0x10000;
        let ptr2 = 0x20000;

        tracker
            .track_unsafe_allocation(ptr1, 1024, "unsafe_block".to_string())
            .unwrap();
        tracker
            .track_ffi_allocation(ptr2, 512, "test_lib".to_string(), "test_malloc".to_string())
            .unwrap();

        // Create passports
        tracker
            .create_and_register_passport(ptr1, "rust_main", SecurityClearance::Public)
            .unwrap();
        tracker
            .create_and_register_passport(ptr2, "ffi_lib", SecurityClearance::Restricted)
            .unwrap();

        // Record boundary events
        tracker
            .record_boundary_event(
                ptr1,
                BoundaryEventType::RustToFfi,
                "rust".to_string(),
                "ffi".to_string(),
            )
            .unwrap();

        // Track function calls
        tracker
            .track_c_function_call("test_lib", "test_malloc", 512, 1000)
            .unwrap();

        // Install hooks
        tracker
            .install_enhanced_libc_hook("malloc".to_string(), HookInstallationMethod::Preload)
            .unwrap();

        // Verify comprehensive state
        let allocations = tracker.get_enhanced_allocations().unwrap();
        assert_eq!(allocations.len(), 2);

        let libraries = tracker.get_c_library_stats().unwrap();
        assert_eq!(libraries.len(), 1);

        let passports = tracker.get_memory_passports().unwrap();
        assert_eq!(passports.len(), 2);

        let hooks = tracker.get_libc_hook_info().unwrap();
        assert_eq!(hooks.len(), 1);

        let stats = tracker.get_stats();
        assert_eq!(stats.total_operations, 2);
        assert_eq!(stats.unsafe_blocks, 1);
        assert_eq!(stats.ffi_calls, 1);

        // Clean up
        tracker.track_enhanced_deallocation(ptr1).unwrap();
        tracker.track_enhanced_deallocation(ptr2).unwrap();

        let final_allocations = tracker.get_enhanced_allocations().unwrap();
        assert!(final_allocations.is_empty());
    }
}