ntoseye 0.31.0

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

/// `EPROCESS.ImageFileName` capacity: the kernel keeps this many bytes of the
/// image name, unterminated when the name is at least this long.
const IMAGE_FILE_NAME_LEN: usize = 15;

/// used for enumeration without loading full WinObject
#[derive(Debug, Clone)]
pub struct ProcessInfo {
    pub pid: u64,
    pub name: String,
    pub dtb: Dtb,
    pub eprocess_va: VirtAddr,
    /// The 32-bit PEB of a WOW64 process (`_EPROCESS.WoW64Process`), `None`
    /// for a native process.
    pub wow64_peb: Option<VirtAddr>,
}

impl ProcessInfo {
    pub fn is_wow64(&self) -> bool {
        self.wow64_peb.is_some()
    }
}

/// module metadata from PEB LDR list
#[derive(Debug, Clone)]
pub struct ModuleInfo {
    pub name: String,
    pub short_name: String,
    pub base_address: VirtAddr,
    pub size: u32,
    /// From a WOW64 process's 32-bit loader list: x86 code, 4-byte pointers.
    pub is_32bit: bool,
    pub entry_point: Option<VirtAddr>,
    pub time_date_stamp: Option<u32>,
    pub checksum: Option<u32>,
    pub file_version: Option<String>,
    pub product_version: Option<String>,
}

impl ModuleInfo {
    pub fn new(name: String, base_address: VirtAddr, size: u32) -> Self {
        let short_name = Self::derive_short_name(&name);
        Self {
            name,
            short_name,
            base_address,
            size,
            is_32bit: false,
            entry_point: None,
            time_date_stamp: None,
            checksum: None,
            file_version: None,
            product_version: None,
        }
    }

    pub fn with_time_date_stamp(mut self, tds: u32) -> Self {
        self.time_date_stamp = Some(tds);
        self
    }

    pub fn with_checksum(mut self, cs: u32) -> Self {
        self.checksum = Some(cs);
        self
    }

    pub fn with_version_info(mut self, file_ver: String, product_ver: String) -> Self {
        self.file_version = Some(file_ver);
        self.product_version = Some(product_ver);
        self
    }

    pub fn derive_short_name(name: &str) -> String {
        let filename = name.rsplit(['\\', '/']).next().unwrap_or(name);
        let without_ext = filename
            .rsplit_once('.')
            .map(|(base, _)| base)
            .unwrap_or(filename);

        let lowered = without_ext.to_lowercase();
        match lowered.as_str() {
            "ntoskrnl" | "ntkrnlmp" | "ntkrnlpa" | "ntkrpamp" => "nt".to_string(),
            _ => lowered,
        }
    }

    pub fn end_address(&self) -> VirtAddr {
        VirtAddr(self.base_address.0.saturating_add(self.size as u64))
    }

    pub fn contains_address(&self, address: VirtAddr) -> bool {
        address.0 >= self.base_address.0 && address.0 < self.end_address().0
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModuleSymbolDiagnostic {
    pub module: String,
    pub phase: &'static str,
    pub compiland: Option<String>,
    pub message: String,
}

#[derive(Debug, Clone, Default)]
pub struct ModuleSymbolLoadReport {
    pub total: usize,
    pub loaded: usize,
    /// Symbol-bearing modules removed from this DTB since the previous refresh.
    pub unloaded: usize,
    pub no_pdb: usize,
    pub skipped: usize,
    pub failed: usize,
    pub diagnostic_count: usize,
    pub diagnostics: Vec<ModuleSymbolDiagnostic>,
}

impl ModuleSymbolLoadReport {
    fn new(total: usize) -> Self {
        Self {
            total,
            ..Self::default()
        }
    }

    fn record_status(&mut self, status: &ModuleSymbolStatus) {
        match status {
            ModuleSymbolStatus::Loaded => {
                self.loaded += 1;
            }
            ModuleSymbolStatus::MissingDebugInfo => {
                self.no_pdb += 1;
            }
            ModuleSymbolStatus::Skipped => {
                self.skipped += 1;
            }
            ModuleSymbolStatus::Failed(_) => {
                self.failed += 1;
            }
        }
    }

    fn record_diagnostics(&mut self, module: &str, diagnostics: Vec<SymbolIndexDiagnostic>) {
        const REPORT_DIAGNOSTIC_LIMIT: usize = 64;
        self.diagnostic_count += diagnostics.len();
        let remaining = REPORT_DIAGNOSTIC_LIMIT.saturating_sub(self.diagnostics.len());
        self.diagnostics
            .extend(diagnostics.into_iter().take(remaining).map(|diagnostic| {
                ModuleSymbolDiagnostic {
                    module: module.to_string(),
                    phase: diagnostic.phase,
                    compiland: diagnostic.compiland,
                    message: diagnostic.message,
                }
            }));
    }

    pub fn failed_count(&self) -> usize {
        self.failed
    }

    /// Fold in a follow-up pass over modules already counted in `total`.
    fn absorb(&mut self, other: Self) {
        self.loaded += other.loaded;
        self.unloaded += other.unloaded;
        self.no_pdb += other.no_pdb;
        self.skipped += other.skipped;
        self.failed += other.failed;
        self.diagnostic_count += other.diagnostic_count;
        self.diagnostics.extend(other.diagnostics);
    }
}

/// A module image addressed by RVA. An on-disk image is complete; an image
/// read from guest memory is demand-read in [`IMAGE_BLOCK`]-sized blocks and
/// keeps every block it has read, so a stack walk costs the blocks its
/// lookups touch rather than the whole `.pdata`/`.rdata` of the module,
/// which for a kernel over a KD serial link is megabytes.
pub struct PeImage {
    size: usize,
    body: ImageBody,
}

enum ImageBody {
    Complete(Vec<u8>),
    Lazy(LazyImage),
}

/// One block is one KD memory request, and a block never straddles a page,
/// so a block is either readable or not as a whole.
const IMAGE_BLOCK: usize = 0x800;

type ImageReader = Box<dyn Fn(usize, &mut [u8]) -> Result<()> + Send + Sync>;

struct LazyImage {
    /// The header page, read up front; what a `PeView` is built on.
    headers: Box<[u8]>,
    /// Reads `buf.len()` bytes of the image at an RVA.
    read: ImageReader,
    /// Blocks by index. A block the target refused (paged out) is not
    /// recorded, so it is asked for again once the target has run.
    blocks: Mutex<HashMap<usize, Box<[u8]>>>,
}

impl std::fmt::Debug for PeImage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PeImage")
            .field("size", &self.size)
            .field("complete", &self.is_complete())
            .finish()
    }
}

impl PeImage {
    /// Wrap fully-available bytes (e.g. a complete on-disk image).
    pub fn complete(bytes: Vec<u8>) -> Self {
        Self {
            size: bytes.len(),
            body: ImageBody::Complete(bytes),
        }
    }

    /// Bytes a `PeView` may be built on: the whole image when complete,
    /// otherwise the header page. Directories past the headers are not in
    /// here; read them through [`read`](Self::read).
    pub fn headers(&self) -> &[u8] {
        match &self.body {
            ImageBody::Complete(bytes) => bytes,
            ImageBody::Lazy(lazy) => &lazy.headers,
        }
    }

    /// Whether every byte is known up front (an on-disk image); a lazy image
    /// can always still hit a paged-out block.
    pub fn is_complete(&self) -> bool {
        matches!(self.body, ImageBody::Complete(_))
    }

    /// Whether `[at, at+len)` is in bounds and readable from the target.
    pub fn is_present(&self, at: usize, len: usize) -> bool {
        self.read(at, len).is_some()
    }

    /// `len` bytes at RVA `at`, or `None` when out of bounds or any block of
    /// the range is paged out. Blocks are fetched on first use.
    pub fn read(&self, at: usize, len: usize) -> Option<Cow<'_, [u8]>> {
        let end = at.checked_add(len)?;
        if end > self.size {
            return None;
        }
        match &self.body {
            ImageBody::Complete(bytes) => Some(Cow::Borrowed(&bytes[at..end])),
            ImageBody::Lazy(lazy) => {
                if len == 0 {
                    return Some(Cow::Borrowed(&[]));
                }
                let mut blocks = lazy.blocks.lock().unwrap_or_else(PoisonError::into_inner);
                let mut out = Vec::with_capacity(len);
                for index in at / IMAGE_BLOCK..=(end - 1) / IMAGE_BLOCK {
                    let block = match blocks.entry(index) {
                        Entry::Occupied(entry) => entry.into_mut(),
                        Entry::Vacant(entry) => entry.insert(lazy.fetch(index, self.size)?),
                    };
                    let start = at.saturating_sub(index * IMAGE_BLOCK);
                    let stop = (end - index * IMAGE_BLOCK).min(block.len());
                    out.extend_from_slice(&block[start..stop]);
                }
                Some(Cow::Owned(out))
            }
        }
    }
}

impl LazyImage {
    fn fetch(&self, index: usize, size: usize) -> Option<Box<[u8]>> {
        let start = index * IMAGE_BLOCK;
        let mut block = vec![0u8; IMAGE_BLOCK.min(size - start)];
        (self.read)(start, &mut block).ok()?;
        Some(block.into_boxed_slice())
    }
}

/// Bytes of a module's headers read before the section table's end is known.
/// A normally linked image keeps its DOS stub, NT headers, and section table
/// well inside this; only an image whose table runs past it costs a second
/// read.
const PE_HEADER_PROBE: usize = 0x400;

/// Where the section table of the headers in `probe` ends, or `None` when
/// the NT headers themselves extend past the probe. A buffer that is not a
/// PE ends at the probe: reading more of it changes nothing.
pub fn pe_headers_end(probe: &[u8]) -> Option<usize> {
    if probe.len() < 0x40 || &probe[..2] != b"MZ" {
        return Some(probe.len());
    }
    let e_lfanew = u32::from_le_bytes(probe[0x3c..0x40].try_into().unwrap()) as usize;
    let nt = probe.get(e_lfanew..e_lfanew.checked_add(24)?)?;
    if &nt[..4] != b"PE\0\0" {
        return Some(probe.len());
    }
    let sections = u16::from_le_bytes([nt[6], nt[7]]) as usize;
    let optional = u16::from_le_bytes([nt[20], nt[21]]) as usize;
    Some(e_lfanew + 24 + optional + sections * 40)
}

/// Read a module's headers into a page-sized buffer, as `PeView` wants them,
/// with a probe-sized first read and a second only when the section table
/// extends past it. The page tail beyond the table stays zero; nothing in it
/// is consulted.
pub fn read_pe_header_page<B: MemoryOps<PhysAddr>>(
    base_address: VirtAddr,
    memory: &memory::AddressSpace<'_, B>,
) -> Result<[u8; PAGE_SIZE]> {
    read_pe_header_page_with(&|address, buf| memory.read_bytes(base_address + address, buf))
}

/// [`read_pe_header_page`] over a reader addressed by RVA.
fn read_pe_header_page_with(
    read: &dyn Fn(u64, &mut [u8]) -> Result<()>,
) -> Result<[u8; PAGE_SIZE]> {
    let mut header_buf = [0u8; PAGE_SIZE];
    read(0, &mut header_buf[..PE_HEADER_PROBE])?;
    let end = pe_headers_end(&header_buf[..PE_HEADER_PROBE])
        .unwrap_or(PAGE_SIZE)
        .min(PAGE_SIZE);
    if end > PE_HEADER_PROBE {
        read(
            PE_HEADER_PROBE as u64,
            &mut header_buf[PE_HEADER_PROBE..end],
        )?;
    }
    Ok(header_buf)
}

/// `SizeOfImage` of either PE format.
pub fn size_of_image(view: &PeView<'_>) -> u32 {
    match view.optional_header() {
        Wrap::T32(header) => header.SizeOfImage,
        Wrap::T64(header) => header.SizeOfImage,
    }
}

/// Preferred `ImageBase` of either PE format.
pub fn image_base(view: &PeView<'_>) -> u64 {
    match view.optional_header() {
        Wrap::T32(header) => u64::from(header.ImageBase),
        Wrap::T64(header) => header.ImageBase,
    }
}

/// Open a module image in guest memory: the headers are read now, the rest
/// on demand through `read`, which reads `buf.len()` bytes at a virtual
/// address of the module's address space.
pub fn read_pe_image(
    base_address: VirtAddr,
    read: impl Fn(VirtAddr, &mut [u8]) -> Result<()> + Send + Sync + 'static,
) -> Result<PeImage> {
    let headers = read_pe_header_page_with(&|address, buf| read(base_address + address, buf))?;
    let size = size_of_image(&PeView::from_bytes(&headers)?) as usize;
    Ok(PeImage {
        size,
        body: ImageBody::Lazy(LazyImage {
            headers: Box::new(headers),
            read: Box::new(move |rva, buf| read(base_address + rva as u64, buf)),
            blocks: Mutex::new(HashMap::new()),
        }),
    })
}

