vmi_os_windows/
lib.rs

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

// Allow Windows-specific naming conventions to be used throughout this module.
#![allow(
    non_snake_case,         // example: AlpcpSendMessage
    non_upper_case_globals, // example: StandbyPageList
)]

use std::{cell::RefCell, collections::HashMap};

use ::object::{
    pe::{
        ImageNtHeaders32, ImageNtHeaders64, IMAGE_DIRECTORY_ENTRY_EXPORT,
        IMAGE_NT_OPTIONAL_HDR32_MAGIC, IMAGE_NT_OPTIONAL_HDR64_MAGIC,
    },
    read::pe::{optional_header_magic, ExportTarget, ImageNtHeaders},
    LittleEndian as LE,
};
use isr_core::Profile;
use vmi_arch_amd64::{Amd64, Cr3};
use vmi_core::{
    os::{
        OsArchitecture, OsExt, OsImageExportedSymbol, OsMapped, OsProcess, OsRegion, OsRegionKind,
        ProcessId, ProcessObject, StructReader, ThreadId, ThreadObject, VmiOs,
    },
    AccessContext, Architecture, Gfn, Hex, MemoryAccess, Pa, Registers as _, Va, VmiCore,
    VmiDriver, VmiError,
};
use vmi_macros::derive_trait_from_impl;
use zerocopy::{FromBytes, IntoBytes};

mod arch;
use self::arch::ArchAdapter;

mod pe;
pub use self::pe::{CodeView, PeError, PeLite, PeLite32, PeLite64};

mod offsets;
use self::offsets::{v1, v2};
pub use self::offsets::{Offsets, OffsetsExt, Symbols}; // TODO: make private + remove offsets() & symbols() methods

/// VMI operations for the Windows operating system.
///
/// `WindowsOs` provides methods and utilities for introspecting a Windows-based
/// virtual machine. It encapsulates Windows-specific knowledge and operations,
/// allowing for high-level interactions with the guest OS structures and processes.
///
/// # Usage
///
/// Create an instance of [`WindowsOs`] using a [`Profile`] that contains information
/// about the specific Windows version being introspected:
///
/// ```no_run
/// use isr::cache::{IsrCache, JsonCodec};
/// use vmi::{VcpuId, VmiCore, VmiDriver, VmiError, os::windows::WindowsOs};
///
/// # fn example<Driver: VmiDriver>(
/// #     driver: Driver
/// # ) -> Result<(), Box<dyn std::error::Error>>
/// # where
/// #     Driver: VmiDriver<Architecture = vmi_arch_amd64::Amd64>,
/// # {
/// // Setup VMI.
/// let core = VmiCore::new(driver)?;
///
/// // Try to find the kernel information.
/// // This is necessary in order to load the profile.
/// let kernel_info = {
///     let _guard = core.pause_guard()?;
///     let registers = core.registers(VcpuId(0))?;
///
///     WindowsOs::find_kernel(&core, &registers)?.expect("kernel information")
/// };
///
/// // Load the profile using the ISR library.
/// let isr = IsrCache::<JsonCodec>::new("cache")?;
/// let entry = isr.entry_from_codeview(kernel_info.codeview)?;
/// let profile = entry.profile()?;
///
/// // Create a new `WindowsOs` instance.
/// let os = WindowsOs::<Driver>::new(&profile)?;
/// # Ok(())
/// # }
/// ```
///
/// # Important Notes
///
/// - Many methods of this struct require pausing the VM to ensure consistency.
///   Use [`pause_guard`] when performing operations that might be affected
///   by concurrent changes in the guest OS.
///
/// - The behavior and accuracy of some methods may vary depending on the
///   Windows version being introspected. Always ensure your [`Profile`] matches
///   the guest OS version.
///
/// # Examples
///
/// Retrieving information about the current process:
///
/// ```no_run
/// # use vmi::{VcpuId, VmiDriver, VmiSession, os::windows::WindowsOs};
/// #
/// # fn example<Driver: VmiDriver>(
/// #     vmi: &VmiSession<Driver, WindowsOs<Driver>>,
/// # ) -> Result<(), Box<dyn std::error::Error>>
/// # where
/// #     Driver: VmiDriver<Architecture = vmi_arch_amd64::Amd64>,
/// # {
/// let registers = vmi.registers(VcpuId(0))?;
/// let current_process = vmi.os().current_process(&registers)?;
/// let process_id = vmi.os().process_id(&registers, current_process)?;
/// let process_name = vmi.os().process_filename(&registers, current_process)?;
/// println!("Current process: {} (PID: {})", process_name, process_id);
/// # Ok(())
/// # }
/// ```
///
/// Enumerating all processes:
///
/// ```no_run
/// # use vmi::{VcpuId, VmiDriver, VmiSession, os::windows::WindowsOs};
/// #
/// # fn example<Driver: VmiDriver>(
/// #     vmi: &VmiSession<Driver, WindowsOs<Driver>>,
/// # ) -> Result<(), Box<dyn std::error::Error>>
/// # where
/// #     Driver: VmiDriver<Architecture = vmi_arch_amd64::Amd64>,
/// # {
/// let registers = vmi.registers(VcpuId(0))?;
/// let processes = vmi.os().processes(&registers)?;
/// for process in processes {
///     println!("Process: {} (PID: {})", process.name, process.id);
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Safety
///
/// While this struct doesn't use unsafe code directly, many of its methods
/// interact with raw memory of the guest OS. Incorrect usage can lead to
/// invalid memory access or misinterpretation of data. Always ensure you're
/// working with the correct memory regions and OS structures.
///
/// [`pause_guard`]: VmiCore::pause_guard
pub struct WindowsOs<Driver>
where
    Driver: VmiDriver,
{
    offsets: Offsets,
    symbols: Symbols,

    kernel_image_base: RefCell<Option<Va>>,
    highest_user_address: RefCell<Option<Va>>,
    object_header_cookie: RefCell<Option<u8>>,
    object_type_cache: RefCell<HashMap<Va, WindowsObjectType>>,

    ki_kva_shadow: RefCell<Option<bool>>,
    mm_pfn_database: RefCell<Option<Va>>,
    nt_build_lab: RefCell<Option<String>>,
    nt_build_lab_ex: RefCell<Option<String>>,

    _marker: std::marker::PhantomData<Driver>,
}

/// Information about the Windows kernel image.
#[derive(Debug)]
pub struct WindowsKernelInformation {
    /// Base virtual address where the kernel image is loaded.
    pub base_address: Va,

    /// Major version number of the Windows kernel.
    pub version_major: u16,

    /// Minor version number of the Windows kernel.
    pub version_minor: u16,

    /// CodeView debugging information for the kernel image.
    pub codeview: CodeView,
}

/// Represents a `_EXCEPTION_RECORD` structure.
#[derive(Debug)]
pub struct WindowsExceptionRecord {
    /// The `ExceptionCode` field of the exception record.
    ///
    /// The reason the exception occurred. This is the code generated by a
    /// hardware exception, or the code specified in the `RaiseException`
    /// function for a software-generated exception.
    pub code: u32,

    /// The `ExceptionFlags` field of the exception record.
    ///
    /// This member contains zero or more exception flags.
    pub flags: u32,

    /// The `ExceptionRecord` field of the exception record.
    ///
    /// A pointer to an associated `EXCEPTION_RECORD` structure.
    /// Exception records can be chained together to provide additional
    /// information when nested exceptions occur.
    pub record: Va,

    /// The `ExceptionAddress` field of the exception record.
    ///
    /// The address where the exception occurred.
    pub address: Va,

    /// The `ExceptionInformation` field of the exception record.
    ///
    /// An array of additional arguments that describe the exception.
    /// The number of elements in the array is determined by the `NumberParameters`
    /// field of the exception record.
    pub information: Vec<u64>,
}

/// Represents a `_HANDLE_TABLE` structure.
#[derive(Debug)]
pub struct WindowsHandleTable {
    /// The `TableCode` field of the handle table.
    ///
    /// A pointer to the top level handle table tree node.
    pub table_code: u64,
}

/// Represents a `_HANDLE_TABLE_ENTRY` structure.
#[derive(Debug)]
pub struct WindowsHandleTableEntry {
    /// The `Object` (or `ObjectPointerBits`) field of the handle table entry.
    ///
    /// A pointer to an `_OBJECT_HEADER` structure.
    pub object: Va, // OBJECT_HEADER

    /// The `ObAttributes` (or `Attributes`) field of the handle table entry.
    pub attributes: u32,

    /// The `GrantedAccess` (or `GrantedAccessBits`) field of the handle table entry.
    pub granted_access: u32,
}

/// Represents a `_PEB` structure.
#[derive(Debug)]
pub struct WindowsPeb {
    /// The address of this `_PEB` structure.
    pub address: Va,

    /// The `Peb->ProcessParameters->CurrentDirectory` field.
    pub current_directory: String,

    /// The `Peb->ProcessParameters->DllPath` field.
    pub dll_path: String,

    /// The `Peb->ProcessParameters->ImagePathName` field.
    pub image_path_name: String,

    /// The `Peb->ProcessParameters->CommandLine` field.
    pub command_line: String,
}

/// Identifies the type of a Windows kernel object.
///
/// Windows uses a object-based kernel architecture where various system
/// resources (processes, threads, files, etc.) are represented as kernel
/// objects. This enum identifies the different types of objects that can
/// be encountered during introspection.
///
/// Each variant corresponds to a specific object type string used internally
/// by the Windows kernel. For example, "Process" for process objects,
/// "Thread" for thread objects, etc.
#[derive(Debug, Clone, Copy)]
pub enum WindowsObjectType {
    /// ALPC Port object.
    ///
    /// Represented by `_ALPC_PORT` structure.
    /// Has `ALPC Port` type name.
    AlpcPort,

    /// Debug object.
    ///
    /// Represented by `_DEBUG_OBJECT` structure.
    /// Has `DebugObject` type name.
    DebugObject,

    /// Device object.
    ///
    /// Represented by `_DEVICE_OBJECT` structure.
    /// Has `Device` type name.
    Device,

    /// Directory object.
    ///
    /// Represented by `_OBJECT_DIRECTORY` structure.
    /// Has `Directory` type name.
    Directory,

    /// Driver object.
    ///
    /// Represented by `_DRIVER_OBJECT` structure.
    /// Has `Driver` type name.
    Driver,

    /// Event object.
    ///
    /// Represented by `_KEVENT` structure.
    /// Has `Event` type name.
    Event,

    /// File object.
    ///
    /// Represented by `_FILE_OBJECT` structure.
    /// Has `File` type name.
    File,

    /// Job object.
    ///
    /// Represented by `_EJOB` structure.
    /// Has `Job` type name.
    Job,

    /// Key object.
    ///
    /// Represented by `_CM_KEY_BODY` structure.
    /// Has `Key` type name.
    Key,

    /// Mutant object.
    ///
    /// Represented by `_KMUTANT` structure.
    /// Has `Mutant` type name.
    Mutant,

    /// Port object.
    ///
    /// Represented by `_PORT_MESSAGE` structure.
    /// Has `Port` type name.
    Port,

    /// Process object.
    ///
    /// Represented by `_EPROCESS` structure.
    /// Has `Process` type name.
    Process,

    /// Section object.
    ///
    /// Represented by `_SECTION` (or `_SECTION_OBJECT`) structure.
    /// Has `Section` type name.
    Section,

    /// Symbolic link object.
    ///
    /// Represented by `_OBJECT_SYMBOLIC_LINK` structure.
    /// Has `SymbolicLink` type name.
    SymbolicLink,

    /// Thread object.
    ///
    /// Represented by `_ETHREAD` structure.
    /// Has `Thread` type name.
    Thread,

    /// Timer object.
    ///
    /// Represented by `_KTIMER` structure.
    /// Has `Timer` type name.
    Timer,

    /// Token object.
    ///
    /// Represented by `_TOKEN` structure.
    /// Has `Token` type name.
    Token,

    /// Type object.
    ///
    /// Represented by `_OBJECT_TYPE` structure.
    /// Has `Type` type name.
    Type,
}

/// A Windows object name.
///
/// Represents the name of a Windows object, along with its directory.
#[derive(Debug)]
pub struct WindowsObjectName {
    /// A `Directory` field of the `_OBJECT_HEADER_NAME_INFO` structure.
    ///
    /// A pointer to the `_OBJECT_DIRECTORY` structure.
    pub directory: Va, // _OBJECT_DIRECTORY*

    /// A `Name` field of the `_OBJECT_HEADER_NAME_INFO` structure.
    pub name: String,
}

/// A Windows object.
#[derive(Debug)]
pub enum WindowsObject {
    /// File object.
    File(WindowsFileObject),

    /// Section object.
    Section(WindowsSectionObject),
}

/// A Windows file object.
#[derive(Debug)]
pub struct WindowsFileObject {
    /// The `DeviceObject` field of the file object.
    ///
    /// A pointer to the `_DEVICE_OBJECT` structure.
    pub device_object: Va,

    /// The `FileName` field of the file object.
    pub filename: String,
}

/// A Windows section object.
#[derive(Debug)]
pub struct WindowsSectionObject {
    /// The virtual address range of the section.
    pub region: OsRegion,

    /// The size of the section.
    pub size: u64,
}

/// Represents a `_VAD` structure.
#[derive(Debug)]
pub struct WindowsVad {
    /// The `StartingVpn` field of the VAD.
    ///
    /// The starting virtual page number of the VAD.
    pub starting_vpn: u64,

    /// The `EndingVpn` field of the VAD.
    ///
    /// The ending virtual page number of the VAD.
    pub ending_vpn: u64,

    /// The `VadType` field of the VAD.
    pub vad_type: u8,