/// Name of the PE section containing `address` within the image loaded at
/// `base` (e.g. `.text`), or `None` if `address` isn't in a section or `base`
/// isn't a readable PE. Reads only the header page, like `read_pe_image`'s
/// prologue.
pub fn section_name_at<'a, B: MemoryOps<PhysAddr>>(
    memory: &memory::AddressSpace<'a, B>,
    base: VirtAddr,
    address: VirtAddr,
) -> Option<String> {
    let rva = u32::try_from(address.0.checked_sub(base.0)?).ok()?;
    let header_buf = read_pe_header_page(base, memory).ok()?;
    let view = PeView::from_bytes(&header_buf).ok()?;
    for section in view.section_headers() {
        let va = section.VirtualAddress;
        let size = section.VirtualSize.max(section.SizeOfRawData);
        if rva >= va && rva < va.saturating_add(size) {
            return section.name().ok().map(|s| s.to_string());
        }
    }
    None
}

/// Read VS_FIXEDFILEINFO from a PE image's resource section in guest memory.
///
/// Reads only the header page + the `.rsrc` section (not the full image) to
/// extract file version and product version strings. Returns `None` if the
/// image has no resources, the resource section is paged out, or no
/// RT_VERSION resource is present.
pub fn read_pe_version_info<B: MemoryOps<PhysAddr>>(
    base: VirtAddr,
    memory: &memory::AddressSpace<'_, B>,
) -> Option<(String, String)> {
    use pelite::image::IMAGE_DIRECTORY_ENTRY_RESOURCE;

    let header_buf = read_pe_header_page(base, memory).ok()?;
    let view = PeView::from_bytes(&header_buf).ok()?;

    let rsrc_dir = view.data_directory().get(IMAGE_DIRECTORY_ENTRY_RESOURCE)?;
    let rsrc_rva = rsrc_dir.VirtualAddress;
    let rsrc_size = (rsrc_dir.Size as usize).min(256 * 1024);
    if rsrc_size < 16 {
        return None;
    }

    let mut rsrc_buf = vec![0u8; rsrc_size];
    memory
        .read_bytes(VirtAddr(base.0 + rsrc_rva as u64), &mut rsrc_buf)
        .ok()?;

    let data_entry_rva = find_rt_version_data_entry(&rsrc_buf, rsrc_rva)?;

    let ver_rva = read_u32_at(&rsrc_buf, data_entry_rva)?;
    let ver_size = read_u32_at(&rsrc_buf, data_entry_rva + 4)? as usize;
    if !(52..=32 * 1024).contains(&ver_size) {
        return None;
    }

    let ver_offset_in_rsrc = (ver_rva as usize).checked_sub(rsrc_rva as usize)?;
    let ver_data = rsrc_buf.get(ver_offset_in_rsrc..ver_offset_in_rsrc + ver_size)?;

    parse_vs_fixedfileinfo(ver_data)
}

const RT_VERSION: u32 = 16;
const VS_FIXEDFILEINFO_SIGNATURE: u32 = 0xFEEF04BD;

/// Navigate the resource directory tree (3 levels) to find the
/// IMAGE_RESOURCE_DATA_ENTRY for the first RT_VERSION resource.
/// Returns the offset within `rsrc` of the data entry (which holds
/// the RVA and size of the VS_VERSION_INFO blob).
fn find_rt_version_data_entry(rsrc: &[u8], rsrc_rva: u32) -> Option<usize> {
    // Level 0: root directory — find type entry for RT_VERSION
    let type_entry = find_resource_id_entry(rsrc, 0, RT_VERSION)?;
    // Level 1: name directory — take first entry
    let name_entry = first_resource_entry(rsrc, type_entry)?;
    // Level 2: language directory — take first entry
    let lang_entry = first_resource_entry(rsrc, name_entry)?;

    // lang_entry should point to a data entry (bit 31 clear)
    if lang_entry & 0x8000_0000 != 0 {
        return None;
    }
    let data_entry_off = lang_entry as usize;
    if data_entry_off + 16 > rsrc.len() {
        return None;
    }

    // Validate: the RVA should fall within the resource section
    let rva = read_u32_at(rsrc, data_entry_off)?;
    if rva < rsrc_rva || (rva as usize - rsrc_rva as usize) >= rsrc.len() {
        return None;
    }
    Some(data_entry_off)
}

/// Scan an IMAGE_RESOURCE_DIRECTORY at `dir_off` for an entry with the
/// given resource ID. Returns the OffsetToData/OffsetToDirectory value
/// from the matching entry (with the high bit preserved).
fn find_resource_id_entry(rsrc: &[u8], dir_off: usize, target_id: u32) -> Option<u32> {
    if dir_off + 16 > rsrc.len() {
        return None;
    }
    let num_named = read_u16_at(rsrc, dir_off + 12)? as usize;
    let num_id = read_u16_at(rsrc, dir_off + 14)? as usize;
    let entries_start = dir_off + 16;
    for i in num_named..(num_named + num_id) {
        let entry_off = entries_start + i * 8;
        let id = read_u32_at(rsrc, entry_off)?;
        if id == target_id {
            return read_u32_at(rsrc, entry_off + 4);
        }
    }
    None
}

/// Return the OffsetToData of the first entry in the directory at the
/// offset encoded in `parent_entry` (which must have bit 31 set for a
/// subdirectory).
fn first_resource_entry(rsrc: &[u8], parent_entry: u32) -> Option<u32> {
    if parent_entry & 0x8000_0000 == 0 {
        return None;
    }
    let dir_off = (parent_entry & 0x7FFF_FFFF) as usize;
    if dir_off + 16 > rsrc.len() {
        return None;
    }
    let num_named = read_u16_at(rsrc, dir_off + 12)? as usize;
    let num_id = read_u16_at(rsrc, dir_off + 14)? as usize;
    if num_named + num_id == 0 {
        return None;
    }
    let first_entry_off = dir_off + 16;
    read_u32_at(rsrc, first_entry_off + 4)
}

fn parse_vs_fixedfileinfo(data: &[u8]) -> Option<(String, String)> {
    // Search for VS_FIXEDFILEINFO signature
    let sig_bytes = VS_FIXEDFILEINFO_SIGNATURE.to_le_bytes();
    let pos = data.windows(4).position(|w| w == sig_bytes)?;
    if pos + 52 > data.len() {
        return None;
    }
    let info = &data[pos..];

    // dwFileVersionMS: HIWORD = Major, LOWORD = Minor
    // dwFileVersionLS: HIWORD = Build, LOWORD = Revision
    let file_minor = u16::from_le_bytes([info[8], info[9]]);
    let file_major = u16::from_le_bytes([info[10], info[11]]);
    let file_revision = u16::from_le_bytes([info[12], info[13]]);
    let file_build = u16::from_le_bytes([info[14], info[15]]);

    let prod_minor = u16::from_le_bytes([info[16], info[17]]);
    let prod_major = u16::from_le_bytes([info[18], info[19]]);
    let prod_revision = u16::from_le_bytes([info[20], info[21]]);
    let prod_build = u16::from_le_bytes([info[22], info[23]]);

    let file_ver = format!(
        "{}.{}.{}.{}",
        file_major, file_minor, file_build, file_revision
    );
    let prod_ver = format!(
        "{}.{}.{}.{}",
        prod_major, prod_minor, prod_build, prod_revision
    );
    Some((file_ver, prod_ver))
}

fn read_u16_at(buf: &[u8], off: usize) -> Option<u16> {
    buf.get(off..off + 2)
        .map(|b| u16::from_le_bytes([b[0], b[1]]))
}

fn read_u32_at(buf: &[u8], off: usize) -> Option<u32> {
    buf.get(off..off + 4)
        .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
}

fn populate_module_versions<B: MemoryOps<PhysAddr>>(
    modules: &mut [ModuleInfo],
    memory: &memory::AddressSpace<'_, B>,
) {
    for module in modules.iter_mut() {
        if let Some((file_ver, prod_ver)) = read_pe_version_info(module.base_address, memory) {
            module.file_version = Some(file_ver);
            module.product_version = Some(prod_ver);
        }
    }
}

/// Build a complete (hole-free) `PeImage` from an on-disk PE file by mapping its
/// raw sections to their RVAs: the same layout `read_pe_image` produces from
/// guest memory, but sourced from the full file. Used to recover read-only data
/// (e.g. unwind tables) when the in-memory image has paged-out holes.
pub fn read_pe_image_from_file(path: &Path) -> Result<PeImage> {
    let data = std::fs::read(path)?;
    let file = PeFile::from_bytes(&data)?;
    let (total_size, size_of_headers) = match file.optional_header() {
        Wrap::T32(header) => (header.SizeOfImage as usize, header.SizeOfHeaders as usize),
        Wrap::T64(header) => (header.SizeOfImage as usize, header.SizeOfHeaders as usize),
    };
    let mut image_buffer = vec![0u8; total_size];

    let headers_size = size_of_headers.min(total_size).min(data.len());
    image_buffer[..headers_size].copy_from_slice(&data[..headers_size]);

    for section in file.section_headers() {
        let v_addr = section.VirtualAddress as usize;
        let raw_ptr = section.PointerToRawData as usize;
        let raw_size = section.SizeOfRawData as usize;
        if raw_size == 0 || v_addr + raw_size > total_size || raw_ptr + raw_size > data.len() {
            continue;
        }
        image_buffer[v_addr..v_addr + raw_size].copy_from_slice(&data[raw_ptr..raw_ptr + raw_size]);
    }

    Ok(PeImage::complete(image_buffer))
}

pub struct SymbolRef<'a> {
    obj: &'a WinObject,
    rva: u32,
}

impl SymbolRef<'_> {
    pub fn address(&self) -> VirtAddr {
        self.obj.address_of(self.rva)
    }

    pub fn read<T>(&self) -> Result<T>
    where
        T: IntoBytes + FromBytes + Copy,
    {
        self.obj.memory().read(self.address())
    }
}

/// The address space a module lives in: AArch64 kernel VAs walk `kernel_dtb`
/// (TTBR1) while `dtb` stays the process root.
fn object_address_space(
    phys: &Arc<PhysMem>,
    dtb: Dtb,
    kernel_dtb: Dtb,
    arch: Arch,
) -> AddressSpace<'_, Arc<PhysMem>> {
    match arch {
        Arch::Amd64 => AddressSpace::new(phys, dtb),
        Arch::Arm64 => AddressSpace::new_arm64(phys, dtb, kernel_dtb),
    }
}

/// A structured view into a loaded module's memory: it carries its own address
/// space (`dtb`) and the handles needed to read and resolve symbols/types
/// (`kvm`, `symbols`), so navigation methods don't take them as arguments. The
/// handles are shared (`Arc`), not borrowed; a `WinObject` can't borrow its
/// `Target` siblings, but it can own a refcounted handle to them.
pub struct WinObject {
    pub base_address: VirtAddr,
    dtb: Dtb,
    arch: Arch,
    /// AArch64 TTBR1 (kernel-space root). Equal to `dtb` for the kernel object
    /// and AMD64; process siblings keep the kernel root for kernel-VA reads.
    kernel_dtb: Dtb,
    /// Header page read at symbol load; nothing from the sections.
    headers: Option<Box<[u8]>>,
    /// Demand-read image shared across stack traces, so each block is
    /// fetched once per session.
    image: Mutex<Option<Arc<PeImage>>>,
    pub guid: Option<u128>,
    phys: Arc<PhysMem>,
    symbols: Arc<SymbolStore>,
}

impl WinObject {
    pub fn new(
        phys: Arc<PhysMem>,
        symbols: Arc<SymbolStore>,
        dtb: Dtb,
        base_address: VirtAddr,
    ) -> Self {
        Self::new_with_arch(phys, symbols, dtb, base_address, Arch::Amd64)
    }

    pub fn new_with_arch(
        phys: Arc<PhysMem>,
        symbols: Arc<SymbolStore>,
        dtb: Dtb,
        base_address: VirtAddr,
        arch: Arch,
    ) -> Self {
        Self {
            base_address,
            dtb,
            arch,
            kernel_dtb: dtb,
            headers: None,
            image: Mutex::new(None),
            guid: None,
            phys,
            symbols,
        }
    }

    pub fn arch(&self) -> Arch {
        self.arch
    }

    pub fn load_symbols(mut self) -> Result<Self> {
        let symbols = Arc::clone(&self.symbols);
        self.guid = symbols.load_from_binary(&mut self, "ntoskrnl.exe")?;
        Ok(self)
    }

    /// Fallback symbol loader for triage dumps where the PE header page isn't
    /// in the dump.  Uses the module's TimeDateStamp + SizeOfImage from the
    /// triage driver list to download the PE from Microsoft's symbol server,
    /// extract the PDB GUID, and load the PDB.
    pub fn load_symbols_from_module_info(
        mut self,
        name: &str,
        time_date_stamp: u32,
        size_of_image: u32,
    ) -> Result<Self> {
        let symbols = Arc::clone(&self.symbols);
        self.guid = symbols.load_from_module_info(
            name,
            self.base_address,
            self.dtb,
            time_date_stamp,
            size_of_image,
        )?;
        Ok(self)
    }

    pub fn dtb(&self) -> Dtb {
        self.dtb
    }

    /// Mark this object's module as the kernel in the shared symbol store:
    /// type/enum layout lookups prefer it, and its address space is visible
    /// from every process. Call after [`load_symbols`](Self::load_symbols) so
    /// `guid` is populated.
    pub fn register_as_kernel(&self) {
        self.symbols.set_kernel(self.guid, self.dtb);
    }

    /// `SizeOfImage` of the module (0 until [`view`](Self::view) has run).
    pub fn binary_size(&self) -> usize {
        self.headers
            .as_deref()
            .and_then(|headers| PeView::from_bytes(headers).ok())
            .map_or(0, |view| size_of_image(&view) as usize)
    }

    /// A sibling object sharing this one's physical-memory and symbol handles,
    /// at a new base in a possibly different address space. Symbols are not
    /// loaded yet (`guid` is `None`).
    pub fn sibling(&self, dtb: Dtb, base_address: VirtAddr) -> WinObject {
        WinObject {
            base_address,
            dtb,
            arch: self.arch,
            kernel_dtb: self.kernel_dtb,
            headers: None,
            image: Mutex::new(None),
            guid: None,
            phys: Arc::clone(&self.phys),
            symbols: Arc::clone(&self.symbols),
        }
    }

    pub fn address_of(&self, rva: impl Into<u64>) -> VirtAddr {
        self.base_address + rva.into()
    }

    fn address_space<'a>(
        &self,
        phys: &'a Arc<PhysMem>,
        dtb: Dtb,
    ) -> AddressSpace<'a, Arc<PhysMem>> {
        object_address_space(phys, dtb, self.kernel_dtb, self.arch)
    }

    pub fn memory(&self) -> AddressSpace<'_, Arc<PhysMem>> {
        self.address_space(&self.phys, self.dtb)
    }

    pub fn symbol<S>(&self, name: S) -> Result<SymbolRef<'_>>
    where
        S: Into<String>,
    {
        let name = name.into();

        let guid = self.guid.ok_or(Error::ExpectedSymbols)?;
        let rva = self
            .symbols
            .symbol_rva(guid, &name)?
            .ok_or(Error::SymbolNotFound(name))?;
        Ok(SymbolRef { obj: self, rva })
    }

    pub fn closest_symbol(&self, address: VirtAddr) -> Result<(String, u32)> {
        let guid = self.guid.ok_or(Error::ExpectedSymbols)?;
        let result = self
            .symbols
            .closest_symbol(guid, self.base_address, address)
            .ok_or(Error::UnknownAddress(address))?;
        Ok(result)
    }

    /// The module's headers, read once from guest memory. Directories past
    /// the headers are not in the view; see [`image`](Self::image) for those.
    pub fn view(&mut self) -> Option<PeView<'_>> {
        if self.headers.is_none() {
            let headers = read_pe_header_page(self.base_address, &self.memory()).ok()?;
            self.headers = Some(Box::new(headers));
        }

        PeView::from_bytes(self.headers.as_deref()?).ok()
    }

    /// The in-memory image (see [`read_pe_image`]), opened on first use and
    /// shared afterwards. `None` when the headers are unreadable; that is
    /// retried next time rather than cached.
    pub fn image(&self) -> Option<Arc<PeImage>> {
        let mut cached = self.image.lock().unwrap_or_else(PoisonError::into_inner);
        if cached.is_none() {
            let (phys, dtb, kernel_dtb, arch) =
                (Arc::clone(&self.phys), self.dtb, self.kernel_dtb, self.arch);
            let image = read_pe_image(self.base_address, move |address, buf| {
                object_address_space(&phys, dtb, kernel_dtb, arch).read_bytes(address, buf)
            })
            .ok()?;
            *cached = Some(Arc::new(image));
        }
        cached.clone()
    }

    /// Resolve this object's struct/type namespace, read in its own address
    /// space. Use [`types_in`](Self::types_in) to read the same types from a
    /// different `dtb` (e.g. ntoskrnl's kernel types against a process's space).
    pub fn types(&self) -> Types<'_> {
        Types {
            obj: self,
            dtb: self.dtb,
        }
    }

    /// Like [`types`](Self::types), but reads against `dtb` instead of this
    /// object's own, for kernel types navigated through a process's space.
    pub fn types_in(&self, dtb: Dtb) -> Types<'_> {
        Types { obj: self, dtb }
    }
}

/// A `WinObject`'s struct/type namespace bound to a read address space: the
/// entry point for layout lookups and fluent cursors. Cheap to copy. To structs
/// what the object itself is to symbols.
#[derive(Clone, Copy)]
pub struct Types<'a> {
    obj: &'a WinObject,
    dtb: Dtb,
}

impl<'a> Types<'a> {
    /// The parsed layout of struct `name` from the object's PDB (cached). A
    /// `module!`-qualified name resolves in this space's modules instead,
    /// which is how a 32-bit layout (`ntdll32!_PEB`) and the nested types it
    /// names are reached.
    pub fn layout<S>(self, name: S) -> Result<Arc<TypeInfo>>
    where
        S: Into<String> + AsRef<str>,
    {
        if name.as_ref().contains('!') {
            return self
                .obj
                .symbols
                .find_type_across_modules(self.dtb, name.as_ref())
                .ok_or_else(|| Error::StructNotFound(name.into()));
        }
        let guid = self.obj.guid.ok_or(Error::ExpectedSymbols)?;
        self.obj
            .symbols
            .dump_struct_with_types(guid, name.as_ref())
            .ok_or_else(|| Error::StructNotFound(name.into()))
    }

    /// Open a struct cursor at `base` in this space. The layout `name` resolves
    /// against the object's PDB; reads come from this space's `dtb`.
    pub fn struct_at(self, name: &str, base: VirtAddr) -> Result<StructRef<'a>> {
        let ti = self.layout(name)?;
        Ok(self.struct_with_layout(ti, base))
    }

    /// Open a struct cursor with an already-resolved layout in this address
    /// space. Callers that cache layouts can avoid repeating the type lookup.
    pub fn struct_with_layout(self, layout: Arc<TypeInfo>, base: VirtAddr) -> StructRef<'a> {
        StructRef {
            obj: self.obj,
            dtb: self.dtb,
            ti: layout,
            base,
            image: None,
        }
    }

    /// Walk an intrusive `_LIST_ENTRY` starting at a bare head address (e.g. a
    /// list-head symbol like `PsLoadedModuleList`), yielding a cursor per
    /// record. `record_type`/`link_field` give the record layout and the
    /// embedded link (`CONTAINING_RECORD`). Iteration is bounded and stops on a
    /// cycle. Shared by [`StructRef::list`], which sources `head` from a field.
    ///
    /// Each record is prefetched (see [`StructRef::prefetch`]) so its fields
    /// and the link to the next record come from one read.
    pub fn list_at(
        self,
        head: VirtAddr,
        record_type: &str,
        link_field: &str,
    ) -> Result<impl Iterator<Item = Result<StructRef<'a>>> + 'a> {
        let (obj, dtb) = (self.obj, self.dtb);
        let record_ti = self.layout(record_type)?;
        let link_offset = record_ti.field_offset(link_field)?;

        let list_memory = |dtb: Dtb| obj.address_space(&obj.phys, dtb);

        const MAX: usize = 1000;
        let pointer_size = usize::from(record_ti.pointer_size);
        let read_link = move |memory: &dyn Fn(&mut [u8]) -> Result<()>| -> Result<VirtAddr> {
            let mut bytes = [0u8; 8];
            memory(&mut bytes[..pointer_size])?;
            Ok(VirtAddr(le_uint(&bytes[..pointer_size])))
        };
        let initial = read_link(&|buf| list_memory(dtb).read_bytes(head, buf))?;
        let mut cursor = ListCursor::new(head, MAX);
        cursor.advance(Ok(initial));

        Ok(std::iter::from_fn(move || {
            let current = cursor.take_current()?;

            let record = Types { obj, dtb }
                .struct_with_layout(
                    Arc::clone(&record_ti),
                    VirtAddr(current.0.wrapping_sub(link_offset)),
                )
                .prefetch();

            // Flink sits at offset 0 of the link's _LIST_ENTRY
            match read_link(&|buf| record.read_bytes_at(link_offset, buf)) {
                Ok(next) => cursor.advance(Ok(next)),
                Err(e) => {
                    cursor.advance(Err(e.to_string()));
                    return Some(Err(e));
                }
            }
            Some(Ok(record))
        }))
    }
}

/// A fluent cursor over a struct instance in guest memory: a resolved layout
/// (`ti`) sitting at `base` in the `dtb` address space, plus the symbol context
/// to resolve the types of fields you walk into. This is to structs what
/// [`SymbolRef`] is to symbols: `follow`/`read_field`/`list` chain off it, and
/// the type cache makes each step's layout lookup cheap.
pub struct StructRef<'a> {
    obj: &'a WinObject,
    dtb: Dtb,
    ti: Arc<TypeInfo>,
    base: VirtAddr,
    /// Prefetched copy of the struct's bytes from `base`; field reads inside
    /// it cost no memory request.
    image: Option<Arc<[u8]>>,
}

/// Largest struct [`StructRef::prefetch`] copies whole. Loader entries,
/// `_EPROCESS`, and `_ETHREAD` all fit; anything bigger keeps per-field reads.
const STRUCT_PREFETCH_MAX: usize = 0x1000;

impl<'a> StructRef<'a> {
    fn memory(&self) -> AddressSpace<'a, Arc<PhysMem>> {
        self.obj.address_space(&self.obj.phys, self.dtb)
    }

    /// Read the struct's bytes once so later field reads are served from the
    /// copy: one request per page instead of one per field on a remote
    /// target. Best-effort; an unreadable or oversized struct keeps per-field
    /// reads, which fail or succeed individually as before.
    pub fn prefetch(mut self) -> Self {
        if self.image.is_none() && self.ti.size != 0 && self.ti.size <= STRUCT_PREFETCH_MAX {
            let mut image = vec![0u8; self.ti.size];
            if self.memory().read_bytes(self.base, &mut image).is_ok() {
                self.image = Some(image.into());
            }
        }
        self
    }

    fn read_bytes_at(&self, offset: u64, out: &mut [u8]) -> Result<()> {
        if let Some(image) = &self.image
            && let Some(bytes) = usize::try_from(offset)
                .ok()
                .and_then(|start| image.get(start..start.checked_add(out.len())?))
        {
            out.copy_from_slice(bytes);
            return Ok(());
        }
        self.memory().read_bytes(self.base + offset, out)
    }

    /// Read an integer field at its PDB-declared width (1..=8 bytes).
    pub fn read_uint(&self, name: &str) -> Result<u64> {
        let field = self.field(name)?;
        self.read_uint_at(name, field.offset as u64, field.size)
    }

    fn read_uint_at(&self, name: &str, offset: u64, size: u64) -> Result<u64> {
        let width = usize::try_from(size)
            .map_err(|_| Error::DebugInfo(format!("field '{name}' has invalid integer width")))?;
        if !(1..=8).contains(&width) {
            return Err(Error::DebugInfo(format!(
                "field '{name}' has invalid integer width {width} (expected 1..=8)"
            )));
        }
        let mut bytes = [0u8; 8];
        self.read_bytes_at(offset, &mut bytes[..width])?;
        Ok(le_uint(&bytes[..width]))
    }

    /// Read an address-valued field at its PDB-declared width: 4 bytes in a
    /// 32-bit module's layout, 8 otherwise.
    pub fn read_pointer(&self, name: &str) -> Result<VirtAddr> {
        self.read_uint(name).map(VirtAddr)
    }

    /// Read a field's raw bytes at its PDB-declared size, rejecting a zero
    /// size or one past the caller's bound.
    pub fn read_field_bytes(&self, name: &str, max_len: usize) -> Result<Vec<u8>> {
        let field = self.field(name)?;
        let size = usize::try_from(field.size)
            .map_err(|_| Error::DebugInfo(format!("field '{name}' has invalid byte width")))?;
        if size == 0 {
            return Err(Error::DebugInfo(format!("field '{name}' has no byte size")));
        }
        if size > max_len {
            return Err(Error::DebugInfo(format!(
                "field '{name}' is {size} bytes (maximum {max_len})"
            )));
        }
        let mut bytes = vec![0u8; size];
        self.read_bytes_at(field.offset as u64, &mut bytes)?;
        Ok(bytes)
    }

    fn read_field_at<T: Copy + zerocopy::FromZeros + FromBytes + IntoBytes>(
        &self,
        offset: u64,
    ) -> Result<T> {
        let mut value = T::new_zeroed();
        self.read_bytes_at(offset, value.as_mut_bytes())?;
        Ok(value)
    }

    /// The address this cursor sits at (e.g. to test a followed pointer for
    /// null without another read).
    pub fn addr(&self) -> VirtAddr {
        self.base
    }

    fn field(&self, name: &str) -> Result<&FieldInfo> {
        self.ti
            .fields
            .get(name)
            .ok_or_else(|| Error::FieldNotFound(name.to_string()))
    }

    /// Wrap a freshly resolved layout at `base`, carrying this cursor's context.
    fn with(&self, ti: Arc<TypeInfo>, base: VirtAddr) -> StructRef<'a> {
        self.obj.types_in(self.dtb).struct_with_layout(ti, base)
    }

    /// Read a scalar field by name. The Rust type `T` (inferred from context)
    /// fixes the read width; the PDB only supplies the offset.
    pub fn read_field<T: Copy + zerocopy::FromZeros + FromBytes + IntoBytes>(
        &self,
        name: &str,
    ) -> Result<T> {
        let offset = self.field(name)?.offset as u64;
        self.read_field_at(offset)
    }

    /// Follow a pointer field to the struct it targets. The target struct type
    /// is taken from the field's own PDB metadata, so the caller never restates
    /// it.
    pub fn follow(&self, name: &str) -> Result<StructRef<'a>> {
        let field = self.field(name)?;
        let ParsedType::Pointer(inner) = &field.type_data else {
            return Err(Error::FieldTypeMismatch(name.to_string(), "pointer".into()));
        };
        let ParsedType::Struct(struct_name) = inner.as_ref() else {
            return Err(Error::FieldTypeMismatch(
                name.to_string(),
                "pointer to struct".into(),
            ));
        };
        let struct_name = struct_name.clone();
        let target = VirtAddr(self.read_uint_at(name, field.offset as u64, field.size)?);
        let ti = self.obj.types_in(self.dtb).layout(&struct_name)?;
        Ok(self.with(ti, target))
    }

    /// View an embedded sub-struct field as a cursor (no pointer deref). Type
    /// derived from the field's PDB metadata.
    pub fn embedded(&self, name: &str) -> Result<StructRef<'a>> {
        let field = self.field(name)?;
        // Embedded structs and unions both resolve by layout name; nested
        // anonymous unions (e.g. `_IRP.Tail`) are unions, so accept both.
        let type_name = match &field.type_data {
            ParsedType::Struct(n) | ParsedType::Union(n) => n.clone(),
            _ => {
                return Err(Error::FieldTypeMismatch(
                    name.to_string(),
                    "struct or union".into(),
                ));
            }
        };
        let base = self.base + field.offset as u64;
        let ti = self.obj.types_in(self.dtb).layout(&type_name)?;
        let mut embedded = self.with(ti, base);
        // Carry the enclosing image so the sub-struct's fields stay free.
        if let Some(image) = &self.image {
            let start = field.offset as usize;
            if let Some(bytes) = image.get(start..start + embedded.ti.size) {
                embedded.image = Some(bytes.into());
            }
        }
        Ok(embedded)
    }

    /// Decode the `_UNICODE_STRING` this cursor points at to a Rust `String`
    /// (empty when null/zero-length). Resolves `Length`/`Buffer` from the PDB
    /// rather than hardcoding them.
    pub fn read_unicode_string(&self) -> Result<String> {
        let length: u16 = self.read_field("Length")?;
        let buffer = self.read_pointer("Buffer")?;
        if length == 0 || buffer.is_zero() {
            return Ok(String::new());
        }
        let mut buf = vec![0u8; length as usize];
        self.memory().read_bytes(buffer, &mut buf)?;
        let u16s: Vec<u16> = buf
            .as_chunks::<2>()
            .0
            .iter()
            .map(|c| u16::from_le_bytes(*c))
            .collect();
        Ok(String::from_utf16_lossy(&u16s))
    }

    /// Decode a `_UNICODE_STRING` field of this struct to a Rust `String`.
    pub fn unicode_string(&self, name: &str) -> Result<String> {
        self.embedded(name)?.read_unicode_string()
    }

    /// Walk an intrusive `_LIST_ENTRY` whose head is `head_field`, yielding a
    /// cursor per record. `record_type` and `link_field` are the one piece the
    /// PDB can't supply (CONTAINING_RECORD isn't type-encoded, and a record may
    /// embed several links). Iteration is bounded and stops on a cycle.
    pub fn list(
        &self,
        head_field: &str,
        record_type: &str,
        link_field: &str,
    ) -> Result<impl Iterator<Item = Result<StructRef<'a>>> + 'a> {
        let head = self.base + self.field(head_field)?.offset as u64;
        self.obj
            .types_in(self.dtb)
            .list_at(head, record_type, link_field)
    }
}