    /// The `Protection` field of the VAD.
    pub protection: u8,

    /// The `PrivateMemory` field of the VAD.
    pub private_memory: bool,

    /// The `MemCommit` field of the VAD.
    pub mem_commit: bool,

    /// The `Left` field of the VAD.
    pub left_child: Va,

    /// The `Right` field of the VAD.
    pub right_child: Va,
}

//
// Private types
//

/// The address space type in a WoW64 process.
enum WindowsWow64Kind {
    /// Native address space
    Native = 0,

    /// x86 (32-bit) address space under WoW64
    X86 = 1,
    // Arm32 = 2,
    // Amd64 = 3,
    // ChpeX86 = 4,
    // VsmEnclave = 5,
}

/// A 32-bit or 64-bit virtual address in WoW64 processes.
struct WindowsWow64Va {
    /// The virtual address.
    va: Va,

    /// The kind of the virtual address.
    kind: WindowsWow64Kind,
}

impl WindowsWow64Va {
    fn native(va: Va) -> Self {
        Self {
            va,
            kind: WindowsWow64Kind::Native,
        }
    }

    fn x86(va: Va) -> Self {
        Self {
            va,
            kind: WindowsWow64Kind::X86,
        }
    }
}

#[derive_trait_from_impl(
    os_session_name = WindowsOsSessionExt,
    os_context_name = WindowsOsExt,
    os_session_prober_name = WindowsOsSessionProberExt,
    os_context_prober_name = WindowsOsProberExt
)]
#[allow(non_snake_case, non_upper_case_globals)]
impl<Driver> WindowsOs<Driver>
where
    Driver: VmiDriver,
    Driver::Architecture: Architecture + ArchAdapter<Driver>,
{
    /// 32-bit current process pseudo-handle (-1).
    pub const NtCurrentProcess32: u64 = 0xffff_ffff;

    /// 64-bit current process pseudo-handle (-1).
    pub const NtCurrentProcess64: u64 = 0xffff_ffff_ffff_ffff;

    /// 32-bit current thread pseudo-handle (-2).
    pub const NtCurrentThread32: u64 = 0xffff_fffe;

    /// 64-bit current thread pseudo-handle (-2).
    pub const NtCurrentThread64: u64 = 0xffff_ffff_ffff_fffe;

    /// Creates a new `WindowsOs` instance.
    pub fn new(profile: &Profile) -> Result<Self, VmiError> {
        Ok(Self {
            offsets: Offsets::new(profile)?,
            symbols: Symbols::new(profile)?,
            kernel_image_base: RefCell::new(None),
            highest_user_address: RefCell::new(None),
            object_header_cookie: RefCell::new(None),
            object_type_cache: RefCell::new(HashMap::new()),
            ki_kva_shadow: RefCell::new(None),
            mm_pfn_database: RefCell::new(None),
            nt_build_lab: RefCell::new(None),
            nt_build_lab_ex: RefCell::new(None),
            _marker: std::marker::PhantomData,
        })
    }

    /// Returns a reference to the Windows-specific memory offsets.
    pub fn offsets(&self) -> &Offsets {
        &self.offsets
    }

    /// Returns a reference to the Windows-specific symbols.
    pub fn symbols(&self) -> &Symbols {
        &self.symbols
    }

    #[expect(clippy::only_used_in_recursion)]
    fn enumerate_tree_node_v1(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        node: Va,
        callback: &mut impl FnMut(Va) -> bool,
        offsets: &v1::Offsets,
    ) -> Result<(), VmiError> {
        let MMADDRESS_NODE = &offsets._MMADDRESS_NODE;

        let balanced_node = StructReader::new(
            vmi,
            registers.address_context(node),
            MMADDRESS_NODE.effective_len(),
        )?;

        let left = Va(balanced_node.read(MMADDRESS_NODE.LeftChild)?);
        if !left.is_null() {
            if !callback(left) {
                return Ok(());
            }

            self.enumerate_tree_node_v1(vmi, registers, left, callback, offsets)?;
        }

        let right = Va(balanced_node.read(MMADDRESS_NODE.RightChild)?);
        if !right.is_null() {
            if !callback(right) {
                return Ok(());
            }

            self.enumerate_tree_node_v1(vmi, registers, right, callback, offsets)?;
        }

        Ok(())
    }

    #[expect(clippy::only_used_in_recursion)]
    fn enumerate_tree_node_v2(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        node: Va,
        callback: &mut impl FnMut(Va) -> bool,
        offsets: &v2::Offsets,
    ) -> Result<(), VmiError> {
        let RTL_BALANCED_NODE = &offsets._RTL_BALANCED_NODE;

        let balanced_node = StructReader::new(
            vmi,
            registers.address_context(node),
            RTL_BALANCED_NODE.effective_len(),
        )?;

        let left = Va(balanced_node.read(RTL_BALANCED_NODE.Left)?);
        if !left.is_null() {
            if !callback(left) {
                return Ok(());
            }

            self.enumerate_tree_node_v2(vmi, registers, left, callback, offsets)?;
        }

        let right = Va(balanced_node.read(RTL_BALANCED_NODE.Right)?);
        if !right.is_null() {
            if !callback(right) {
                return Ok(());
            }

            self.enumerate_tree_node_v2(vmi, registers, right, callback, offsets)?;
        }

        Ok(())
    }

    fn enumerate_tree_v1(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        root: Va,
        mut callback: impl FnMut(Va) -> bool,
        offsets: &v1::Offsets,
    ) -> Result<(), VmiError> {
        self.enumerate_tree_node_v1(vmi, registers, root, &mut callback, offsets)
    }

    fn enumerate_tree_v2(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        root: Va,
        mut callback: impl FnMut(Va) -> bool,
        offsets: &v2::Offsets,
    ) -> Result<(), VmiError> {
        callback(root);
        self.enumerate_tree_node_v2(vmi, registers, root, &mut callback, offsets)
    }

    fn image_exported_symbols_generic<Pe>(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        image_base: Va,
    ) -> Result<Vec<OsImageExportedSymbol>, VmiError>
    where
        Pe: ImageNtHeaders,
    {
        let mut data = [0u8; Amd64::PAGE_SIZE as usize];
        vmi.read(registers.address_context(image_base), &mut data)?;

        let pe = PeLite::<Pe>::parse(&data).map_err(|err| VmiError::Os(err.into()))?;
        let entry = pe.data_directories[IMAGE_DIRECTORY_ENTRY_EXPORT];

        let mut data = vec![0u8; entry.size.get(LE) as usize];
        vmi.read(
            registers.address_context(image_base + entry.virtual_address.get(LE) as u64),
            &mut data,
        )?;

        let exports = pe.exports(&data).map_err(|err| VmiError::Os(err.into()))?;
        Ok(exports
            .iter()
            .filter_map(|export| match export.target {
                ExportTarget::Address(address) => Some(OsImageExportedSymbol {
                    name: String::from_utf8_lossy(export.name?).to_string(),
                    address: image_base + address as u64,
                }),
                _ => None,
            })
            .collect())
    }

    // region: File

    /// Extracts the `FileName` from a `FILE_OBJECT` structure.
    ///
    /// # Equivalent C pseudo-code
    ///
    /// ```c
    /// UNICODE_STRING FileName = FileObject->FileName;
    /// return FileName;
    /// ```
    ///
    /// # Notes
    ///
    /// This operation might fail as the filename is allocated from paged pool.
    pub fn file_object_to_filename(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        file_object: Va,
    ) -> Result<String, VmiError> {
        let FILE_OBJECT = &self.offsets.common._FILE_OBJECT;

        // Note that filename is allocated from paged pool,
        // so this read might fail.
        self.read_unicode_string(
            vmi,
            registers.address_context(file_object + FILE_OBJECT.FileName.offset),
        )
    }

    /// Constructs the full path of a file from its `FILE_OBJECT`.
    ///
    /// This function first reads the `DeviceObject` field of the `FILE_OBJECT`
    /// structure. Then it reads the `ObjectNameInfo` of the `DeviceObject`
    /// and its directory. Finally, it concatenates the device directory
    /// name, device name, and file name.
    ///
    /// # Equivalent C pseudo-code
    ///
    /// ```c
    /// PDEVICE_OBJECT DeviceObject = FileObject->DeviceObject;
    ///
    /// POBJECT_HEADER_NAME_INFO DeviceNameInfo = ObjectNameInfo(DeviceObject);
    /// POBJECT_HEADER_NAME_INFO DeviceDirectoryNameInfo = DeviceNameInfo->Directory
    ///     ? ObjectNameInfo(DeviceNameInfo->Directory)
    ///     : NULL;
    ///
    /// if (DeviceDirectoryNameInfo->Name != NULL) {
    ///     FullPath += '\\' + DeviceDirectoryNameInfo->Name;
    /// }
    ///
    /// if (DeviceNameInfo->Name != NULL) {
    ///     FullPath += '\\' + DeviceNameInfo->Name;
    /// }
    ///
    /// FullPath += FileObject->FileName;
    ///
    /// return FullPath;
    /// ```
    ///
    /// # Panics
    /// Panics if the provided object is not a file object.
    pub fn file_object_to_full_path(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        file_object: Va,
    ) -> Result<String, VmiError> {
        let file = match self.parse_file_object(vmi, registers, file_object)? {
            WindowsObject::File(file) => file,
            _ => panic!("Not a file object"),
        };

        let device = self.object_name(vmi, registers, file.device_object)?;
        let directory = match &device {
            Some(device) => self.object_name(vmi, registers, device.directory)?,
            None => None,
        };

        let mut result = String::new();
        if let Some(directory) = directory {
            result.push('\\');
            result.push_str(&directory.name);
        }

        if let Some(device) = device {
            result.push('\\');
            result.push_str(&device.name);
        }

        result.push_str(&file.filename);

        Ok(result)
    }

    /// Extracts the filename from a `CONTROL_AREA` structure.
    ///
    /// This function first reads the `FilePointer` field of the `CONTROL_AREA`
    /// structure, then reads the `FileName` field of the `FILE_OBJECT`
    /// structure pointed by the `FilePointer`.
    ///
    /// # Equivalent C pseudo-code
    ///
    /// ```c
    /// PFILE_OBJECT FileObject = ControlArea->FilePointer;
    /// UNICODE_STRING FileName = FileObject->FileName;
    /// return FileName;
    /// ```
    pub fn control_area_to_filename(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        control_area: Va,
    ) -> Result<String, VmiError> {
        let EX_FAST_REF = &self.offsets.common._EX_FAST_REF;
        let CONTROL_AREA = &self.offsets.common._CONTROL_AREA;

        let file_pointer = vmi.read_va(
            registers.address_context(control_area + CONTROL_AREA.FilePointer.offset),
            registers.address_width(),
        )?;

        // The file pointer is in fact an `_EX_FAST_REF` structure,
        // where the low bits are used to store the reference count.
        debug_assert_eq!(EX_FAST_REF.RefCnt.offset, 0);
        debug_assert_eq!(EX_FAST_REF.RefCnt.bit_position, 0);
        let file_pointer = file_pointer & !((1 << EX_FAST_REF.RefCnt.bit_length) - 1);
        //let file_pointer = file_pointer & !0xf;

        self.file_object_to_filename(vmi, registers, file_pointer)
    }

    // endregion: File

    // region: Handle

    /// Checks if the given handle is a kernel handle.
    pub fn is_kernel_handle(
        &self,
        _vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        handle: u64,
    ) -> Result<bool, VmiError> {
        const KERNEL_HANDLE_MASK32: u64 = 0x8000_0000;
        const KERNEL_HANDLE_MASK64: u64 = 0xffff_ffff_8000_0000;

        match registers.effective_address_width() {
            4 => Ok(handle & KERNEL_HANDLE_MASK32 == KERNEL_HANDLE_MASK32),
            8 => Ok(handle & KERNEL_HANDLE_MASK64 == KERNEL_HANDLE_MASK64),
            _ => panic!("Unsupported address width"),
        }
    }

    /// Retrieves the handle table for a given process.
    pub fn handle_table(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
    ) -> Result<WindowsHandleTable, VmiError> {
        let EPROCESS = &self.offsets.common._EPROCESS;
        let HANDLE_TABLE = &self.offsets.common._HANDLE_TABLE;

        let handle_table = vmi.read_va(
            registers.address_context(process.0 + EPROCESS.ObjectTable.offset),
            registers.address_width(),
        )?;

        let table_code = vmi.read_address(
            registers.address_context(handle_table + HANDLE_TABLE.TableCode.offset),
            registers.address_width(),
        )?;

        Ok(WindowsHandleTable { table_code })
    }

    /// Looks up a specific handle table entry for a given process and handle.
    pub fn handle_table_entry(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
        handle: u64,
    ) -> Result<Option<WindowsHandleTableEntry>, VmiError> {
        let mut process = process;
        let mut handle = handle;

        if self.is_kernel_handle(vmi, registers, handle)? {
            process = self.system_process(vmi, registers)?;
            handle &= 0x7fff_ffff;
        }

        let handle_table = self.handle_table(vmi, registers, process)?;
        let entry_address =
            self.handle_table_entry_lookup(vmi, registers, &handle_table, handle)?;
        self.parse_handle_table_entry(vmi, registers, entry_address)
    }

    /// Performs a lookup in the handle table to find the address of a handle
    /// table entry.
    ///
    /// Implements the multi-level handle table lookup algorithm used by
    /// Windows. Returns the virtual address of the handle table entry.
    pub fn handle_table_entry_lookup(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        handle_table: &WindowsHandleTable,
        handle: u64,
    ) -> Result<Va, VmiError> {
        const SIZEOF_POINTER: u64 = 8;
        const SIZEOF_HANDLE_TABLE_ENTRY: u64 = 16;

        const LOWLEVEL_COUNT: u64 = 256; // (TABLE_PAGE_SIZE / sizeof(HANDLE_TABLE_ENTRY))
        const MIDLEVEL_COUNT: u64 = 512; // (PAGE_SIZE / sizeof(PHANDLE_TABLE_ENTRY))

        const LEVEL_CODE_MASK: u64 = 3;
        const HANDLE_VALUE_INC: u64 = 4;

        let level = handle_table.table_code & LEVEL_CODE_MASK;
        let table = Va(handle_table.table_code - level);

        //
        // The 2 least significant bits of a handle are available to the
        // application and are ignored by the system.
        //

        let mut index = handle & !0b11;

        match level {
            0 => Ok(table + index * (SIZEOF_HANDLE_TABLE_ENTRY / HANDLE_VALUE_INC)),

            1 => {
                let table2 = table;
                let i = index % (LOWLEVEL_COUNT * HANDLE_VALUE_INC);

                index -= i;
                let j = index / (LOWLEVEL_COUNT * HANDLE_VALUE_INC);

                let table1 = vmi.read_va(
                    registers.address_context(table2 + j * SIZEOF_POINTER),
                    registers.address_width(),
                )?;

                Ok(table1 + i * (SIZEOF_HANDLE_TABLE_ENTRY / HANDLE_VALUE_INC))
            }

            2 => {
                let table3 = table;
                let i = index % (LOWLEVEL_COUNT * HANDLE_VALUE_INC);

                index -= i;
                let mut k = index / (LOWLEVEL_COUNT * HANDLE_VALUE_INC);

                let j = k % MIDLEVEL_COUNT;
                k -= j;
                k /= MIDLEVEL_COUNT;

                let table2 = vmi.read_va(
                    registers.address_context(table3 + k * SIZEOF_POINTER),
                    registers.address_width(),
                )?;
                let table1 = vmi.read_va(
                    registers.address_context(table2 + j * SIZEOF_POINTER),
                    registers.address_width(),
                )?;

                Ok(table1 + i * (SIZEOF_HANDLE_TABLE_ENTRY / HANDLE_VALUE_INC))
            }

            _ => unreachable!(),
        }
    }

    /// Converts a handle to the virtual address of the corresponding object.
    ///
    /// Uses the handle table entry lookup to find the object address for a
    /// given handle.
    pub fn handle_to_object_address(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
        handle: u64,
    ) -> Result<Option<Va>, VmiError> {
        Ok(self
            .handle_table_entry(vmi, registers, process, handle)?
            .map(|entry| entry.object))
    }

    /// Retrieves the WindowsObject corresponding to a given handle in a
    /// process.
    pub fn handle_to_object(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
        handle: u64,
    ) -> Result<Option<WindowsObject>, VmiError> {
        match self.handle_to_object_address(vmi, registers, process, handle)? {
            Some(object) => self.object_from_address(vmi, registers, object),
            None => Ok(None),
        }
    }

    /// Parses a Windows object from its memory address.
    ///
    /// Determines the object type and calls the appropriate parsing method.
    /// Currently supports File and Section object types.
    pub fn object_from_address(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        object: Va,
    ) -> Result<Option<WindowsObject>, VmiError> {
        match self.object_type(vmi, registers, object)? {
            Some(WindowsObjectType::File) => {
                Ok(Some(self.parse_file_object(vmi, registers, object)?))
            }
            Some(WindowsObjectType::Section) => self.parse_section_object(vmi, registers, object),
            _ => Ok(None),
        }
    }

    /// Parses a FILE_OBJECT structure.
    ///
    /// Extracts the device object and filename from the FILE_OBJECT.
    /// Returns a WindowsObject::File variant.
    fn parse_file_object(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        object: Va,
    ) -> Result<WindowsObject, VmiError> {
        let FILE_OBJECT = &self.offsets.common._FILE_OBJECT;

        let device_object = vmi.read_va(
            registers.address_context(object + FILE_OBJECT.DeviceObject.offset),
            registers.address_width(),
        )?;

        let filename = self.file_object_to_filename(vmi, registers, object)?;
        Ok(WindowsObject::File(WindowsFileObject {
            device_object,
            filename,
        }))
    }

    /// Parses a Windows section object.
    ///
    /// Delegates to version-specific parsing methods based on the available
    /// offsets. Returns a WindowsObject::Section variant.
    fn parse_section_object(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        object: Va,
    ) -> Result<Option<WindowsObject>, VmiError> {
        match &self.offsets.ext {
            Some(OffsetsExt::V1(offsets)) => Ok(Some(
                self.parse_section_object_v1(vmi, registers, object, offsets)?,
            )),
            Some(OffsetsExt::V2(offsets)) => Ok(Some(
                self.parse_section_object_v2(vmi, registers, object, offsets)?,
            )),
            None => panic!("OffsetsExt not set"),
        }
    }

    fn parse_section_object_v1(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        object: Va,
        offsets: &v1::Offsets,
    ) -> Result<WindowsObject, VmiError> {
        let SECTION_OBJECT = &offsets._SECTION_OBJECT;
        let SEGMENT_OBJECT = &offsets._SEGMENT_OBJECT;
        let MMSECTION_FLAGS = &self.offsets.common._MMSECTION_FLAGS;

        let section = StructReader::new(
            vmi,
            registers.address_context(object),
            SECTION_OBJECT.effective_len(),
        )?;
        let starting_vpn = section.read(SECTION_OBJECT.StartingVa)?;
        let ending_vpn = section.read(SECTION_OBJECT.EndingVa)?;
        let segment = section.read(SECTION_OBJECT.Segment)?;

        let segment = StructReader::new(
            vmi,
            registers.address_context(segment.into()),
            SEGMENT_OBJECT.effective_len(),
        )?;
        let size = segment.read(SEGMENT_OBJECT.SizeOfSegment)?;
        let flags = segment.read(SEGMENT_OBJECT.MmSectionFlags)?;
        let flags = vmi.read_u32(registers.address_context(flags.into()))? as u64;

        let file = MMSECTION_FLAGS.File.value_from(flags) != 0;
        let _image = MMSECTION_FLAGS.Image.value_from(flags) != 0;

        let kind = if file {
            let control_area = vmi.read_va(
                registers.address_context(object + SEGMENT_OBJECT.ControlArea.offset),
                registers.address_width(),
            )?;

            let path = self.control_area_to_filename(vmi, registers, control_area);

            OsRegionKind::Mapped(OsMapped {
                path: path.map(Some),
            })
        }
        else {
            OsRegionKind::Private
        };

        Ok(WindowsObject::Section(WindowsSectionObject {
            region: OsRegion {
                start: Va(starting_vpn << 12),
                end: Va((ending_vpn + 1) << 12),
                protection: MemoryAccess::default(),
                kind,
            },
            size,
        }))
    }

    fn parse_section_object_v2(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        object: Va,
        offsets: &v2::Offsets,
    ) -> Result<WindowsObject, VmiError> {
        let SECTION = &offsets._SECTION;
        let MMSECTION_FLAGS = &self.offsets.common._MMSECTION_FLAGS;

        let section = StructReader::new(
            vmi,
            registers.address_context(object),
            SECTION.effective_len(),
        )?;
        let starting_vpn = section.read(SECTION.StartingVpn)?;
        let ending_vpn = section.read(SECTION.EndingVpn)?;
        let size = section.read(SECTION.SizeOfSection)?;
        let flags = section.read(SECTION.Flags)?;

        let file = MMSECTION_FLAGS.File.value_from(flags) != 0;
        let _image = MMSECTION_FLAGS.Image.value_from(flags) != 0;

        //
        // We have to distinguish between FileObject and ControlArea.
        // Here's an excerpt from _SECTION:
        //
        //     union {
        //       union {
        //         PCONTROL_AREA ControlArea;
        //         PFILE_OBJECT FileObject;
        //         struct {
        //           ULONG_PTR RemoteImageFileObject : 1;
        //           ULONG_PTR RemoteDataFileObject : 1;
        //         };
        //       };
        //     };
        //
        // Based on information from Geoff Chappell's website, we can determine whether
        // ControlArea is in fact FileObject by checking the lowest 2 bits of the
        // pointer.
        //
        // ref: https://www.geoffchappell.com/studies/windows/km/ntoskrnl/inc/ntos/mi/section.htm
        //

        let kind = if file {
            let control_area = vmi.read_va(
                registers.address_context(object + SECTION.ControlArea.offset),
                registers.address_width(),
            )?;

            let path = if u64::from(control_area) & 0x3 != 0 {
                let file_object = control_area;
                self.file_object_to_filename(vmi, registers, file_object)
            }
            else {
                self.control_area_to_filename(vmi, registers, control_area)
            };

            OsRegionKind::Mapped(OsMapped {
                path: path.map(Some),
            })
        }
        else {
            OsRegionKind::Private
        };

        Ok(WindowsObject::Section(WindowsSectionObject {
            region: OsRegion {
                start: Va(starting_vpn << 12),
                end: Va((ending_vpn + 1) << 12),
                protection: MemoryAccess::default(),
                kind,
            },
            size,
        }))
    }

    fn parse_handle_table_entry(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        entry: Va,
    ) -> Result<Option<WindowsHandleTableEntry>, VmiError> {
        match &self.offsets.ext {
            Some(OffsetsExt::V1(offsets)) => {
                self.parse_handle_table_entry_v1(vmi, registers, entry, offsets)
            }
            Some(OffsetsExt::V2(offsets)) => {
                self.parse_handle_table_entry_v2(vmi, registers, entry, offsets)
            }
            None => panic!("OffsetsExt not set"),
        }
    }

    fn parse_handle_table_entry_v1(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        entry: Va,
        offsets: &v1::Offsets,
    ) -> Result<Option<WindowsHandleTableEntry>, VmiError> {
        const OBJ_PROTECT_CLOSE: u64 = 0x00000001;
        const OBJ_INHERIT: u64 = 0x00000002;
        const OBJ_AUDIT_OBJECT_CLOSE: u64 = 0x00000004;
        const OBJ_HANDLE_ATTRIBUTES: u64 = OBJ_PROTECT_CLOSE | OBJ_INHERIT | OBJ_AUDIT_OBJECT_CLOSE;

        let HANDLE_TABLE_ENTRY = &offsets._HANDLE_TABLE_ENTRY;
        let OBJECT_HEADER = &self.offsets.common._OBJECT_HEADER;

        let handle_table_entry = StructReader::new(
            vmi,
            registers.address_context(entry),
            HANDLE_TABLE_ENTRY.effective_len(),
        )?;
        let object = handle_table_entry.read(HANDLE_TABLE_ENTRY.Object)?;
        let attributes = handle_table_entry.read(HANDLE_TABLE_ENTRY.ObAttributes)?;
        let granted_access = handle_table_entry.read(HANDLE_TABLE_ENTRY.GrantedAccess)? as u32;

        let object = Va(object & !OBJ_HANDLE_ATTRIBUTES);
        let object = object + OBJECT_HEADER.Body.offset;

        let attributes = (attributes & OBJ_HANDLE_ATTRIBUTES) as u32;

        Ok(Some(WindowsHandleTableEntry {
            object,
            attributes,
            granted_access,
        }))
    }

    fn parse_handle_table_entry_v2(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        entry: Va,
        offsets: &v2::Offsets,
    ) -> Result<Option<WindowsHandleTableEntry>, VmiError> {
        let HANDLE_TABLE_ENTRY = &offsets._HANDLE_TABLE_ENTRY;
        let OBJECT_HEADER = &self.offsets.common._OBJECT_HEADER;

        #[repr(C)]
        #[derive(Debug, Copy, Clone, FromBytes, IntoBytes)]
        #[allow(non_camel_case_types, non_snake_case)]
        struct _HANDLE_TABLE_ENTRY {
            LowValue: u64,
            HighValue: u64,
        }

        // Fetch the handle table entry
        let handle_table_entry =
            vmi.read_struct::<_HANDLE_TABLE_ENTRY>(registers.address_context(entry))?;

        // Parse the handle table entry
        let object_pointer_bits = HANDLE_TABLE_ENTRY
            .ObjectPointerBits
            .value_from(handle_table_entry.LowValue);

        let attributes = HANDLE_TABLE_ENTRY
            .Attributes
            .value_from(handle_table_entry.LowValue) as u32;

        let granted_access = HANDLE_TABLE_ENTRY
            .GrantedAccessBits
            .value_from(handle_table_entry.HighValue) as u32;

        let object = Va(0xffff_0000_0000_0000 | object_pointer_bits << 4);
        let object = object + OBJECT_HEADER.Body.offset;

        Ok(Some(WindowsHandleTableEntry {
            object,
            attributes,
            granted_access,
        }))
    }

    // endregion: Handle

    // region: Kernel

    /// Locates the Windows kernel in memory based on the CPU registers.
    /// This function is architecture-specific.
    ///
    /// On AMD64, the kernel is located by taking the `MSR_LSTAR` value and
    /// reading the virtual memory page by page backwards until the `MZ` header
    /// is found.
    pub fn find_kernel(
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
    ) -> Result<Option<WindowsKernelInformation>, VmiError> {
        Driver::Architecture::find_kernel(vmi, registers)
    }

    /// Retrieves the kernel information string.
    ///
    /// # Implementation Details
    ///
    /// The kernel information string is located by reading the `NtBuildLabEx`
    /// symbol from the kernel image.
    pub fn kernel_information_string_ex(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<<Driver as VmiDriver>::Architecture as Architecture>::Registers,
    ) -> Result<Option<String>, VmiError> {
        let NtBuildLabEx = match self.symbols.NtBuildLabEx {
            Some(offset) => offset,
            None => return Ok(None),
        };

        if let Some(nt_build_lab_ex) = self.nt_build_lab_ex.borrow().as_ref() {
            return Ok(Some(nt_build_lab_ex.clone()));
        }

        let kernel_image_base = self.kernel_image_base(vmi, registers)?;
        let nt_build_lab_ex =
            vmi.read_string(registers.address_context(kernel_image_base + NtBuildLabEx))?;
        *self.nt_build_lab_ex.borrow_mut() = Some(nt_build_lab_ex.clone());

        Ok(Some(nt_build_lab_ex))
    }

    // endregion: Kernel

    // region: Memory

    /// Retrieves information about a Virtual Address Descriptor (VAD) for a
    /// given address.
    ///
    /// This method extracts details such as the starting and ending virtual
    /// page numbers, VAD type, memory protection, and other flags
    /// associated with the specified VAD.
    pub fn vad(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        vad: Va,
    ) -> Result<WindowsVad, VmiError> {
        let MMVAD_FLAGS = &self.offsets.common._MMVAD_FLAGS;
        let MMVAD_SHORT = &self.offsets.common._MMVAD_SHORT;

        let mmvad = StructReader::new(
            vmi,
            registers.address_context(vad),
            MMVAD_SHORT.effective_len(),
        )?;
        let starting_vpn_low = mmvad.read(MMVAD_SHORT.StartingVpn)?;
        let ending_vpn_low = mmvad.read(MMVAD_SHORT.EndingVpn)?;
        let starting_vpn_high = match MMVAD_SHORT.StartingVpnHigh {
            Some(StartingVpnHigh) => mmvad.read(StartingVpnHigh)?,
            None => 0,
        };
        let ending_vpn_high = match MMVAD_SHORT.EndingVpnHigh {
            Some(EndingVpnHigh) => mmvad.read(EndingVpnHigh)?,
            None => 0,
        };

        let starting_vpn = (starting_vpn_high << 32) | starting_vpn_low;
        let ending_vpn = (ending_vpn_high << 32) | ending_vpn_low;

        let vad_flags = mmvad.read(MMVAD_SHORT.VadFlags)?;
        let vad_type = MMVAD_FLAGS.VadType.value_from(vad_flags) as u8;
        let protection = MMVAD_FLAGS.Protection.value_from(vad_flags) as u8;
        let private_memory = MMVAD_FLAGS.PrivateMemory.value_from(vad_flags) != 0;

        // If `MMVAD_FLAGS.MemCommit` is present (Windows 7), then we fetch the
        // value from it. Otherwise, we load the `VadFlags1` field from the VAD
        // and fetch it from there.
        let mem_commit = match MMVAD_FLAGS.MemCommit {
            // `MemCommit` is present in `MMVAD_FLAGS`
            Some(MemCommit) => MemCommit.value_from(vad_flags) != 0,

            None => match (&self.offsets.ext, MMVAD_SHORT.VadFlags1) {
                // `MemCommit` is present in `MMVAD_FLAGS1`
                (Some(OffsetsExt::V2(offsets)), Some(VadFlags1)) => {
                    let MMVAD_FLAGS1 = &offsets._MMVAD_FLAGS1;
                    let vad_flags1 = mmvad.read(VadFlags1)?;
                    MMVAD_FLAGS1.MemCommit.value_from(vad_flags1) != 0
                }
                _ => {
                    panic!("Failed to read MemCommit from VAD");
                }
            },
        };

        let left_child = Va(mmvad.read(MMVAD_SHORT.Left)?);
        let right_child = Va(mmvad.read(MMVAD_SHORT.Right)?);

        Ok(WindowsVad {
            starting_vpn,
            ending_vpn,
            vad_type,
            protection,
            private_memory,
            mem_commit,
            left_child,
            right_child,
        })
    }

    /// Locates the `VadRoot` for a given process. Returns the address of the
    /// root node.
    ///
    /// # Equivalent C pseudo-code
    ///
    /// ```c
    /// // For Windows 7:
    /// return Process->VadRoot->BalancedRoot;
    ///
    /// // For Windows 8 and later:
    /// return Process->VadRoot->Root;
    /// ```
    pub fn vad_root(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
    ) -> Result<Va, VmiError> {
        match &self.offsets.ext {
            Some(OffsetsExt::V1(offsets)) => self.vad_root_v1(vmi, registers, process, offsets),
            Some(OffsetsExt::V2(offsets)) => self.vad_root_v2(vmi, registers, process, offsets),
            None => panic!("OffsetsExt not set"),
        }
    }

    fn vad_root_v1(
        &self,
        _vmi: &VmiCore<Driver>,
        _registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
        offsets: &v1::Offsets,
    ) -> Result<Va, VmiError> {
        let EPROCESS = &self.offsets.common._EPROCESS;
        let MM_AVL_TABLE = &offsets._MM_AVL_TABLE;

        // The `_MM_AVL_TABLE::BalancedRoot` field is of `_MMADDRESS_NODE` type,
        // which represents the root.
        let vad_root = process.0 + EPROCESS.VadRoot.offset + MM_AVL_TABLE.BalancedRoot.offset;

        Ok(vad_root)
    }

    fn vad_root_v2(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
        offsets: &v2::Offsets,
    ) -> Result<Va, VmiError> {
        let EPROCESS = &self.offsets.common._EPROCESS;
        let RTL_AVL_TREE = &offsets._RTL_AVL_TREE;

        // The `RTL_AVL_TREE::Root` field is of pointer type (`_RTL_BALANCED_NODE*`),
        // thus we need to dereference it to get the actual node.
        let vad_root = vmi.read_va(
            registers
                .address_context(process.0 + EPROCESS.VadRoot.offset + RTL_AVL_TREE.Root.offset),
            registers.address_width(),
        )?;

        Ok(vad_root)
    }

    /// Retrieves the `VadHint` for a given process. Returns the address of the
    /// hint node in the VAD tree.
    ///
    /// The VAD hint is an optimization used by Windows to speed up VAD lookups.
    /// This method returns the address of the hint node in the VAD tree.
    ///
    /// # Equivalent C pseudo-code
    ///
    /// ```c
    /// // For Windows 7:
    /// return Process->VadRoot->NodeHint;
    ///
    /// // For Windows 8 and later:
    /// return Process->VadRoot->Hint;
    /// ```
    pub fn vad_hint(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
    ) -> Result<Va, VmiError> {
        match &self.offsets.ext {
            Some(OffsetsExt::V1(offsets)) => self.vad_hint_v1(vmi, registers, process, offsets),
            Some(OffsetsExt::V2(offsets)) => self.vad_hint_v2(vmi, registers, process, offsets),
            None => panic!("OffsetsExt not set"),
        }
    }

    fn vad_hint_v1(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
        offsets: &v1::Offsets,
    ) -> Result<Va, VmiError> {
        let EPROCESS = &self.offsets.common._EPROCESS;
        let MM_AVL_TABLE = &offsets._MM_AVL_TABLE;

        let vad_hint = vmi.read_va(
            registers.address_context(
                process.0 + EPROCESS.VadRoot.offset + MM_AVL_TABLE.NodeHint.offset,
            ),
            registers.address_width(),
        )?;

        Ok(vad_hint)
    }

    fn vad_hint_v2(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
        _offsets: &v2::Offsets,
    ) -> Result<Va, VmiError> {
        let EPROCESS = &self.offsets.common._EPROCESS;

        let VadHint = EPROCESS
            .VadHint
            .expect("VadHint is not present in common offsets");

        let vad_hint = vmi.read_va(
            registers.address_context(process.0 + VadHint.offset),
            registers.address_width(),
        )?;

        Ok(vad_hint)
    }

    /// Converts a VAD (Virtual Address Descriptor) to an [`OsRegion`] structure.
    ///
    /// This method extracts information from a VAD and creates an `OsRegion`
    /// object, which includes details about the memory region's address range,
    /// protection, and mapping type.
    pub fn vad_to_region(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        vad: Va,
    ) -> Result<OsRegion, VmiError> {
        let MMVAD = &self.offsets.common._MMVAD;
        let SUBSECTION = &self.offsets.common._SUBSECTION;

        let mmvad = self.vad(vmi, registers, vad)?;
        let start = Va(mmvad.starting_vpn << 12);
        let end = Va((mmvad.ending_vpn + 1) << 12);

        const MM_ZERO_ACCESS: u8 = 0; // this value is not used.
        const MM_READONLY: u8 = 1;
        const MM_EXECUTE: u8 = 2;
        const MM_EXECUTE_READ: u8 = 3;
        const MM_READWRITE: u8 = 4; // bit 2 is set if this is writable.
        const MM_WRITECOPY: u8 = 5;
        const MM_EXECUTE_READWRITE: u8 = 6;
        const MM_EXECUTE_WRITECOPY: u8 = 7;

        let protection = match mmvad.protection {
            MM_ZERO_ACCESS => MemoryAccess::default(),
            MM_READONLY => MemoryAccess::R,
            MM_EXECUTE => MemoryAccess::X,
            MM_EXECUTE_READ => MemoryAccess::RX,
            MM_READWRITE => MemoryAccess::RW,
            MM_WRITECOPY => MemoryAccess::RW, // REVIEW: is this correct?
            MM_EXECUTE_READWRITE => MemoryAccess::RWX,
            MM_EXECUTE_WRITECOPY => MemoryAccess::RWX, // REVIEW: is this correct?
            _ => MemoryAccess::default(),
        };

        const VadImageMap: u8 = 2;

        if mmvad.vad_type != VadImageMap {
            return Ok(OsRegion {
                start,
                end,
                protection,
                kind: OsRegionKind::Private,
            });
        }

        let subsection = vmi.read_va(
            registers.address_context(vad + MMVAD.Subsection.offset),
            registers.address_width(),
        )?;

        let control_area = vmi.read_va(
            registers.address_context(subsection + SUBSECTION.ControlArea.offset),
            registers.address_width(),
        )?;

        // Note that filename is allocated from paged pool,
        // so this read might fail.
        let path = self.control_area_to_filename(vmi, registers, control_area);

        Ok(OsRegion {
            start,
            end,
            protection,
            kind: OsRegionKind::Mapped(OsMapped {
                path: path.map(Some),
            }),
        })
    }

    /// Retrieves all memory regions associated with a process's VAD tree.
    ///
    /// This method traverses the entire VAD tree of a process and converts
    /// each VAD into an [`OsRegion`], providing a comprehensive view of the
    /// process's virtual address space.
    pub fn vad_root_to_regions(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        vad_root: Va,
    ) -> Result<Vec<OsRegion>, VmiError> {
        let mut result = Vec::new();

        self.enumerate_tree(vmi, registers, vad_root, |vad| {
            match self.vad_to_region(vmi, registers, vad) {
                Ok(region) => result.push(region),
                Err(err) => tracing::warn!(?err, ?vad, "Failed to convert VAD to region"),
            }

            true
        })?;

        Ok(result)
    }

    /// Locates the VAD that encompasses a specific virtual address in a process.
    ///
    /// This method efficiently searches the VAD tree to find the VAD node that
    /// corresponds to the given virtual address within the process's address
    /// space. Its functionality is similar to the Windows kernel's internal
    /// `MiLocateAddress()` function.
    ///
    /// Returns virtual address of the matching VAD if found, or `None` if the
    /// address is not within any VAD.
    ///
    pub fn find_process_vad(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
        address: Va,
    ) -> Result<Option<Va>, VmiError> {
        let mut vad_va = self.vad_hint(vmi, registers, process)?;

        if vad_va.is_null() {
            return Ok(None);
        }

        let vpn = address.0 >> 12;

        let vad = self.vad(vmi, registers, vad_va)?;
        if vpn >= vad.starting_vpn && vpn <= vad.ending_vpn {
            return Ok(Some(vad_va));
        }

        vad_va = self.vad_root(vmi, registers, process)?;

        while !vad_va.is_null() {
            let vad = self.vad(vmi, registers, vad_va)?;

            if vpn < vad.starting_vpn {
                vad_va = vad.left_child;
            }
            else if vpn > vad.ending_vpn {
                vad_va = vad.right_child;
            }
            else {
                return Ok(Some(vad_va));
            }
        }

        Ok(None)
    }

    /// Retrieves the virtual address of the Page Frame Number (PFN) database.
    ///
    /// The PFN database is a critical data structure in Windows memory management,
    /// containing information about each physical page in the system.
    ///
    /// # Implementation Details
    ///
    /// The PFN database is located by reading the `MmPfnDatabase` symbol from
    /// the kernel image.
    fn pfn_database(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
    ) -> Result<Va, VmiError> {
        let MmPfnDatabase = self.symbols.MmPfnDatabase;

        if let Some(mm_pfn_database) = self.mm_pfn_database.borrow().as_ref() {
            return Ok(*mm_pfn_database);
        }

        let kernel_image_base = self.kernel_image_base(vmi, registers)?;
        let mm_pfn_database = vmi.read_va(
            registers.address_context(kernel_image_base + MmPfnDatabase),
            registers.address_width(),
        )?;
        *self.mm_pfn_database.borrow_mut() = Some(mm_pfn_database);
        Ok(mm_pfn_database)
    }

    fn modify_pfn_reference_count(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        pfn: Gfn,
        increment: i16,
    ) -> Result<Option<u16>, VmiError> {
        let MMPFN = &self.offsets.common._MMPFN;

        // const ZeroedPageList: u16 = 0;
        // const FreePageList: u16 = 1;
        const StandbyPageList: u16 = 2; //this list and before make up available pages.
        const ModifiedPageList: u16 = 3;
        const ModifiedNoWritePageList: u16 = 4;
        // const BadPageList: u16 = 5;
        const ActiveAndValid: u16 = 6;
        // const TransitionPage: u16 = 7;

        let pfn = self.pfn_database(vmi, registers)? + u64::from(pfn) * MMPFN.len() as u64;

        //
        // In the _MMPFN structure, the fields are like this:
        //
        // ```c
        // struct _MMPFN {
        //     ...
        //     union {
        //         USHORT ReferenceCount;
        //         struct {
        //             UCHAR PageLocation : 3;
        //             ...
        //         } e1;
        //         ...
        //     } u3;
        // };
        // ```
        //
        // On the systems tested (Win7 - Win11), the `PageLocation` is right
        // after `ReferenceCount`. We can read the value of both fields at once.
        //

        debug_assert_eq!(MMPFN.ReferenceCount.size, 2);
        debug_assert_eq!(
            MMPFN.ReferenceCount.offset + MMPFN.ReferenceCount.size,
            MMPFN.PageLocation.offset
        );
        debug_assert_eq!(MMPFN.PageLocation.bit_position, 0);
        debug_assert_eq!(MMPFN.PageLocation.bit_length, 3);

        let pfn_value =
            vmi.read_u32(registers.address_context(pfn + MMPFN.ReferenceCount.offset))?;
        let flags = (pfn_value >> 16) as u16;
        let ref_count = (pfn_value & 0xFFFF) as u16;

        let page_location = flags & 7;

        tracing::debug!(
            %pfn,
            ref_count,
            flags = %Hex(flags),
            page_location,
            increment,
            "Modifying PFN reference count"
        );

        //
        // Make sure the page is good (when coming from hibernate/standby pages
        // can be in modified state).
        //

        if !matches!(
            page_location,
            StandbyPageList | ModifiedPageList | ModifiedNoWritePageList | ActiveAndValid
        ) {
            tracing::warn!(
                %pfn,
                ref_count,
                flags = %Hex(flags),
                page_location,
                increment,
                "Page is not active and valid"
            );
            return Ok(None);
        }

        if ref_count == 0 {
            tracing::warn!(
                %pfn,
                ref_count,
                flags = %Hex(flags),
                page_location,
                increment,
                "Page is not initialized"
            );
            return Ok(None);
        }

        let new_ref_count = match ref_count.checked_add_signed(increment) {
            Some(new_ref_count) => new_ref_count,
            None => {
                tracing::warn!(
                    %pfn,
                    ref_count,
                    flags = %Hex(flags),
                    page_location,
                    increment,
                    "Page is at maximum reference count"
                );
                return Ok(None);
            }
        };

        vmi.write_u16(
            registers.address_context(pfn + MMPFN.ReferenceCount.offset),
            new_ref_count,
        )?;

        Ok(Some(new_ref_count))
    }

    /// Increments the reference count of a Page Frame Number (PFN).
    ///
    /// This method is used to "lock" a physical page by increasing its
    /// reference count, preventing it from being paged out or reallocated.
    ///
    /// Returns the new reference count if successful, or `None` if the
    /// operation failed (e.g., if the page is not in a valid state).
    ///
    /// # Implementation Details
    ///
    /// The method works by:
    /// 1. Locating the `_MMPFN` structure for the given PFN within the `MmPfnDatabase`.
    /// 2. Incrementing the `ReferenceCount` member of the `_MMPFN` structure.
    ///
    /// # Warning
    ///
    /// This function can potentially cause race conditions if the virtual machine
    /// is not paused during its execution. It is strongly recommended to pause
    /// the virtual machine before calling this function and resume it afterwards.
    ///
    /// Failure to pause the VM may result in inconsistent state or potential
    /// crashes if the page is concurrently modified by the guest OS.
    ///
    /// # Examples:
    ///
    /// ```no_run
    /// # use vmi::{
    /// #     arch::amd64::{Amd64, Registers},
    /// #     os::windows::WindowsOs,
    /// #     Architecture, Gfn, VmiCore, VmiDriver, VmiError,
    /// # };
    /// #
    /// # fn example<Driver>(
    /// #     vmi: &VmiCore<Driver>,
    /// #     os: &WindowsOs<Driver>,
    /// #     registers: &Registers,
    /// #     pfn: Gfn,
    /// # ) -> Result<(), VmiError>
    /// # where
    /// #   Driver: VmiDriver<Architecture = Amd64>,
    /// # {
    /// let _pause_guard = vmi.pause_guard()?;
    /// os.lock_pfn(vmi, registers, pfn)?;
    /// // The VM will automatically resume when `_guard` goes out of scope
    /// # Ok(())
    /// # }
    /// ```
    pub fn lock_pfn(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        pfn: Gfn,
    ) -> Result<Option<u16>, VmiError> {
        self.modify_pfn_reference_count(vmi, registers, pfn, 1)
    }

    /// Decrements the reference count of a Page Frame Number (PFN).
    ///
    /// This method is used to "unlock" a physical page by decreasing its
    /// reference count, potentially allowing it to be paged out or reallocated
    /// if the count reaches zero.
    ///
    /// Returns the new reference count if successful, or `None` if the
    /// operation failed (e.g., if the page is not in a valid state).
    ///
    /// # Implementation Details
    ///
    /// The method works by:
    /// 1. Locating the `_MMPFN` structure for the given PFN within the `MmPfnDatabase`.
    /// 2. Decrementing the `ReferenceCount` member of the `_MMPFN` structure.
    ///
    /// # Warning
    ///
    /// This function can potentially cause race conditions if the virtual machine
    /// is not paused during its execution. It is strongly recommended to pause
    /// the virtual machine before calling this function and resume it afterwards.
    ///
    /// Failure to pause the VM may result in inconsistent state or potential
    /// crashes if the page is concurrently modified by the guest OS.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use vmi_arch_amd64::{Amd64, Registers};
    /// # use vmi_core::{Architecture, Gfn, VmiCore, VmiDriver, VmiError, VmiOs};
    /// # use vmi_os_windows::WindowsOs;
    /// #
    /// # fn example<Driver>(
    /// #     vmi: &VmiCore<Driver>,
    /// #     os: &WindowsOs<Driver>,
    /// #     registers: &Registers,
    /// #     pfn: Gfn,
    /// # ) -> Result<(), VmiError>
    /// # where
    /// #     Driver: VmiDriver<Architecture = Amd64>,
    /// # {
    /// let _pause_guard = vmi.pause_guard()?;
    /// os.unlock_pfn(vmi, registers, pfn)?;
    /// // The VM will automatically resume when `_guard` goes out of scope
    /// # Ok(())
    /// # }
    /// ```
    pub fn unlock_pfn(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        pfn: Gfn,
    ) -> Result<Option<u16>, VmiError> {
        self.modify_pfn_reference_count(vmi, registers, pfn, -1)
    }

    // endregion: Memory

    // region: Misc

    /// Retrieves the virtual address of the current Kernel Processor Control
    /// Region (KPCR).
    ///
    /// The KPCR is a per-processor data structure in Windows that contains
    /// critical information about the current processor state. This method
    /// returns the virtual address of the KPCR for the current processor.
    pub fn current_kpcr(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
    ) -> Va {
        Driver::Architecture::current_kpcr(self, vmi, registers)
    }

    /// Extracts information from an exception record at the specified address.
    ///
    /// This method reads and parses an `EXCEPTION_RECORD` structure from
    /// memory, providing detailed information about an exception that has
    /// occurred in the system. The returned [`WindowsExceptionRecord`]
    /// contains data such as the exception code, flags, and related memory
    /// addresses.
    pub fn exception_record(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        address: Va,
    ) -> Result<WindowsExceptionRecord, VmiError> {
        #[repr(C)]
        #[derive(Debug, Copy, Clone, FromBytes, IntoBytes)]
        #[allow(non_camel_case_types, non_snake_case)]
        struct _EXCEPTION_RECORD {
            ExceptionCode: u32,
            ExceptionFlags: u32,
            ExceptionRecord: u64,
            ExceptionAddress: u64,
            NumberParameters: u64,
            ExceptionInformation: [u64; 15],
        }

        let record = vmi.read_struct::<_EXCEPTION_RECORD>(registers.address_context(address))?;

        Ok(WindowsExceptionRecord {
            code: record.ExceptionCode,
            flags: record.ExceptionFlags,
            record: record.ExceptionRecord.into(),
            address: record.ExceptionAddress.into(),
            information: record.ExceptionInformation
                [..u64::min(record.NumberParameters, 15) as usize]
                .to_vec(),
        })
    }

    /// Retrieves the last status value for the current thread.
    ///
    /// In Windows, the last status value is typically used to store error codes
    /// or success indicators from system calls. This method reads this value
    /// from the Thread Environment Block (TEB) of the current thread, providing
    /// insight into the outcome of recent operations performed by the thread.
    ///
    /// Returns `None` if the TEB is not available.
    ///
    /// # Notes
    ///
    /// `LastStatusValue` is a `NTSTATUS` value, whereas `LastError` is a Win32
    /// error code. The two values are related but not identical. You can obtain
    /// the Win32 error code by calling
    /// [`VmiOs::last_error`](crate::VmiOs::last_error).
    ///
    /// # Implementation Details
    ///
    /// ```c
    /// return NtCurrentTeb()->LastStatusValue;
    /// ```
    pub fn last_status(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
    ) -> Result<Option<u32>, VmiError> {
        let KTHREAD = &self.offsets.common._KTHREAD;
        let TEB = &self.offsets.common._TEB;

        let current_thread = self.current_thread(vmi, registers)?;
        let teb = vmi.read_va(
            registers.address_context(current_thread.0 + KTHREAD.Teb.offset),
            registers.address_width(),
        )?;

        if teb.is_null() {
            return Ok(None);
        }

        let result = vmi.read_u32(registers.address_context(teb + TEB.LastStatusValue.offset))?;
        Ok(Some(result))
    }

    // endregion: Misc

    // region: Object

    /// Retrieves the object header cookie used for obfuscating object types.
    /// Returns `None` if the cookie is not present in the kernel image.
    ///
    /// # Notes
    ///
    /// Windows 10 introduced a security feature that obfuscates the type
    /// of kernel objects by XORing the `TypeIndex` field in the object header
    /// with a random cookie value. This method fetches that cookie, which is
    /// essential for correctly interpreting object headers in memory.
    ///
    /// # Implementation Details
    ///
    /// The object header cookie is located by reading the `ObHeaderCookie`
    /// symbol from the kernel image.
    pub fn object_header_cookie(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
    ) -> Result<Option<u8>, VmiError> {
        if let Some(cookie) = *self.object_header_cookie.borrow() {
            return Ok(Some(cookie));
        }

        let ObHeaderCookie = match self.symbols.ObHeaderCookie {
            Some(cookie) => cookie,
            None => return Ok(None),
        };

        let kernel_image_base = self.kernel_image_base(vmi, registers)?;
        let cookie = vmi.read_u8(registers.address_context(kernel_image_base + ObHeaderCookie))?;
        *self.object_header_cookie.borrow_mut() = Some(cookie);
        Ok(Some(cookie))
    }

    /// Determines the type of a Windows kernel object.
    ///
    /// This method analyzes the object header of a given kernel object
    /// and returns its type (e.g., Process, Thread, File). It handles the
    /// obfuscation introduced by the object header cookie, ensuring accurate
    /// type identification even on systems with this security feature enabled.
    pub fn object_type(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        object: Va,
    ) -> Result<Option<WindowsObjectType>, VmiError> {
        let ObTypeIndexTable = self.symbols.ObTypeIndexTable;
        let OBJECT_HEADER = &self.offsets.common._OBJECT_HEADER;

        let object_header = object - OBJECT_HEADER.Body.offset;
        let type_index =
            vmi.read_u8(registers.address_context(object_header + OBJECT_HEADER.TypeIndex.offset))?;

        let index = match self.object_header_cookie(vmi, registers)? {
            Some(cookie) => {
                //
                // TypeIndex ^ 2nd least significate byte of OBJECT_HEADER address ^
                // nt!ObHeaderCookie ref: https://medium.com/@ashabdalhalim/a-light-on-windows-10s-object-header-typeindex-value-e8f907e7073a
                //

                let salt = (u64::from(object_header) >> 8) as u8;
                type_index ^ salt ^ cookie
            }
            None => type_index,
        };

        let index = index as u64;

        let kernel_image_base = self.kernel_image_base(vmi, registers)?;
        let object_type = vmi.read_va(
            registers.address_context(
                kernel_image_base + ObTypeIndexTable + index * 8, // REVIEW: replace 8 with registers.address_width()?
            ),
            registers.address_width(),
        )?;

        if let Some(typ) = self.object_type_cache.borrow().get(&object_type) {
            return Ok(Some(*typ));
        }

        let object_name = self.read_unicode_string(
            vmi,
            registers.address_context(object_type + self.offsets.common._OBJECT_TYPE.Name.offset),
        )?;

        let typ = match object_name.as_str() {
            "ALPC Port" => WindowsObjectType::AlpcPort,
            "DebugObject" => WindowsObjectType::DebugObject,
            "Device" => WindowsObjectType::Device,
            "Directory" => WindowsObjectType::Directory,
            "Driver" => WindowsObjectType::Driver,
            "Event" => WindowsObjectType::Event,
            "File" => WindowsObjectType::File,
            "Job" => WindowsObjectType::Job,
            "Key" => WindowsObjectType::Key,
            "Mutant" => WindowsObjectType::Mutant,
            "Port" => WindowsObjectType::Port,
            "Process" => WindowsObjectType::Process,
            "Section" => WindowsObjectType::Section,
            "SymbolicLink" => WindowsObjectType::SymbolicLink,
            "Thread" => WindowsObjectType::Thread,
            "Timer" => WindowsObjectType::Timer,
            "Token" => WindowsObjectType::Token,
            "Type" => WindowsObjectType::Type,
            _ => return Ok(None),
        };

        self.object_type_cache.borrow_mut().insert(object_type, typ);

        Ok(Some(typ))
    }

    /// Retrieves the name of a named kernel object.
    ///
    /// Many Windows kernel objects (like mutexes, events, etc.) can have names.
    /// This method extracts the name of such an object, if present. It also
    /// provides information about the object's containing directory in the
    /// object namespace.
    pub fn object_name(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        object: Va,
    ) -> Result<Option<WindowsObjectName>, VmiError> {
        let ObpInfoMaskToOffset = self.symbols.ObpInfoMaskToOffset;
        let OBJECT_HEADER = &self.offsets.common._OBJECT_HEADER;
        let OBJECT_HEADER_NAME_INFO = &self.offsets.common._OBJECT_HEADER_NAME_INFO;

        let object_header = object - OBJECT_HEADER.Body.offset;
        let info_mask =
            vmi.read_u8(registers.address_context(object_header + OBJECT_HEADER.InfoMask.offset))?;

        bitflags::bitflags! {
            struct InfoFlags: u8 {
                const CREATOR_INFO = 0x01;
                const NAME_INFO = 0x02;
                const HANDLE_INFO = 0x04;
                const QUOTA_INFO = 0x08;
                const PROCESS_INFO = 0x10;
            }
        }

        let info_flags = InfoFlags::from_bits_truncate(info_mask);
        if !info_flags.contains(InfoFlags::NAME_INFO) {
            return Ok(None);
        }

        // Offset = ObpInfoMaskToOffset[OBJECT_HEADER->InfoMask & (DesiredHeaderBit |
        // (DesiredHeaderBit-1))]

        let mask = info_mask & (InfoFlags::NAME_INFO.bits() | (InfoFlags::NAME_INFO.bits() - 1));
        let mask = mask as u64;

        let kernel_image_base = self.kernel_image_base(vmi, registers)?;
        let offset = vmi
            .read_u8(registers.address_context(kernel_image_base + ObpInfoMaskToOffset + mask))?
            as u64;

        let object_header_name_info = object_header - offset;

        let directory = vmi.read_va(
            registers.address_context(
                object_header_name_info + OBJECT_HEADER_NAME_INFO.Directory.offset,
            ),
            registers.address_width(),
        )?;

        let name = self.read_unicode_string(
            vmi,
            registers
                .address_context(object_header_name_info + OBJECT_HEADER_NAME_INFO.Name.offset),
        )?;

        Ok(Some(WindowsObjectName { directory, name }))
    }

    /// Converts an `OBJECT_ATTRIBUTES` structure to an object name string.
    ///
    /// `OBJECT_ATTRIBUTES` is a structure used in many Windows system calls to
    /// specify an object. This method interprets that structure and extracts
    /// a meaningful name or path for the object. It handles both absolute and
    /// relative object names, considering the root directory if specified.
    ///
    /// Returns `None` if the `_OBJECT_ATTRIBUTES::ObjectName` field is `NULL`.
    pub fn object_attributes_to_object_name(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
        object_attributes: Va,
    ) -> Result<Option<String>, VmiError> {
        let OBJECT_ATTRIBUTES = &self.offsets.common._OBJECT_ATTRIBUTES;

        let object_name_address = vmi.read_va(
            registers.address_context(object_attributes + OBJECT_ATTRIBUTES.ObjectName.offset),
            registers.address_width(),
        )?;

        if object_name_address.is_null() {
            return Ok(None);
        }

        let object_name =
            self.read_unicode_string(vmi, registers.address_context(object_name_address))?;

        let root_directory = vmi.read_va(
            registers.address_context(object_attributes + OBJECT_ATTRIBUTES.RootDirectory.offset),
            registers.address_width(),
        )?;

        if root_directory.is_null() {
            return Ok(Some(object_name));
        }

        let object =
            match self.handle_to_object(vmi, registers, process, u64::from(root_directory))? {
                Some(object) => object,
                None => return Ok(Some(object_name)),
            };

        let root_name = match object {
            WindowsObject::File(file) => Some(file.filename),
            WindowsObject::Section(section) => match section.region.kind {
                OsRegionKind::Mapped(mapped) => mapped.path?,
                _ => None,
            },
        };

        match root_name {
            Some(root_name) => Ok(Some(format!("{root_name}\\{object_name}"))),
            None => Ok(Some(object_name)),
        }
    }

    // endregion: Object

    // region: PEB

    /// Retrieves the Process Environment Block (PEB) for a given process.
    ///
    /// The PEB contains crucial information about a process, including its
    /// loaded modules, environment variables, and command line arguments.
    pub fn process_peb(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
    ) -> Result<WindowsPeb, VmiError> {
        let root = self.process_translation_root(vmi, registers, process)?;

        let address = self.__process_peb_address(vmi, registers, process, root)?;
        let current_directory = self.__process_current_directory(vmi, registers, process, root)?;
        let dll_path = self.__process_dll_path(vmi, registers, process, root)?;
        let image_path_name = self.__process_image_path_name(vmi, registers, process, root)?;
        let command_line = self.__process_command_line(vmi, registers, process, root)?;

        Ok(WindowsPeb {
            address: address.va,
            current_directory,
            dll_path,
            image_path_name,
            command_line,
        })
    }

    /// Internal method to get the address of the PEB.
    ///
    /// This method handles both native (non-WoW64) processes and WoW64
    /// processes, returning the appropriate PEB address based on the
    /// process architecture.
    fn __process_peb_address(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
        root: Pa,
    ) -> Result<WindowsWow64Va, VmiError> {
        let EPROCESS = &self.offsets.common._EPROCESS;

        let wow64 = vmi.read_va(
            (process.0 + EPROCESS.WoW64Process.offset, root),
            registers.address_width(),
        )?;

        if wow64.is_null() {
            let peb64 = vmi.read_va(
                (process.0 + EPROCESS.Peb.offset, root),
                registers.address_width(),
            )?;

            Ok(WindowsWow64Va::native(peb64))
        }
        else {
            let peb32 = match &self.offsets.ext {
                Some(OffsetsExt::V1(_)) => wow64,
                Some(OffsetsExt::V2(v2)) => vmi.read_va(
                    (wow64 + v2._EWOW64PROCESS.Peb.offset, root),
                    registers.address_width(),
                )?,
                None => panic!("OffsetsExt not set"),
            };

            Ok(WindowsWow64Va::x86(peb32))
        }
    }

    /// Internal method to retrieve the address of
    /// `RTL_USER_PROCESS_PARAMETERS`.
    ///
    /// This structure contains various process-specific parameters, including
    /// the command line, current directory, and DLL search path.
    fn __process_rtl_process_parameters(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
        root: Pa,
    ) -> Result<WindowsWow64Va, VmiError> {
        let address = self.__process_peb_address(vmi, registers, process, root)?;

        match address.kind {
            WindowsWow64Kind::Native => {
                let PEB = &self.offsets.common._PEB;

                let va = vmi.read_va(
                    (address.va + PEB.ProcessParameters.offset, root),
                    registers.address_width(),
                )?;

                Ok(WindowsWow64Va::native(va))
            }
            WindowsWow64Kind::X86 => {
                const PEB32_ProcessParameters_offset: u64 = 0x10;

                let va = vmi.read_va(
                    (address.va + PEB32_ProcessParameters_offset, root),
                    registers.address_width(),
                )?;

                Ok(WindowsWow64Va::x86(va))
            }
        }
    }

    /// Gets the current working directory of a process.
    ///
    /// This method retrieves the full path of the current working directory
    /// for the specified process.
    ///
    /// # Equivalent C pseudo-code
    ///
    /// ```c
    /// PRTL_USER_PROCESS_PARAMETERS ProcessParameters = NtCurrentPeb()->ProcessParameters;
    /// PUNICODE_STRING CurrentDirectory = ProcessParameters->CurrentDirectory;
    /// return CurrentDirectory;
    /// ```
    pub fn process_current_directory(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
    ) -> Result<String, VmiError> {
        let root = self.process_translation_root(vmi, registers, process)?;
        self.__process_current_directory(vmi, registers, process, root)
    }

    /// Internal method to get the current directory, handling both 32-bit and
    /// 64-bit processes.
    fn __process_current_directory(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
        root: Pa,
    ) -> Result<String, VmiError> {
        let address = self.__process_rtl_process_parameters(vmi, registers, process, root)?;

        match address.kind {
            WindowsWow64Kind::Native => {
                self.process_current_directory_native(vmi, root, address.va)
            }
            WindowsWow64Kind::X86 => self.process_current_directory_32bit(vmi, root, address.va),
        }
    }

    /// Retrieves the current directory for a native (non-WoW64) process.
    fn process_current_directory_native(
        &self,
        vmi: &VmiCore<Driver>,
        root: Pa,
        rtl_process_parameters: Va,
    ) -> Result<String, VmiError> {
        let CURDIR = &self.offsets.common._CURDIR;
        let RTL_USER_PROCESS_PARAMETERS = &self.offsets.common._RTL_USER_PROCESS_PARAMETERS;

        self.read_unicode_string(
            vmi,
            (
                rtl_process_parameters
                    + RTL_USER_PROCESS_PARAMETERS.CurrentDirectory.offset
                    + CURDIR.DosPath.offset,
                root,
            ),
        )
    }

    /// Retrieves the current directory for a 32-bit process running under
    /// WoW64.
    fn process_current_directory_32bit(
        &self,
        vmi: &VmiCore<Driver>,
        root: Pa,
        rtl_process_parameters: Va,
    ) -> Result<String, VmiError> {
        const RTL_USER_PROCESS_PARAMETERS32_CurrentDirectory_offset: u64 = 0x24;

        self.read_unicode_string32(
            vmi,
            (
                rtl_process_parameters + RTL_USER_PROCESS_PARAMETERS32_CurrentDirectory_offset,
                root,
            ),
        )
    }

    /// Gets the DLL search path for a process.
    ///
    /// This method retrieves the list of directories that the system searches
    /// when loading DLLs for the specified process.
    ///
    /// # Equivalent C pseudo-code
    ///
    /// ```c
    /// PRTL_USER_PROCESS_PARAMETERS ProcessParameters = NtCurrentPeb()->ProcessParameters;
    /// PUNICODE_STRING DllPath = ProcessParameters->DllPath;
    /// return DllPath;
    /// ```
    pub fn process_dll_path(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
    ) -> Result<String, VmiError> {
        let root = self.process_translation_root(vmi, registers, process)?;
        self.__process_dll_path(vmi, registers, process, root)
    }

    /// Internal method to get the DLL path, handling both 32-bit and 64-bit
    /// processes.
    fn __process_dll_path(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
        root: Pa,
    ) -> Result<String, VmiError> {
        let address = self.__process_rtl_process_parameters(vmi, registers, process, root)?;

        match address.kind {
            WindowsWow64Kind::Native => self.process_dll_path_native(vmi, root, address.va),
            WindowsWow64Kind::X86 => self.process_dll_path_32bit(vmi, root, address.va),
        }
    }

    /// Retrieves the DLL search path for a native (non-WoW64) process.
    fn process_dll_path_native(
        &self,
        vmi: &VmiCore<Driver>,
        root: Pa,
        rtl_process_parameters: Va,
    ) -> Result<String, VmiError> {
        let RTL_USER_PROCESS_PARAMETERS = &self.offsets.common._RTL_USER_PROCESS_PARAMETERS;

        self.read_unicode_string(
            vmi,
            (
                rtl_process_parameters + RTL_USER_PROCESS_PARAMETERS.DllPath.offset,
                root,
            ),
        )
    }

    /// Retrieves the DLL search path for a 32-bit process running under WoW64.
    fn process_dll_path_32bit(
        &self,
        vmi: &VmiCore<Driver>,
        root: Pa,
        rtl_process_parameters: Va,
    ) -> Result<String, VmiError> {
        const RTL_USER_PROCESS_PARAMETERS32_DllPath_offset: u64 = 0x30;

        self.read_unicode_string32(
            vmi,
            (
                rtl_process_parameters + RTL_USER_PROCESS_PARAMETERS32_DllPath_offset,
                root,
            ),
        )
    }

    /// Gets the full path of the executable image for a process.
    ///
    /// This method retrieves the full file system path of the main executable
    /// that was used to create the specified process.
    ///
    /// # Equivalent C pseudo-code
    ///
    /// ```c
    /// PRTL_USER_PROCESS_PARAMETERS ProcessParameters = NtCurrentPeb()->ProcessParameters;
    /// PUNICODE_STRING ImagePathName = ProcessParameters->ImagePathName;
    /// return ImagePathName;
    /// ```
    pub fn process_image_path_name(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
    ) -> Result<String, VmiError> {
        let root = self.process_translation_root(vmi, registers, process)?;
        self.__process_image_path_name(vmi, registers, process, root)
    }

    /// Internal method to get the image path name, handling both 32-bit and
    /// 64-bit processes.
    fn __process_image_path_name(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
        root: Pa,
    ) -> Result<String, VmiError> {
        let address = self.__process_rtl_process_parameters(vmi, registers, process, root)?;

        match address.kind {
            WindowsWow64Kind::Native => self.process_image_path_name_native(vmi, root, address.va),
            WindowsWow64Kind::X86 => self.process_image_path_name_32bit(vmi, root, address.va),
        }
    }

    /// Retrieves the image path name for a native (non-WoW64) process.
    fn process_image_path_name_native(
        &self,
        vmi: &VmiCore<Driver>,
        root: Pa,
        rtl_process_parameters: Va,
    ) -> Result<String, VmiError> {
        let RTL_USER_PROCESS_PARAMETERS = &self.offsets.common._RTL_USER_PROCESS_PARAMETERS;

        self.read_unicode_string(
            vmi,
            (
                rtl_process_parameters + RTL_USER_PROCESS_PARAMETERS.ImagePathName.offset,
                root,
            ),
        )
    }

    /// Retrieves the image path name for a 32-bit process running under WoW64.
    fn process_image_path_name_32bit(
        &self,
        vmi: &VmiCore<Driver>,
        root: Pa,
        rtl_process_parameters: Va,
    ) -> Result<String, VmiError> {
        const RTL_USER_PROCESS_PARAMETERS32_ImagePathName_offset: u64 = 0x38;

        self.read_unicode_string32(
            vmi,
            (
                rtl_process_parameters + RTL_USER_PROCESS_PARAMETERS32_ImagePathName_offset,
                root,
            ),
        )
    }

    /// Gets the command line used to launch a process.
    ///
    /// This method retrieves the full command line string, including the
    /// executable path and any arguments, used to start the specified process.
    ///
    /// # Equivalent C pseudo-code
    ///
    /// ```c
    /// PRTL_USER_PROCESS_PARAMETERS ProcessParameters = NtCurrentPeb()->ProcessParameters;
    /// PUNICODE_STRING CommandLine = ProcessParameters->CommandLine;
    /// return CommandLine;
    /// ```
    pub fn process_command_line(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
    ) -> Result<String, VmiError> {
        let root = self.process_translation_root(vmi, registers, process)?;
        self.__process_command_line(vmi, registers, process, root)
    }

    /// Internal method to get the command line, handling both 32-bit and 64-bit
    /// processes.
    fn __process_command_line(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
        root: Pa,
    ) -> Result<String, VmiError> {
        let address = self.__process_rtl_process_parameters(vmi, registers, process, root)?;

        match address.kind {
            WindowsWow64Kind::Native => self.process_command_line_native(vmi, root, address.va),
            WindowsWow64Kind::X86 => self.process_command_line_32bit(vmi, root, address.va),
        }
    }

    /// Retrieves the command line for a native (non-WoW64) process.
    fn process_command_line_native(
        &self,
        vmi: &VmiCore<Driver>,
        root: Pa,
        rtl_process_parameters: Va,
    ) -> Result<String, VmiError> {
        let RTL_USER_PROCESS_PARAMETERS = &self.offsets.common._RTL_USER_PROCESS_PARAMETERS;

        self.read_unicode_string(
            vmi,
            (
                rtl_process_parameters + RTL_USER_PROCESS_PARAMETERS.CommandLine.offset,
                root,
            ),
        )
    }

    /// Retrieves the command line for a 32-bit process running under WoW64.
    fn process_command_line_32bit(
        &self,
        vmi: &VmiCore<Driver>,
        root: Pa,
        rtl_process_parameters: Va,
    ) -> Result<String, VmiError> {
        const RTL_USER_PROCESS_PARAMETERS32_CommandLine_offset: u64 = 0x40;

        self.read_unicode_string32(
            vmi,
            (
                rtl_process_parameters + RTL_USER_PROCESS_PARAMETERS32_CommandLine_offset,
                root,
            ),
        )
    }

    // endregion: PEB

    // region: Process

    /// Extracts the `EPROCESS` structure from a `KTHREAD` structure.
    ///
    /// # Equivalent C pseudo-code
    ///
    /// ```c
    /// return Thread->Process;
    /// ```
    pub fn process_from_thread(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        thread: ThreadObject,
    ) -> Result<ProcessObject, VmiError> {
        let KTHREAD = &self.offsets.common._KTHREAD;

        let process = vmi.read_va(
            registers.address_context(thread.0 + KTHREAD.Process.offset),
            registers.address_width(),
        )?;

        Ok(ProcessObject(process))
    }

    /// Extracts the `EPROCESS` structure from a `KAPC_STATE` structure.
    ///
    /// # Equivalent C pseudo-code
    ///
    /// ```c
    /// return Thread->ApcState->Process;
    /// ```
    pub fn process_from_thread_apc_state(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        thread: ThreadObject,
    ) -> Result<ProcessObject, VmiError> {
        let KTHREAD = &self.offsets.common._KTHREAD;
        let KAPC_STATE = &self.offsets.common._KAPC_STATE;

        let process = vmi.read_va(
            registers
                .address_context(thread.0 + KTHREAD.ApcState.offset + KAPC_STATE.Process.offset),
            registers.address_width(),
        )?;

        Ok(ProcessObject(process))
    }

    /// Constructs an [`OsProcess`] from an `_EPROCESS`.
    pub fn process_object_to_process(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
    ) -> Result<OsProcess, VmiError> {
        let EPROCESS = &self.offsets.common._EPROCESS;
        let KPROCESS = &self.offsets.common._KPROCESS;

        let id =
            vmi.read_u32(registers.address_context(process.0 + EPROCESS.UniqueProcessId.offset))?;

        let name =
            vmi.read_string(registers.address_context(process.0 + EPROCESS.ImageFileName.offset))?;

        let translation_root = vmi.read_address(
            registers.address_context(process.0 + KPROCESS.DirectoryTableBase.offset),
            registers.address_width(),
        )?;

        Ok(OsProcess {
            id: id.into(),
            object: process,
            name,
            translation_root: translation_root.into(),
        })
    }

    // endregion: Process

    // region: String

    /// Reads string from an `_ANSI_STRING` structure.
    ///
    /// This method reads a native `_ANSI_STRING` structure which contains
    /// an ASCII/ANSI string. The structure is read according to the current
    /// OS's architecture (32-bit or 64-bit).
    pub fn read_ansi_string(
        &self,
        vmi: &VmiCore<Driver>,
        ctx: impl Into<AccessContext>,
    ) -> Result<String, VmiError> {
        let mut ctx = ctx.into();

        //
        // `_ANSI_STRING` is unfortunately missing in the PDB symbols.
        // However, its layout is same as `_UNICODE_STRING`.
        //

        let ANSI_STRING = &self.offsets.common._UNICODE_STRING;

        let string = StructReader::new(vmi, ctx, ANSI_STRING.effective_len())?;
        let string_length = string.read(ANSI_STRING.Length)?;
        let string_buffer = string.read(ANSI_STRING.Buffer)?;

        ctx.address = string_buffer;

        let mut buffer = vec![0u8; string_length as usize];
        vmi.read(ctx, &mut buffer)?;

        Ok(String::from_utf8_lossy(&buffer).into())
    }

    /// Reads string from a 32-bit version of `_ANSI_STRING` structure.
    ///
    /// This method is specifically for reading `_ANSI_STRING` structures in
    /// 32-bit processes or WoW64 processes where pointers are 32 bits.
    pub fn read_ansi_string32(
        &self,
        vmi: &VmiCore<Driver>,
        ctx: impl Into<AccessContext>,
    ) -> Result<String, VmiError> {
        let mut ctx = ctx.into();

        let mut buffer = [0u8; 8];
        vmi.read(ctx, &mut buffer)?;

        let string_length = u16::from_le_bytes([buffer[0], buffer[1]]);
        // let string_maximum_length = u16::from_le_bytes([buffer[2], buffer[3]]);
        let string_buffer = u32::from_le_bytes([buffer[4], buffer[5], buffer[6], buffer[7]]);

        ctx.address = string_buffer as u64;

        let mut buffer = vec![0u8; string_length as usize];
        vmi.read(ctx, &mut buffer)?;

        Ok(String::from_utf8_lossy(&buffer).into())
    }

    /// Reads string from a 64-bit version of `_ANSI_STRING` structure.
    ///
    /// This method is specifically for reading `_ANSI_STRING` structures in
    /// 64-bit processes where pointers are 64 bits.
    pub fn read_ansi_string64(
        &self,
        vmi: &VmiCore<Driver>,
        ctx: impl Into<AccessContext>,
    ) -> Result<String, VmiError> {
        let mut ctx = ctx.into();

        let mut buffer = [0u8; 16];
        vmi.read(ctx, &mut buffer)?;

        let string_length = u16::from_le_bytes([buffer[0], buffer[1]]);
        // let string_maximum_length = u16::from_le_bytes([buffer[2], buffer[3]]);
        let string_buffer = u64::from_le_bytes([
            buffer[8], buffer[9], buffer[10], buffer[11], buffer[12], buffer[13], buffer[14],
            buffer[15],
        ]);

        ctx.address = string_buffer;

        let mut buffer = vec![0u8; string_length as usize];
        vmi.read(ctx, &mut buffer)?;

        Ok(String::from_utf8_lossy(&buffer).into())
    }

    /// Reads string from a `_UNICODE_STRING` structure.
    ///
    /// This method reads a native `_UNICODE_STRING` structure which contains
    /// a UTF-16 string. The structure is read according to the current OS's
    /// architecture (32-bit or 64-bit).
    pub fn read_unicode_string(
        &self,
        vmi: &VmiCore<Driver>,
        ctx: impl Into<AccessContext>,
    ) -> Result<String, VmiError> {
        let mut ctx = ctx.into();

        let UNICODE_STRING = &self.offsets.common._UNICODE_STRING;

        let string = StructReader::new(vmi, ctx, UNICODE_STRING.effective_len())?;
        let string_length = string.read(UNICODE_STRING.Length)?;
        let string_buffer = string.read(UNICODE_STRING.Buffer)?;

        ctx.address = string_buffer;

        let mut buffer = vec![0u8; string_length as usize];
        vmi.read(ctx, &mut buffer)?;

        Ok(String::from_utf16_lossy(
            &buffer
                .chunks_exact(2)
                .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]))
                .collect::<Vec<_>>(),
        ))
    }

    /// Reads string from a 32-bit version of `_UNICODE_STRING` structure.
    ///
    /// This method is specifically for reading `_UNICODE_STRING` structures
    /// in 32-bit processes or WoW64 processes where pointers are 32 bits.
    pub fn read_unicode_string32(
        &self,
        vmi: &VmiCore<Driver>,
        ctx: impl Into<AccessContext>,
    ) -> Result<String, VmiError> {
        let mut ctx = ctx.into();

        let mut buffer = [0u8; 8];
        vmi.read(ctx, &mut buffer)?;

        let string_length = u16::from_le_bytes([buffer[0], buffer[1]]);
        // let string_maximum_length = u16::from_le_bytes([buffer[2], buffer[3]]);
        let string_buffer = u32::from_le_bytes([buffer[4], buffer[5], buffer[6], buffer[7]]);

        ctx.address = string_buffer as u64;

        let mut buffer = vec![0u8; string_length as usize];
        vmi.read(ctx, &mut buffer)?;

        Ok(String::from_utf16_lossy(
            &buffer
                .chunks_exact(2)
                .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]))
                .collect::<Vec<_>>(),
        ))
    }

    /// Reads string from a 64-bit version of `_UNICODE_STRING` structure.
    ///
    /// This method is specifically for reading `_UNICODE_STRING` structures
    /// in 64-bit processes where pointers are 64 bits.
    pub fn read_unicode_string64(
        &self,
        vmi: &VmiCore<Driver>,
        ctx: impl Into<AccessContext>,
    ) -> Result<String, VmiError> {
        let mut ctx = ctx.into();

        let mut buffer = [0u8; 16];
        vmi.read(ctx, &mut buffer)?;

        let us_length = u16::from_le_bytes([buffer[0], buffer[1]]);
        // let us_maximum_length = u16::from_le_bytes([buffer[2], buffer[3]]);
        let us_buffer = u64::from_le_bytes([
            buffer[8], buffer[9], buffer[10], buffer[11], buffer[12], buffer[13], buffer[14],
            buffer[15],
        ]);

        ctx.address = us_buffer;

        let mut buffer = vec![0u8; us_length as usize];
        vmi.read(ctx, &mut buffer)?;

        Ok(String::from_utf16_lossy(
            &buffer
                .chunks_exact(2)
                .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]))
                .collect::<Vec<_>>(),
        ))
    }

    // endregion: String

    // region: User Address

    /// Returns the lowest user-mode address.
    ///
    /// This method returns a constant value (0x10000) representing the lowest
    /// address that can be used by user-mode applications in Windows.
    ///
    /// # Notes
    ///
    /// * Windows creates a `NO_ACCESS` VAD (Virtual Address Descriptor) for the first 64KB
    ///   of virtual memory. This means the VA range 0-0x10000 is off-limits for usage.
    /// * This behavior is consistent across all Windows versions from XP through
    ///   recent Windows 11, and applies to x86, x64, and ARM64 architectures.
    /// * Many Windows APIs leverage this fact to determine whether an input argument
    ///   is a pointer or not. Here are two notable examples:
    ///
    ///   1. The `FindResource()` function accepts an `lpName` parameter of type `LPCTSTR`,
    ///      which can be either:
    ///      - A pointer to a valid string
    ///      - A value created by `MAKEINTRESOURCE(ID)`
    ///
    ///         This allows `FindResource()` to accept `WORD` values (unsigned shorts) with
    ///         a maximum value of 0xFFFF, distinguishing them from valid memory addresses.
    ///
    ///   2. The `AddAtom()` function similarly accepts an `lpString` parameter of type `LPCTSTR`.
    ///      This parameter can be:
    ///      - A pointer to a null-terminated string (max 255 bytes)
    ///      - An integer atom converted using the `MAKEINTATOM(ID)` macro
    ///
    ///   In both cases, the API can distinguish between valid pointers (which will be
    ///   above 0x10000) and integer values (which will be below 0x10000), allowing
    ///   for flexible parameter usage without ambiguity.
    pub fn lowest_user_address(
        &self,
        _vmi: &VmiCore<Driver>,
        _registers: &<Driver::Architecture as Architecture>::Registers,
    ) -> Result<Va, VmiError> {
        Ok(Va(0x10000))
    }

    /// Retrieves the highest user-mode address.
    ///
    /// This method reads the highest user-mode address from the Windows kernel.
    /// The value is cached after the first read for performance.
    pub fn highest_user_address(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
    ) -> Result<Va, VmiError> {
        if let Some(highest_user_address) = *self.highest_user_address.borrow() {
            return Ok(highest_user_address);
        }

        let MmHighestUserAddress =
            self.kernel_image_base(vmi, registers)? + self.symbols.MmHighestUserAddress;

        let highest_user_address = vmi.read_va(
            registers.address_context(MmHighestUserAddress),
            registers.address_width(),
        )?;
        *self.highest_user_address.borrow_mut() = Some(highest_user_address);
        Ok(highest_user_address)
    }

    /// Checks if a given address is a valid user-mode address.
    ///
    /// This method determines whether the provided address falls within
    /// the range of valid user-mode addresses in Windows.
    pub fn is_valid_user_address(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        address: Va,
    ) -> Result<bool, VmiError> {
        let lowest_user_address = self.lowest_user_address(vmi, registers)?;
        let highest_user_address = self.highest_user_address(vmi, registers)?;

        Ok(address >= lowest_user_address && address <= highest_user_address)
    }

    // endregion: User Address
}