/// Read a loader-table record (`_LDR_DATA_TABLE_ENTRY` / `_KLDR_DATA_TABLE_ENTRY`)
/// into a `ModuleInfo`, or `None` when it has no base address (skip it). Shared
/// by the process- and kernel-module walks, which differ only in their list.
fn module_info_from_record(record: &StructRef<'_>) -> Result<Option<ModuleInfo>> {
    let dll_base = record.read_pointer("DllBase")?;
    if dll_base.is_zero() {
        return Ok(None);
    }
    let size_of_image: u32 = record.read_field("SizeOfImage")?;
    let name = record
        .unicode_string("BaseDllName")
        .ok()
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| "<unknown>".to_string());
    let mut info = ModuleInfo::new(name, dll_base, size_of_image);
    if let Ok(entry_point) = record.read_pointer("EntryPoint")
        && !entry_point.is_zero()
    {
        info.entry_point = Some(entry_point);
    }
    if let Ok(tds) = record.read_field::<u32>("TimeDateStamp") {
        info = info.with_time_date_stamp(tds);
    }
    if let Ok(cs) = record.read_field::<u32>("CheckSum") {
        info = info.with_checksum(cs);
    }
    Ok(Some(info))
}

pub struct Guest {
    pub ntoskrnl: WinObject,
    memo: Mutex<HaltMemo>,
}

/// The `_EPROCESS` fields process enumeration needs, fetched with one read
/// covering their span instead of one request per field over the transport.
struct EprocessSpan {
    start: u64,
    bytes: Vec<u8>,
    unique_process_id_offset: u64,
    dir_table_base_offset: u64,
    active_process_links_offset: u64,
    image_file_name_offset: u64,
    /// `WoW64Process`, absent from an x86 kernel's `_EPROCESS`.
    wow64_process_offset: Option<u64>,
}

impl EprocessSpan {
    fn new(guest: &Guest) -> Result<Self> {
        let eprocess = guest.ntoskrnl.types().layout("_EPROCESS")?;
        let kprocess = guest.ntoskrnl.types().layout("_KPROCESS")?;
        let unique_process_id_offset = eprocess.field_offset("UniqueProcessId")?;
        let dir_table_base_offset =
            eprocess.field_offset("Pcb")? + kprocess.field_offset("DirectoryTableBase")?;
        let active_process_links_offset = eprocess.field_offset("ActiveProcessLinks")?;
        let image_file_name_offset = eprocess.field_offset("ImageFileName")?;
        let wow64_process_offset = eprocess
            .field_offset("WoW64Process")
            .or_else(|_| eprocess.field_offset("Wow64Process"))
            .ok();
        let start = unique_process_id_offset
            .min(dir_table_base_offset)
            .min(active_process_links_offset)
            .min(image_file_name_offset)
            .min(wow64_process_offset.unwrap_or(u64::MAX));
        let end = (unique_process_id_offset + 8)
            .max(dir_table_base_offset + 8)
            .max(active_process_links_offset + 8)
            .max(image_file_name_offset + IMAGE_FILE_NAME_LEN as u64)
            .max(wow64_process_offset.map_or(0, |offset| offset + 8));
        Ok(Self {
            start,
            bytes: vec![0u8; (end - start) as usize],
            unique_process_id_offset,
            dir_table_base_offset,
            active_process_links_offset,
            image_file_name_offset,
            wow64_process_offset,
        })
    }

    fn read(&mut self, memory: &impl MemoryOps<VirtAddr>, eprocess: VirtAddr) -> Result<()> {
        memory.read_bytes(eprocess + self.start, &mut self.bytes)
    }

    fn u64_at(&self, offset: u64) -> u64 {
        let start = (offset - self.start) as usize;
        u64::from_le_bytes(self.bytes[start..start + 8].try_into().unwrap())
    }

    fn pid(&self) -> u64 {
        self.u64_at(self.unique_process_id_offset)
    }

    fn dtb(&self) -> Dtb {
        self.u64_at(self.dir_table_base_offset) & !0xfff
    }

    fn active_process_links_flink(&self) -> VirtAddr {
        VirtAddr(self.u64_at(self.active_process_links_offset))
    }

    fn image_file_name(&self) -> &[u8] {
        let start = (self.image_file_name_offset - self.start) as usize;
        &self.bytes[start..start + IMAGE_FILE_NAME_LEN]
    }

    /// `_EPROCESS.WoW64Process`: null for a native process.
    fn wow64_process(&self) -> Option<VirtAddr> {
        self.wow64_process_offset
            .map(|offset| VirtAddr(self.u64_at(offset)))
            .filter(|pointer| !pointer.is_zero())
    }
}

/// Guest-derived lists memoized for one halt epoch (see
/// [`PhysMem::halt_epoch`]). A halted guest cannot relink these lists, so the
/// first walk per halt serves every later caller: the break context, the
/// stop-time symbol refresh, completions, and listing commands would otherwise
/// each re-walk the same kernel lists over the transport. Failed walks are not
/// remembered.
#[derive(Default)]
struct HaltMemo {
    epoch: Option<u64>,
    processes: Option<Vec<ProcessInfo>>,
    kernel_modules: Option<Vec<ModuleInfo>>,
    drivers: Option<Vec<DriverObjectInfo>>,
    /// Loader lists by `_EPROCESS`; every thread of a process walked in one
    /// halt shares them.
    process_modules: HashMap<VirtAddr, Option<Vec<ModuleInfo>>>,
}

fn is_valid_kernel_dtb_amd64(phys: &PhysMem, dtb: Dtb) -> Result<bool> {
    let Ok(kernel_pml4) = phys.read::<[PageTableEntry; 256]>(dtb + 8 * 256) else {
        // Candidate sits outside mapped guest RAM (below the aarch64 RAM
        // base, in an MMIO hole, or past the end): not a kernel root.
        return Ok(false);
    };

    if kernel_pml4
        .into_iter()
        .filter(|e| e.page_frame() == dtb)
        .count()
        != 1
    {
        return Ok(false);
    }

    // Check if use KUSER_SHARED_DATA is mapped
    const KUSER_SHARED_DATA_VA: VirtAddr = VirtAddr::from_u64(0xfffff78000000000);

    let addr_space = AddressSpace::new(phys, dtb);

    if let Some(xlat) = addr_space.virt_to_phys(KUSER_SHARED_DATA_VA)?
        && !xlat.user
        && xlat.nx
    {
        Ok(true)
    } else {
        Ok(false)
    }
}

fn find_kernel_dtb_amd64(phys: &PhysMem) -> Result<Option<Dtb>> {
    let base = phys.ram_base();
    for dtb in (base + 0x1000..base + 0x1000000).step_by(PAGE_SIZE) {
        if is_valid_kernel_dtb_amd64(phys, dtb)? {
            return Ok(Some(dtb));
        }
    }

    Ok(None)
}

/// AArch64 kernel (TTBR1) root candidate: KUSER_SHARED_DATA must translate to
/// the *actual* shared-data page. Windows maps KUSER user-accessible (AP[2]=1)
/// and with UXN set, so attribute checks can't discriminate a real root from a
/// random table that happens to translate something; the page content can —
/// KUSER carries ImageNumberLow/High 0xaa64 at offset 0x2C and the
/// "C:\Windows" system root at 0x30 (this ARM64 layout differs from x64's
/// 0x20/0x38, so those offsets are checked exactly as observed).
fn is_valid_kernel_dtb_arm64(phys: &PhysMem, dtb: Dtb) -> Result<bool> {
    const KUSER_SHARED_DATA_VA: VirtAddr = VirtAddr::from_u64(0xfffff78000000000);

    let addr_space = AddressSpace::new_arm64(phys, dtb, dtb);
    let Some(xlat) = addr_space.virt_to_phys(KUSER_SHARED_DATA_VA)? else {
        return Ok(false);
    };
    let mut buf = [0u8; 0x40];
    if phys.read_bytes(xlat.address, &mut buf).is_err() {
        return Ok(false);
    }
    Ok(buf[0x2C..0x30] == [0x64, 0xaa, 0x64, 0xaa]
        && buf[0x30] == b'C'
        && buf[0x32] == b':'
        && buf[0x34] == b'\\')
}

/// Read the PE machine type of the kernel image found through `dtb` with the
/// arch's walker, or `None` when no valid PE header is there. This is the
/// definitive architecture check: a kernel image's machine must be 0x8664
/// (AMD64) or 0xaa64 (ARM64), which an accidental page-table false positive
/// cannot satisfy.
fn kernel_machine_at(dtb: Dtb, phys: &PhysMem, arch: Arch) -> Result<Option<u16>> {
    let base = match arch {
        Arch::Amd64 => find_ntoskrnl_va(dtb, phys)?,
        Arch::Arm64 => find_ntoskrnl_va_arm64(dtb, phys)?,
    };
    let Some(base) = base else {
        return Ok(None);
    };
    let space = match arch {
        Arch::Amd64 => AddressSpace::new(phys, dtb),
        Arch::Arm64 => AddressSpace::new_arm64(phys, dtb, dtb),
    };
    // The base must read as a real DOS header ("MZ" + 0x90) through this
    // walker — a page-table false positive cannot satisfy this plus a valid
    // PE signature and matching machine type.
    let mut dos = [0u8; 4];
    if space.read_bytes(base, &mut dos).is_err() || dos != [0x4d, 0x5a, 0x90, 0x00] {
        return Ok(None);
    }
    let lfanew: u32 = match space.read(base + 0x3Cu64) {
        Ok(v) => v,
        Err(_) => return Ok(None),
    };
    if lfanew == 0 || lfanew > 0x1000 {
        return Ok(None);
    }
    let mut sig = [0u8; 6];
    if space.read_bytes(base + lfanew as u64, &mut sig).is_err() || &sig[..4] != b"PE\0\0" {
        return Ok(None);
    }
    Ok(Some(u16::from_le_bytes([sig[4], sig[5]])))
}

/// Discover the kernel page-table root and guest architecture. The AMD64
/// descriptor format is tried first (the historical default), but a candidate
/// only counts when the kernel image found through it is genuinely an AMD64
/// PE: an AArch64 guest's TTBR1 tables can false-positive the x64 descriptor
/// checks (Windows maps its own page tables), and the weak MZ+POOLCODE page
/// heuristic can match a data page. The PE machine type is the tie-breaker.
pub fn find_kernel(phys: &PhysMem) -> Result<Option<(Dtb, Arch)>> {
    if let Some(dtb) = find_kernel_dtb_amd64(phys)?
        && matches!(kernel_machine_at(dtb, phys, Arch::Amd64)?, Some(0x8664))
    {
        return Ok(Some((dtb, Arch::Amd64)));
    }
    for dtb in find_kernel_dtb_arm64_candidates(phys)? {
        if matches!(kernel_machine_at(dtb, phys, Arch::Arm64)?, Some(0xaa64)) {
            return Ok(Some((dtb, Arch::Arm64)));
        }
    }
    Ok(None)
}

/// Scan guest RAM for AArch64 TTBR1 roots: page-aligned pages whose L0 entry
/// for KUSER_SHARED_DATA is a table descriptor pointing inside RAM. The full
/// translation must reach a page with the ARM64 KUSER signature; the caller
/// then validates the kernel image's PE machine type.
fn find_kernel_dtb_arm64_candidates(phys: &PhysMem) -> Result<Vec<Dtb>> {
    const KUSER_L0_INDEX: u64 = 495;
    const MAX_CANDIDATES: usize = 32;
    let base = phys.ram_base();
    let ram_end = base.saturating_add(phys.ram_size());
    let mut out = Vec::new();
    for dtb in (base.saturating_add(0x1000)..ram_end).step_by(PAGE_SIZE) {
        let Ok(entry) = phys.read::<PageTableEntry>(dtb + 8 * KUSER_L0_INDEX) else {
            continue;
        };
        // Table descriptor (bits[1:0] = 0b11) whose table lies in RAM.
        if entry.0 & 0b11 != 0b11 {
            continue;
        }
        let frame = entry.arm64_page_frame();
        if frame < base || frame >= ram_end {
            continue;
        }
        if is_valid_kernel_dtb_arm64(phys, dtb)? {
            out.push(dtb);
            if out.len() >= MAX_CANDIDATES {
                break;
            }
        }
    }
    Ok(out)
}

fn is_ntoskrnl_header(header: &[u8]) -> bool {
    header.len() >= 4
        && header[..4] == [0x4d, 0x5a, 0x90, 0x00]
        && header.as_chunks::<8>().0.iter().any(|c| c == b"POOLCODE")
}

fn is_ntoskrnl_pte(phys: &PhysMem, pte: PageTableEntry) -> Result<bool> {
    if pte.is_user() || !pte.is_nx() {
        return Ok(false);
    }

    let Ok(header) = phys.read::<[u8; 0x1000]>(pte.page_frame()) else {
        return Ok(false);
    };
    Ok(is_ntoskrnl_header(&header))
}

fn find_ntoskrnl_va(kernel_dtb: Dtb, phys: &PhysMem) -> Result<Option<VirtAddr>> {
    const KERNEL_VA_MIN: VirtAddr = VirtAddr::from_u64(0xfffff80000000000);
    const KERNEL_VA_MAX: VirtAddr = VirtAddr::from_u64(0xfffff80800000000);

    let pml4e_count = KERNEL_VA_MAX.pml4_index() - KERNEL_VA_MIN.pml4_index() + 1;

    let Ok(kernel_pml4) = phys.read::<[PageTableEntry; 256]>(kernel_dtb + 8 * 256) else {
        return Ok(None);
    };
    for (rel_pml4_index, pml4e) in kernel_pml4
        .into_iter()
        .enumerate()
        .skip(KERNEL_VA_MIN.pml4_index() - 256)
        .take(pml4e_count)
    {
        let pml4_index = 256 + rel_pml4_index;

        if !pml4e.is_present() {
            continue;
        }
        let Ok(pdpt) = phys.read::<[PageTableEntry; 512]>(pml4e.page_frame()) else {
            continue;
        };

        let pdpte_count = if pml4_index == pml4e_count - 1 {
            KERNEL_VA_MAX.pdpt_index() + 1
        } else {
            512
        };

        for (pdpt_index, pdpte) in pdpt.into_iter().take(pdpte_count).enumerate() {
            if !pdpte.is_present() {
                continue;
            }

            if pdpte.is_large_page() {
                if let Ok(true) = is_ntoskrnl_pte(phys, pdpte) {
                    return Ok(Some(VirtAddr::construct(pml4_index, pdpt_index, 0, 0)));
                }

                continue;
            }

            let Ok(pd) = phys.read::<[PageTableEntry; 512]>(pdpte.page_frame()) else {
                continue;
            };

            let pde_count = if pdpt_index == pdpte_count - 1 {
                KERNEL_VA_MAX.pd_index() + 1
            } else {
                512
            };

            for (pd_index, pde) in pd.into_iter().take(pde_count).enumerate() {
                if !pde.is_present() {
                    continue;
                }

                if pde.is_large_page() {
                    if let Ok(true) = is_ntoskrnl_pte(phys, pde) {
                        return Ok(Some(VirtAddr::construct(
                            pml4_index, pdpt_index, pd_index, 0,
                        )));
                    }

                    continue;
                }

                let Ok(pt) = phys.read::<[PageTableEntry; 512]>(pde.page_frame()) else {
                    continue;
                };

                let pte_count = if pd_index == pde_count - 1 {
                    KERNEL_VA_MAX.pt_index() + 1
                } else {
                    512
                };

                for (pt_index, pte) in pt.into_iter().take(pte_count).enumerate() {
                    if !pte.is_present() {
                        continue;
                    }

                    if let Ok(true) = is_ntoskrnl_pte(phys, pte) {
                        return Ok(Some(VirtAddr::construct(
                            pml4_index, pdpt_index, pd_index, pt_index,
                        )));
                    }
                }
            }
        }
    }

    Ok(None)
}

fn is_ntoskrnl_pte_arm64(phys: &PhysMem, pte: PageTableEntry) -> Result<bool> {
    // Kernel code pages: AP[2]=0 (not user), PXN=0 (executable from EL1).
    // (UXN is always set on Windows kernel pages, so it cannot identify code.)
    if pte.arm64_is_user() || !pte.arm64_is_pxn() {
        return Ok(false);
    }

    is_ntoskrnl_header_at(phys, pte.arm64_page_frame())
}

/// Whether the physical page at `frame` holds the ntoskrnl PE header
/// (MZ + POOLCODE marker). Tolerant of unreadable/unmapped frames.
fn is_ntoskrnl_header_at(phys: &PhysMem, frame: u64) -> Result<bool> {
    let Ok(header) = phys.read::<[u8; 0x1000]>(frame) else {
        return Ok(false);
    };
    Ok(is_ntoskrnl_header(&header))
}

/// Same bounded kernel-VA scan as [`find_ntoskrnl_va`] but interpreting
/// AArch64 descriptors (TTBR1 root, 4 KiB granule). The VA index math is
/// identical to x64's four 9-bit levels.
fn find_ntoskrnl_va_arm64(kernel_dtb: Dtb, phys: &PhysMem) -> Result<Option<VirtAddr>> {
    // Cover the Windows ARM64 kernel VA range. Unlike the AMD64 scan's narrow
    // low-kernel slot, this includes every populated L0 slot from 496 through
    // the inclusive upper bound.
    const KERNEL_VA_MIN: VirtAddr = VirtAddr::from_u64(0xfffff80000000000);
    const KERNEL_VA_MAX: VirtAddr = VirtAddr::from_u64(0xffffff8000000000);

    let pml4e_count = KERNEL_VA_MAX.pml4_index() - KERNEL_VA_MIN.pml4_index() + 1;

    let Ok(kernel_table) = phys.read::<[PageTableEntry; 256]>(kernel_dtb + 8 * 256) else {
        return Ok(None);
    };
    for (rel_index, l0) in kernel_table
        .into_iter()
        .enumerate()
        .skip(KERNEL_VA_MIN.pml4_index() - 256)
        .take(pml4e_count)
    {
        let pml4_index = 256 + rel_index;

        if !l0.arm64_is_valid() || l0.arm64_is_block() {
            continue;
        }
        let Ok(l1_table) = phys.read::<[PageTableEntry; 512]>(l0.arm64_page_frame()) else {
            continue;
        };

        let on_upper_l0 = pml4_index == KERNEL_VA_MAX.pml4_index();
        let l1_count = if on_upper_l0 {
            KERNEL_VA_MAX.pdpt_index() + 1
        } else {
            512
        };

        for (l1_index, l1) in l1_table.into_iter().take(l1_count).enumerate() {
            if !l1.arm64_is_valid() {
                continue;
            }

            if l1.arm64_is_block() {
                // A 1 GiB block is unlikely for ntoskrnl. Probe each 2 MiB
                // boundary and reconstruct the matching VA at the L2 index.
                let block = l1.arm64_page_frame();
                for l2_index in 0..512u64 {
                    if is_ntoskrnl_header_at(phys, block + l2_index * (2 << 20))? {
                        return Ok(Some(VirtAddr::construct(
                            pml4_index,
                            l1_index,
                            l2_index as usize,
                            0,
                        )));
                    }
                }
                continue;
            }

            let Ok(l2_table) = phys.read::<[PageTableEntry; 512]>(l1.arm64_page_frame()) else {
                continue;
            };

            let on_upper_l1 = on_upper_l0 && l1_index == KERNEL_VA_MAX.pdpt_index();
            let l2_count = if on_upper_l1 {
                KERNEL_VA_MAX.pd_index() + 1
            } else {
                512
            };

            for (l2_index, l2) in l2_table.into_iter().take(l2_count).enumerate() {
                if !l2.arm64_is_valid() {
                    continue;
                }

                if l2.arm64_is_block() {
                    // Probe every 4 KiB page in the 2 MiB block; the PE image
                    // need not begin at the block's first page.
                    let block = l2.arm64_page_frame();
                    for pt_index in 0..512u64 {
                        if is_ntoskrnl_header_at(phys, block + pt_index * 0x1000)? {
                            return Ok(Some(VirtAddr::construct(
                                pml4_index,
                                l1_index,
                                l2_index,
                                pt_index as usize,
                            )));
                        }
                    }
                    continue;
                }

                let Ok(l3_table) = phys.read::<[PageTableEntry; 512]>(l2.arm64_page_frame()) else {
                    continue;
                };

                let on_upper_l2 = on_upper_l1 && l2_index == KERNEL_VA_MAX.pd_index();
                let l3_count = if on_upper_l2 {
                    KERNEL_VA_MAX.pt_index() + 1
                } else {
                    512
                };

                for (l3_index, l3) in l3_table.into_iter().take(l3_count).enumerate() {
                    if l3.0 & 0b11 != 0b11 {
                        continue;
                    }

                    if let Ok(true) = is_ntoskrnl_pte_arm64(phys, l3) {
                        return Ok(Some(VirtAddr::construct(
                            pml4_index, l1_index, l2_index, l3_index,
                        )));
                    }
                }
            }
        }
    }

    Ok(None)
}

/// Scan captured virtual memory regions for the ntoskrnl PE header.
///
/// Triage dumps have no page tables, so we can't walk the PML4. Instead we
/// probe the identity-mapped virtual memory for the MZ header + POOLCODE
/// marker, the same heuristic `is_ntoskrnl_pte` uses but at the virtual
/// layer.
fn find_ntoskrnl_va_triage(kernel_dtb: Dtb, phys: &PhysMem) -> Result<Option<VirtAddr>> {
    let space = AddressSpace::new(phys, kernel_dtb);

    // No PDB yet, so PsLoadedModuleList can't be walked; probe the data
    // blocks for kernel-space PE headers instead.
    if let Some(dmp_info) = phys.dmp_info() {
        // Check triage driver base addresses first — ntoskrnl is typically
        // the first entry and this avoids scanning up to 4096 pages.
        let mut header = vec![0u8; 0x1000];
        for driver in &dmp_info.triage_drivers {
            let candidate = VirtAddr(driver.base);
            if space.read_bytes(candidate, &mut header).is_err() {
                continue;
            }
            if is_ntoskrnl_header(&header) {
                return Ok(Some(candidate));
            }
        }

        // Fallback: scan backwards from PsLoadedModuleList.
        let ps_loaded = dmp_info.ps_loaded_module_list;
        if ps_loaded >= 0xfffff80000000000 {
            let page_base = ps_loaded & !0xFFF;
            for offset in (0..0x100_0000u64).step_by(0x1000) {
                let candidate = page_base - offset;
                if space.read_bytes(VirtAddr(candidate), &mut header).is_err() {
                    continue;
                }
                if is_ntoskrnl_header(&header) {
                    return Ok(Some(VirtAddr(candidate)));
                }
            }
        }
    }

    Ok(None)
}