#[allow(non_snake_case)]
impl<Driver> VmiOs<Driver> for WindowsOs<Driver>
where
    Driver: VmiDriver,
    Driver::Architecture: Architecture + ArchAdapter<Driver>,
{
    fn kernel_image_base(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
    ) -> Result<Va, VmiError> {
        Driver::Architecture::kernel_image_base(self, vmi, registers)
    }

    fn kernel_information_string(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<<Driver as VmiDriver>::Architecture as Architecture>::Registers,
    ) -> Result<String, VmiError> {
        let NtBuildLab = self.symbols.NtBuildLab;

        if let Some(nt_build_lab) = self.nt_build_lab.borrow().as_ref() {
            return Ok(nt_build_lab.clone());
        }

        let kernel_image_base = self.kernel_image_base(vmi, registers)?;
        let nt_build_lab =
            vmi.read_string(registers.address_context(kernel_image_base + NtBuildLab))?;
        *self.nt_build_lab.borrow_mut() = Some(nt_build_lab.clone());
        Ok(nt_build_lab)
    }

    fn kpti_enabled(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<<Driver as VmiDriver>::Architecture as Architecture>::Registers,
    ) -> Result<bool, VmiError> {
        let KiKvaShadow = self.symbols.KiKvaShadow;

        if let Some(ki_kva_shadow) = self.ki_kva_shadow.borrow().as_ref() {
            return Ok(*ki_kva_shadow);
        }

        let KiKvaShadow = match KiKvaShadow {
            Some(KiKvaShadow) => KiKvaShadow,
            None => {
                *self.ki_kva_shadow.borrow_mut() = Some(false);
                return Ok(false);
            }
        };

        let kernel_image_base = self.kernel_image_base(vmi, registers)?;
        let ki_kva_shadow =
            vmi.read_u8(registers.address_context(kernel_image_base + KiKvaShadow))? != 0;
        *self.ki_kva_shadow.borrow_mut() = Some(ki_kva_shadow);
        Ok(ki_kva_shadow)
    }

    fn system_process(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<<Driver as VmiDriver>::Architecture as Architecture>::Registers,
    ) -> Result<ProcessObject, VmiError> {
        let PsInitialSystemProcess =
            self.kernel_image_base(vmi, registers)? + self.symbols.PsInitialSystemProcess;

        let process = vmi.read_va(
            registers.address_context(PsInitialSystemProcess),
            registers.address_width(),
        )?;

        Ok(ProcessObject(process))
    }

    fn thread_id(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        thread: ThreadObject,
    ) -> Result<ThreadId, VmiError> {
        let ETHREAD = &self.offsets.common._ETHREAD;
        let CLIENT_ID = &self.offsets.common._CLIENT_ID;

        let result = vmi.read_u32(
            registers
                .address_context(thread.0 + ETHREAD.Cid.offset + CLIENT_ID.UniqueThread.offset),
        )?;

        Ok(ThreadId(result))
    }

    fn process_id(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
    ) -> Result<ProcessId, VmiError> {
        let EPROCESS = &self.offsets.common._EPROCESS;

        let result =
            vmi.read_u32(registers.address_context(process.0 + EPROCESS.UniqueProcessId.offset))?;

        Ok(ProcessId(result))
    }

    fn current_thread(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
    ) -> Result<ThreadObject, VmiError> {
        let KPCR = &self.offsets.common._KPCR;
        let KPRCB = &self.offsets.common._KPRCB;

        let kpcr = self.current_kpcr(vmi, registers);

        if kpcr.is_null() {
            return Err(VmiError::Other("Invalid KPCR"));
        }

        let addr = kpcr + KPCR.Prcb.offset + KPRCB.CurrentThread.offset;
        let result = vmi.read_va(registers.address_context(addr), registers.address_width())?;

        Ok(ThreadObject(result))
    }

    fn current_thread_id(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
    ) -> Result<ThreadId, VmiError> {
        let thread = self.current_thread(vmi, registers)?;

        if thread.is_null() {
            return Err(VmiError::Other("Invalid thread"));
        }

        self.thread_id(vmi, registers, thread)
    }

    fn current_process(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
    ) -> Result<ProcessObject, VmiError> {
        let thread = self.current_thread(vmi, registers)?;

        if thread.is_null() {
            return Err(VmiError::Other("Invalid thread"));
        }

        self.process_from_thread_apc_state(vmi, registers, thread)
    }

    fn current_process_id(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
    ) -> Result<ProcessId, VmiError> {
        let process = self.current_process(vmi, registers)?;

        if process.is_null() {
            return Err(VmiError::Other("Invalid process"));
        }

        self.process_id(vmi, registers, process)
    }

    fn processes(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
    ) -> Result<Vec<OsProcess>, VmiError> {
        let mut result = Vec::new();

        let PsActiveProcessHead =
            self.kernel_image_base(vmi, registers)? + self.symbols.PsActiveProcessHead;
        let EPROCESS = &self.offsets.common._EPROCESS;

        self.enumerate_list(vmi, registers, PsActiveProcessHead, |entry| {
            let process_object = entry - EPROCESS.ActiveProcessLinks.offset;

            if let Ok(process) =
                self.process_object_to_process(vmi, registers, process_object.into())
            {
                result.push(process)
            }

            true
        })?;

        Ok(result)
    }

    fn process_parent_process_id(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
    ) -> Result<ProcessId, VmiError> {
        let EPROCESS = &self.offsets.common._EPROCESS;

        let result = vmi.read_u32(
            registers.address_context(process.0 + EPROCESS.InheritedFromUniqueProcessId.offset),
        )?;

        Ok(ProcessId(result))
    }

    fn process_architecture(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
    ) -> Result<OsArchitecture, VmiError> {
        let EPROCESS = &self.offsets.common._EPROCESS;

        let wow64process = vmi.read_va(
            registers.address_context(process.0 + EPROCESS.WoW64Process.offset),
            registers.address_width(),
        )?;

        if wow64process.is_null() {
            Ok(OsArchitecture::Amd64)
        }
        else {
            Ok(OsArchitecture::X86)
        }
    }

    fn process_translation_root(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
    ) -> Result<Pa, VmiError> {
        let KPROCESS = &self.offsets.common._KPROCESS;

        let current_process = self.current_process(vmi, registers)?;

        if process == current_process {
            return Ok(registers.translation_root(process.0));
        }

        let root = Cr3::from(u64::from(vmi.read_va(
            registers.address_context(process.0 + KPROCESS.DirectoryTableBase.offset),
            registers.address_width(),
        )?));

        Ok(Pa::from(root))
    }

    fn process_user_translation_root(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
    ) -> Result<Pa, VmiError> {
        let KPROCESS = &self.offsets.common._KPROCESS;
        let UserDirectoryTableBase = match &KPROCESS.UserDirectoryTableBase {
            Some(UserDirectoryTableBase) => UserDirectoryTableBase,
            None => return self.process_translation_root(vmi, registers, process),
        };

        let root = u64::from(vmi.read_va(
            registers.address_context(process.0 + UserDirectoryTableBase.offset),
            registers.address_width(),
        )?);

        if root < Driver::Architecture::PAGE_SIZE {
            return self.process_translation_root(vmi, registers, process);
        }

        Ok(Pa::from(Cr3::from(root)))
    }

    fn process_filename(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
    ) -> Result<String, VmiError> {
        let EPROCESS = &self.offsets.common._EPROCESS;

        vmi.read_string(registers.address_context(process.0 + EPROCESS.ImageFileName.offset))
    }

    fn process_image_base(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
    ) -> Result<Va, VmiError> {
        let EPROCESS = &self.offsets.common._EPROCESS;

        vmi.read_va(
            registers.address_context(process.0 + EPROCESS.SectionBaseAddress.offset),
            registers.address_width(),
        )
    }

    fn process_regions(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
    ) -> Result<Vec<OsRegion>, VmiError> {
        let vad_root = self.vad_root(vmi, registers, process)?;
        self.vad_root_to_regions(vmi, registers, vad_root)
    }

    fn process_address_is_valid(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
        address: Va,
    ) -> Result<Option<bool>, VmiError> {
        Driver::Architecture::process_address_is_valid(self, vmi, registers, process, address)
    }

    fn find_process_region(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        process: ProcessObject,
        address: Va,
    ) -> Result<Option<OsRegion>, VmiError> {
        let vad = match self.find_process_vad(vmi, registers, process, address)? {
            Some(vad) => vad,
            None => return Ok(None),
        };

        Ok(Some(self.vad_to_region(vmi, registers, vad)?))
    }

    fn image_architecture(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        image_base: Va,
    ) -> Result<OsArchitecture, VmiError> {
        let mut data = [0u8; Amd64::PAGE_SIZE as usize];
        vmi.read(registers.address_context(image_base), &mut data)?;

        let pe_magic = optional_header_magic(data.as_ref())
            .map_err(|_| VmiError::Os(PeError::InvalidPeMagic.into()))?;

        match pe_magic {
            IMAGE_NT_OPTIONAL_HDR32_MAGIC => Ok(OsArchitecture::X86),
            IMAGE_NT_OPTIONAL_HDR64_MAGIC => Ok(OsArchitecture::Amd64),
            _ => Ok(OsArchitecture::Unknown),
        }
    }

    fn image_exported_symbols(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        image_base: Va,
    ) -> Result<Vec<OsImageExportedSymbol>, VmiError> {
        match self.image_architecture(vmi, registers, image_base)? {
            OsArchitecture::Unknown => Err(VmiError::Os(PeError::InvalidPeMagic.into())),
            OsArchitecture::X86 => {
                tracing::trace!(?image_base, "32-bit PE");
                self.image_exported_symbols_generic::<ImageNtHeaders32>(vmi, registers, image_base)
            }
            OsArchitecture::Amd64 => {
                tracing::trace!(?image_base, "64-bit PE");
                self.image_exported_symbols_generic::<ImageNtHeaders64>(vmi, registers, image_base)
            }
        }
    }

    fn syscall_argument(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        index: u64,
    ) -> Result<u64, VmiError> {
        Driver::Architecture::syscall_argument(self, vmi, registers, index)
    }

    fn function_argument(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        index: u64,
    ) -> Result<u64, VmiError> {
        Driver::Architecture::function_argument(self, vmi, registers, index)
    }

    fn function_return_value(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
    ) -> Result<u64, VmiError> {
        Driver::Architecture::function_return_value(self, vmi, registers)
    }

    fn last_error(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
    ) -> Result<Option<u32>, VmiError> {
        let KTHREAD = &self.offsets.common._KTHREAD;
        let TEB = &self.offsets.common._TEB;

        let current_thread = self.current_thread(vmi, registers)?;
        let teb = vmi.read_va(
            registers.address_context(current_thread.0 + KTHREAD.Teb.offset),
            registers.address_width(),
        )?;

        if teb.is_null() {
            return Ok(None);
        }

        let result = vmi.read_u32(registers.address_context(teb + TEB.LastErrorValue.offset))?;

        Ok(Some(result))
    }
}

impl<Driver> OsExt<Driver> for WindowsOs<Driver>
where
    Driver: VmiDriver,
    Driver::Architecture: Architecture + ArchAdapter<Driver>,
{
    fn enumerate_list(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        list_head: Va,
        mut callback: impl FnMut(Va) -> bool,
    ) -> Result<(), VmiError> {
        let mut entry = vmi.read_va(
            registers.address_context(list_head),
            registers.address_width(),
        )?;

        while entry != list_head {
            if !callback(entry) {
                break;
            }

            entry = vmi.read_va(registers.address_context(entry), registers.address_width())?;
        }

        Ok(())
    }

    fn enumerate_tree(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &<Driver::Architecture as Architecture>::Registers,
        root: Va,
        callback: impl FnMut(Va) -> bool,
    ) -> Result<(), VmiError> {
        match &self.offsets.ext {
            Some(OffsetsExt::V1(offsets)) => {
                self.enumerate_tree_v1(vmi, registers, root, callback, offsets)
            }
            Some(OffsetsExt::V2(offsets)) => {
                self.enumerate_tree_v2(vmi, registers, root, callback, offsets)
            }
            None => panic!("OffsetsExt not set"),
        }
    }
}