fn find_ntoskrnl(phys: Arc<PhysMem>, symbols: Arc<SymbolStore>) -> Result<Option<WinObject>> {
    let Some((kernel_dtb, arch)) = find_kernel(&phys)? else {
        return Ok(None);
    };

    let ntoskrnl_va = match arch {
        Arch::Amd64 => find_ntoskrnl_va(kernel_dtb, &phys)?,
        Arch::Arm64 => find_ntoskrnl_va_arm64(kernel_dtb, &phys)?,
    };
    let Some(ntoskrnl_va) = ntoskrnl_va else {
        return Ok(None);
    };

    Ok(Some(WinObject::new_with_arch(
        phys,
        symbols,
        kernel_dtb,
        ntoskrnl_va,
        arch,
    )))
}

impl Guest {
    pub fn from_kernel(ntoskrnl: WinObject) -> Self {
        Self {
            ntoskrnl,
            memo: Mutex::new(HaltMemo::default()),
        }
    }

    fn memo(&self) -> MutexGuard<'_, HaltMemo> {
        self.memo.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Serve `slot` from the current halt's memo, walking with `walk` on a
    /// miss. Memory without a halt signal is never memoized.
    fn memoized<T: Clone>(
        &self,
        slot: impl Fn(&mut HaltMemo) -> &mut Option<Vec<T>>,
        walk: impl FnOnce() -> Result<Vec<T>>,
    ) -> Result<Vec<T>> {
        let Some(epoch) = self.ntoskrnl.phys.halt_epoch() else {
            return walk();
        };
        {
            let mut memo = self.memo();
            if memo.epoch != Some(epoch) {
                *memo = HaltMemo {
                    epoch: Some(epoch),
                    ..HaltMemo::default()
                };
            }
            if let Some(list) = slot(&mut memo) {
                return Ok(list.clone());
            }
        }
        let list = walk()?;
        let mut memo = self.memo();
        if memo.epoch == Some(epoch) {
            *slot(&mut memo) = Some(list.clone());
        }
        Ok(list)
    }

    pub fn memoized_drivers(
        &self,
        walk: impl FnOnce() -> Result<Vec<DriverObjectInfo>>,
    ) -> Result<Vec<DriverObjectInfo>> {
        self.memoized(|memo| &mut memo.drivers, walk)
    }

    fn queue_module_symbol_load(
        symbols: &SymbolStore,
        downloads: &mut Vec<ModuleSymbolLoad>,
        ready: &mut Vec<ModuleSymbolLoad>,
        load: ModuleSymbolLoad,
    ) {
        if symbols.has_matching_pdb(&load.job) {
            ready.push(load);
        } else {
            downloads.push(load);
        }
    }

    fn apply_module_symbol_status(
        symbols: &SymbolStore,
        report: &mut ModuleSymbolLoadReport,
        dtb: Dtb,
        module: &ModuleInfo,
        status: ModuleSymbolStatus,
    ) {
        symbols.set_module_symbol_status(dtb, module.base_address, status.clone());
        report.record_status(&status);
    }

    pub fn new_with_kernel_base_hint(
        phys: Arc<PhysMem>,
        symbols: Arc<SymbolStore>,
        kernel_base_hint: Option<VirtAddr>,
    ) -> Result<Self> {
        let ntoskrnl = if let Some(kernel_base) = kernel_base_hint {
            let (kernel_dtb, arch) = find_kernel(&phys)?.ok_or(Error::NtoskrnlNotFound)?;
            WinObject::new_with_arch(phys, symbols, kernel_dtb, kernel_base, arch)
        } else {
            find_ntoskrnl(phys, symbols)?.ok_or(Error::NtoskrnlNotFound)?
        }
        .load_symbols()?;

        // Type/enum layout lookups prefer the kernel's definitions over
        // same-named user-mode types once attached to a process; tell the
        // symbol store which guid is the kernel's.
        ntoskrnl.register_as_kernel();

        Ok(Self::from_kernel(ntoskrnl))
    }

    pub fn new(phys: Arc<PhysMem>, symbols: Arc<SymbolStore>) -> Result<Self> {
        Self::new_with_kernel_base_hint(phys, symbols, None)
    }

    pub fn new_with_dtb(
        phys: Arc<PhysMem>,
        symbols: Arc<SymbolStore>,
        kernel_dtb: Dtb,
    ) -> Result<Self> {
        let is_triage = kernel_dtb == DTB_IDENTITY;

        // Dumps carry the machine type; live sessions reach this only from
        // discovery, which already resolved the arch.
        let arch = phys
            .dmp_info()
            .and_then(|info| info.system_info.as_ref())
            .and_then(|si| Arch::from_machine_type(si.machine_image_type as u16))
            .unwrap_or(Arch::Amd64);

        let ntoskrnl_va = if is_triage {
            find_ntoskrnl_va_triage(kernel_dtb, &phys)?
        } else {
            match arch {
                Arch::Amd64 => find_ntoskrnl_va(kernel_dtb, &phys)?,
                Arch::Arm64 => find_ntoskrnl_va_arm64(kernel_dtb, &phys)?,
            }
        };

        // For triage dumps, fall back to kern_base from KDDEBUGGER_DATA64
        // when the PE header page isn't captured in the dump.
        let ntoskrnl_va = match ntoskrnl_va {
            Some(va) => va,
            None if is_triage => phys
                .dmp_info()
                .and_then(|i| i.kern_base)
                .map(VirtAddr)
                .ok_or(Error::NtoskrnlNotFound)?,
            None => return Err(Error::NtoskrnlNotFound),
        };

        let obj = WinObject::new_with_arch(
            Arc::clone(&phys),
            Arc::clone(&symbols),
            kernel_dtb,
            ntoskrnl_va,
            arch,
        );

        // Try normal symbol loading first; for triage dumps where the PE
        // header isn't in memory, fall back to downloading by image metadata.
        let ntoskrnl = match obj.load_symbols() {
            Ok(loaded) => loaded,
            Err(_) if is_triage => {
                let driver = phys
                    .dmp_info()
                    .and_then(|info| info.triage_drivers.iter().find(|d| d.base == ntoskrnl_va.0))
                    .cloned()
                    .ok_or(Error::NtoskrnlNotFound)?;

                WinObject::new_with_arch(phys, symbols, kernel_dtb, ntoskrnl_va, arch)
                    .load_symbols_from_module_info(
                        &driver.name,
                        driver.time_date_stamp,
                        driver.size,
                    )?
            }
            Err(e) => return Err(e),
        };

        ntoskrnl.register_as_kernel();
        Ok(Self::from_kernel(ntoskrnl))
    }

    pub fn enumerate_processes(&self) -> Result<Vec<ProcessInfo>> {
        self.memoized(|memo| &mut memo.processes, || self.walk_processes())
    }

    fn walk_processes(&self) -> Result<Vec<ProcessInfo>> {
        let memory = self.ntoskrnl.memory();
        let mut span = EprocessSpan::new(self)?;

        let ps_initial_system_process: VirtAddr =
            self.ntoskrnl.symbol("PsInitialSystemProcess")?.read()?;
        let ps_active_process_head = self
            .ntoskrnl
            .symbol("PsActiveProcessHead")
            .ok()
            .map(|s| s.address());

        let mut processes = Vec::new();
        let mut visited = HashSet::new();

        let mut current_eprocess = ps_initial_system_process;

        // Cycle detection handles a corrupt list that loops; the cap handles
        // one that wanders through unrelated memory without repeating.
        const PROCESS_WALK_LIMIT: usize = 65_536;
        while processes.len() < PROCESS_WALK_LIMIT {
            if current_eprocess.0 == 0 || visited.contains(&current_eprocess.0) {
                break;
            }
            visited.insert(current_eprocess.0);

            span.read(&memory, current_eprocess)?;
            let dtb = span.dtb();
            if dtb == 0 {
                break;
            }

            processes.push(ProcessInfo {
                pid: span.pid(),
                name: self.process_name_from_image_file_name(
                    current_eprocess,
                    dtb,
                    span.image_file_name(),
                ),
                dtb,
                eprocess_va: current_eprocess,
                wow64_peb: self.wow64_peb(dtb, span.wow64_process()),
            });

            let flink = span.active_process_links_flink();
            if flink.0 == 0 || Some(flink) == ps_active_process_head {
                break;
            }

            current_eprocess = flink - span.active_process_links_offset;
            if current_eprocess == ps_initial_system_process {
                break;
            }
        }

        Ok(processes)
    }

    /// The process at `eprocess_va` without walking the process list: one
    /// EPROCESS span read plus the PEB walk only for a possibly truncated
    /// name.
    pub fn process_at(&self, eprocess_va: VirtAddr) -> Result<ProcessInfo> {
        let mut span = EprocessSpan::new(self)?;
        span.read(&self.ntoskrnl.memory(), eprocess_va)?;
        let dtb = span.dtb();
        Ok(ProcessInfo {
            pid: span.pid(),
            name: self.process_name_from_image_file_name(eprocess_va, dtb, span.image_file_name()),
            dtb,
            eprocess_va,
            wow64_peb: self.wow64_peb(dtb, span.wow64_process()),
        })
    }

    /// The 32-bit PEB behind `_EPROCESS.WoW64Process`: since Windows 10 1511
    /// the pointer is to an `_EWOW64PROCESS` holding it, before that it was
    /// the PEB itself. Unreadable is reported as native rather than failing
    /// process enumeration.
    fn wow64_peb(&self, dtb: Dtb, wow64_process: Option<VirtAddr>) -> Option<VirtAddr> {
        let pointer = wow64_process?;
        let types = self.ntoskrnl.types_in(dtb);
        let peb = match types.struct_at("_EWOW64PROCESS", pointer) {
            Ok(ewow64) => ewow64.read_pointer("Peb").ok()?,
            Err(Error::StructNotFound(_)) => pointer,
            Err(_) => return None,
        };
        (!peb.is_zero()).then_some(peb)
    }

    /// Display name for the process at `eprocess_va` given its raw
    /// `EPROCESS.ImageFileName` bytes. The kernel keeps only the first 15
    /// bytes of the image name, so the PEB loader list (a page-walked read of
    /// user memory) is consulted only when the field is full and may be
    /// truncated; every shorter name is complete as is.
    fn process_name_from_image_file_name(
        &self,
        eprocess_va: VirtAddr,
        dtb: Dtb,
        image_file_name: &[u8],
    ) -> String {
        let len = image_file_name
            .iter()
            .position(|&c| c == 0)
            .unwrap_or(image_file_name.len());
        if len == IMAGE_FILE_NAME_LEN
            && dtb != 0
            && let Ok(full) = self.full_process_name(eprocess_va, dtb)
        {
            return full;
        }
        if len == 0 {
            return "<unknown>".to_string();
        }
        String::from_utf8_lossy(&image_file_name[..len]).to_string()
    }

    /// Display name for the process at `eprocess_va` without walking the
    /// process list: the `ImageFileName` read plus, only for a possibly
    /// truncated name, the process DTB and PEB walk.
    pub fn process_name_at(&self, eprocess_va: VirtAddr) -> Option<String> {
        let mut span = EprocessSpan::new(self).ok()?;
        span.read(&self.ntoskrnl.memory(), eprocess_va).ok()?;
        if span.image_file_name()[0] == 0 {
            return None;
        }
        Some(self.process_name_from_image_file_name(
            eprocess_va,
            span.dtb(),
            span.image_file_name(),
        ))
    }

    fn full_process_name(&self, eprocess_va: VirtAddr, dtb: Dtb) -> Result<String> {
        // The process dtb maps both the kernel _EPROCESS and the user-space PEB
        // it points at, so the whole walk reads through one address space:
        // ntoskrnl's kernel types viewed in the process's space.
        let eprocess = self
            .ntoskrnl
            .types_in(dtb)
            .struct_at("_EPROCESS", eprocess_va)?;

        let peb = eprocess.follow("Peb")?;
        let image_base: VirtAddr = peb.read_field("ImageBaseAddress")?;
        if image_base.is_zero() {
            return Err(Error::MissingImageBase);
        }

        for record in peb.follow("Ldr")?.list(
            "InLoadOrderModuleList",
            "_LDR_DATA_TABLE_ENTRY",
            "InLoadOrderLinks",
        )? {
            let record = record?;
            let dll_base: VirtAddr = record.read_field("DllBase")?;
            if dll_base == image_base {
                return record.unicode_string("BaseDllName");
            }
        }

        Err(Error::MissingImage)
    }

    pub fn winobj_from_process_info(&self, info: &ProcessInfo) -> Result<WinObject> {
        let eprocess = self
            .ntoskrnl
            .types_in(info.dtb)
            .struct_at("_EPROCESS", info.eprocess_va)?;

        let peb = eprocess.follow("Peb")?;
        if peb.addr().is_zero() {
            return Err(Error::MissingPEB);
        }

        let base_address: VirtAddr = peb.read_field("ImageBaseAddress")?;
        Ok(self.ntoskrnl.sibling(info.dtb, base_address))
    }

    pub fn process_modules(&self, info: &ProcessInfo) -> Result<Vec<ModuleInfo>> {
        self.memoized(
            |memo| memo.process_modules.entry(info.eprocess_va).or_default(),
            || self.walk_process_modules(info),
        )
    }

    fn walk_process_modules(&self, info: &ProcessInfo) -> Result<Vec<ModuleInfo>> {
        let eprocess = self
            .ntoskrnl
            .types_in(info.dtb)
            .struct_at("_EPROCESS", info.eprocess_va)?;

        let peb = eprocess.follow("Peb")?;
        if peb.addr().is_zero() {
            return Err(Error::MissingPEB);
        }

        let ldr = peb.follow("Ldr")?;
        if ldr.addr().is_zero() {
            // process still initializing: no loaded-module list yet
            return Ok(Vec::new());
        }

        let mut modules = Vec::new();
        for record in ldr.list(
            "InLoadOrderModuleList",
            "_LDR_DATA_TABLE_ENTRY",
            "InLoadOrderLinks",
        )? {
            if let Some(module) = module_info_from_record(&record?)? {
                modules.push(module);
            }
        }

        if let Some(peb32) = info.wow64_peb {
            for mut module in self.process_modules32(info.dtb, peb32)? {
                // Both lists carry the executable itself (one mapping, x86
                // code) and an ntdll (two: the 32-bit copy is addressed as
                // `ntdll32!`, as WinDbg's wow64exts does).
                if let Some(native) = modules
                    .iter_mut()
                    .find(|native| native.base_address == module.base_address)
                {
                    native.is_32bit = true;
                    continue;
                }
                if modules
                    .iter()
                    .any(|native| native.short_name == module.short_name)
                {
                    module.short_name.push_str("32");
                }
                modules.push(module);
            }
        }

        Ok(modules)
    }

    /// The 32-bit loader list of a WOW64 process. `_PEB_LDR_DATA32` and
    /// `_LDR_DATA_TABLE_ENTRY32` are not in the kernel's PDB and the 32-bit
    /// ntdll's is not loaded before this walk finds it, so the entry layout
    /// is the fixed x86 ABI (unchanged since Windows 2000): `DllBase` +0x18,
    /// `EntryPoint` +0x1c, `SizeOfImage` +0x20, `BaseDllName` +0x2c,
    /// `TimeDateStamp` +0x44.
    fn process_modules32(&self, dtb: Dtb, peb32: VirtAddr) -> Result<Vec<ModuleInfo>> {
        const IN_LOAD_ORDER_MODULE_LIST: u64 = 0x0c;
        const ENTRY_LEN: usize = 0x48;
        const MAX: usize = 1000;

        let types = self.ntoskrnl.types_in(dtb);
        let ldr: u32 = types.struct_at("_PEB32", peb32)?.read_field("Ldr")?;
        if ldr == 0 {
            return Ok(Vec::new());
        }
        let memory = self.ntoskrnl.address_space(&self.ntoskrnl.phys, dtb);
        let head = VirtAddr(u64::from(ldr) + IN_LOAD_ORDER_MODULE_LIST);
        let read_link = |address: VirtAddr| memory.read::<u32>(address).map(u64::from);

        let mut modules = Vec::new();
        let mut cursor = ListCursor::new(head, MAX);
        cursor.advance(
            read_link(head)
                .map(VirtAddr)
                .map_err(|error| error.to_string()),
        );
        while let Some(current) = cursor.take_current() {
            let mut entry = [0u8; ENTRY_LEN];
            if let Err(error) = memory.read_bytes(current, &mut entry) {
                cursor.advance(Err(error.to_string()));
                return Err(error);
            }
            let u32_at =
                |offset: usize| u32::from_le_bytes(entry[offset..offset + 4].try_into().unwrap());
            cursor.advance(Ok(VirtAddr(u64::from(u32_at(0)))));

            let dll_base = u32_at(0x18);
            if dll_base == 0 {
                continue;
            }
            let name_len = usize::from(u16::from_le_bytes([entry[0x2c], entry[0x2d]]));
            let name_buffer = u32_at(0x30);
            let name = if name_len == 0 || name_buffer == 0 {
                String::new()
            } else {
                let mut buf = vec![0u8; name_len];
                memory
                    .read_bytes(VirtAddr(u64::from(name_buffer)), &mut buf)
                    .map(|()| {
                        let u16s: Vec<u16> = buf
                            .as_chunks::<2>()
                            .0
                            .iter()
                            .map(|c| u16::from_le_bytes(*c))
                            .collect();
                        String::from_utf16_lossy(&u16s)
                    })
                    .unwrap_or_default()
            };
            let name = if name.is_empty() {
                "<unknown>".to_string()
            } else {
                name
            };
            let mut module = ModuleInfo::new(name, VirtAddr(u64::from(dll_base)), u32_at(0x20))
                .with_time_date_stamp(u32_at(0x44));
            module.is_32bit = true;
            let entry_point = u32_at(0x1c);
            if entry_point != 0 {
                module.entry_point = Some(VirtAddr(u64::from(entry_point)));
            }
            modules.push(module);
        }
        Ok(modules)
    }

    pub fn kernel_modules(&self) -> Result<Vec<ModuleInfo>> {
        self.memoized(
            |memo| &mut memo.kernel_modules,
            || self.walk_kernel_modules(),
        )
    }

    fn walk_kernel_modules(&self) -> Result<Vec<ModuleInfo>> {
        let head = self.ntoskrnl.symbol("PsLoadedModuleList")?.address();

        // The kernel uses the _KLDR variant; fall back to _LDR if it's absent
        let record_type = if self
            .ntoskrnl
            .types()
            .layout("_KLDR_DATA_TABLE_ENTRY")
            .is_ok()
        {
            "_KLDR_DATA_TABLE_ENTRY"
        } else {
            "_LDR_DATA_TABLE_ENTRY"
        };

        let mut modules = Vec::new();
        for record in self
            .ntoskrnl
            .types()
            .list_at(head, record_type, "InLoadOrderLinks")?
        {
            if let Some(module) = module_info_from_record(&record?)? {
                modules.push(module);
            }
        }

        Ok(modules)
    }

    pub fn populate_kernel_module_versions(&self, modules: &mut [ModuleInfo]) {
        let memory = self.ntoskrnl.memory();
        populate_module_versions(modules, &memory);
    }

    pub fn populate_process_module_versions(&self, modules: &mut [ModuleInfo], info: &ProcessInfo) {
        let process_mem = self.ntoskrnl.sibling(info.dtb, VirtAddr(0));
        let memory = process_mem.memory();
        populate_module_versions(modules, &memory);
    }

    fn is_session_space(addr: VirtAddr) -> bool {
        let prefix = addr.0 >> 44;
        prefix == 0xFFFF8 || prefix == 0xFFFF9 || prefix == 0xFFFFA
    }

    pub fn load_module_symbols(
        phys: &PhysMem,
        symbols: &SymbolStore,
        modules: Vec<ModuleInfo>,
        dtb: Dtb,
        skip_session_space: bool,
        arch: Arch,
    ) -> Result<ModuleSymbolLoadReport> {
        let mut report = ModuleSymbolLoadReport::new(modules.len());
        let mut jobs_with_info: Vec<ModuleSymbolLoad> = Vec::new();
        let mut image_jobs: Vec<(DownloadJob, ModuleInfo)> = Vec::new();
        let mut ready_to_load: Vec<ModuleSymbolLoad> = Vec::new();

        for module in modules {
            if skip_session_space && Self::is_session_space(module.base_address) {
                Self::apply_module_symbol_status(
                    symbols,
                    &mut report,
                    dtb,
                    &module,
                    ModuleSymbolStatus::Skipped,
                );
                continue;
            }

            match symbols.extract_download_job(phys, dtb, &module, arch) {
                Ok(ModuleSymbolDiscovery::Ready { job, guid, source }) => {
                    Self::queue_module_symbol_load(
                        symbols,
                        &mut jobs_with_info,
                        &mut ready_to_load,
                        ModuleSymbolLoad::new(job, guid, source, module, dtb),
                    );
                }
                Ok(ModuleSymbolDiscovery::NeedsImage { image_job }) => {
                    image_jobs.push((image_job, module));
                }
                Err(_e) if module.time_date_stamp.is_some() => {
                    let tds = module.time_date_stamp.unwrap();
                    match SymbolStore::build_image_download_job(&module.name, tds, module.size) {
                        Ok(image_job) => image_jobs.push((image_job, module)),
                        Err(e) => Self::apply_module_symbol_status(
                            symbols,
                            &mut report,
                            dtb,
                            &module,
                            ModuleSymbolStatus::Failed(e.to_string()),
                        ),
                    }
                }
                Err(e) => {
                    Self::apply_module_symbol_status(
                        symbols,
                        &mut report,
                        dtb,
                        &module,
                        ModuleSymbolStatus::Failed(e.to_string()),
                    );
                }
            }
        }

        let image_results =
            download_jobs_parallel(image_jobs.iter().map(|(job, _)| job.clone()).collect());

        for ((image_job, module), result) in image_jobs.into_iter().zip(image_results) {
            match result {
                Ok(_) => match symbols.extract_download_job_from_image_file(&image_job.path) {
                    Ok(Some((job, guid))) => {
                        Self::queue_module_symbol_load(
                            symbols,
                            &mut jobs_with_info,
                            &mut ready_to_load,
                            ModuleSymbolLoad::new(
                                job,
                                guid,
                                ModuleSymbolSource::Image,
                                module,
                                dtb,
                            ),
                        );
                    }
                    Ok(None) => {
                        Self::apply_module_symbol_status(
                            symbols,
                            &mut report,
                            dtb,
                            &module,
                            ModuleSymbolStatus::MissingDebugInfo,
                        );
                    }
                    Err(e) => {
                        Self::apply_module_symbol_status(
                            symbols,
                            &mut report,
                            dtb,
                            &module,
                            ModuleSymbolStatus::Failed(e.to_string()),
                        );
                    }
                },
                Err(e) => {
                    Self::apply_module_symbol_status(
                        symbols,
                        &mut report,
                        dtb,
                        &module,
                        ModuleSymbolStatus::Failed(e.to_string()),
                    );
                }
            }
        }

        let download_results =
            download_jobs_parallel(jobs_with_info.iter().map(|load| load.job.clone()).collect());

        // Modules whose remembered PDB no longer resolves: forget the record
        // and rediscover them from the target below.
        let mut stale_identities: Vec<ModuleInfo> = Vec::new();
        for (load, result) in jobs_with_info.into_iter().zip(download_results) {
            match result {
                Ok(_) => ready_to_load.push(load),
                Err(_) if matches!(load.source, ModuleSymbolSource::Identity) => {
                    stale_identities.push(load.module);
                }
                Err(e) => {
                    Self::apply_module_symbol_status(
                        symbols,
                        &mut report,
                        dtb,
                        &load.module,
                        ModuleSymbolStatus::Failed(e.to_string()),
                    );
                }
            }
        }

        if !ready_to_load.is_empty() {
            let pb = ProgressBar::new(ready_to_load.len() as u64);
            pb.set_style(
                ProgressStyle::with_template("Indexing [{bar:40}] {pos}/{len}")
                    .unwrap()
                    .progress_chars("#-"),
            );

            // Two modules can share a PDB guid, and indexing one guid is
            // serialized behind a per-guid `OnceLock` inside the symbol store.
            // Indexing also nests rayon, and a worker that blocks in a nested
            // region steals other items from this very loop: if it picked up a
            // second module with the guid it is already initializing, it would
            // park on that `OnceLock` waiting for itself. Give the parallel
            // pass one module per guid and run any duplicates afterwards, where
            // they take the already-indexed fast path.
            let (first_per_guid, duplicate_guids) =
                partition_first_occurrence(ready_to_load, |load| load.guid);

            let mut results = first_per_guid
                .into_par_iter()
                .map(|load| {
                    let result = symbols.load_downloaded_pdb(&load);
                    pb.inc(1);
                    (load, result)
                })
                .collect::<Vec<_>>();
            results.extend(duplicate_guids.into_iter().map(|load| {
                let result = symbols.load_downloaded_pdb(&load);
                pb.inc(1);
                (load, result)
            }));

            pb.finish_and_clear();

            for (load, result) in results {
                match result {
                    Ok(_) => {
                        report.record_status(&ModuleSymbolStatus::Loaded);
                        report.record_diagnostics(
                            &load.module.name,
                            symbols.index_diagnostics(load.guid),
                        );
                        if !matches!(load.source, ModuleSymbolSource::Identity) {
                            symbols.remember_module_identity(&load.module, &load.job);
                        }
                    }
                    Err(_) if matches!(load.source, ModuleSymbolSource::Identity) => {
                        stale_identities.push(load.module);
                    }
                    Err(e) => {
                        Self::apply_module_symbol_status(
                            symbols,
                            &mut report,
                            dtb,
                            &load.module,
                            ModuleSymbolStatus::Failed(e.to_string()),
                        );
                    }
                }
            }
        }

        if !stale_identities.is_empty() {
            for module in &stale_identities {
                symbols.forget_module_identity(module);
            }
            report.absorb(Self::load_module_symbols(
                phys,
                symbols,
                stale_identities,
                dtb,
                skip_session_space,
                arch,
            )?);
        }

        Ok(report)
    }

    pub fn load_all_kernel_module_symbols(
        &self,
        phys: &PhysMem,
        symbols: &SymbolStore,
    ) -> Result<ModuleSymbolLoadReport> {
        let mut modules = self.kernel_modules()?;
        if !modules
            .iter()
            .any(|module| module.base_address == self.ntoskrnl.base_address)
        {
            let size = self.ntoskrnl.binary_size().try_into().unwrap_or(u32::MAX);
            if size != 0 {
                modules.insert(
                    0,
                    ModuleInfo::new("ntoskrnl.exe".to_string(), self.ntoskrnl.base_address, size),
                );
            }
        }
        let dtb = self.ntoskrnl.dtb();
        Self::load_module_symbols(phys, symbols, modules, dtb, true, self.ntoskrnl.arch())
    }

    pub fn load_missing_kernel_module_symbols(
        &self,
        phys: &PhysMem,
        symbols: &SymbolStore,
    ) -> Result<ModuleSymbolLoadReport> {
        let dtb = self.ntoskrnl.dtb();
        let modules = self.kernel_modules()?;
        if modules.is_empty() {
            return Ok(ModuleSymbolLoadReport::new(0));
        }

        let unloaded = symbols.retain_modules_for_dtb(dtb, &modules);
        let missing = modules
            .into_iter()
            .filter(|module| {
                symbols
                    .module_symbol_status(dtb, module.base_address)
                    .is_none()
            })
            .collect::<Vec<_>>();

        let mut report =
            Self::load_module_symbols(phys, symbols, missing, dtb, true, self.ntoskrnl.arch())?;
        report.unloaded = unloaded;
        Ok(report)
    }

    pub fn load_all_process_module_symbols(
        &self,
        phys: &PhysMem,
        symbols: &SymbolStore,
        info: &ProcessInfo,
    ) -> Result<ModuleSymbolLoadReport> {
        let modules = self.process_modules(info)?;
        let dtb = info.dtb;
        Self::load_module_symbols(phys, symbols, modules, dtb, false, self.ntoskrnl.arch())
    }

    /// Load symbols for an explicit set of modules under `dtb`. Used to lazily
    /// resolve the modules a backtrace touches (e.g. user-mode frames in a
    /// process we never attached to). Callers filter out already-attempted
    /// modules; this loads whatever it is given.
    pub fn load_symbols_for_modules(
        &self,
        phys: &PhysMem,
        symbols: &SymbolStore,
        modules: Vec<ModuleInfo>,
        dtb: Dtb,
    ) -> Result<ModuleSymbolLoadReport> {
        Self::load_module_symbols(phys, symbols, modules, dtb, false, self.ntoskrnl.arch())
    }
}

/// Split `items` into the first item per distinct key and every later item
/// sharing a key already seen, preserving input order in both halves.
///
/// Used to keep a parallel pass to one item per key while still processing the
/// rest; nothing is dropped.
fn partition_first_occurrence<T, K: Eq + std::hash::Hash>(
    items: Vec<T>,
    key: impl Fn(&T) -> K,
) -> (Vec<T>, Vec<T>) {
    let mut first = Vec::with_capacity(items.len());
    let mut rest = Vec::new();
    let mut seen = HashSet::new();
    for item in items {
        if seen.insert(key(&item)) {
            first.push(item);
        } else {
            rest.push(item);
        }
    }
    (first, rest)
}

#[cfg(test)]
mod tests {
    use super::{
        IMAGE_BLOCK, ModuleSymbolLoadReport, PE_HEADER_PROBE, PeImage, partition_first_occurrence,
        read_pe_header_page, read_pe_image,
    };
    use crate::backend::MemoryOps;
    use crate::error::{Error, Result};
    use crate::memory::{AddressSpace, DTB_IDENTITY};
    use crate::symbols::SymbolIndexDiagnostic;
    use crate::types::{PhysAddr, VirtAddr};
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};

    /// Indexing one PDB guid is serialized behind a per-guid `OnceLock`, and a
    /// rayon worker blocked in a nested parallel region steals other items
    /// from the same loop. Two modules sharing a guid must therefore never be
    /// in the parallel pass together, and neither may be dropped.
    #[test]
    fn same_key_items_are_deferred_out_of_the_parallel_pass() {
        let modules = vec![
            (7u32, "a.sys"),
            (9, "b.sys"),
            (7, "c.sys"),
            (8, "d.sys"),
            (7, "e.sys"),
            (9, "f.sys"),
        ];

        let (first, rest) = partition_first_occurrence(modules, |(guid, _)| *guid);

        assert_eq!(first, vec![(7, "a.sys"), (9, "b.sys"), (8, "d.sys")]);
        assert_eq!(rest, vec![(7, "c.sys"), (7, "e.sys"), (9, "f.sys")]);
    }

    /// Identity-mapped memory holding one image at `base`; reads outside it
    /// fail like an unmapped page. Counts the bytes handed out.
    struct ImageMemory {
        base: u64,
        bytes: Vec<u8>,
        read: AtomicUsize,
        /// Bytes past this offset read as unmapped.
        readable: AtomicUsize,
    }

    impl ImageMemory {
        fn new(base: u64, bytes: Vec<u8>) -> Self {
            Self {
                base,
                readable: AtomicUsize::new(bytes.len()),
                bytes,
                read: AtomicUsize::new(0),
            }
        }

        fn bytes_read(&self) -> usize {
            self.read.load(Ordering::Relaxed)
        }
    }

    impl MemoryOps<PhysAddr> for ImageMemory {
        fn read_bytes(&self, addr: PhysAddr, buf: &mut [u8]) -> Result<()> {
            let start = addr
                .checked_sub(self.base)
                .filter(|start| {
                    start + buf.len() as u64 <= self.readable.load(Ordering::Relaxed) as u64
                })
                .ok_or(Error::BadPhysicalAddress(addr))? as usize;
            buf.copy_from_slice(&self.bytes[start..start + buf.len()]);
            self.read.fetch_add(buf.len(), Ordering::Relaxed);
            Ok(())
        }

        fn write_bytes(&self, _addr: PhysAddr, _buf: &[u8]) -> Result<()> {
            unreachable!()
        }
    }

    fn open_image(memory: &Arc<ImageMemory>) -> PeImage {
        let memory = Arc::clone(memory);
        read_pe_image(VirtAddr(memory.base), move |address, buf| {
            AddressSpace::new(&memory, DTB_IDENTITY).read_bytes(address, buf)
        })
        .unwrap()
    }

    /// A PE32+ image with `.text` at 0x1000 and `.rdata` at 0x2000, each one
    /// page, filled with distinct bytes.
    fn synthetic_image() -> Vec<u8> {
        synthetic_image_with_pe_at(0x80)
    }

    fn synthetic_image_with_pe_at(pe: usize) -> Vec<u8> {
        let mut image = vec![0u8; 0x3000];
        image[..2].copy_from_slice(b"MZ");
        image[0x3c..0x40].copy_from_slice(&(pe as u32).to_le_bytes());
        image[pe..pe + 4].copy_from_slice(b"PE\0\0");
        image[pe + 4..pe + 6].copy_from_slice(&0x8664u16.to_le_bytes());
        image[pe + 6..pe + 8].copy_from_slice(&2u16.to_le_bytes());
        image[pe + 20..pe + 22].copy_from_slice(&240u16.to_le_bytes());
        let opt = pe + 24;
        image[opt..opt + 2].copy_from_slice(&0x20bu16.to_le_bytes());
        image[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes());
        image[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes());
        image[opt + 56..opt + 60].copy_from_slice(&0x3000u32.to_le_bytes());
        image[opt + 60..opt + 64].copy_from_slice(&0x1000u32.to_le_bytes());
        image[opt + 108..opt + 112].copy_from_slice(&16u32.to_le_bytes());
        let sections = opt + 240;
        for (index, (name, va, fill)) in [
            (b".text\0\0\0", 0x1000u32, 0xccu8),
            (b".rdata\0\0", 0x2000, 0xdd),
        ]
        .into_iter()
        .enumerate()
        {
            let header = sections + 40 * index;
            image[header..header + 8].copy_from_slice(name);
            image[header + 8..header + 12].copy_from_slice(&0x1000u32.to_le_bytes());
            image[header + 12..header + 16].copy_from_slice(&va.to_le_bytes());
            image[header + 16..header + 20].copy_from_slice(&0x1000u32.to_le_bytes());
            image[header + 20..header + 24].copy_from_slice(&va.to_le_bytes());
            image[va as usize..va as usize + 0x1000].fill(fill);
        }
        image
    }

    /// Opening an image costs the header probe; a lookup fetches the one
    /// block it lands in, and a second lookup in that block costs nothing.
    #[test]
    fn lazy_image_fetches_blocks_on_first_use() {
        let memory = Arc::new(ImageMemory::new(0x10_0000, synthetic_image()));
        let image = open_image(&memory);
        assert!(!image.is_complete());
        assert_eq!(memory.bytes_read(), PE_HEADER_PROBE);

        assert_eq!(&image.read(0x2200, 0x100).unwrap()[..], &[0xdd; 0x100][..]);
        assert_eq!(memory.bytes_read(), PE_HEADER_PROBE + IMAGE_BLOCK);
        assert_eq!(&image.read(0x2300, 0x10).unwrap()[..], &[0xdd; 0x10][..]);
        assert_eq!(memory.bytes_read(), PE_HEADER_PROBE + IMAGE_BLOCK);

        // A range spanning two blocks is stitched from both: the header
        // page's tail and the first bytes of `.text`.
        let across = image.read(2 * IMAGE_BLOCK - 4, 8).unwrap();
        assert_eq!(&across[..4], &[0; 4]);
        assert_eq!(&across[4..], &[0xcc; 4]);
        assert!(image.read(0x2ff0, 0x11).is_none());
    }

    /// A block the target refuses is a hole: the read reports it rather
    /// than serving zeros, and it is asked for again rather than remembered,
    /// so a page that is resident by the next lookup is served.
    #[test]
    fn lazy_image_reports_unreadable_blocks() {
        let memory = Arc::new(ImageMemory::new(0x10_0000, synthetic_image()));
        memory.readable.store(0x2000, Ordering::Relaxed);
        let image = open_image(&memory);

        assert!(image.is_present(0x1000, 0x10));
        assert!(!image.is_present(0x2000, 4));
        assert!(image.read(0x1ff0, 0x20).is_none());

        memory.readable.store(0x3000, Ordering::Relaxed);
        assert_eq!(&image.read(0x2000, 4).unwrap()[..], &[0xdd; 4][..]);
    }

    /// The header probe alone covers a normally linked image; a section table
    /// that runs past the probe is completed by a second read instead of
    /// being parsed from zeros.
    #[test]
    fn read_pe_header_page_extends_past_probe_only_when_needed() {
        let base = 0x10_0000u64;
        let memory = ImageMemory::new(base, synthetic_image());
        let space = AddressSpace::new(&memory, DTB_IDENTITY);
        let header = read_pe_header_page(VirtAddr(base), &space).unwrap();
        assert_eq!(memory.bytes_read(), PE_HEADER_PROBE);
        assert_eq!(&header[..PE_HEADER_PROBE], &memory.bytes[..PE_HEADER_PROBE]);

        let late_pe = PE_HEADER_PROBE - 0x40;
        let memory = ImageMemory::new(base, synthetic_image_with_pe_at(late_pe));
        let space = AddressSpace::new(&memory, DTB_IDENTITY);
        let header = read_pe_header_page(VirtAddr(base), &space).unwrap();
        let table_end = late_pe + 24 + 240 + 2 * 40;
        assert_eq!(memory.bytes_read(), table_end);
        assert_eq!(&header[..table_end], &memory.bytes[..table_end]);
        assert!(header[table_end..].iter().all(|&byte| byte == 0));
    }

    #[test]
    fn symbol_report_preserves_index_diagnostics_and_total_count() {
        let mut report = ModuleSymbolLoadReport::new(1);
        let diagnostics = (0..70)
            .map(|index| SymbolIndexDiagnostic {
                phase: "line iteration",
                compiland: Some(format!("{index}.obj")),
                message: "malformed line record".to_string(),
            })
            .collect();
        report.record_diagnostics("driver.sys", diagnostics);

        assert_eq!(report.diagnostic_count, 70);
        assert_eq!(report.diagnostics.len(), 64);
        assert_eq!(report.diagnostics[0].module, "driver.sys");
        assert_eq!(report.diagnostics[0].compiland.as_deref(), Some("0.obj"));
    }
}