dbgscope 0.1.0

Typed WinDbg/DbgEng debug sessions, with kernel pool and user heap walkers built on them.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
use std::collections::HashMap;
use std::ffi::CString;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock};
use std::thread;
use std::time::{Duration, Instant};

use thiserror::Error;
use windows::Win32::Foundation::{E_INVALIDARG, E_NOINTERFACE, S_FALSE, S_OK};
use windows::core::{HRESULT, IUnknown, Interface, PCSTR, PCWSTR, PWSTR};

// Import the necessary Windows Debug Engine interfaces
use windows::Win32::System::Diagnostics::Debug::Extensions::{
    DEBUG_ANY_ID, DEBUG_ATTACH_KERNEL_CONNECTION, DEBUG_ATTACH_LOCAL_KERNEL, DEBUG_BREAKPOINT_CODE,
    DEBUG_BREAKPOINT_DATA, DEBUG_BREAKPOINT_DEFERRED, DEBUG_BREAKPOINT_ENABLED,
    DEBUG_BREAKPOINT_ONE_SHOT, DEBUG_CLASS_KERNEL, DEBUG_ENGOPT_INITIAL_BREAK,
    DEBUG_EVENT_BREAKPOINT, DEBUG_EXECUTE_ECHO, DEBUG_INTERRUPT_ACTIVE, DEBUG_KERNEL_SMALL_DUMP,
    DEBUG_MODNAME_SYMBOL_FILE, DEBUG_MODULE_PARAMETERS, DEBUG_MODULE_USER_MODE,
    DEBUG_OUTCTL_THIS_CLIENT, DEBUG_OUTPUT_NORMAL, DEBUG_REGISTER_DESCRIPTION,
    DEBUG_REGISTER_SUB_REGISTER, DEBUG_STACK_FRAME, DEBUG_STATUS_GO, DEBUG_STATUS_GO_HANDLED,
    DEBUG_STATUS_GO_NOT_HANDLED, DEBUG_STATUS_MASK, DEBUG_STATUS_NO_DEBUGGEE,
    DEBUG_STATUS_REVERSE_GO, DEBUG_STATUS_REVERSE_STEP_BRANCH, DEBUG_STATUS_REVERSE_STEP_INTO,
    DEBUG_STATUS_REVERSE_STEP_OVER, DEBUG_STATUS_STEP_BRANCH, DEBUG_STATUS_STEP_INTO,
    DEBUG_STATUS_STEP_OVER, DEBUG_SYMINFO_IMAGEHLP_MODULEW64, DEBUG_SYMTYPE_CODEVIEW,
    DEBUG_SYMTYPE_COFF, DEBUG_SYMTYPE_DEFERRED, DEBUG_SYMTYPE_DIA, DEBUG_SYMTYPE_EXPORT,
    DEBUG_SYMTYPE_NONE, DEBUG_SYMTYPE_PDB, DEBUG_SYMTYPE_SYM, DEBUG_VALUE, DEBUG_VALUE_FLOAT32,
    DEBUG_VALUE_FLOAT64, DEBUG_VALUE_FLOAT80, DEBUG_VALUE_FLOAT82, DEBUG_VALUE_FLOAT128,
    DEBUG_VALUE_INT8, DEBUG_VALUE_INT16, DEBUG_VALUE_INT32, DEBUG_VALUE_INT64,
    DEBUG_VALUE_VECTOR64, DEBUG_VALUE_VECTOR128, DebugConnectWide, IDebugAdvanced2,
    IDebugBreakpoint, IDebugBreakpoint2, IDebugClient6, IDebugControl4, IDebugDataSpaces4,
    IDebugEventContextCallbacks, IDebugOutputCallbacks, IDebugRegisters, IDebugSymbols3,
    IDebugSystemObjects,
};
use windows::Win32::System::Diagnostics::Debug::IMAGEHLP_MODULEW64;

/// Callback type for breakpoint events that receives the breakpoint, context, and flags
pub type BreakpointCallback =
    Box<dyn Fn(&IDebugBreakpoint2, *const std::ffi::c_void, u32) -> windows::core::Result<()>>;

#[derive(Debug, Error)]
pub enum DbgEngError {
    #[error("Failed to initialize COM: {0}")]
    ComInitFailed(#[from] windows::core::Error),

    #[error("Failed to create debug client: {0}")]
    CreateClientFailed(windows::core::Error),

    #[error("Failed to get debug control: {0}")]
    GetControlFailed(windows::core::Error),

    #[error("Failed to get debug symbols: {0}")]
    GetSymbolsFailed(windows::core::Error),

    #[error("Failed to attach to kernel: {0}")]
    AttachFailed(windows::core::Error),

    #[error("Debug command failed: {0}")]
    CommandFailed(windows::core::Error),

    #[error("Symbol path operation failed: {0}")]
    SymbolPathFailed(windows::core::Error),

    #[error("Breakpoint failed: {0}")]
    BreakpointFailed(windows::core::Error),

    #[error("Invalid command string (contains interior NUL)")]
    InvalidCommand,

    #[error(
        "No active debuggee — attach to a target, launch a process, or open a dump/trace first"
    )]
    NoDebuggee,

    #[error(
        "kernel target did not break in within the attach timeout — is it reachable and in debug mode?"
    )]
    KernelBreakTimeout,

    #[error("Operation failed: {0}")]
    OperationFailed(windows::core::Error),

    #[error("{operation} failed: {source}")]
    Context {
        operation: String,
        #[source]
        source: windows::core::Error,
    },

    #[error("short virtual read at {address:#x}: requested {requested} bytes, read {actual}")]
    ShortRead {
        address: u64,
        requested: usize,
        actual: usize,
    },

    #[error("requested debugger buffer is too large: {0} bytes")]
    BufferTooLarge(usize),

    #[error("debugger text contains an interior NUL")]
    InvalidOutput,

    #[error("this scope was read from a target the engine no longer holds")]
    ScopeFromAnotherTarget,
}

/// Fallback length of `_EPROCESS::ImageFileName` when the field's own size cannot be read.
///
/// 15 bytes on every Windows version this can attach to. Only reached when symbols answer the
/// field's *offset* but not its type, which should not happen — it is here so that a partial
/// symbol answer produces a slightly short name rather than no name at all.
const EPROCESS_IMAGE_NAME_LEN: u32 = 15;

/// Buffer to ask a module's names into when the engine reports no size for them, which is what
/// an *unloaded* module's parameters carry. Big enough for a full image path.
const MODULE_NAME_FALLBACK: usize = 260;

/// `DEBUG_MODULE_PARAMETERS::Flags`: this module has unloaded. Zero — `DEBUG_MODULE_LOADED` — is
/// the other state, so the flag is what separates the two halves of the engine's module list.
const DEBUG_MODULE_UNLOADED: u32 = 0x0000_0001;

/// `CreateProcess` flag: debug only the launched process, not its children.
const DEBUG_ONLY_THIS_PROCESS: u32 = 0x0000_0002;
/// `CreateProcess` flag: give the launched target its own console. Without this a
/// console target inherits the host's stdout — fatal when the host's stdout is an
/// MCP/JSON-RPC channel, as the target's prints corrupt the stream.
const CREATE_NEW_CONSOLE: u32 = 0x0000_0010;
/// `AttachProcess` default attach flags.
const DEBUG_ATTACH_DEFAULT: u32 = 0x0000_0000;
/// `EndSession` flag used on teardown: detach passively without resuming.
const DEBUG_END_PASSIVE: u32 = 0x0000_0000;
/// `EndSession` flag: actively detach — the engine talks to the target to resume it
/// before disconnecting, so a live kernel is left running instead of frozen at a break.
const DEBUG_END_ACTIVE_DETACH: u32 = 0x0000_0002;
/// How long to wait for a freshly launched/attached target to reach its initial
/// break before giving up (ms).
const LIVE_WAIT_MS: u32 = 30_000;
/// `WaitForEvent` timeout for a *live kernel* target. DbgEng requires INFINITE here —
/// a finite timeout on a live kernel connection returns `E_NOTIMPL` (the engine never
/// drives the connection). See [`DebugEngine::is_live_kernel`].
const WAIT_INFINITE: u32 = u32::MAX;
/// Upper bound (ms) on a live-kernel break-in wait. The wait itself must be INFINITE
/// (a finite `WaitForEvent` returns `E_NOTIMPL` on a live kernel), so a watchdog forces
/// it to return after this long. Generous, to allow a KDNET resync (~25s observed).
///
/// **Bounds less than it appears to.** The watchdog works by `SetInterrupt`, which only
/// reaches a target that has *connected*, so this caps a connected-but-unresponsive target
/// and nothing else. One that never dials in — powered off, wrong key, not booted with
/// `bcdedit /debug on` — blocks past this bound indefinitely (measured: >300s, killed).
/// See [`DebugEngine::attach_kernel`].
const KERNEL_ATTACH_WAIT_MS: u32 = 60_000;

/// Buffer sizes offered to `GetScope` for a scope's register context, smallest first.
///
/// The engine rejects a buffer below the target's `CONTEXT` size and accepts anything at or
/// above it (measured — see [`DebugEngine::scope`]), so the first size accepted is the smallest
/// here that fits, and the first three are the `CONTEXT` sizes of the architectures dbgeng
/// debugs: x86 (716), ARM64 (912), x64 (1232). The doubling tail is for a target whose context
/// is larger than any of them — a size this crate has not seen, and would otherwise refuse to
/// read a scope for at all.
const SCOPE_CONTEXT_SIZES: &[u32] = &[716, 912, 1232, 2048, 4096, 8192, 16384, 32768, 65536];

/// Ctrl+Breaks one engine from another thread.
///
/// `SetInterrupt` is the one DbgEng call documented as safe from any thread — the rest of the
/// engine is single-thread-affine — which is the whole reason this can exist without a second
/// threading model. It is also the only call this makes.
///
/// Two kinds of caller, and the engine cannot tell them apart: the watchdogs below, which raise
/// an interrupt when a deadline passes, and a **host that has decided to stop waiting** — an
/// operator abandoning a runaway `s` search, say. The second is why this is public. Everything
/// about *which* operation an interrupt is meant for belongs to that host: this addresses an
/// engine, so whatever it is running now is what stops.
pub struct InterruptHandle {
    /// An owned reference, not a borrowed pointer. A handle is public now, so it can outlive the
    /// `DebugEngine` it came from — and a raw pointer would then be a dangling one at exactly the
    /// moment a host reaches for it. The refcount costs nothing and makes the lifetime a fact
    /// rather than a convention.
    control: IDebugControl4,
    /// Set whenever this handle raises an interrupt, and cleared by the command that finds it.
    ///
    /// Shared with the engine so [`DebugEngine::execute_command_bounded`] can tell an aborted
    /// `Execute` from a failed one *without* being the thread that asked. Without it an interrupt
    /// on request is indistinguishable from a command error, and the output captured up to the
    /// break is discarded with it — which is most of what an interrupted search is worth.
    raised: Arc<AtomicBool>,
}
// SAFETY: `control` is only ever handed to SetInterrupt, the one cross-thread-safe DbgEng call.
// The other cross-thread touch is the `Release` on drop, which rests on the same assumption
// [`DebugEngine`]'s own `Send`/`Sync` below already make about these interfaces; a handle held for
// the life of a process (the intended use) never reaches it at all.
unsafe impl Send for InterruptHandle {}
// SAFETY: as above — sharing a handle only shares the ability to make that one call.
unsafe impl Sync for InterruptHandle {}

impl InterruptHandle {
    /// Asks the engine this came from to break out of whatever it is running.
    ///
    /// Returns as soon as the request is lodged, not when the engine acts on it: a long command
    /// polls for the flag exactly as it does for a human's Ctrl+Break, so the operation ends at
    /// its next poll and its own caller is who observes that. Two limits carry over from the
    /// engine, both of them properties of `SetInterrupt` rather than of this: a command that never
    /// polls is not reached, and neither is a live-kernel wait whose target has not yet connected
    /// (see [`DebugEngine::wait_for_event_bounded`]).
    pub fn interrupt(&self) -> Result<(), DbgEngError> {
        // Stored *before* the call, so the flag can never become visible later than the break it
        // explains — a bounded command reads it after `Execute` returns, and one that read `false`
        // there would report the abort it caused as a debugger error.
        self.raised.store(true, Ordering::SeqCst);
        unsafe { self.control.SetInterrupt(DEBUG_INTERRUPT_ACTIVE) }.map_err(|source| {
            DbgEngError::Context {
                operation: "requesting a debugger interrupt".into(),
                source,
            }
        })
    }
}

/// How often a watchdog past its deadline raises the break again.
///
/// One `SetInterrupt` is a request, not a guarantee: the engine acts on it at its next poll, and a
/// busy operation can be between polls when it arrives. Repeating costs one call on a path that
/// has already given up on the deadline.
const WATCHDOG_REPEAT: Duration = Duration::from_millis(200);

/// A thread that Ctrl+Breaks an operation once a deadline passes — and that stops **the moment**
/// it is disarmed, rather than at the end of a poll interval.
///
/// That last property is the whole reason this is a type rather than two `thread::spawn`s.
/// Both bounded paths here used to poll a flag on a fixed sleep, so `join` waited out whatever was
/// left of it: **every** bounded operation paid up to one interval, whether or not it came close to
/// its deadline. windbg-mcp measured that tax at ~200ms on a command whose unbounded median was
/// 0.22ms, and routed its cheap queries around the bounded path to avoid it — a design decision
/// taken to work around a sleep. A condition variable makes the disarm immediate, so the bound
/// costs nothing until it is actually reached.
///
/// The break itself is a closure rather than an [`InterruptHandle`], which is what lets the
/// behaviour be tested without a debuggee: the unit tests below arm one over a counter.
struct Watchdog {
    /// Set by [`Self::disarm`] and read by the thread; the condvar is what wakes it to see that.
    disarmed: Arc<(Mutex<bool>, Condvar)>,
    /// Whether the deadline was ever reached — the fact a caller needs, since a forced break is
    /// not the event it was waiting for.
    fired: Arc<AtomicBool>,
    thread: Option<thread::JoinHandle<()>>,
}

impl Watchdog {
    /// Arms a watchdog that calls `on_deadline` once `deadline` has passed, and again every
    /// [`WATCHDOG_REPEAT`] until it is disarmed.
    ///
    /// A zero `deadline` fires immediately, which is what a caller asking for no time at all
    /// means; a caller wanting *no bound* does not arm one.
    fn arm(deadline: Duration, on_deadline: impl Fn() + Send + 'static) -> Self {
        let disarmed = Arc::new((Mutex::new(false), Condvar::new()));
        let fired = Arc::new(AtomicBool::new(false));
        let woken = Arc::clone(&disarmed);
        let raised = Arc::clone(&fired);
        let thread = thread::spawn(move || {
            let (lock, wake) = &*woken;
            let start = Instant::now();
            loop {
                // Past the deadline the only question left is when to repeat; before it, sleep
                // exactly as long as there is left, so a watchdog that is never reached wakes
                // once.
                let nap = if raised.load(Ordering::SeqCst) {
                    WATCHDOG_REPEAT
                } else {
                    deadline.saturating_sub(start.elapsed())
                };
                {
                    let stop = lock.lock().unwrap_or_else(|e| e.into_inner());
                    if *stop {
                        return;
                    }
                    // The guard is dropped at the end of this block, so the interrupt below is
                    // never raised while holding a lock the disarming thread wants.
                    let (stop, _) = wake
                        .wait_timeout(stop, nap)
                        .unwrap_or_else(|e| e.into_inner());
                    if *stop {
                        return;
                    }
                }
                // A spurious wake-up lands here too, and is harmless: the deadline decides,
                // not the fact of having woken.
                if start.elapsed() >= deadline {
                    on_deadline();
                    raised.store(true, Ordering::SeqCst);
                }
            }
        });
        Self {
            disarmed,
            fired,
            thread: Some(thread),
        }
    }

    /// Stops the watchdog, waits for its thread, and reports whether it had raised a break.
    fn disarm(mut self) -> bool {
        self.stop();
        self.fired.load(Ordering::SeqCst)
    }

    /// Idempotent, so [`Drop`] can run it again after [`Self::disarm`] already has — and so a
    /// panic between arming and disarming still ends the thread rather than leaking it.
    fn stop(&mut self) {
        {
            let (lock, wake) = &*self.disarmed;
            let mut stop = lock.lock().unwrap_or_else(|e| e.into_inner());
            *stop = true;
            wake.notify_all();
        }
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }
}

impl Drop for Watchdog {
    fn drop(&mut self) {
        self.stop();
    }
}

/// Whether an execution status means the engine has been told to run and is waiting for a
/// `WaitForEvent` to pump it.
///
/// Every go and every step, forward and reverse — not `DEBUG_STATUS_BREAK` (stopped),
/// `DEBUG_STATUS_NO_DEBUGGEE` (nothing to run) or the housekeeping statuses, all of which are
/// states an ordinary command can be issued in.
///
/// Masked because `GetExecutionStatus` is documented to carry flags above the status itself
/// (`DEBUG_STATUS_INSIDE_WAIT`, `DEBUG_STATUS_WAIT_TIMEOUT`); they do not fit the `u32` this
/// binding returns, so the mask is insurance rather than a fix, and it costs nothing.
fn is_running_status(status: u32) -> bool {
    matches!(
        status & DEBUG_STATUS_MASK,
        DEBUG_STATUS_GO
            | DEBUG_STATUS_GO_HANDLED
            | DEBUG_STATUS_GO_NOT_HANDLED
            | DEBUG_STATUS_STEP_OVER
            | DEBUG_STATUS_STEP_INTO
            | DEBUG_STATUS_STEP_BRANCH
            | DEBUG_STATUS_REVERSE_GO
            | DEBUG_STATUS_REVERSE_STEP_BRANCH
            | DEBUG_STATUS_REVERSE_STEP_OVER
            | DEBUG_STATUS_REVERSE_STEP_INTO
    )
}

/// Encodes a `&str` as a NUL-terminated UTF-16 buffer for the `*Wide` DbgEng APIs.
fn to_wide(s: &str) -> Vec<u16> {
    s.encode_utf16().chain(std::iter::once(0)).collect()
}

/// Where execution stopped after a [`DebugEngine::run_to_address`] request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RunToOutcome {
    /// The target reached the requested address.
    Hit,
    /// The target stopped at a different address (another breakpoint or an exception)
    /// before reaching the requested one.
    StoppedElsewhere { stopped_at: u64 },
    /// The target did not stop within the timeout — the address was not reached with the
    /// current input/state.
    Timeout,
    /// The target went away before it reached anything: it ran to completion, or its session was
    /// torn down. Terminal, and the same ending [`CommandRun::target_gone`] reports — nothing
    /// will run against this engine again. Says nothing about whether `address` was reachable.
    TargetGone,
}

/// Result of [`DebugEngine::run_to_address`]: the structured [`RunToOutcome`] plus the
/// debugger text captured across the run (the stop banner, for context/logging).
#[derive(Debug, Clone)]
pub struct RunToResult {
    pub outcome: RunToOutcome,
    pub output: String,
}

/// Why a command stopped before it finished.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Interruption {
    /// The watchdog's deadline passed and it Ctrl+Broke the engine. Nobody outside this crate can
    /// see that happen, so a caller rendering for a human should say so — and say what to do about
    /// it, which is to scope the command and retry.
    Deadline { after_ms: u32 },
    /// A host asked, through an [`InterruptHandle`]. Distinct from a deadline because the advice
    /// is different and mostly unnecessary: that caller knows, having asked.
    OnRequest,
}

/// What a command produced, and whether it finished — the same shape as [`RunToResult`], and for
/// the same reason.
///
/// A `String` alone cannot answer "did this run?", and an interrupted command is exactly the case
/// where the text looks like an answer and is not: a search cut short prints the hits it had
/// reached and nothing to say there were more. Encoding it as an `Err` is no better — it discards
/// the output, which is the whole reason to interrupt rather than end the session.
#[derive(Debug, Clone)]
pub struct CommandRun {
    pub output: String,
    /// `None` when the command ran to completion.
    pub cut_short: Option<Interruption>,
    /// The engine held no debuggee once this run ended: the target exited, or the session was
    /// otherwise torn down under the pump.
    ///
    /// **Terminal, and not a failure.** A program running to completion is the ordinary end of a
    /// `go`, and it is the one ending that leaves the engine unable to answer about a target ever
    /// again — every later command fails, and execution control *faults the process*
    /// ([`DebugEngine::execute_command_bounded`]). It is reported here rather than as an `Err`
    /// because the output above it is real and this is the only copy of it: the module loads, a
    /// breakpoint banner, whatever an embedded script printed before the target ran out. A caller
    /// should report the ending and retire the session; nothing will run against this engine
    /// again.
    ///
    /// It is not only the pumping paths that report it. A command can take the target away
    /// *itself* — measured, `.detach` leaves `DEBUG_STATUS_NO_DEBUGGEE` the moment it returns,
    /// with nothing left to pump and so nothing for [`DebugEngine::settle`] to report — so
    /// [`DebugEngine::execute_command_bounded`] answers the same question after its command.
    /// One field, whichever way the target went.
    ///
    /// (`.kill` is not one of them, which is worth knowing before pattern-matching on command
    /// names instead: it leaves the engine at `DEBUG_STATUS_BREAK` with a readable stack in
    /// `ntdll!LdrShutdownProcess`, and the target goes away on the *next* resume, which is where
    /// the pump reports it.)
    pub target_gone: bool,
}

impl CommandRun {
    /// The output, for a caller that has already dealt with [`Self::cut_short`] — or one running a
    /// command it knows cannot be interrupted.
    pub fn into_output(self) -> String {
        self.output
    }
}

/// `DEBUG_INVALID_OFFSET` from `dbgeng.h`: the engine's "there is no address here".
///
/// Spelled out because the `windows` crate does not generate it, and the value matters — a
/// breakpoint reporting it is one that has not resolved, which is not the same as one at zero.
const DEBUG_INVALID_OFFSET: u64 = u64::MAX;

/// What one register holds, decoded from the engine's tagged union.
///
/// `DEBUG_VALUE` is a union plus a `Type` discriminant, and reading the wrong arm is not a
/// compile error or even a runtime one — it is a plausible-looking number. So the tag is read
/// once, here, and each arm keeps a shape it can hold losslessly: the wide floats and the vector
/// registers stay as bytes rather than being squeezed into an `f64` that cannot represent them.
#[derive(Debug, Clone, PartialEq)]
pub enum RegisterValue {
    /// An integer register, zero-extended to 64 bits from whatever width the engine reported.
    Int(u64),
    /// A floating-point register narrow enough to be exact in an `f64` (`f32`/`f64`).
    Float(f64),
    /// An x87 (80/82/128-bit) or vector (`xmm`/`ymm`) register, in the engine's byte order.
    /// Kept raw because there is no scalar to narrow it to without losing part of it.
    Bytes(Vec<u8>),
    /// The engine holds no value for this register in this target — a minidump without
    /// floating-point state reads this way — or reported a type this build does not decode.
    Unavailable,
}

impl RegisterValue {
    /// Decodes one `DEBUG_VALUE` by its own tag.
    fn decode(value: &DEBUG_VALUE) -> Self {
        // SAFETY: every read below is of the arm `value.Type` names, which is the contract
        // `DEBUG_VALUE` is defined by, and the engine fills the whole struct. An unrecognised
        // tag reads no arm at all.
        unsafe {
            match value.Type {
                DEBUG_VALUE_INT8 => Self::Int(u64::from(value.Anonymous.I8)),
                DEBUG_VALUE_INT16 => Self::Int(u64::from(value.Anonymous.I16)),
                DEBUG_VALUE_INT32 => Self::Int(u64::from(value.Anonymous.I32)),
                DEBUG_VALUE_INT64 => Self::Int(value.Anonymous.Anonymous.I64),
                DEBUG_VALUE_FLOAT32 => Self::Float(f64::from(value.Anonymous.F32)),
                DEBUG_VALUE_FLOAT64 => Self::Float(value.Anonymous.F64),
                DEBUG_VALUE_FLOAT80 => Self::Bytes(value.Anonymous.F80Bytes.to_vec()),
                DEBUG_VALUE_FLOAT82 => Self::Bytes(value.Anonymous.F82Bytes.to_vec()),
                DEBUG_VALUE_FLOAT128 => Self::Bytes(value.Anonymous.F128Bytes.to_vec()),
                DEBUG_VALUE_VECTOR64 => Self::Bytes(value.Anonymous.VI8[..8].to_vec()),
                DEBUG_VALUE_VECTOR128 => Self::Bytes(value.Anonymous.VI8.to_vec()),
                _ => Self::Unavailable,
            }
        }
    }
}

/// What the engine says a register **is**, as distinct from what it currently holds.
///
/// [`DebugEngine::register_values`] reports one field of this — [`Register::subregister`], the
/// `DEBUG_REGISTER_SUB_REGISTER` flag — because that is the one a caller filtering "real
/// registers" from "views of them" reaches for. This is the whole of
/// `DEBUG_REGISTER_DESCRIPTION`, for a caller who has found that flag insufficient and needs to
/// see what else the engine offers: it is clear for `xmm0/0`…`xmm0/3` on x64 and for `w0`–`w30`
/// on ARM64, both of which are pieces of wider registers by every other measure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RegisterDescription {
    /// The engine's own name for it, lowercase.
    pub name: String,
    /// The `DEBUG_VALUE_*` type the engine reports this register's value as.
    pub kind: u32,
    /// `DEBUG_REGISTER_SUB_REGISTER`, and whatever else this engine sets.
    pub flags: u32,
    /// The index of the register this one is a piece of. **The engine documents this as
    /// meaningful only when [`Self::flags`] says the register is a sub-register**, which is
    /// exactly the limitation a caller needs to be able to check rather than assume.
    pub subreg_master: u32,
    /// How many **bits** of the master this register covers, under the same condition — the unit
    /// is the engine's, and it is the one a reader assumes wrongly: `eax` reports 32.
    pub subreg_length: u32,
    pub subreg_mask: u64,
    pub subreg_shift: u32,
}

/// One register of the target's context, as [`DebugEngine::register_values`] reports it.
#[derive(Debug, Clone, PartialEq)]
pub struct Register {
    /// The engine's own name for it, lowercase (`rax`, `xmm0`, `cs`, `efl`).
    pub name: String,
    pub value: RegisterValue,
    /// Whether this register is a *view* of another rather than storage of its own — `eax`
    /// within `rax`, `al` within `ax`. Reported rather than filtered because which of the two a
    /// caller wants depends entirely on what they are doing.
    pub subregister: bool,
}

/// How much symbol information the engine has for a module — the `lm` "symbols" column.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum SymbolKind {
    /// No symbols at all.
    #[default]
    None,
    /// Symbols have not been loaded yet; the engine will fetch them when something needs them.
    /// The most consequential value here, because it is *not* a statement that symbols are
    /// missing — a `deferred` module usually resolves fine on first use.
    Deferred,
    Coff,
    CodeView,
    Pdb,
    /// Names taken from the image's export table: enough for `module!Export`, nothing more.
    Export,
    Sym,
    Dia,
    /// A symbol type this build does not name, kept as the engine's own code rather than
    /// flattened into `None` — which would read as "no symbols" for something that has them.
    Other(u32),
}

impl SymbolKind {
    fn from_engine(code: u32) -> Self {
        match code {
            DEBUG_SYMTYPE_NONE => Self::None,
            DEBUG_SYMTYPE_COFF => Self::Coff,
            DEBUG_SYMTYPE_CODEVIEW => Self::CodeView,
            DEBUG_SYMTYPE_PDB => Self::Pdb,
            DEBUG_SYMTYPE_EXPORT => Self::Export,
            DEBUG_SYMTYPE_DEFERRED => Self::Deferred,
            DEBUG_SYMTYPE_SYM => Self::Sym,
            DEBUG_SYMTYPE_DIA => Self::Dia,
            other => Self::Other(other),
        }
    }

    /// Whether this symbol provider exposes private type information suitable for allocator
    /// layout resolution.
    pub fn has_type_info(self) -> bool {
        matches!(self, Self::Pdb | Self::Dia)
    }
}

/// One module, as [`DebugEngine::modules`] and [`DebugEngine::unloaded_modules`] report it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Module {
    pub base: u64,
    pub size: u32,
    /// The name symbols are qualified by — the `nt` in `nt!KeBugCheckEx`.
    ///
    /// **Empty for an unloaded module**, which is not a truncation bug but the fact: there is no
    /// module left to qualify a symbol with. `lm` prints [`Self::image_name`] in its name column
    /// for those rows, and so should anything rendering them.
    pub name: String,
    /// The image's own name (`ntkrnlmp.exe`).
    ///
    /// The one name an *unloaded* module still has, and the kernel stores it truncated — twelve
    /// characters, so `WpdUpFltr.sys` comes back as `WpdUpFltr.sy`. `lm` shows the same truncation
    /// because it is reading the same list.
    pub image_name: String,
    /// The path the engine loaded the image from, where it has one.
    pub loaded_image_name: String,
    pub timestamp: u32,
    pub checksum: u32,
    pub symbols: SymbolKind,
    /// Whether this is a user-mode module. On a kernel target both kinds can be present.
    pub user_mode: bool,
    /// Whether this module has **unloaded**: the engine's own `DEBUG_MODULE_UNLOADED` flag, not
    /// an inference from which call produced it.
    ///
    /// Carried on the value so a `Module` that has been passed around still knows which half of
    /// the engine's list it came from — the distinction decides whether `base` is where the image
    /// *is* or where it *was*.
    pub unloaded: bool,
}

/// Stable identity and symbol provenance for one loaded image.
///
/// The PE tuple is what DbgEng and symbol servers use to distinguish builds; the base is
/// included because resolved globals are addresses in this particular target. `symbol_file`
/// is the exact file DbgEng selected for the module, rather than a path inferred from the
/// configured symbol search path.
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct ModuleIdentity {
    pub name: String,
    pub image_name: String,
    pub loaded_image_name: String,
    pub symbol_file: String,
    pub symbols: SymbolKind,
    pub base: u64,
    pub size: u32,
    pub timestamp: u32,
    pub checksum: u32,
}

/// Which PDB the engine has for a module, in the form a symbol server is keyed by.
///
/// The *image* is identified by `TimeDateStamp` + `SizeOfImage` ([`Module`]); its symbols are
/// identified by this pair instead, and the two are not interchangeable — a build can be rebuilt
/// with the same timestamp and a new PDB signature.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PdbIdentity {
    /// The signature as a symbol server path spells it: 32 uppercase hex digits, no braces and no
    /// dashes. Deliberately not the braced form `Debug` would print — this is the string that goes
    /// in `<pdb>/<guid><age>/<pdb>`, and reformatting it is the caller's least useful job.
    pub guid: String,
    /// The age, which the same path appends to the GUID in hex.
    pub age: u32,
    /// Whether the engine matched a PDB it then found did **not** belong to this image. A caller
    /// reading symbols from it is reading another build's names.
    pub unmatched: bool,
    /// The file the engine actually loaded, where it says. Empty when it has none.
    pub file: String,
}

impl Module {
    /// One past the last byte of the image — the end of the `start end` pair `lm` prints.
    pub fn end(&self) -> u64 {
        self.base.saturating_add(u64::from(self.size))
    }
}

/// The kernel image a target is running: where it is loaded, and which build it is.
///
/// Hashable and comparable so it can key a cache of anything derived from the kernel's types
/// and globals — which is why the build fields travel with the base rather than beside it. See
/// [`DebugEngine::kernel_image`] for what each field is and why these three.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct KernelImage {
    /// Where `nt` is loaded. Globals resolved against it are addresses, so this is part of the
    /// identity of anything resolved, not merely of the lookup that found it.
    pub base: u64,
    pub size: u32,
    pub timestamp: u32,
    pub checksum: u32,
}

/// The bug check a target stopped on, as [`DebugEngine::bug_check`] reports it.
///
/// The engine's own five values and nothing else: what each parameter *means* is per-code lore
/// that lives in `!analyze`'s tables, not in the engine, so it is not invented here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BugCheck {
    /// The bug check code — `0x9f` for `DRIVER_POWER_STATE_FAILURE`.
    pub code: u32,
    /// The four parameters, in the order the bug check screen and `!analyze` print them as
    /// `Arg1`..`Arg4`.
    pub parameters: [u64; 4],
}

/// One frame of a stack walk, as [`DebugEngine::stack_frames`] reports it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StackFrame {
    /// Its position in the walk: 0 is the innermost frame, where the target is stopped.
    pub index: u32,
    /// The instruction this frame is executing at — the address a symbol or `module+RVA` is
    /// resolved from.
    pub instruction_offset: u64,
    pub return_offset: u64,
    pub frame_offset: u64,
    pub stack_offset: u64,
    /// `module!Symbol` as the engine resolves [`Self::instruction_offset`], or `None` when
    /// nothing resolves — the normal case for a driver with no PDB.
    pub symbol: Option<String>,
    /// How far past [`Self::symbol`] the instruction is; zero when there is no symbol.
    pub displacement: u64,
}

/// One disassembled instruction, as [`DebugEngine::disassemble`] reports it.
///
/// The engine has no structured disassembly — `IDebugControl::Disassemble` renders one line of
/// text and says where the next instruction starts — so this is that line split at its two column
/// boundaries, with the address taken from the walk rather than parsed back out of it. A line the
/// split does not recognise keeps everything after the address in [`Self::text`] and leaves
/// [`Self::bytes`] empty, rather than guessing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Instruction {
    /// Where the instruction is. **Not** parsed from the rendered line: it is the offset this
    /// walk asked about, which is the previous instruction's end.
    pub address: u64,
    /// The encoding, as the engine prints it — `48895c2408`. Empty when the line carried no byte
    /// column, which is not a shape any current engine produces for a readable address.
    pub bytes: String,
    /// The mnemonic and its operands — `mov qword ptr [rsp+8],rbx` — with the engine's column
    /// padding collapsed to single spaces, since the columns it was aligning are separate fields
    /// here. Operand symbols are the engine's own (`call nt!KeBugCheckEx (fffff803`...)`).
    pub text: String,
}

/// The engine's current **scope**: which instruction, which frame, and the register context
/// those are read through — what `.frame`, `.cxr`, `.ecxr` and `.trap` set, and what `dt`, `dv`,
/// `k` and every register read are answered against.
///
/// Held in order to be handed back. A scope is a position in someone else's session, and its
/// fields are the engine's own bookkeeping — a [`DEBUG_STACK_FRAME`] it walked, and an opaque
/// context blob whose layout is the target's `CONTEXT` — so this is a token to return through
/// [`DebugEngine::set_scope`] rather than a record to edit. [`DebugEngine::scope_guard`] is the
/// usual way to use one.
///
/// Compares by value, so "the scope did not move" is a thing a caller can assert.
#[derive(Clone, PartialEq)]
pub struct Scope {
    instruction: u64,
    frame: DEBUG_STACK_FRAME,
    /// The target's register context, verbatim. Empty when the scope carries none — see
    /// [`DebugEngine::scope`].
    context: Vec<u8>,
    /// Which target this was read from, so a restore cannot land on a later one. See
    /// [`DebugEngine::target_identity`].
    target: u64,
}

impl Scope {
    /// The instruction the scope is on — frame 0's program counter, unless a frame or a
    /// register context was selected, in which case it is that one's.
    pub fn instruction_offset(&self) -> u64 {
        self.instruction
    }

    /// The frame the scope names, as the engine walked it.
    pub fn frame(&self) -> &DEBUG_STACK_FRAME {
        &self.frame
    }

    /// Whether the scope carries a register context.
    ///
    /// `false` is a legitimate scope rather than a failed read: a target with no thread context
    /// to offer still has a position, and restoring a scope that never had a context must not —
    /// and does not — fail.
    pub fn has_context(&self) -> bool {
        !self.context.is_empty()
    }
}

impl std::fmt::Debug for Scope {
    /// Summarizes the context rather than printing it: the blob is a kilobyte of register
    /// state whose bytes mean nothing outside the engine, and a derived `Debug` puts all of
    /// it in every log line and assertion message that mentions a scope.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Scope")
            .field("instruction", &format_args!("{:#x}", self.instruction))
            .field("frame", &self.frame.FrameNumber)
            .field(
                "frame_offset",
                &format_args!("{:#x}", self.frame.FrameOffset),
            )
            .field("context", &format_args!("{} bytes", self.context.len()))
            .field("target", &self.target)
            .finish()
    }
}

/// What kind of event a breakpoint watches for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BreakpointKind {
    /// Execution reaching an address (`bp`).
    Code,
    /// Access to a range of memory (`ba`).
    Data,
    /// A type this build does not name, kept as the engine's own code.
    Other(u32),
}

impl BreakpointKind {
    fn from_engine(code: u32) -> Self {
        match code {
            DEBUG_BREAKPOINT_CODE => Self::Code,
            DEBUG_BREAKPOINT_DATA => Self::Data,
            other => Self::Other(other),
        }
    }
}

/// One breakpoint the engine holds, as [`DebugEngine::breakpoints`] reports it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BreakpointInfo {
    /// The id the debugger prints and `bc`/`bd`/`be` take.
    pub id: u32,
    pub kind: BreakpointKind,
    /// Where it will fire, or `None` while it is [deferred](Self::deferred) — its module is not
    /// loaded, so it has no address yet. Never zero for "unknown".
    pub address: Option<u64>,
    /// The expression the engine is still holding this breakpoint as — in practice a deferred
    /// one (`hevd!Trigger+0x40` for a driver that has not loaded). A breakpoint that resolved
    /// when it was set keeps its [address](Self::address) instead and the engine no longer holds
    /// the text, so `None` here is the normal case for a live breakpoint, not a gap.
    pub expression: Option<String>,
    /// The command string the debugger runs each time it fires, where it has one.
    pub command: Option<String>,
    /// The thread it is restricted to, or `None` for any thread.
    pub thread: Option<u32>,
    pub enabled: bool,
    /// Waiting for its module to load, and therefore not yet resolved to an address.
    pub deferred: bool,
    /// Removes itself the first time it fires.
    pub one_shot: bool,
    /// How many times it must be reached before it stops the target (1 = every time).
    pub pass_count: u32,
    /// How many of those passes are still to go.
    pub passes_remaining: u32,
}

/// Reads a string out of one of DbgEng's two-call string getters.
///
/// They all take the same shape — a buffer, its length, and an out-parameter for the size the
/// engine wanted — and they all truncate silently when the buffer is short. So the size is asked
/// for first with no buffer at all, and the read that follows is exactly big enough; a name that
/// grew between the two calls (it cannot here — nothing is running) would still be NUL-terminated
/// rather than clipped mid-way.
fn read_engine_string(
    mut get: impl FnMut(Option<&mut [u8]>, Option<*mut u32>) -> windows::core::Result<()>,
) -> windows::core::Result<String> {
    let mut needed = 0u32;
    get(None, Some(&mut needed))?;
    if needed <= 1 {
        return Ok(String::new());
    }
    let mut buffer = vec![0u8; needed as usize];
    get(Some(&mut buffer), None)?;
    Ok(nul_terminated(&buffer))
}

/// Splits one rendered disassembly line into its byte and mnemonic columns.
///
/// The line is `<address> <bytes> <mnemonic and operands>`, whitespace-separated, and the address
/// is discarded because the walk already knows it — reading it back would make the record depend
/// on a rendering it does not otherwise trust. Anything the shape does not fit keeps its whole
/// remainder as text, so an engine that renders differently loses a column rather than an
/// instruction.
fn split_instruction(address: u64, line: &str) -> Instruction {
    let mut columns = line.trim().splitn(3, char::is_whitespace);
    let (_address, bytes, rest) = (columns.next(), columns.next(), columns.next());
    match (bytes, rest) {
        (Some(bytes), Some(rest)) => Instruction {
            address,
            bytes: bytes.to_string(),
            text: collapse_spaces(rest),
        },
        // One column past the address, or none: keep it whole rather than calling it an encoding.
        (Some(only), None) => Instruction {
            address,
            bytes: String::new(),
            text: collapse_spaces(only),
        },
        _ => Instruction {
            address,
            bytes: String::new(),
            text: collapse_spaces(line),
        },
    }
}

/// Runs of whitespace as one space. The engine pads its columns to align them in a listing, and
/// the alignment means nothing once the columns are separate fields.
fn collapse_spaces(text: &str) -> String {
    text.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// A PDB signature as a symbol server path spells it: 32 uppercase hex digits.
///
/// Not `{:?}` on the GUID, which prints the braced, dashed form no path uses, and not a
/// byte-order-preserving hex dump either — the first three fields are written as the numbers they
/// are and only the trailing eight bytes are laid out in order. Getting that wrong produces a URL
/// that 404s, which is a hard failure to read backwards.
fn format_pdb_guid(guid: &windows::core::GUID) -> String {
    let mut out = format!("{:08X}{:04X}{:04X}", guid.data1, guid.data2, guid.data3);
    for byte in guid.data4 {
        out.push_str(&format!("{byte:02X}"));
    }
    out
}

/// A NUL-terminated wide string out of a fixed engine buffer.
fn wide_to_string(buffer: &[u16]) -> String {
    let end = buffer.iter().position(|&c| c == 0).unwrap_or(buffer.len());
    String::from_utf16_lossy(&buffer[..end])
}

/// The text up to the first NUL in an engine-filled buffer.
fn nul_terminated(buffer: &[u8]) -> String {
    let end = buffer.iter().position(|&b| b == 0).unwrap_or(buffer.len());
    String::from_utf8_lossy(&buffer[..end]).into_owned()
}

/// Hands out a fresh identity for every engine, and again whenever one releases its
/// target. Caches that ask "is this still the same target?" cannot use the kernel base
/// alone — two dumps from one boot share it — and dbgeng holds one debuggee session per
/// process, so per-engine identity plus a bump on release covers every case.
static NEXT_TARGET_IDENTITY: AtomicU64 = AtomicU64::new(1);

fn next_target_identity() -> u64 {
    NEXT_TARGET_IDENTITY.fetch_add(1, Ordering::Relaxed)
}

/// The identity currently in force for each debug client, so one **outlives the wrapper it was
/// issued to**.
///
/// A borrowed engine is built afresh around the same `IDebugClient6` for every extension
/// command, so its identity has to be stable across those wrappers or each command misses every
/// cache. Deriving it from the client pointer did that, and lost each wrapper's lifecycle with
/// the wrapper: an `end_session` bumped a field on a value dropped moments later, so the next
/// wrapper restored the original pointer-derived identity and could be served a snapshot
/// gathered from the target before it. The identity lives here instead, where the bump survives.
///
/// An entry is only ever cache warmth. Forgetting one costs a re-resolve and a re-walk, never a
/// stale answer, since a fresh identity matches nothing — which is why this can simply drop
/// everything when it grows rather than needing an eviction policy to reason about.
///
/// **What it does not fix**: a client the *host* released, with another allocated at the same
/// address, inherits the first one's identity. Every client this code creates itself reissues
/// instead — see [`DebugEngine::new`] and [`DebugEngine::create_from_windbg_client`] — so what
/// is left is the case we cannot observe. That was equally true of the pointer-derived scheme
/// this replaces, and closing it needs an identity read from the debuggee rather than from the
/// client holding it.
fn client_identities() -> &'static Mutex<HashMap<usize, u64>> {
    static IDENTITIES: OnceLock<Mutex<HashMap<usize, u64>>> = OnceLock::new();
    IDENTITIES.get_or_init(Mutex::default)
}

/// How many clients' identities to remember before dropping the lot; see [`client_identities`]
/// for why dropping them is safe. Sized well past the handful of clients any real host holds —
/// the extension reuses exactly one — so reaching it means something is creating clients in a
/// loop, and that is the case worth bounding.
const MAX_REMEMBERED_CLIENTS: usize = 64;

fn client_key(client: &IDebugClient6) -> usize {
    client.as_raw() as usize
}

/// The registry, recovered if a thread panicked while holding it.
///
/// Poisoning carries nothing here: the map holds `u64` and no invariant a panic could leave
/// half-applied. Propagating it would, though — `from_client_interface` is infallible, so one
/// unrelated panic would turn every later wrap into a second one. Same recovery as
/// [`DebugEngine::release_deferred_inputs`].
fn locked_identities() -> MutexGuard<'static, HashMap<usize, u64>> {
    client_identities()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

/// The identity in force for `client`, issuing one if this is the first wrapper to ask.
fn identity_of(client: &IDebugClient6) -> u64 {
    identity_for(client_key(client))
}

/// Issues a fresh identity for `client` and records it, so nothing cached against the target it
/// is letting go of can be handed to a later wrapper around the same client.
fn reissue_identity(client: &IDebugClient6) -> u64 {
    reissue_for(client_key(client))
}

/// The two above, over the key rather than the COM pointer it comes from — which is all the
/// registry deals in, and all a test of it needs.
fn identity_for(key: usize) -> u64 {
    let mut identities = locked_identities();
    // Only a client we have never seen can push the map over its cap, and only then is
    // anything dropped. Clearing before the lookup would take the identity of the very client
    // being asked about — a live one, mid-session — and hand it a new one, which is a cache
    // thrown away for the caller that arrived rather than for the ones that left.
    if !identities.contains_key(&key) && identities.len() >= MAX_REMEMBERED_CLIENTS {
        identities.clear();
    }
    *identities.entry(key).or_insert_with(next_target_identity)
}

fn reissue_for(key: usize) -> u64 {
    let identity = next_target_identity();
    locked_identities().insert(key, identity);
    identity
}

pub struct DebugEngine {
    client: IDebugClient6,
    control: IDebugControl4,
    dataspaces: IDebugDataSpaces4,
    symbols: IDebugSymbols3,
    /// Whether this engine opened its own session (via `DebugCreate`) and is thus
    /// responsible for ending it on `Drop`. False when wrapping a borrowed WinDbg
    /// client, so going out of scope can't stop the host's active session.
    owns_session: bool,
    /// Input buffers handed to DbgEng by a *deferred* call — `CreateProcessWide`, which
    /// spawns at the next `WaitForEvent` and reads the command line then, and the kernel
    /// connection string, whose link is likewise established during the wait.
    ///
    /// They live here, not in [`PendingTarget`], because the engine is what DbgEng reads
    /// them on behalf of and the guard's lifetime is the caller's to end. A guard that
    /// owned them would be a use-after-free the moment it was dropped without waiting — and
    /// the alternative, waiting from `Drop`, can block without bound on a kernel attach
    /// whose link is still coming up (`SetInterrupt` cannot cancel that wait; see
    /// [`DebugEngine::wait_for_event_bounded`]). Owning them here costs one small
    /// allocation per open, released when the session ends.
    ///
    /// **Why not release each entry as soon as its `wait()` succeeds?** It looks safe — the
    /// spawn has happened, the link is up — but that is an inference about DbgEng's
    /// internals, not a documented guarantee, and `.restart` re-launches a process from the
    /// original command line. If the engine kept the caller's pointer for that, an early
    /// release would be a use-after-free, which is the one bug this field exists to prevent.
    /// End of session is the only release point that needs no such inference. The cost is a
    /// per-open allocation retained until then, and — for a *borrowed* client, which never
    /// reaches `end_session` — retained for good. Verifying on hardware that DbgEng does not
    /// re-read the buffer (drive `.restart` after a `launch_process`) is what would make a
    /// tighter release safe.
    deferred_inputs: Mutex<Vec<TargetInput>>,
    /// Whether an interrupt has been raised on this engine and not yet accounted for. Shared with
    /// every [`InterruptHandle`] this engine hands out; see there for what it buys.
    interrupt_raised: Arc<AtomicBool>,
    /// The system pids of live user-mode processes this engine **attached** to rather than
    /// created — the ones ending the session must let go of rather than take with it.
    ///
    /// Read by [`Self::end_session`] and by `Drop`, which is why it lives here rather than being
    /// passed in at teardown: a caller can end a session explicitly, but nothing gets to say
    /// anything when the engine is simply dropped, and a process this crate did not create should
    /// survive either ending. It is the same asymmetry [`Self::resume_and_detach_live_kernel`]
    /// exists for, on the target type that had never been given it.
    ///
    /// **A set of pids rather than a flag about the session**, which two rounds of review argued
    /// its way to and is worth keeping in one piece. DbgEng holds **several** user-mode processes
    /// in one session — `|` lists them, and says `attach` or `create` against each — so an engine
    /// can be attached to somebody's service *and* have launched a program of its own, and a
    /// session-wide answer is wrong for one of them whichever way it goes. Provenance is per
    /// process because the fact is.
    ///
    /// **Recorded by the opener rather than asked of DbgEng.** `|` knows, but that is text; the
    /// API does not expose it (`GetDebuggeeType` answers `DEBUG_CLASS_USER_WINDOWS` /
    /// `DEBUG_USER_WINDOWS_PROCESS` for a launch and an attach alike), and parsing a debugger's
    /// human output to decide whether to kill somebody's process is not a thing to build.
    ///
    /// **Per wrapper, not per client**, which is a deliberate difference from the target identity
    /// beside it and was raised in review as a defect. Two wrappers around one `IDebugClient6`
    /// would not see each other's attachments — true, and it is the same for `deferred_inputs`,
    /// because a session belongs to the wrapper that opened it. The identity registry is keyed by
    /// client for a reason that does not transfer: it is a **cache tag**, so losing one costs a
    /// re-read, and that is what lets it have a cap and evict. Losing an attachment kills
    /// somebody's process. Sharing this the same way would put the crate's most consequential
    /// decision behind an eviction policy, to serve an arrangement nothing here makes — the
    /// extension's borrowed wrapper never attaches and never ends a session.
    attached_processes: Mutex<std::collections::HashSet<u32>>,
}

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

unsafe impl Sync for DebugEngine {}
unsafe impl Send for DebugEngine {}

impl DebugEngine {
    /// Creates a new instance of the Debug Engine client
    pub fn new() -> Self {
        // Create the debug client
        let client: IDebugClient6 =
            unsafe { windows::Win32::System::Diagnostics::Debug::Extensions::DebugCreate() }
                .expect("[-] Failed to create debug client");

        // We opened this session, so we own its teardown.
        let mut engine = Self::from_client_interface(client);
        engine.owns_session = true;
        // A client this new cannot be one anything holds a cached view of — whatever address
        // it landed on. Reissuing rather than adopting whatever `identity_of` found there is
        // what makes a recycled pointer harmless for the case we control.
        reissue_identity(&engine.client);
        engine
    }

    /// Connects to a debugging **server** — an engine running in another process — and drives
    /// its session over DbgEng's remote transport.
    ///
    /// `remote_options` is the connection string `cdb -remote` takes:
    /// `npipe:pipe=<name>,server=<host>` or `tcp:port=<n>,server=<host>`. The server side is
    /// any engine host started with the matching `-server` option.
    ///
    /// The reason to reach for this over [`Self::new`] is that **an extension loads in the
    /// server**, where it meets the target, rather than in this process. So an engine host of a
    /// different architecture can run one this process could never load — a 32-bit `sos.dll`
    /// against a 32-bit CLR, driven from an x64 caller, which no in-process arrangement can do
    /// because the CLR data access DLL is architecture-paired to the target as well as the host.
    ///
    /// **The session belongs to the server, so this engine is a borrowed one**
    /// (`owns_session` stays false, via [`Self::try_from_client_interface`]): dropping it
    /// disconnects this client and leaves the server's target alone. Ending that target is the
    /// business of whoever started the host — and on a remote client `EndSession` would reach
    /// across and tear down a session this process never opened.
    ///
    /// Two measured properties of the remote transport, both surprising enough to state here:
    ///
    /// - **A remote client refuses `QueryInterface` for `IUnknown`** (`0x80010103`), so
    ///   [`Self::try_from_windbg_client`] — which takes an `&IUnknown` — cannot be used to wrap
    ///   one. That is why this goes through the typed constructor. `IDebugControl4`,
    ///   `IDebugDataSpaces4`, `IDebugSymbols3` and `IDebugAdvanced2` are all present.
    /// - **`IDebugAdvanced2::GetSymbolInformation` does not cross the transport**, so
    ///   [`Self::module_pdb`] fails with `E_INVALIDARG` against any remote session. Measured
    ///   with the client and server on the *same* architecture as well as across x86/x64, and
    ///   against an in-process engine on the same target where it succeeds — so it is the
    ///   transport rather than a struct whose size the two ends disagree about. Everything else
    ///   this type offers was exercised over a remote session and works.
    ///
    /// A version skew between the two engines is reported as `0x8007053D`, *"The server is
    /// currently disabled"*, which names neither end: a client whose `dbgeng.dll` is older than
    /// the server's is refused. Load both from the same debugger package.
    pub fn connect(remote_options: &str) -> Result<Self, DbgEngError> {
        let wide: Vec<u16> = remote_options
            .encode_utf16()
            .chain(std::iter::once(0))
            .collect();
        let mut raw: *mut std::ffi::c_void = std::ptr::null_mut();
        // SAFETY: `wide` is NUL-terminated and outlives the call, and `raw` receives an owned
        // interface pointer on success — taken over by the `from_raw` below.
        unsafe {
            DebugConnectWide(
                PCWSTR::from_raw(wide.as_ptr()),
                &IDebugClient6::IID,
                &raw mut raw,
            )
        }
        .map_err(|source| DbgEngError::Context {
            operation: format!("connecting to the debugging server at `{remote_options}`"),
            source,
        })?;
        // SAFETY: the call above returned success, so `raw` is an owned `IDebugClient6`.
        let client: IDebugClient6 = unsafe { IDebugClient6::from_raw(raw) };
        let engine = Self::try_from_client_interface(client)?;
        // A client this new cannot be one anything holds a cached view of, whatever address it
        // landed on — the same reasoning as [`Self::new`], and it applies here for the same
        // reason: this call, not the caller, is what created the pointer.
        reissue_identity(&engine.client);
        Ok(engine)
    }

    pub fn from_windbg_client(client: &IUnknown) -> Self {
        let client: IDebugClient6 = client.cast().expect("[-] Failed to cast debug client");
        Self::from_client_interface(client)
    }

    /// Fallible counterpart used by native extension callbacks.  Extension entry
    /// points must translate bad client interfaces to HRESULTs instead of panicking.
    pub fn try_from_windbg_client(client: &IUnknown) -> Result<Self, DbgEngError> {
        let client: IDebugClient6 = client.cast().map_err(|source| DbgEngError::Context {
            operation: "querying IDebugClient6".into(),
            source,
        })?;
        Self::try_from_client_interface(client)
    }

    pub fn create_from_windbg_client(client: &IUnknown) -> Self {
        let client: IDebugClient6 = client.cast().expect("[-] Failed to cast debug client");
        let new_client = unsafe {
            client
                .CreateClient()
                .expect("[-] Failed to create debug client")
        }
        .cast::<IDebugClient6>()
        .expect("[-] Failed to cast debug client");
        // `CreateClient` hands back a client this code just made, so — exactly as in `new` — it
        // cannot be one anything holds a cached view of, whatever address it landed on.
        // Adopting what `identity_of` found there would inherit a released client's identity
        // the moment the allocator reused its address.
        let engine = Self::from_client_interface(new_client);
        reissue_identity(&engine.client);
        engine
    }

    pub fn from_client_interface(client: IDebugClient6) -> Self {
        let control: IDebugControl4 = client
            .cast::<IDebugControl4>()
            .expect("[-] Failed to get debug control interface");

        let dataspaces: IDebugDataSpaces4 = client
            .cast::<IDebugDataSpaces4>()
            .expect("[-] Failed to get debug data spaces interface");

        let symbols: IDebugSymbols3 = client
            .cast::<IDebugSymbols3>()
            .expect("[-] Failed to get debug symbols interface");

        Self {
            client,
            control,
            dataspaces,
            symbols,
            // Default to "borrowed": constructors that wrap an existing WinDbg client
            // go through here, and only `new()` (which calls `DebugCreate`) sets this.
            owns_session: false,
            deferred_inputs: Mutex::new(Vec::new()),
            interrupt_raised: Arc::new(AtomicBool::new(false)),
            attached_processes: Mutex::new(std::collections::HashSet::new()),
        }
    }

    pub fn try_from_client_interface(client: IDebugClient6) -> Result<Self, DbgEngError> {
        let control = client
            .cast::<IDebugControl4>()
            .map_err(|source| DbgEngError::Context {
                operation: "querying IDebugControl4".into(),
                source,
            })?;
        let dataspaces =
            client
                .cast::<IDebugDataSpaces4>()
                .map_err(|source| DbgEngError::Context {
                    operation: "querying IDebugDataSpaces4".into(),
                    source,
                })?;
        let symbols = client
            .cast::<IDebugSymbols3>()
            .map_err(|source| DbgEngError::Context {
                operation: "querying IDebugSymbols3".into(),
                source,
            })?;
        Ok(Self {
            client,
            control,
            dataspaces,
            symbols,
            owns_session: false,
            deferred_inputs: Mutex::new(Vec::new()),
            interrupt_raised: Arc::new(AtomicBool::new(false)),
            attached_processes: Mutex::new(std::collections::HashSet::new()),
        })
    }

    /// A handle another thread can use to Ctrl+Break whatever this engine is running.
    ///
    /// The engine stays confined to its own thread; this is the one thing about it that may be
    /// touched from outside, and only because `SetInterrupt` is documented as safe there. See
    /// [`InterruptHandle`].
    pub fn interrupt_handle(&self) -> InterruptHandle {
        InterruptHandle {
            control: self.control.clone(),
            raised: Arc::clone(&self.interrupt_raised),
        }
    }

    /// A value that identifies the target this engine currently holds.
    ///
    /// Changes when the engine is replaced *or* when it releases its target, so a cache
    /// keyed on it cannot serve data gathered from a previous target. The kernel base is
    /// not sufficient on its own: two dumps from the same boot share it.
    ///
    /// Read from the registry keyed on this engine's *client* — see [`client_identities`] —
    /// rather than from a copy taken when this wrapper was built. Two things follow, and both
    /// are the point:
    ///
    /// - a host that rebuilds its engine around one client, as a WinDbg extension does per
    ///   command, keeps its caches across the rebuild *and* cannot lose a release an earlier
    ///   wrapper performed;
    /// - two wrappers coexisting around one client agree. A copy in each would not: an
    ///   `end_session` through one would move that one and the registry, leaving the other
    ///   answering with an identity whose target is gone, and a cache keyed on it would be
    ///   served for whatever was opened next.
    ///
    /// A client whose entry was dropped to keep the registry bounded is issued a later
    /// identity here, never an earlier one. That costs a re-walk, and — in the one case that
    /// compares two reads, [`Self::set_scope`] — a restore refused rather than a restore onto
    /// the wrong target. Both are the safe direction.
    pub fn target_identity(&self) -> u64 {
        identity_of(&self.client)
    }

    pub fn read_memory(&self, address: u64, size: usize) -> Result<Vec<u8>, DbgEngError> {
        let size_u32 = u32::try_from(size).map_err(|_| DbgEngError::BufferTooLarge(size))?;
        let mut buffer = vec![0; size];
        let mut read = 0u32;
        unsafe {
            self.dataspaces.ReadVirtual(
                address,
                buffer.as_mut_ptr().cast(),
                size_u32,
                Some(&mut read),
            )
        }
        .map_err(|source| DbgEngError::Context {
            operation: format!("reading {size} bytes of virtual memory at {address:#x}"),
            source,
        })?;
        if read as usize != size {
            return Err(DbgEngError::ShortRead {
                address,
                requested: size,
                actual: read as usize,
            });
        }

        Ok(buffer)
    }

    pub fn kernel_base(&self) -> Result<u64, DbgEngError> {
        let name = CString::new("nt").unwrap();
        let mut base = 0u64;
        unsafe {
            self.symbols.GetModuleByModuleName(
                PCSTR::from_raw(name.as_ptr().cast()),
                0,
                None,
                Some(&mut base),
            )
        }
        .map_err(|source| DbgEngError::Context {
            operation: "discovering the nt kernel base".into(),
            source,
        })?;
        Ok(base)
    }

    /// Where `nt` is loaded **and which build it is**.
    ///
    /// The base alone does not identify a kernel. Two targets from different Windows builds can
    /// load `nt` at the same address — the debugger says nothing about the change — so anything
    /// caching type offsets or globals against a base can serve one build's layout for another
    /// and mis-decode every structure it reads, confidently. That is what this exists for; see
    /// [`Self::kernel_base`] when only the address is wanted.
    ///
    /// `TimeDateStamp` and `SizeOfImage` are the identity a symbol server keys the *binary* on
    /// — the `65F579991450000` in a downloaded `ntkrnlmp.exe` path is exactly this pair — so
    /// they change with the build by construction. `CheckSum` comes along because it is in the
    /// same read and narrows it further.
    ///
    /// One caveat worth knowing: a target whose headers the engine could not read reports these
    /// as zero, and two such builds at one base are indistinguishable again. That is the state
    /// this replaced, not a regression from it.
    pub fn kernel_image(&self) -> Result<KernelImage, DbgEngError> {
        let base = self.kernel_base()?;
        let mut params = DEBUG_MODULE_PARAMETERS::default();
        // Looked up by base rather than by index: `GetModuleByModuleName` hands back an
        // address, and asking for the parameters of *that* module is one call, where finding
        // its index first would be two and could race a module list that changed between them.
        unsafe {
            self.symbols
                .GetModuleParameters(1, Some(&base), 0, &mut params)
        }
        .map_err(|source| DbgEngError::Context {
            operation: format!("reading the parameters of the kernel image at {base:#x}"),
            source,
        })?;
        Ok(KernelImage {
            base,
            size: params.Size,
            timestamp: params.TimeDateStamp,
            checksum: params.Checksum,
        })
    }

    pub fn symbol_offset(&self, name: &str) -> Result<u64, DbgEngError> {
        let name = CString::new(name).map_err(|_| DbgEngError::InvalidCommand)?;
        unsafe {
            self.symbols
                .GetOffsetByName(PCSTR::from_raw(name.as_ptr().cast()))
        }
        .map_err(|source| DbgEngError::Context {
            operation: format!("resolving symbol {}", name.to_string_lossy()),
            source,
        })
    }

    pub fn type_id(&self, module: u64, name: &str) -> Result<u32, DbgEngError> {
        let name = CString::new(name).map_err(|_| DbgEngError::InvalidCommand)?;
        unsafe {
            self.symbols
                .GetTypeId(module, PCSTR::from_raw(name.as_ptr().cast()))
        }
        .map_err(|source| DbgEngError::Context {
            operation: format!("resolving type {}", name.to_string_lossy()),
            source,
        })
    }

    pub fn type_size(&self, module: u64, type_id: u32) -> Result<u32, DbgEngError> {
        unsafe { self.symbols.GetTypeSize(module, type_id) }.map_err(|source| {
            DbgEngError::Context {
                operation: format!("resolving size of type id {type_id}"),
                source,
            }
        })
    }

    pub fn field_offset(&self, module: u64, type_id: u32, field: &str) -> Result<u32, DbgEngError> {
        let field = CString::new(field).map_err(|_| DbgEngError::InvalidCommand)?;
        unsafe {
            self.symbols
                .GetFieldOffset(module, type_id, PCSTR::from_raw(field.as_ptr().cast()))
        }
        .map_err(|source| DbgEngError::Context {
            operation: format!("resolving field {}", field.to_string_lossy()),
            source,
        })
    }

    /// Resolve a field's PDB type id and byte offset in one DbgEng call.
    pub fn field_type_and_offset(
        &self,
        module: u64,
        type_id: u32,
        field: &str,
    ) -> Result<(u32, u32), DbgEngError> {
        let field = CString::new(field).map_err(|_| DbgEngError::InvalidCommand)?;
        let mut field_type = 0u32;
        let mut offset = 0u32;
        unsafe {
            self.symbols.GetFieldTypeAndOffset(
                module,
                type_id,
                PCSTR::from_raw(field.as_ptr().cast()),
                Some(&mut field_type),
                Some(&mut offset),
            )
        }
        .map_err(|source| DbgEngError::Context {
            operation: format!(
                "resolving type and offset of field {}",
                field.to_string_lossy()
            ),
            source,
        })?;
        Ok((field_type, offset))
    }

    /// Enumerate the named fields DbgEng exposes for a PDB type.
    ///
    /// DbgEng has no field-count getter. Its documented enumeration contract is consecutive
    /// indices ending at the first failed `GetFieldName`, so a corrupt provider cannot turn
    /// this into an unbounded loop.
    pub fn field_names(&self, module: u64, type_id: u32) -> Vec<String> {
        const MAX_FIELDS: u32 = 4096;
        let mut fields = Vec::new();
        for index in 0..MAX_FIELDS {
            let name = read_engine_string(|buffer, size| unsafe {
                self.symbols
                    .GetFieldName(module, type_id, index, buffer, size)
            });
            match name {
                Ok(name) if !name.is_empty() => fields.push(name),
                Ok(_) | Err(_) => break,
            }
        }
        fields
    }

    /// The PEB of DbgEng's current process.
    pub fn current_process_peb(&self) -> Result<u64, DbgEngError> {
        let objects: IDebugSystemObjects =
            self.client.cast().map_err(|source| DbgEngError::Context {
                operation: "obtaining the system-objects interface".into(),
                source,
            })?;
        unsafe { objects.GetCurrentProcessPeb() }.map_err(|source| DbgEngError::Context {
            operation: "reading the current process PEB".into(),
            source,
        })
    }

    /// The operating-system process id of DbgEng's current process.
    pub fn current_process_system_id(&self) -> Result<u32, DbgEngError> {
        let objects: IDebugSystemObjects =
            self.client.cast().map_err(|source| DbgEngError::Context {
                operation: "obtaining the system-objects interface".into(),
                source,
            })?;
        unsafe { objects.GetCurrentProcessSystemId() }.map_err(|source| DbgEngError::Context {
            operation: "reading the current process id".into(),
            source,
        })
    }

    pub fn valid_virtual_region(
        &self,
        base: u64,
        size: usize,
    ) -> Result<(u64, usize), DbgEngError> {
        let size_u32 = u32::try_from(size).map_err(|_| DbgEngError::BufferTooLarge(size))?;
        let mut valid_base = 0;
        let mut valid_size = 0;
        unsafe {
            self.dataspaces
                .GetValidRegionVirtual(base, size_u32, &mut valid_base, &mut valid_size)
        }
        .map_err(|source| DbgEngError::Context {
            operation: format!("querying valid virtual region at {base:#x}"),
            source,
        })?;
        Ok((valid_base, valid_size as usize))
    }

    pub fn interrupted(&self) -> Result<bool, DbgEngError> {
        // The generated windows wrapper calls HRESULT::ok(), which deliberately
        // maps both S_OK and S_FALSE to Ok(()). GetInterrupt uses that distinction:
        // S_OK means Ctrl+C was requested and S_FALSE means it was not.
        let result = unsafe {
            (Interface::vtable(&self.control).GetInterrupt)(Interface::as_raw(&self.control))
        };
        match result {
            S_OK => Ok(true),
            S_FALSE => Ok(false),
            result => Err(DbgEngError::Context {
                operation: "polling debugger interrupt".into(),
                source: windows::core::Error::from_hresult(HRESULT(result.0)),
            }),
        }
    }

    fn output_inner(&self, text: &str, dml: bool) -> Result<(), DbgEngError> {
        // DbgEng's output parameter is printf-style. Doubling percent signs makes
        // user-controlled tags and diagnostics data rather than format directives.
        let escaped = text.replace('%', "%%");
        let message = CString::new(escaped).map_err(|_| DbgEngError::InvalidOutput)?;
        let outctl = if dml {
            DEBUG_OUTCTL_THIS_CLIENT | 0x20
        } else {
            DEBUG_OUTCTL_THIS_CLIENT
        };
        unsafe {
            self.control.ControlledOutput(
                outctl,
                DEBUG_OUTPUT_NORMAL,
                PCSTR::from_raw(message.as_ptr().cast()),
            )
        }
        .map_err(|source| DbgEngError::Context {
            operation: "writing debugger output".into(),
            source,
        })
    }

    pub fn output(&self, text: &str) -> Result<(), DbgEngError> {
        self.output_inner(text, false)
    }

    pub fn output_dml(&self, text: &str) -> Result<(), DbgEngError> {
        self.output_inner(text, true)
    }

    pub fn execution_status(&self) -> Result<u32, DbgEngError> {
        unsafe { self.control.GetExecutionStatus() }.map_err(|source| DbgEngError::Context {
            operation: "querying target execution status".into(),
            source,
        })
    }

    pub fn processor_type(&self) -> Result<u32, DbgEngError> {
        unsafe { self.control.GetActualProcessorType() }.map_err(|source| DbgEngError::Context {
            operation: "querying target processor type".into(),
            source,
        })
    }

    pub fn is_kernel_target(&self) -> Result<bool, DbgEngError> {
        let mut class = 0;
        let mut qualifier = 0;
        unsafe { self.control.GetDebuggeeType(&mut class, &mut qualifier) }.map_err(|source| {
            DbgEngError::Context {
                operation: "querying target type".into(),
                source,
            }
        })?;
        Ok(class == DEBUG_CLASS_KERNEL)
    }

    /// Asks the engine to break in as soon as a freshly attached target initializes
    /// (the equivalent of kd's `-b`), so a kernel attach stops the target at the
    /// connection's first event instead of letting it run free.
    fn request_initial_break(&self) -> Result<(), DbgEngError> {
        unsafe { self.control.AddEngineOptions(DEBUG_ENGOPT_INITIAL_BREAK) }
            .map_err(DbgEngError::OperationFailed)
    }

    /// Disarms the initial-break option once the target has stopped, so subsequent
    /// `go`/step run to real breakpoints instead of immediately re-breaking. Best-effort.
    fn clear_initial_break(&self) {
        unsafe {
            let _ = self.control.RemoveEngineOptions(DEBUG_ENGOPT_INITIAL_BREAK);
        }
    }

    /// Breaking into a live kernel via INITIAL_BREAK leaves *one further* break-in
    /// pending: the next resume re-breaks immediately at `nt!DbgBreakPointWithStatus`
    /// (the "CTRL+C/CTRL+BREAK" artifact) before the target makes progress. Consume it
    /// here — resume once and let it re-break — so the target is left cleanly halted and
    /// the caller's first real `go`/step runs to an actual breakpoint. Best-effort.
    fn absorb_initial_break_artifact(&self) {
        // The spurious re-break fires immediately on resume; a short bound keeps this
        // from hanging if (unexpectedly) it doesn't.
        let _ = self.execute_and_wait("g", 5_000);
    }

    /// Whether the current target is a *live* kernel connection (net/1394/serial/local/
    /// EXDI/IDNA) as opposed to a kernel dump or a user-mode target. A live kernel
    /// requires an INFINITE `WaitForEvent` timeout; a finite one returns `E_NOTIMPL`.
    fn is_live_kernel(&self) -> bool {
        let mut class = 0u32;
        let mut qualifier = 0u32;
        if unsafe { self.control.GetDebuggeeType(&mut class, &mut qualifier) }.is_err() {
            return false;
        }
        // Dump qualifiers are >= DEBUG_KERNEL_SMALL_DUMP; live connections are below it.
        class == DEBUG_CLASS_KERNEL && qualifier < DEBUG_KERNEL_SMALL_DUMP
    }

    /// Attaches to the local kernel and breaks in.
    ///
    /// Returns an error rather than panicking when the attach fails (e.g. the host
    /// was not booted with local kernel debugging enabled), so callers driving the
    /// engine on a worker thread can surface a clean message instead of unwinding.
    ///
    /// Fuses the attach with the break-in wait, so a failure cannot say which half
    /// failed. Use [`Self::attach_local_kernel_begin`] when that matters.
    pub fn attach_local_kernel(&self) -> Result<(), DbgEngError> {
        self.attach_local_kernel_begin()?.wait()
    }

    /// [`Self::attach_local_kernel`] up to — and not including — the break-in wait.
    ///
    /// An `Ok` means the engine has claimed the local kernel as its target, so attaching
    /// again is no longer a clean retry. See [`PendingTarget`].
    pub fn attach_local_kernel_begin(&self) -> Result<PendingTarget<'_>, DbgEngError> {
        self.request_initial_break()?;
        unsafe {
            self.client
                .AttachKernel(DEBUG_ATTACH_LOCAL_KERNEL, None)
                .map_err(DbgEngError::AttachFailed)?;
        }
        // A live kernel needs an INFINITE WaitForEvent (a finite timeout returns
        // E_NOTIMPL); INITIAL_BREAK makes it stop at the first event. `wait()` bounds it
        // so an unresponsive target can't hang the engine thread forever.
        self.forget_attachments();
        Ok(PendingTarget::new(self, WaitKind::KernelBreakIn))
    }

    /// Attaches to a kernel over a connection string (e.g. `net:port=50000,key=...`)
    /// and breaks in.
    ///
    /// Returns an error rather than panicking when the connection string is invalid or
    /// the attach fails (e.g. the transport/port is already owned by another debugger).
    ///
    /// # Blocks indefinitely if the target never connects
    ///
    /// **This call has no effective upper bound.** If the guest does not dial in — powered
    /// off, unreachable, wrong key, or (most commonly) not booted with `bcdedit /debug on` —
    /// it blocks in the transport like `kd` does, and the `KERNEL_ATTACH_WAIT_MS` watchdog
    /// cannot cancel it: `SetInterrupt` only reaches a wait whose target has *connected*.
    /// Measured at over 300s against a 60s bound before the run was killed.
    ///
    /// [`DbgEngError::KernelBreakTimeout`] therefore covers only a target that connects and
    /// *then* fails to break in — not the far more common case of one that never connects.
    ///
    /// Callers that must stay responsive (a server, an MCP endpoint) need a **separate process
    /// they can kill**. Moving the call to a worker thread and abandoning it is not a recovery:
    /// detaching a `JoinHandle` frees nothing, so the thread, its stack, this `DebugEngine`, its
    /// COM objects and the claimed transport endpoint all live on, still blocked, for the life
    /// of the process. Retrying then leaks another set and can find the endpoint still held.
    /// Nothing can interrupt the wait from outside, so the only way to reclaim the resources is
    /// to exit the process holding them.
    ///
    /// Fuses the attach with the break-in wait, so a failure cannot say which half
    /// failed. Use [`Self::attach_kernel_begin`] when that matters.
    pub fn attach_kernel(&self, connection_string: &str) -> Result<(), DbgEngError> {
        self.attach_kernel_begin(connection_string)?.wait()
    }

    /// [`Self::attach_kernel`] up to — and not including — the break-in wait.
    ///
    /// An `Ok` means the engine has taken the connection, so dialing again is no longer a
    /// clean retry — it re-dials a link that may already be up. See [`PendingTarget`].
    pub fn attach_kernel_begin(
        &self,
        connection_string: &str,
    ) -> Result<PendingTarget<'_>, DbgEngError> {
        let connection =
            CString::new(connection_string).map_err(|_| DbgEngError::InvalidCommand)?;

        self.request_initial_break()?;
        unsafe {
            self.client
                .AttachKernel(
                    DEBUG_ATTACH_KERNEL_CONNECTION,
                    PCSTR::from_raw(connection.as_ptr() as *const u8),
                )
                .map_err(DbgEngError::AttachFailed)?;
        }
        // Live kernel: INFINITE wait is mandatory (finite → E_NOTIMPL). INITIAL_BREAK
        // above makes the engine stop once the KDNET link establishes, and `wait()` bounds
        // it so an unreachable target can't hang the engine thread forever. The connection
        // string rides along because that link is only established during the wait.
        self.retain_deferred_input(TargetInput::Ansi(connection));
        self.forget_attachments();
        Ok(PendingTarget::new(self, WaitKind::KernelBreakIn))
    }

    /// Shared tail of the kernel attach paths: wait (bounded) for the INITIAL_BREAK stop,
    /// clear the option, and absorb the one spurious re-break it leaves. Returns
    /// [`DbgEngError::KernelBreakTimeout`] if the target never broke in within the bound,
    /// rather than reporting a false success.
    ///
    /// That covers a target that *connects* and then fails to break in — wedged, or spinning
    /// somewhere the break-in cannot be serviced. A target that never connects at all does not
    /// reach this error: the watchdog cannot interrupt a dial that has not established its
    /// link, so the wait blocks instead — see [`Self::wait_for_event_bounded`]. Note that a
    /// guest not booted with `bcdedit /debug on` is the *second* case, not the first: it never
    /// dials, so it hangs rather than timing out.
    fn wait_for_kernel_break_in(&self) -> Result<(), DbgEngError> {
        let (waited, timed_out) = self.wait_for_event_bounded(KERNEL_ATTACH_WAIT_MS);
        self.clear_initial_break();
        waited.map_err(DbgEngError::CommandFailed)?;
        // If the watchdog forced the wait to return, the target never reached its
        // INITIAL_BREAK on its own within the bound — the stop (if any) is a forced
        // Ctrl+Break, not the clean break-in. Report a timeout and skip the absorb (there
        // is no INITIAL_BREAK artifact to consume). Also treat a wait that returned with
        // no debuggee as a timeout, defensively.
        let status =
            unsafe { self.control.GetExecutionStatus() }.map_err(DbgEngError::CommandFailed)?;
        if timed_out || status == DEBUG_STATUS_NO_DEBUGGEE {
            return Err(DbgEngError::KernelBreakTimeout);
        }
        self.absorb_initial_break_artifact();
        Ok(())
    }

    /// Sets (replaces) the symbol search path.
    pub fn set_symbol_path(&self, symbol_path: &str) -> Result<(), DbgEngError> {
        let path = CString::new(symbol_path).map_err(|_| DbgEngError::InvalidCommand)?;
        unsafe {
            self.symbols
                .SetSymbolPath(PCSTR::from_raw(path.as_ptr() as *const u8))
                .map_err(DbgEngError::SymbolPathFailed)
        }
    }

    /// Appends a directory (or `srv*` spec) to the symbol search path, preserving the
    /// existing entries (e.g. the OS symbol server). Goes through the DbgEng API, so
    /// unlike the `.sympath+` command it takes only a path and cannot swallow trailing
    /// `;`-separated commands.
    pub fn append_symbol_path(&self, symbol_path: &str) -> Result<(), DbgEngError> {
        let path = CString::new(symbol_path).map_err(|_| DbgEngError::InvalidCommand)?;
        unsafe {
            self.symbols
                .AppendSymbolPath(PCSTR::from_raw(path.as_ptr() as *const u8))
                .map_err(DbgEngError::SymbolPathFailed)
        }
    }

    /// Executes a debug command and returns its full textual output.
    ///
    /// Refuses with [`DbgEngError::NoDebuggee`] when the engine holds no target: arbitrary text
    /// reaching an engine in that state can fault the process, and this cannot tell which text
    /// would. See [`Self::refuse_without_a_debuggee`].
    pub fn execute_command(&self, command: &str) -> Result<String, DbgEngError> {
        self.refuse_without_a_debuggee()?;
        self.execute_fixed_command(command)
    }

    /// [`Self::execute_command`] without the no-debuggee guard, for this crate's own command
    /// literals.
    ///
    /// The guard refuses everything because it cannot tell caller text that reaches execution
    /// from text that does not. A literal written *here* is known text, and one of them has to
    /// run before a target exists: `sxe ibp` is how [`Self::launch_process_begin`] and
    /// [`Self::attach_process_begin`] arm the initial break, on an engine that is holding
    /// nothing at the time.
    ///
    /// **Nothing that can reach execution may be passed here**, and nothing a caller supplied.
    /// The fault the guard prevents is a `STATUS_ACCESS_VIOLATION` inside DbgEng, which no
    /// `catch_unwind` traps.
    fn execute_fixed_command(&self, command: &str) -> Result<String, DbgEngError> {
        // DbgEng reads a NUL-terminated C string; a `&str` is not NUL-terminated,
        // so build a `CString` and keep it alive for the duration of `Execute`.
        let cmd_c = CString::new(command).map_err(|_| DbgEngError::InvalidCommand)?;
        let cmd = PCSTR::from_raw(cmd_c.as_ptr() as *const u8);

        // Buffer accumulates output across the many Output() callbacks DbgEng emits
        // (one per chunk/line) — it must append, not overwrite.
        let mut output_buffer = Vec::<u8>::with_capacity(4096);
        let output_callbacks = OutputCallbacks::new(&mut output_buffer);
        let output_interface: IDebugOutputCallbacks = output_callbacks.into();

        // Set the output callbacks
        unsafe {
            self.client
                .SetOutputCallbacks(Some(&output_interface))
                .map_err(DbgEngError::CommandFailed)?;
        }

        // Execute the command
        let result = unsafe {
            self.control
                .Execute(DEBUG_OUTCTL_THIS_CLIENT, cmd, DEBUG_EXECUTE_ECHO)
        };

        // Always detach the callbacks before `output_interface`/`output_buffer` drop.
        unsafe {
            let _ = self.client.SetOutputCallbacks(None);
        }

        result.map_err(DbgEngError::CommandFailed)?;

        Ok(String::from_utf8_lossy(&output_buffer).to_string())
    }

    /// Like [`Self::execute_command`], but **bounded**: a watchdog thread `SetInterrupt`s the
    /// engine after `timeout_ms` so a runaway command — most importantly a broad `s` memory
    /// search — aborts and frees the single engine thread instead of pinning it (every later
    /// call would otherwise block behind it). `SetInterrupt` is the one DbgEng call documented
    /// as safe from another thread (see [`InterruptHandle`]); a long command polls for it
    /// exactly as WinDbg's Ctrl+Break does.
    ///
    /// Returns [`CommandRun`]: whatever output was captured, **and** whether the command finished.
    /// A break — the watchdog's or a host's, through an [`InterruptHandle`] — is reported in
    /// `cut_short` rather than as an error, because the output up to it is the point; the `Execute`
    /// error it provokes is not surfaced. `timeout_ms == 0` disables the watchdog (equivalent to
    /// [`Self::execute_command`], plus the reporting).
    ///
    /// Refuses with [`DbgEngError::NoDebuggee`] when the engine holds no target — the same guard
    /// [`Self::execute_and_wait`] has, and for a hazard that is not confined to execution control:
    /// see [`Self::refuse_without_a_debuggee`]. That guard is also what lets
    /// [`CommandRun::target_gone`] be reported here at all: with one refused at the door, a
    /// missing debuggee afterwards means *this* command took the target away.
    ///
    /// **Both facts, or neither is usable.** Returning the text alone makes an aborted command
    /// indistinguishable from one that ran, so every caller downstream has to be told through some
    /// side channel — and each place that is forgotten reports a break as a fact about the target.
    /// Returning the error alone throws the output away, which on an interrupted search is all
    /// there was. Callers that want the note a human reads should render it from `cut_short`; it
    /// deliberately does not go into the text, since prose in a return value is a fact the next
    /// caller has to string-match for.
    pub fn execute_command_bounded(
        &self,
        command: &str,
        timeout_ms: u32,
    ) -> Result<CommandRun, DbgEngError> {
        self.refuse_without_a_debuggee()?;
        let cmd_c = CString::new(command).map_err(|_| DbgEngError::InvalidCommand)?;
        let cmd = PCSTR::from_raw(cmd_c.as_ptr() as *const u8);

        // Whatever was raised before this command belongs to the last one. A request that arrives
        // from here on is about what runs below; one left standing from an earlier operation would
        // otherwise make the *next* command swallow a genuine error as though it had been aborted.
        self.interrupt_raised.store(false, Ordering::SeqCst);

        let mut output_buffer = Vec::<u8>::with_capacity(4096);
        let output_callbacks = OutputCallbacks::new(&mut output_buffer);
        let output_interface: IDebugOutputCallbacks = output_callbacks.into();
        unsafe {
            self.client
                .SetOutputCallbacks(Some(&output_interface))
                .map_err(DbgEngError::CommandFailed)?;
        }

        // Arm a watchdog that Ctrl+Breaks the engine after `timeout_ms` so a long `Execute`
        // returns instead of hanging the engine thread. Mirrors `wait_for_event_bounded`.
        let watchdog = (timeout_ms > 0).then(|| {
            let handle = self.interrupt_handle();
            Watchdog::arm(Duration::from_millis(u64::from(timeout_ms)), move || {
                let _ = handle.interrupt();
            })
        });

        let result = unsafe {
            self.control
                .Execute(DEBUG_OUTCTL_THIS_CLIENT, cmd, DEBUG_EXECUTE_ECHO)
        };

        let by_watchdog = watchdog.is_some_and(Watchdog::disarm);

        // Always detach the callbacks before `output_interface`/`output_buffer` drop.
        unsafe {
            let _ = self.client.SetOutputCallbacks(None);
        }

        // Either origin aborts the command the same way, so both take the recovery below; only the
        // note is the watchdog's alone. Swapped rather than read, so a request that arrived while
        // this command ran is accounted for here and cannot be charged to the next one.
        let interrupted = by_watchdog | self.interrupt_raised.swap(false, Ordering::SeqCst);
        if interrupted {
            // The watchdog may have raised `SetInterrupt` right as `Execute` finished (or fired
            // once more before we joined it), leaving a Ctrl+Break pending with no command
            // running. Consume it via `GetInterrupt`, which does clear the pending flag.
            //
            // Retained as insurance, not as a fix for an observed bug. Measured against dbgeng
            // 10.0.26100.1 on a user-mode target (see the `#[ignore]`d tests below, which are
            // the record): `GetInterrupt` clears the flag, and the flag is a flag rather than a
            // counter — three `SetInterrupt`s still take one poll to clear. But a pending
            // interrupt did *not* abort a following command in any case tried, short or long:
            // a `version` produced byte-identical output drained and undrained, and a 38s
            // interrupt-polling `.for` ran to completion either way (37.94s vs 37.91s). The
            // engine appears to reset the request when `Execute` begins a command, which is
            // also how WinDbg behaves — a Ctrl+Break pressed while idle does not kill the next
            // command you type.
            //
            // So this is a no-op on the engine it was measured against. It costs one call on an
            // already-exceptional path, the behaviour is undocumented by Microsoft and may vary
            // by engine version, and the live-kernel path was not measured — which is why it
            // stays rather than being deleted on the strength of one environment.
            let _ = self.interrupted();
        }
        // A watchdog-forced interrupt makes `Execute` fail (or return partial output); that is
        // expected, so only propagate a genuine (non-interrupted) error.
        if !interrupted {
            result.map_err(DbgEngError::CommandFailed)?;
        }

        Ok(CommandRun {
            output: String::from_utf8_lossy(&output_buffer).to_string(),
            // Which origin, not merely that one happened: the advice differs. A deadline says
            // "scope it and retry", a request says "you asked" — and only the caller that renders
            // for a human needs either.
            cut_short: match (by_watchdog, interrupted) {
                (true, _) => Some(Interruption::Deadline {
                    after_ms: timeout_ms,
                }),
                (false, true) => Some(Interruption::OnRequest),
                (false, false) => None,
            },
            // Nothing here pumps, but a command can still take the target away by itself:
            // `.detach`, `q` and `qd` return with the engine already holding nothing, and no
            // later pump will ever mention it. The guard at the top is what makes this mean
            // "this command did it" rather than "there was never anything here".
            target_gone: self.lost_its_target(),
        })
    }

    /// Waits for the target to break
    pub fn wait_for_event(&self, timeout_ms: u32) -> Result<(), DbgEngError> {
        let result = unsafe { self.control.WaitForEvent(0, timeout_ms) };

        if result.is_err() {
            return Err(DbgEngError::CommandFailed(result.err().unwrap()));
        }

        Ok(())
    }

    /// `WaitForEvent` with the INFINITE timeout a live kernel requires, but **bounded**:
    /// after `timeout_ms` a watchdog thread Ctrl+Breaks the target via `SetInterrupt`
    /// (the one DbgEng call safe from another thread) so the wait returns instead of
    /// hanging the single engine thread forever — e.g. a `go`/step that never hits a
    /// breakpoint, or an attach whose target is reachable but won't break in.
    ///
    /// Returns the raw `WaitForEvent` result **and** a `bool` that is `true` when the
    /// watchdog had to force the return — in that case the stop is a forced Ctrl+Break,
    /// not the event the caller was waiting for, so callers must not treat it as a normal
    /// completion (e.g. an attach should report a timeout rather than a clean break-in).
    ///
    /// Limitation: `SetInterrupt` can only unblock a wait once the target is *connected*.
    /// A wait still establishing the KDNET link (e.g. an unreachable target) cannot be
    /// cancelled this way and will block like `kd` itself does on a dead connection.
    /// Measured (`cargo run --example kdtest -- --timeout-probe`, in-box dbgeng on Windows 11
    /// 26200): dialing a port nothing answers on returned from `AttachKernel` in ~8ms and was
    /// still blocked in this wait when killed at 300s — five times `timeout_ms`, no return.
    /// So the `bool` below can only ever be `true` for a target that connected; an
    /// unreachable one hangs instead of timing out.
    fn wait_for_event_bounded(&self, timeout_ms: u32) -> (windows::core::Result<()>, bool) {
        let handle = self.interrupt_handle();
        // Ctrl+Break a connected target so the engine thread's WaitForEvent returns with a stop.
        let watchdog = Watchdog::arm(Duration::from_millis(u64::from(timeout_ms)), move || {
            let _ = handle.interrupt();
        });
        let result = unsafe { self.control.WaitForEvent(0, WAIT_INFINITE) };
        (result, watchdog.disarm())
    }

    /// Issues an execution-control command (`g`, `t`, `p`, `g-`, `t-`, `p-`, …) and
    /// drives it to the next stop.
    ///
    /// Unlike [`Self::execute_command`], commands that *resume* the target only set the
    /// engine running when `Execute` returns — the target doesn't actually move until
    /// `WaitForEvent` pumps it. This captures output across both the command and the
    /// resulting execution (so e.g. a "Breakpoint N hit" message is included), which is
    /// what makes go/step (and TTD forward/reverse navigation) actually advance.
    ///
    /// `cut_short` says which of the three things happened, and a caller that ignores it reports
    /// "the target stopped here" for two cases where it did not. [`Interruption::OnRequest`] is a
    /// host asking through an [`InterruptHandle`]; [`Interruption::Deadline`] is `timeout_ms`
    /// passing with the target still going, so the break is this crate's own and the position is
    /// wherever the target happened to be; `None` is the target stopping on its own.
    ///
    /// **The wait is [`Self::wait_for_event_bounded`] for every target type, and that is load
    /// bearing rather than uniform-for-neatness.** A live kernel needs the INFINITE wait because a
    /// finite one returns `E_NOTIMPL` there — but a finite `WaitForEvent` is not usable on the
    /// others either, and fails far more quietly: on expiry it returns `S_FALSE` with the target
    /// **still running** and the engine holding no current process/thread, and nothing recovers
    /// from that. [`Self::run_to_address`] has said so since it was written, and used the bounded
    /// wait everywhere for that reason, while this function kept the finite one for user-mode,
    /// dumps and TTD. Measured on a user-mode target: one `go` with nothing to stop it left every
    /// later command — `bl`, `r`, `? @$ip` — failing with `0x80040205`, permanently.
    pub fn execute_and_wait(
        &self,
        command: &str,
        timeout_ms: u32,
    ) -> Result<CommandRun, DbgEngError> {
        // Whatever was raised before this belongs to the last operation; see
        // `execute_command_bounded`, which clears it for the same reason.
        self.interrupt_raised.store(false, Ordering::SeqCst);
        // Nothing to run against is refused up front rather than driven into DbgEng, which
        // faults the process on it — see `refuse_without_a_debuggee`. It is also what makes the
        // check *after* the wait mean what it says: a debuggee missing there left during this
        // call.
        self.refuse_without_a_debuggee()?;

        let cmd_c = CString::new(command).map_err(|_| DbgEngError::InvalidCommand)?;
        let cmd = PCSTR::from_raw(cmd_c.as_ptr() as *const u8);

        let mut output_buffer = Vec::<u8>::with_capacity(4096);
        let output_callbacks = OutputCallbacks::new(&mut output_buffer);
        let output_interface: IDebugOutputCallbacks = output_callbacks.into();

        unsafe {
            self.client
                .SetOutputCallbacks(Some(&output_interface))
                .map_err(DbgEngError::CommandFailed)?;
        }

        // Initiate execution, then pump events until the target stops again.
        let exec = unsafe {
            self.control
                .Execute(DEBUG_OUTCTL_THIS_CLIENT, cmd, DEBUG_EXECUTE_ECHO)
        };
        let (waited, by_watchdog) = if exec.is_ok() {
            self.wait_for_event_bounded(timeout_ms)
        } else {
            (Ok(()), false)
        };

        unsafe {
            let _ = self.client.SetOutputCallbacks(None);
        }

        // A break — either origin's — makes both of these fail, exactly as it does in
        // `execute_command_bounded` — and for the same reason the output must survive it, since a
        // `go` stopped on request has still moved the target and the caller needs to see where to.
        //
        // **The origin is decided by the watchdog's own flag, not by `interrupt_raised`**, which
        // the watchdog sets too (that is what `InterruptHandle::interrupt` does). Reading the
        // shared flag alone reports this crate's own deadline as "a host asked" — which it did on
        // the live-kernel path for as long as that path was the only bounded one, and would now
        // do so on every target.
        let interrupted = by_watchdog | self.interrupt_raised.swap(false, Ordering::SeqCst);
        // Asked before either error is propagated, because the target running out is what makes
        // both of them fail: a debuggee that exits during the wait leaves `WaitForEvent`
        // answering `E_UNEXPECTED`, and reporting that is reporting a program's ordinary ending
        // as a catastrophe — while discarding the output the run had already captured.
        let target_gone = self.lost_its_target();
        if interrupted {
            // As there: consume anything the engine did not, so the next operation starts clean.
            let _ = self.interrupted();
        } else if !target_gone {
            exec.map_err(DbgEngError::CommandFailed)?;
            waited.map_err(DbgEngError::CommandFailed)?;
        }

        Ok(CommandRun {
            output: String::from_utf8_lossy(&output_buffer).to_string(),
            cut_short: match (by_watchdog, interrupted) {
                (true, _) => Some(Interruption::Deadline {
                    after_ms: timeout_ms,
                }),
                (false, true) => Some(Interruption::OnRequest),
                (false, false) => None,
            },
            target_gone,
        })
    }

    /// Whether the engine has been *told to run* and is waiting to be pumped.
    ///
    /// This is the state a plain [`Self::execute_command`] leaves behind when the text it was
    /// given happened to be execution control — `g`, `p`, `t`, a `;` list ending in one, a script
    /// that reaches one. `Execute` sets the run state and returns; only a `WaitForEvent` moves the
    /// target. Until one does, the engine answers read-only commands normally and refuses every
    /// execution-control command with `0x80040205`, which reads as a half-alive session.
    ///
    /// Ask the engine rather than reading the command, because no list of command names can be
    /// exhaustive — the data model, an alias, and `.if` all reach execution without saying so.
    pub fn is_running(&self) -> Result<bool, DbgEngError> {
        Ok(is_running_status(self.execution_status()?))
    }

    /// Whether the engine is holding a target at all.
    ///
    /// One status value answers it, and it is the same value whether the engine has never had a
    /// target or has just lost one. Measured on dbgeng 10.0.26100.1 (ARM64): a debuggee that
    /// exits during a wait leaves `GetExecutionStatus` reading `DEBUG_STATUS_NO_DEBUGGEE`, with
    /// `GetNumberProcesses`, `GetCurrentProcessSystemId` and `GetExitCode` all failing
    /// `E_UNEXPECTED` beside it and `.lastevent` answering `<no event>` — so the status is the
    /// only one of them that says anything, and what it says is reliable.
    ///
    /// An unreadable status is not an answer, and this does not collapse one into `true`: what to
    /// do when the engine cannot be asked differs by caller, and each one below decides.
    ///
    /// Public because a caller holding a session needs it for the same reason this crate does —
    /// once the answer is `false`, nothing but teardown will work, and every road in refuses.
    pub fn has_target(&self) -> Result<bool, DbgEngError> {
        Ok(self.execution_status()? != DEBUG_STATUS_NO_DEBUGGEE)
    }

    /// Refuses an operation that would drive DbgEng with nothing behind it.
    ///
    /// **This is what stands between a caller's text and an access violation**, not a tidiness
    /// check. Execution control reaching an engine that holds no debuggee faults *inside* DbgEng
    /// — a structured exception, which `catch_unwind` cannot trap, so it takes the whole process
    /// down instead of failing the call. Measured twice on dbgeng 10.0.26100.1 (ARM64), each
    /// time a `STATUS_ACCESS_VIOLATION` exit: once on an engine whose debuggee had just exited,
    /// and once on a **fresh** engine that never had one. The second is what says the trigger is
    /// the missing debuggee rather than the departure.
    ///
    /// So it cannot be narrowed to text that looks like execution control: `g`, an alias, a
    /// `.if` branch and `dx …ExecuteCommand("g")` all reach it, and the list that would catch
    /// them cannot be finished — the same reason [`Self::settle`] asks the engine instead of
    /// reading the command. What the breadth costs is the few engine-level commands that do work
    /// without a target (`version`, `.echo`, `.sympath`), which are refused too.
    ///
    /// **And one of this crate's own openers is in that group**, which is not obvious and is why
    /// [`Self::execute_fixed_command`] exists: arming the initial break runs `sxe ibp` on an
    /// engine that by definition holds nothing yet, so guarding it refuses every
    /// [`Self::launch_process`] and [`Self::attach_process`] on the machine. The guard is about
    /// text a *caller* supplied; a literal written here is not that.
    fn refuse_without_a_debuggee(&self) -> Result<(), DbgEngError> {
        match self.has_target()? {
            true => Ok(()),
            false => Err(DbgEngError::NoDebuggee),
        }
    }

    /// Whether the engine has lost its target, asked after an operation that could have taken it.
    ///
    /// Asked of the engine rather than read off a `WaitForEvent` result, because that result is
    /// `E_UNEXPECTED` — "Catastrophic failure", which names nothing and is also what a genuinely
    /// broken engine answers — and because two of the four callers do not wait at all. Every one
    /// of them refuses to *start* without a debuggee, so a missing one here means the target left
    /// during this call.
    ///
    /// An unreadable status answers `false`. This decides whether to **suppress** the wait's
    /// error, and suppressing one on a guess would report a broken engine as a program that
    /// finished.
    fn lost_its_target(&self) -> bool {
        !self.has_target().unwrap_or(true)
    }

    /// Pumps the engine to a stop if a command left it running, and reports what happened:
    /// `Ok(None)` when there was nothing to settle, `Ok(Some(run))` with the output the pump
    /// captured otherwise — `cut_short` being [`Interruption::Deadline`] when the target had not
    /// stopped by `timeout_ms` and was broken in at the bound, and [`CommandRun::target_gone`]
    /// when the pump ended because the target *left* rather than stopped.
    ///
    /// That third answer is not a failure and must not be reported as one: running a program to
    /// completion is what a `g` is for, and it is the case where the pump's own output is the
    /// only copy there will ever be.
    ///
    /// This is the recovery for the state [`Self::is_running`] describes, and it is why that state
    /// need not be prevented by inspecting command text. Calling it after every plain `Execute`
    /// costs one `GetExecutionStatus` in the ordinary case.
    ///
    /// A `timeout_ms` of zero breaks the target in at once rather than disabling the bound — the
    /// same meaning it has for [`Self::run_to_address`], and the opposite of
    /// [`Self::execute_command_bounded`]'s. There is no "wait for ever" here on purpose: this runs
    /// on a path whose caller has already spent most of its budget.
    pub fn settle(&self, timeout_ms: u32) -> Result<Option<CommandRun>, DbgEngError> {
        if !self.is_running()? {
            return Ok(None);
        }
        // Whatever was raised before this belongs to the last operation; see
        // `execute_command_bounded`, which clears it for the same reason.
        self.interrupt_raised.store(false, Ordering::SeqCst);

        // Captured, because the pump is where the interesting output is: the command that set the
        // run state printed only its own echo, and the breakpoint banner, module loads and stop
        // reason all arrive here.
        let mut output_buffer = Vec::<u8>::with_capacity(4096);
        let output_callbacks = OutputCallbacks::new(&mut output_buffer);
        let output_interface: IDebugOutputCallbacks = output_callbacks.into();
        unsafe {
            self.client
                .SetOutputCallbacks(Some(&output_interface))
                .map_err(DbgEngError::CommandFailed)?;
        }

        let (waited, by_watchdog) = self.wait_for_event_bounded(timeout_ms);

        unsafe {
            let _ = self.client.SetOutputCallbacks(None);
        }

        // The same three-way origin as `execute_and_wait`, for the same reason: the watchdog's own
        // flag decides, because `interrupt_raised` is set by the watchdog too.
        let interrupted = by_watchdog | self.interrupt_raised.swap(false, Ordering::SeqCst);
        // And the same question after the wait, for the same reason — with more riding on it
        // here, because the pump is where the output is. A target that runs out mid-pump fails
        // the wait with `E_UNEXPECTED`, and propagating that threw away the breakpoint banner,
        // the module loads and anything an embedded script printed, precisely on the run that
        // has no successor to print them again.
        let target_gone = self.lost_its_target();
        if interrupted {
            let _ = self.interrupted();
        } else if !target_gone {
            waited.map_err(DbgEngError::CommandFailed)?;
        }

        Ok(Some(CommandRun {
            output: String::from_utf8_lossy(&output_buffer).to_string(),
            cut_short: match (by_watchdog, interrupted) {
                (true, _) => Some(Interruption::Deadline {
                    after_ms: timeout_ms,
                }),
                (false, true) => Some(Interruption::OnRequest),
                (false, false) => None,
            },
            target_gone,
        }))
    }

    /// Runs the target until it reaches `address` and reports a **structured** stop reason
    /// instead of raw text. A [`RunToOutcome::Hit`] confirms empirically that the current
    /// input/state actually drives execution to that block.
    ///
    /// Uses an explicitly managed breakpoint ([`ScopedBreakpoint`]) plus a plain `g`, so the
    /// breakpoint is removed on *every* exit path — hit, stopped elsewhere, timed out, or
    /// errored. The caller's own breakpoints are untouched.
    ///
    /// Every target type uses one wait: `WaitForEvent(INFINITE)` bounded by the same watchdog
    /// as [`Self::execute_and_wait`], so `timeout_ms` caps it and a target that never reaches
    /// `address` is left broken in rather than running.
    ///
    /// A *finite* `WaitForEvent` is not usable here even where DbgEng accepts one. It returns
    /// `S_FALSE` with the target still running and the engine holding no current
    /// process/thread, and nothing recovers from that — a subsequent `SetInterrupt` plus
    /// `WaitForEvent` never delivers a break, because the engine is no longer pumping events.
    /// Commands needing a current process (`bl` among them) fail from then on.
    ///
    /// Classification is by the actual stop, not the watchdog: a hit at `address` landing in
    /// the same window the deadline passes still reports [`RunToOutcome::Hit`]; only a break
    /// *elsewhere* is [`RunToOutcome::StoppedElsewhere`], and a target that had to be forced
    /// to a halt is [`RunToOutcome::Timeout`].
    ///
    /// `timeout_ms == 0` means an *immediate* timeout — the watchdog's deadline has already
    /// passed on its first check, so it interrupts at once and the result is a
    /// [`RunToOutcome::Timeout`] with the target barely resumed. Note this is the opposite of
    /// [`Self::execute_command_bounded`], where `0` disables the watchdog entirely. The
    /// asymmetry is deliberate: there, an unbounded command is a documented escape hatch
    /// (plain `execute_command`), whereas here "no bound" would mean waiting forever for a
    /// target that may never reach `address`, hanging the single engine thread — the exact
    /// outcome the watchdog exists to prevent.
    pub fn run_to_address(
        &self,
        address: u64,
        timeout_ms: u32,
    ) -> Result<RunToResult, DbgEngError> {
        // Refuse when there's nothing to run: driving `g` with no debuggee faults DbgEng in a
        // way `catch_unwind` cannot trap — see `refuse_without_a_debuggee`.
        self.refuse_without_a_debuggee()?;
        // An explicitly managed breakpoint, not `g <addr>`. WinDbg's one-shot form auto-clears
        // only when *hit* and hands back no handle, so every other exit — stopped elsewhere,
        // timed out, errored — left it armed with no way to remove it, and a later unrelated
        // `g` passing `address` could stop there spuriously. This guard removes it on every
        // path, including the `?` returns below.
        let _breakpoint = ScopedBreakpoint::at(self, address)?;

        let cmd_c = CString::new("g").map_err(|_| DbgEngError::InvalidCommand)?;
        let cmd = PCSTR::from_raw(cmd_c.as_ptr() as *const u8);

        let mut output_buffer = Vec::<u8>::with_capacity(4096);
        let output_callbacks = OutputCallbacks::new(&mut output_buffer);
        let output_interface: IDebugOutputCallbacks = output_callbacks.into();
        unsafe {
            self.client
                .SetOutputCallbacks(Some(&output_interface))
                .map_err(DbgEngError::CommandFailed)?;
        }

        let exec = unsafe {
            self.control
                .Execute(DEBUG_OUTCTL_THIS_CLIENT, cmd, DEBUG_EXECUTE_ECHO)
        };
        // One wait for every target type: `WaitForEvent(INFINITE)` bounded by a watchdog that
        // Ctrl+Breaks at `timeout_ms`. A *finite* wait cannot be used here even where DbgEng
        // allows one — it returns S_FALSE with the target still running and the engine holding
        // no current process/thread, and no interrupt afterwards recovers it, because the
        // engine is no longer pumping events. `expired` is then simply "the watchdog fired".
        let (waited, expired) = if exec.is_ok() {
            let (waited, forced) = self.wait_for_event_bounded(timeout_ms);
            // A forced return is reported as `Ok`, so only a genuine failure propagates.
            let waited = if forced {
                Ok(())
            } else {
                waited.map_err(DbgEngError::CommandFailed)
            };
            (waited, forced)
        } else {
            (Ok(()), false)
        };

        unsafe {
            let _ = self.client.SetOutputCallbacks(None);
        }

        let output = String::from_utf8_lossy(&output_buffer).to_string();

        // Read before the two errors below, which is what an exit makes of them: a target can
        // run out on the way to `address` as readily as during a plain `go`, and the same
        // `E_UNEXPECTED` comes back. Reported as an outcome with its output rather than as a
        // failure — see `RunToOutcome::TargetGone`.
        if self.lost_its_target() {
            return Ok(RunToResult {
                outcome: RunToOutcome::TargetGone,
                output,
            });
        }
        exec.map_err(DbgEngError::CommandFailed)?;
        waited?;

        if expired {
            // The watchdog has already broken the target in, so the caller is not left with a
            // running one. A hit landing in the same window as the deadline is still a hit, so
            // consult the instruction pointer before concluding otherwise — leniently, since a
            // failed read here means "no clean stop to report", which is the timeout.
            if self.instruction_pointer().ok() == Some(address) {
                return Ok(RunToResult {
                    outcome: RunToOutcome::Hit,
                    output,
                });
            }
            return Ok(RunToResult {
                outcome: RunToOutcome::Timeout,
                output,
            });
        }

        // The target stopped on its own.
        let rip = self.instruction_pointer()?;
        let outcome = if rip == address {
            RunToOutcome::Hit
        } else {
            RunToOutcome::StoppedElsewhere { stopped_at: rip }
        };
        Ok(RunToResult { outcome, output })
    }

    pub fn create_debug_event_context_callbacks(
        callback: Option<BreakpointCallback>,
    ) -> IDebugEventContextCallbacks {
        let callbacks = DebugEventContextCallbacks::new(callback);
        callbacks.into()
    }

    pub fn set_breakpoint_event_callbacks(&self, event_callbacks: IDebugEventContextCallbacks) {
        unsafe {
            self.client
                .SetEventContextCallbacks(Some(&event_callbacks))
                .expect("[-] Failed to set event callbacks");
        };
    }

    pub fn log(&self, message: &str) {
        let message = CString::new(message).expect("Failed to create CString");
        let message = PCSTR::from_raw(message.as_ptr() as *const u8);
        unsafe { self.control.Output(DEBUG_OUTPUT_NORMAL, message) }
            .expect("[-] Failed to log message");
    }

    /// Reloads symbols. `args` mirrors `.reload` arguments — e.g. "/f HEVD.sys" to
    /// force-load one module's symbols, or "" to reload all deferred modules.
    pub fn reload_symbols(&self, args: &str) -> Result<(), DbgEngError> {
        let args = CString::new(args).map_err(|_| DbgEngError::InvalidCommand)?;
        unsafe {
            self.symbols
                .Reload(PCSTR::from_raw(args.as_ptr() as *const u8))
                .map_err(DbgEngError::OperationFailed)
        }
    }

    /// Returns the current register set as formatted text (`r`).
    pub fn registers(&self) -> Result<String, DbgEngError> {
        self.execute_command("r")
    }

    /// Reads the engine's current [`Scope`], so it can be put back later.
    ///
    /// **What this is for.** Commands move the scope, and some move it as a side effect of
    /// answering an unrelated question. Measured against dbgeng `10.0.29547.1002` on four
    /// targets — a `0x13A` kernel bug check, a `0xD1` driver fault, a `0x9F` power-state
    /// watchdog, and a user-mode access violation: `!analyze -v` ends with the scope at the
    /// target's *default*, so a session that had frame 3 selected is on frame 0 afterwards, and
    /// one that had `.ecxr`'s context selected has lost it. Nothing was written to the debuggee
    /// — but two identical stack reads either side of the analysis describe different things,
    /// which is the same problem for a host that has to report which of its calls mutate state.
    /// Saving the scope first and restoring it after makes the analysis observably
    /// scope-neutral.
    ///
    /// The current thread and process are *not* part of a scope, and do not need restoring
    /// alongside one — for a better reason than "the analysis leaves them alone". It does move
    /// them: on the `0x9F`, where the thread `!analyze` blames is not the one the dump opens on,
    /// its output says `Implicit thread is now ffffe284fe4dd040` partway through. It puts them
    /// back before it returns, which the scope is precisely what it does *not* do.
    ///
    /// **Sizing the context blob.** `GetScope` neither reports nor negotiates the size of the
    /// context it wants: it rejects a buffer smaller than the target's `CONTEXT` with
    /// `E_INVALIDARG` and accepts any buffer at or above it, filling the front. (Measured on an
    /// x64 target, kernel and user-mode alike: 1231 bytes rejected, 1232 — the x64 `CONTEXT` —
    /// accepted, as is 4096.) So the ask walks [`SCOPE_CONTEXT_SIZES`] upward and keeps the
    /// first size the engine accepts, which is the smallest of them that covers the target's
    /// context. `sizeof(CONTEXT)` for *this* process would be the wrong number: the target's
    /// architecture is the engine's business, not the host's.
    ///
    /// **A scope with no register context is legitimate**, so if the engine will not answer the
    /// context form but will answer the contextless one (`GetScope` with no buffer, which is its
    /// own documented form), that is the scope — [`Scope::has_context`] says which happened, and
    /// [`Self::set_scope`] restores either.
    ///
    /// An engine with no target answers `E_UNEXPECTED` to both forms (measured: before any open,
    /// after `end_session`, and on a dump named but never waited for), and that comes back as an
    /// error rather than as an empty scope.
    pub fn scope(&self) -> Result<Scope, DbgEngError> {
        let mut refusal = None;
        for &size in SCOPE_CONTEXT_SIZES {
            let mut instruction = 0u64;
            let mut frame = DEBUG_STACK_FRAME::default();
            let mut context = vec![0u8; size as usize];
            match unsafe {
                self.symbols.GetScope(
                    Some(&mut instruction),
                    Some(&mut frame),
                    Some(context.as_mut_ptr().cast()),
                    size,
                )
            } {
                Ok(()) => {
                    return Ok(Scope {
                        instruction,
                        frame,
                        context,
                        target: self.target_identity(),
                    });
                }
                // "That buffer is too small for this target's context" — try the next size up.
                Err(why) if why.code() == E_INVALIDARG => refusal = Some(why),
                // Anything else is the engine declining to produce a context at all, which is
                // not the same as declining to produce a scope.
                Err(why) => {
                    refusal = Some(why);
                    break;
                }
            }
        }
        self.contextless_scope(refusal)
    }

    /// The scope with no register context — the fallback of [`Self::scope`], and the shape a
    /// target that has no thread context answers with. `refusal` is why the context form did
    /// not work, reported if this form fails too.
    fn contextless_scope(
        &self,
        refusal: Option<windows::core::Error>,
    ) -> Result<Scope, DbgEngError> {
        let mut instruction = 0u64;
        let mut frame = DEBUG_STACK_FRAME::default();
        unsafe {
            self.symbols
                .GetScope(Some(&mut instruction), Some(&mut frame), None, 0)
        }
        .map_err(|source| DbgEngError::Context {
            operation: "reading the debugger's scope".into(),
            // The context read is the one that was actually wanted, so its failure is the
            // one worth reporting when neither form works.
            source: refusal.unwrap_or(source),
        })?;
        Ok(Scope {
            instruction,
            frame,
            context: Vec::new(),
            target: self.target_identity(),
        })
    }

    /// Puts a [`Scope`] back — `.cxr`'s mechanism, with the engine's own bytes.
    ///
    /// Refused if the engine no longer holds the target the scope was read from: the frame and
    /// context describe *that* target's stack, and applying them to a later one would point the
    /// session at an address that means nothing there. This is the case a long-lived
    /// [`ScopeGuard`] hits when whatever it wrapped replaced the target underneath it.
    ///
    /// **What that check does and does not cover.** [`Self::target_identity`] is a per-engine
    /// generation, bumped when this engine is created and when `end_session` releases its
    /// target — so it catches the destructive case, a session ended and another opened, where
    /// the saved addresses are meaningless. It says nothing about *movement inside* one
    /// session, and there are two such cases:
    ///
    /// - **A different process or thread is current.** A scope is engine-global, not per-thread,
    ///   so a scope captured while one process was current is restored as-is while another is —
    ///   which is what `.cxr` does deliberately, and is wrong only if the caller did not mean it.
    ///   A guard wrapping one command is not exposed to this by a command that moves the thread
    ///   and moves it back, which is what `!analyze -v` was measured doing (see [`Self::scope`]):
    ///   what matters at the restore is where the thread ended up, not where it went.
    /// - **A borrowed WinDbg client whose host switched targets.** The identity is held per
    ///   client and reissued when an `end_session` goes through *this* engine, so a change
    ///   WinDbg makes on its own — opening another dump under an extension — does not move it.
    ///
    /// In both, the caller is the only one who can know, and a guard held across such a change
    /// restores a scope its target no longer means.
    pub fn set_scope(&self, scope: &Scope) -> Result<(), DbgEngError> {
        if scope.target != self.target_identity() {
            return Err(DbgEngError::ScopeFromAnotherTarget);
        }
        unsafe {
            self.symbols.SetScope(
                scope.instruction,
                Some(&scope.frame),
                // A scope that carried no context is restored as one: passing a buffer the
                // engine never gave us would be inventing register state.
                if scope.context.is_empty() {
                    None
                } else {
                    Some(scope.context.as_ptr().cast())
                },
                scope.context.len() as u32,
            )
        }
        .map_err(|source| DbgEngError::Context {
            operation: "restoring the debugger's scope".into(),
            source,
        })
    }

    /// Reads the current [`Scope`] and hands back a guard that restores it when dropped.
    ///
    /// The shape to wrap a scope-moving command in, because it puts the scope back on *every*
    /// path out — an early return, an error, a panic unwinding through the caller — which is
    /// exactly where a hand-written restore is forgotten:
    ///
    /// ```no_run
    /// # use dbgscope::dbgeng::DebugEngine;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let engine = DebugEngine::new();
    /// let analysis = {
    ///     let _scope = engine.scope_guard()?;
    ///     engine.execute_command("!analyze -v")?
    /// }; // the scope `!analyze` moved is back here
    /// # let _ = analysis;
    /// # Ok(())
    /// # }
    /// ```
    pub fn scope_guard(&self) -> Result<ScopeGuard<'_>, DbgEngError> {
        Ok(ScopeGuard {
            engine: self,
            saved: self.scope()?,
        })
    }

    /// The current register set as **values**, read through `IDebugRegisters`.
    ///
    /// The same registers [`Self::registers`] prints, minus the printing. `r` renders a target's
    /// context as a paragraph — `rax=0000000000000000 rbx=…`, the flags as mnemonics, the current
    /// instruction disassembled on the end — and a host that needs `rsp` as a number has to find
    /// it in there. That parse is the thing this exists to delete: the widths, the grouping and
    /// the flag spelling are all presentation, and they differ by processor, by target kind and by
    /// engine build.
    ///
    /// Every register the engine knows is returned, subregisters included (`eax` as well as
    /// `rax`), because which of those a caller wants depends on what they are doing —
    /// [`Register::subregister`] is how they narrow it.
    ///
    /// A register the engine cannot produce a value for is reported as
    /// [`RegisterValue::Unavailable`] rather than failing the call: a minidump carrying no
    /// floating-point state answers exactly that way for `st0`–`st7`, and losing the general
    /// registers over it would be absurd. An `Err` here means the *set* could not be read at all.
    pub fn register_values(&self) -> Result<Vec<Register>, DbgEngError> {
        let registers: IDebugRegisters =
            self.client.cast().map_err(|source| DbgEngError::Context {
                operation: "obtaining the register interface".into(),
                source,
            })?;
        let count =
            unsafe { registers.GetNumberRegisters() }.map_err(|source| DbgEngError::Context {
                operation: "counting the target's registers".into(),
                source,
            })?;
        let mut out = Vec::with_capacity(count as usize);
        for index in 0..count {
            let mut description = DEBUG_REGISTER_DESCRIPTION::default();
            let name = read_engine_string(|buffer, size| unsafe {
                registers.GetDescription(index, buffer, size, Some(&mut description))
            })
            .map_err(|source| DbgEngError::Context {
                operation: format!("describing register {index}"),
                source,
            })?;
            // Read one at a time rather than through `GetValues`, which fetches the whole bank in
            // one call: a bank read fails as a unit, and the failures worth surviving here are
            // per-register (the absent x87/vector state of a minidump). One call per register buys
            // the granularity that makes `Unavailable` an answer instead of an error.
            let mut value = DEBUG_VALUE::default();
            let value = match unsafe { registers.GetValue(index, &mut value) } {
                Ok(()) => RegisterValue::decode(&value),
                Err(_) => RegisterValue::Unavailable,
            };
            out.push(Register {
                name,
                value,
                subregister: description.Flags & DEBUG_REGISTER_SUB_REGISTER != 0,
            });
        }
        Ok(out)
    }

    /// Every register's **description**, without reading a value for any of them.
    ///
    /// The same enumeration [`Self::register_values`] performs, minus the per-register `GetValue`
    /// — so it is cheap, and it answers a different question: not "what is in this register" but
    /// "what does the engine say this register is". A caller that wants to know whether `w0` is a
    /// view of `x0`, or whether `xmm0/0` is a piece of `xmm0`, has to be able to look at
    /// `SubregMaster` and decide for itself, because the flag beside it does not say so on either
    /// architecture.
    ///
    /// Indexes are positions in this list, which is the engine's own register order — so
    /// [`RegisterDescription::subreg_master`] indexes the same `Vec` it came from.
    pub fn register_descriptions(&self) -> Result<Vec<RegisterDescription>, DbgEngError> {
        let registers: IDebugRegisters =
            self.client.cast().map_err(|source| DbgEngError::Context {
                operation: "obtaining the register interface".into(),
                source,
            })?;
        let count =
            unsafe { registers.GetNumberRegisters() }.map_err(|source| DbgEngError::Context {
                operation: "counting the target's registers".into(),
                source,
            })?;
        let mut out = Vec::with_capacity(count as usize);
        for index in 0..count {
            let mut description = DEBUG_REGISTER_DESCRIPTION::default();
            let name = read_engine_string(|buffer, size| unsafe {
                registers.GetDescription(index, buffer, size, Some(&mut description))
            })
            .map_err(|source| DbgEngError::Context {
                operation: format!("describing register {index}"),
                source,
            })?;
            out.push(RegisterDescription {
                name,
                kind: description.Type,
                flags: description.Flags,
                subreg_master: description.SubregMaster,
                subreg_length: description.SubregLength,
                subreg_mask: description.SubregMask,
                subreg_shift: description.SubregShift,
            });
        }
        Ok(out)
    }

    /// The current instruction pointer, read typed via `IDebugRegisters` (no text parse).
    ///
    /// Public because "where is the target stopped?" is the question every host asks after
    /// resuming one, and the alternatives are all text: `r` to be parsed, or `? @$ip` to be read
    /// back out of `Evaluate expression:`.
    pub fn instruction_pointer(&self) -> Result<u64, DbgEngError> {
        let registers: IDebugRegisters =
            self.client.cast().map_err(|source| DbgEngError::Context {
                operation: "obtaining the register interface".into(),
                source,
            })?;
        unsafe { registers.GetInstructionOffset() }.map_err(|source| DbgEngError::Context {
            operation: "reading the instruction pointer".into(),
            source,
        })
    }

    /// The loaded modules, read through `IDebugSymbols3` — what `lm` renders above its
    /// `Unloaded modules:` line, as data.
    ///
    /// Ordered as the engine holds them (by load order), and **loaded modules only**. The tail of
    /// modules that have since unloaded is [`Self::unloaded_modules`]: a different question about
    /// a different kind of thing, and one `lm` does print, so a host rendering that text beside
    /// these values needs both to describe the same listing.
    ///
    /// [`Module::symbols`] is the column hosts most often reach into `lm` for — "does this
    /// module have real symbols, or is it deferred / export-only?" — and it is a value here
    /// rather than a parenthesised word.
    pub fn modules(&self) -> Result<Vec<Module>, DbgEngError> {
        let (loaded, _) = self.module_counts()?;
        self.module_range(0, loaded)
    }

    /// Locate a loaded module by the name used to qualify its symbols.
    pub fn module(&self, name: &str) -> Result<Module, DbgEngError> {
        let name = CString::new(name).map_err(|_| DbgEngError::InvalidCommand)?;
        let mut index = 0u32;
        let mut base = 0u64;
        unsafe {
            self.symbols.GetModuleByModuleName(
                PCSTR::from_raw(name.as_ptr().cast()),
                0,
                Some(&mut index),
                Some(&mut base),
            )
        }
        .map_err(|source| DbgEngError::Context {
            operation: format!("locating module {}", name.to_string_lossy()),
            source,
        })?;
        let mut params = DEBUG_MODULE_PARAMETERS::default();
        unsafe {
            self.symbols
                .GetModuleParameters(1, Some(&base), 0, &mut params)
        }
        .map_err(|source| DbgEngError::Context {
            operation: format!("reading parameters of module at {base:#x}"),
            source,
        })?;
        Ok(self.named_module(index, &params))
    }

    /// The exact PDB or symbol file DbgEng selected for `module_base`.
    pub fn module_symbol_file(&self, module_base: u64) -> Result<String, DbgEngError> {
        read_engine_string(|buffer, size| unsafe {
            self.symbols.GetModuleNameString(
                DEBUG_MODNAME_SYMBOL_FILE,
                DEBUG_ANY_ID,
                module_base,
                buffer,
                size,
            )
        })
        .map_err(|source| DbgEngError::Context {
            operation: format!("reading the symbol file for module at {module_base:#x}"),
            source,
        })
    }

    /// Image and symbol identity for a loaded module.
    /// The **PDB** identity for a loaded module — the `GUID` + `age` a symbol server is keyed by.
    ///
    /// `Ok(None)` when the engine has no PDB signature for the module, which is the ordinary case
    /// for one whose symbols are still deferred: this reports what the engine *has*, and it has
    /// nothing until something has made it look. It is not an error, and it is not "this module
    /// has no symbols" either — the two are told apart by [`Module::symbols`].
    ///
    /// Read through `IDebugAdvanced2::GetSymbolInformation`, which fills dbghelp's own
    /// `IMAGEHLP_MODULEW64`. The interface is cast per call rather than held: this is asked once
    /// per module that has symbols, not once per operation, and a `QueryInterface` is cheaper than
    /// another field on every engine that never asks.
    pub fn module_pdb(&self, base: u64) -> Result<Option<PdbIdentity>, DbgEngError> {
        let advanced =
            self.client
                .cast::<IDebugAdvanced2>()
                .map_err(|source| DbgEngError::Context {
                    operation: "querying IDebugAdvanced2".into(),
                    source,
                })?;
        let mut info = IMAGEHLP_MODULEW64 {
            SizeOfStruct: std::mem::size_of::<IMAGEHLP_MODULEW64>() as u32,
            ..Default::default()
        };
        let filled = unsafe {
            advanced.GetSymbolInformation(
                DEBUG_SYMINFO_IMAGEHLP_MODULEW64,
                base,
                0,
                Some((&raw mut info).cast()),
                std::mem::size_of::<IMAGEHLP_MODULEW64>() as u32,
                None,
                None,
                None,
            )
        };
        // **No not-found mapping here, deliberately.** `module_at` treats `E_INVALIDARG` as "no
        // module holds this offset" because that is measurably what the engine means *there*, and
        // copying the convention across looked natural. It is wrong here: this call's plausible
        // failures are the call itself being wrong — a struct size this dbghelp does not
        // recognise, an interface it does not implement — and reporting those as "this module has
        // no PDB" would be a quiet, believable claim about the target made out of a broken call.
        // An engine with nothing to say fills the struct and leaves the signature zeroed, which is
        // the check below; it does not fail.
        filled.map_err(|source| DbgEngError::Context {
            operation: format!("reading the PDB identity of the module at {base:#x}"),
            source,
        })?;
        let guid = info.PdbSig70;
        // An all-zero signature is the engine saying it has none — a module whose symbols are
        // deferred fills the struct and leaves this empty rather than failing the call.
        if guid.data1 == 0 && guid.data2 == 0 && guid.data3 == 0 && guid.data4 == [0; 8] {
            return Ok(None);
        }
        Ok(Some(PdbIdentity {
            guid: format_pdb_guid(&guid),
            age: info.PdbAge,
            unmatched: info.PdbUnmatched.as_bool(),
            file: wide_to_string(&info.LoadedPdbName),
        }))
    }

    pub fn module_identity(&self, name: &str) -> Result<ModuleIdentity, DbgEngError> {
        let module = self.module(name)?;
        let symbol_file = self.module_symbol_file(module.base)?;
        Ok(ModuleIdentity {
            name: module.name,
            image_name: module.image_name,
            loaded_image_name: module.loaded_image_name,
            symbol_file,
            symbols: module.symbols,
            base: module.base,
            size: module.size,
            timestamp: module.timestamp,
            checksum: module.checksum,
        })
    }

    /// The modules that have **unloaded**, which the engine keeps a bounded tail of and `lm`
    /// prints under `Unloaded modules:`.
    ///
    /// A different question from [`Self::modules`], and worth asking: a stack frame or a pool
    /// pointer into a driver that is no longer there resolves to no loaded module at all, and
    /// this tail is what names it. `!analyze` reads the same list.
    ///
    /// **Read through the same index space**, because that is how the engine exposes it:
    /// `GetNumberModules` returns the two counts, and the unloaded ones are
    /// [indexed after the loaded ones][counts] — indices `Loaded..Loaded + Unloaded`. So this is
    /// `GetModuleParameters` over that range, not a second enumeration.
    ///
    /// **Empty is an ordinary answer.** Windows does not track unloaded modules everywhere — for
    /// user-mode targets only since Server 2003, per the same page — and a target that tracks
    /// them has simply not unloaded anything yet. Neither is a failure, so both are `Ok(vec![])`.
    ///
    /// The fields that describe an image (`base`, `size`, the names) are the ones that were true
    /// when it was loaded; `symbols` says what the engine holds for it now, which is usually
    /// nothing.
    ///
    /// [counts]: https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/dbgeng/nf-dbgeng-idebugsymbols-getnumbermodules
    pub fn unloaded_modules(&self) -> Result<Vec<Module>, DbgEngError> {
        let (loaded, unloaded) = self.module_counts()?;
        self.module_range(loaded, unloaded)
    }

    /// How many modules the engine holds: `(loaded, unloaded)`.
    fn module_counts(&self) -> Result<(u32, u32), DbgEngError> {
        let mut loaded = 0u32;
        let mut unloaded = 0u32;
        unsafe { self.symbols.GetNumberModules(&mut loaded, &mut unloaded) }.map_err(|source| {
            DbgEngError::Context {
                operation: "counting the target's modules".into(),
                source,
            }
        })?;
        Ok((loaded, unloaded))
    }

    /// `count` modules starting at `start` in the engine's own index space.
    fn module_range(&self, start: u32, count: u32) -> Result<Vec<Module>, DbgEngError> {
        if count == 0 {
            return Ok(Vec::new());
        }
        // One call for the whole range: the parameters are the engine's own bookkeeping and
        // cannot fail per-module the way a register read can.
        let mut params = vec![DEBUG_MODULE_PARAMETERS::default(); count as usize];
        unsafe {
            self.symbols
                .GetModuleParameters(count, None, start, params.as_mut_ptr())
        }
        .map_err(|source| DbgEngError::Context {
            operation: "reading module parameters".into(),
            source,
        })?;

        let mut out = Vec::with_capacity(count as usize);
        for (offset, params) in params.iter().enumerate() {
            out.push(self.named_module(start + offset as u32, params));
        }
        Ok(out)
    }

    /// The module holding `address`, or `None` if the address is in no loaded module.
    ///
    /// `None` is the ordinary answer, not a failure: a stack frame can point into a driver that
    /// was unloaded before the dump was written, or into pool. So the engine's "no module here"
    /// is reported as an absent module rather than as an error, and only a call that actually
    /// broke comes back as one.
    ///
    /// Asked of the engine (`GetModuleByOffset`) rather than answered by scanning
    /// [`Self::modules`], because these are not the same question: the engine's own containment
    /// test is what `module!Symbol` is resolved with, and a scan would additionally have to
    /// decide what to do about the modules whose ranges overlap. It is also much less work when
    /// the caller has a handful of addresses rather than a need for the whole table.
    pub fn module_at(&self, address: u64) -> Result<Option<Module>, DbgEngError> {
        let mut index = 0u32;
        match unsafe {
            self.symbols
                .GetModuleByOffset(address, 0, Some(&mut index), None)
        } {
            Ok(()) => {}
            // "No module holds this offset" — the answer this reports as `None`.
            //
            // Two codes, because the engine is not the only implementation and the documentation
            // names neither. `E_INVALIDARG` is what a real dbgeng 10.x answers, measured against a
            // kernel dump for a pool address, an unmapped kernel address and a null one — the
            // offset *is* the parameter it is calling incorrect. `E_NOINTERFACE` is what Wine's
            // dbgeng and the neighbouring `IDebugSymbols` lookups answer for not-found, so it is
            // accepted too rather than turned into an error on a host that answers that way.
            Err(why) if matches!(why.code(), E_INVALIDARG | E_NOINTERFACE) => return Ok(None),
            // Anything else is the lookup itself failing — no debuggee, a target that has gone
            // away — and reporting that as "the address is in no module" would turn a broken
            // engine into a stack frame attributed to nothing, which reads like a finding.
            Err(source) => {
                return Err(DbgEngError::Context {
                    operation: format!("locating the module holding {address:#x}"),
                    source,
                });
            }
        }
        let mut params = DEBUG_MODULE_PARAMETERS::default();
        // `Count = 1, Start = index`: the parameters for that one module.
        unsafe {
            self.symbols
                .GetModuleParameters(1, None, index, &mut params)
        }
        .map_err(|source| DbgEngError::Context {
            operation: format!("reading the parameters of the module at {address:#x}"),
            source,
        })?;
        Ok(Some(self.named_module(index, &params)))
    }

    /// Fills in a [`Module`]'s names from the engine, given parameters already read for it.
    ///
    /// Infallible by design: the parameters carry everything structural (base, size, symbol
    /// state), so a module whose *names* cannot be read is still a module, reported with empty
    /// name fields rather than dropped from the table or turned into an error.
    fn named_module(&self, index: u32, params: &DEBUG_MODULE_PARAMETERS) -> Module {
        let mut name = String::new();
        let mut image_name = String::new();
        let mut loaded_image_name = String::new();
        // Names come back in a single call with three buffers, each optional. Sized from the
        // parameters above rather than from a guess, because a loaded-image name is a full
        // path and truncating it silently would be worse than not reporting it.
        // A size of **zero** is not "no name": an unloaded module's parameters carry no sizes at
        // all, and the engine still has the (truncated) name `lm` prints for it under
        // `Unloaded modules:`. Measured on a kernel dump — every unloaded entry reports
        // `ModuleNameSize == 0` — where sizing from it produced fifty nameless modules. So a
        // reported size is believed and an absent one falls back to a path-sized buffer.
        let sized = |reported: u32| {
            vec![
                0u8;
                if reported == 0 {
                    MODULE_NAME_FALLBACK
                } else {
                    reported as usize
                }
            ]
        };
        let mut name_buffer = sized(params.ModuleNameSize);
        let mut image_buffer = sized(params.ImageNameSize);
        let mut loaded_buffer = sized(params.LoadedImageNameSize);
        let named = unsafe {
            self.symbols.GetModuleNames(
                index,
                0,
                Some(&mut image_buffer),
                None,
                Some(&mut name_buffer),
                None,
                Some(&mut loaded_buffer),
                None,
            )
        };
        if named.is_ok() {
            name = nul_terminated(&name_buffer);
            image_name = nul_terminated(&image_buffer);
            loaded_image_name = nul_terminated(&loaded_buffer);
        }
        Module {
            base: params.Base,
            size: params.Size,
            name,
            image_name,
            loaded_image_name,
            timestamp: params.TimeDateStamp,
            checksum: params.Checksum,
            symbols: SymbolKind::from_engine(params.SymbolType),
            user_mode: params.Flags & DEBUG_MODULE_USER_MODE != 0,
            unloaded: params.Flags & DEBUG_MODULE_UNLOADED != 0,
        }
    }

    /// The bug check this target stopped on, or `None` if it did not stop on one.
    ///
    /// `None` covers the two ordinary cases together — a live kernel simply broken into, and a
    /// kernel dump that is not a crash dump — because the engine reports both the same way: code
    /// zero, which is not a bug check code. Distinguishing them is a question about the *target*,
    /// not about this call.
    ///
    /// Fails on a user-mode target, where the engine has no bug check data to read at all. That
    /// is deliberately an error rather than `None`: "this process did not bug check" is not a
    /// fact about a process, and a caller that treats it as one is asking the wrong tool.
    pub fn bug_check(&self) -> Result<Option<BugCheck>, DbgEngError> {
        let mut code = 0u32;
        let mut parameters = [0u64; 4];
        let [arg1, arg2, arg3, arg4] = &mut parameters;
        unsafe {
            self.control
                .ReadBugCheckData(&mut code, arg1, arg2, arg3, arg4)
        }
        .map_err(|source| DbgEngError::Context {
            operation: "reading the target's bug check data".into(),
            source,
        })?;
        if code == 0 {
            return Ok(None);
        }
        Ok(Some(BugCheck { code, parameters }))
    }

    /// The current thread's stack, read through `IDebugControl` — what `k` renders, as data.
    ///
    /// Walked from the current context (`GetStackTrace` with zero offsets), so on a crash dump
    /// this is the stack of the thread the dump was written for, and on a live target the stack
    /// of whatever the engine is stopped in.
    ///
    /// Each frame carries the symbol the engine resolves its instruction pointer to, split into
    /// the `module!Symbol` name and the displacement past it. Both are `None`/zero rather than
    /// invented when nothing resolves — a driver with no PDB is exactly the case a caller needs
    /// to detect, so that it can fall back to `module+RVA` from [`Self::module_at`].
    ///
    /// `max_frames` bounds the walk. Zero frames is a legitimate ask and returns an empty stack
    /// without touching the engine.
    pub fn stack_frames(&self, max_frames: usize) -> Result<Vec<StackFrame>, DbgEngError> {
        if max_frames == 0 {
            return Ok(Vec::new());
        }
        let mut raw = vec![DEBUG_STACK_FRAME::default(); max_frames];
        let mut filled = 0u32;
        // Zero for all three offsets means "walk from the current register context", which is
        // what `k` does. Supplying them explicitly is for walking a stack that is not the
        // current one, which is a different question than this answers.
        unsafe {
            self.control
                .GetStackTrace(0, 0, 0, &mut raw, Some(&mut filled))
        }
        .map_err(|source| DbgEngError::Context {
            operation: "walking the current thread's stack".into(),
            source,
        })?;
        // Clamped to the buffer as well as to what the engine says it filled: `filled` is the
        // engine's own count, and trusting it past the allocation would be a trust decision this
        // does not need to make.
        raw.truncate((filled as usize).min(max_frames));
        Ok(raw
            .iter()
            .enumerate()
            .map(|(index, frame)| {
                let (symbol, displacement) = self.symbol_at(frame.InstructionOffset);
                StackFrame {
                    index: index as u32,
                    instruction_offset: frame.InstructionOffset,
                    return_offset: frame.ReturnOffset,
                    frame_offset: frame.FrameOffset,
                    stack_offset: frame.StackOffset,
                    symbol,
                    displacement,
                }
            })
            .collect())
    }

    /// Disassembles `count` instructions from `address` — what `u` renders, as data.
    ///
    /// Walks forward the way the engine does: each instruction's end is the next one's start, so
    /// every address here is the engine's own arithmetic rather than a length this code guessed.
    /// `count` bounds the walk; zero is a legitimate ask and returns nothing without touching the
    /// engine.
    ///
    /// **A short answer is a fact about the target, not an error.** Disassembly runs forward into
    /// whatever follows, and what follows the end of a function may be unmapped, unreadable, or
    /// not code at all. So a walk that cannot render its *first* instruction fails — there is
    /// nothing to report and the caller asked about that address specifically — while one that
    /// stops later returns what it has. A caller that needs to know compares the length it got
    /// with the length it asked for, exactly as [`Self::stack_frames`] expects.
    ///
    /// Flags are zero: the same rendering `u` produces by default, without the effective-address
    /// annotation, which is a fact about the *current register context* rather than about the
    /// instruction and would make two identical calls differ.
    pub fn disassemble(&self, address: u64, count: usize) -> Result<Vec<Instruction>, DbgEngError> {
        let mut out = Vec::with_capacity(count.min(64));
        let mut at = address;
        for _ in 0..count {
            let mut next = 0u64;
            let line = read_engine_string(|buffer, size| unsafe {
                self.control.Disassemble(at, 0, buffer, size, &mut next)
            });
            let line = match line {
                Ok(line) if !line.trim().is_empty() => line,
                // The first one failing is the caller's own question going unanswered; a later one
                // is the end of what can be read, and the instructions before it are still good.
                Ok(_) | Err(_) if !out.is_empty() => break,
                Ok(_) => {
                    return Err(DbgEngError::Context {
                        operation: format!("disassembling {at:#x}"),
                        source: S_FALSE.into(),
                    });
                }
                Err(source) => {
                    return Err(DbgEngError::Context {
                        operation: format!("disassembling {at:#x}"),
                        source,
                    });
                }
            };
            out.push(split_instruction(at, &line));
            // An engine that does not advance would spin here forever rendering one instruction.
            if next <= at {
                break;
            }
            at = next;
        }
        Ok(out)
    }

    /// The `module!Symbol` an address resolves to and how far past it the address is.
    ///
    /// Infallible: an address that resolves to nothing is the normal case for a module without
    /// symbols, and reporting it as a failure would make every unsymbolised frame fail a stack
    /// walk that is otherwise perfectly good.
    fn symbol_at(&self, address: u64) -> (Option<String>, u64) {
        let mut displacement = 0u64;
        let name = read_engine_string(|buffer, size| unsafe {
            self.symbols
                .GetNameByOffset(address, buffer, size, Some(&mut displacement))
        });
        match name {
            Ok(name) if !name.is_empty() => (Some(name), displacement),
            _ => (None, 0),
        }
    }

    /// The image name of the process the engine's context is currently in — what a bug check
    /// screen and `!analyze` call `PROCESS_NAME`.
    ///
    /// **Two different reads, because "the current process" means two different things.** On a
    /// user-mode target it is the debuggee, and the engine names it directly. On a kernel target
    /// `GetCurrentProcessExecutableName` answers with the *kernel image* — `ntkrnlmp.exe`, for
    /// every process there has ever been — which is not an answer, so the name is read out of the
    /// current `_EPROCESS` instead.
    ///
    /// The kernel path therefore needs symbols for `nt`. Without them it fails rather than
    /// falling back to the executable name: `ntkrnlmp.exe` presented as the crashing process is
    /// worse than no answer, because it looks like one.
    ///
    /// # Which field, and why it is not the obvious one
    ///
    /// `_EPROCESS::ImageFileName` is the obvious one and it is **15 bytes**, so it silently
    /// truncates: `mm_exploit_v5.exe` reads back as `mm_exploit_v5.`, which looks like a name and
    /// is not one. Measured against a real crash dump, where `!analyze` printed the full name
    /// beside this function's truncated one.
    ///
    /// So the audit name is preferred — `SeAuditProcessCreationInfo.ImageFileName`, an
    /// `OBJECT_NAME_INFORMATION` holding the full NT path, of which the leaf is taken. It is what
    /// `!analyze` reports. `ImageFileName` remains the fallback for a target whose audit name is
    /// not there to read (it is a pointer, and a partial dump need not have captured what it
    /// points at), because a truncated name beats no name.
    pub fn current_process_name(&self) -> Result<String, DbgEngError> {
        let system: IDebugSystemObjects =
            self.client.cast().map_err(|source| DbgEngError::Context {
                operation: "querying IDebugSystemObjects".into(),
                source,
            })?;
        if !self.is_kernel_target()? {
            return read_engine_string(|buffer, size| unsafe {
                system.GetCurrentProcessExecutableName(buffer, size)
            })
            .map_err(|source| DbgEngError::Context {
                operation: "reading the current process's image name".into(),
                source,
            });
        }
        // On a kernel target the "process data offset" is the current `_EPROCESS`.
        let process = unsafe { system.GetCurrentProcessDataOffset() }.map_err(|source| {
            DbgEngError::Context {
                operation: "locating the current process's EPROCESS".into(),
                source,
            }
        })?;
        let nt = self.kernel_base()?;
        let eprocess = self.type_id(nt, "_EPROCESS")?;
        if let Some(full) = self.audit_image_name(nt, eprocess, process) {
            return Ok(full);
        }
        let offset = self.field_offset(nt, eprocess, "ImageFileName")?;
        // `ImageFileName` is a fixed-size array, NUL-*padded* rather than NUL-terminated: a name
        // that fills it has no terminator at all, which is why the length is read from the type
        // and the result cut at the first NUL rather than parsed as a C string.
        let size = self
            .field_size(nt, eprocess, "ImageFileName")
            .unwrap_or(EPROCESS_IMAGE_NAME_LEN) as usize;
        let raw = self.read_memory(process.saturating_add(u64::from(offset)), size)?;
        Ok(nul_terminated(&raw))
    }

    /// The leaf of `SeAuditProcessCreationInfo.ImageFileName`, the full NT path of a process's
    /// image — `mm_exploit_v5.exe` where `_EPROCESS::ImageFileName` has only `mm_exploit_v5.`.
    ///
    /// Best-effort throughout, returning `None` rather than an error at every step: this is the
    /// *better* of two answers and the caller has the other one. It is several dereferences deep,
    /// and each of them is a page a partial crash dump is entitled not to have captured.
    ///
    /// The field's offset is resolved from symbols, because that is what moves between builds. The
    /// two structures it leads through are not read through symbols: `OBJECT_NAME_INFORMATION`
    /// begins with its `UNICODE_STRING`, and a `UNICODE_STRING` on x64 is `{u16 Length, u16
    /// MaximumLength, u32 pad, u64 Buffer}`. That is ABI, not a build detail.
    fn audit_image_name(&self, nt: u64, eprocess: u32, process: u64) -> Option<String> {
        let offset = self
            .field_offset(nt, eprocess, "SeAuditProcessCreationInfo")
            .ok()?;
        // The structure's single member is the `OBJECT_NAME_INFORMATION*`, so its address is the
        // structure's own.
        let name_info = u64::from_le_bytes(
            self.read_memory(process.checked_add(u64::from(offset))?, 8)
                .ok()?
                .try_into()
                .ok()?,
        );
        if name_info == 0 {
            return None;
        }
        let unicode_string = self.read_memory(name_info, 16).ok()?;
        let length = u16::from_le_bytes(unicode_string[0..2].try_into().ok()?) as usize;
        let buffer = u64::from_le_bytes(unicode_string[8..16].try_into().ok()?);
        // A zero-length or absurd name is not an answer. The bound is generous — an NT path can be
        // long — and exists only so a wild `Length` cannot ask for a huge read.
        if buffer == 0 || length == 0 || length > 2 * 1024 {
            return None;
        }
        let raw = self.read_memory(buffer, length).ok()?;
        let wide: Vec<u16> = raw
            .chunks_exact(2)
            .map(|pair| u16::from_le_bytes([pair[0], pair[1]]))
            .collect();
        let path = String::from_utf16_lossy(&wide);
        // The leaf, as `!analyze` prints it: the path is
        // `\Device\HarddiskVolume3\Users\Admin\mm_exploit_v5.exe`.
        let leaf = path.rsplit(['\\', '/']).next().unwrap_or(&path).trim();
        (!leaf.is_empty()).then(|| leaf.to_string())
    }

    /// The size of one field of a type, for a field whose length is part of its meaning.
    ///
    /// Best-effort — `None` rather than an error — because every caller has something sensible to
    /// do without it, and a type this build cannot measure is not a reason to fail a read whose
    /// offset resolved fine.
    fn field_size(&self, module: u64, type_id: u32, field: &str) -> Option<u32> {
        let name = CString::new(field).ok()?;
        let mut field_type = 0u32;
        let mut offset = 0u32;
        unsafe {
            self.symbols.GetFieldTypeAndOffset(
                module,
                type_id,
                PCSTR::from_raw(name.as_ptr().cast()),
                Some(&mut field_type),
                Some(&mut offset),
            )
        }
        .ok()?;
        self.type_size(module, field_type).ok()
    }

    /// Every breakpoint the engine holds, read through `IDebugControl` — what `bl` renders, as
    /// data.
    ///
    /// The distinction `bl` makes with a `u`/`e` letter and a blank address column is a typed one
    /// here: a deferred breakpoint has [`BreakpointInfo::address`] `None`, because its module is
    /// not loaded and it therefore *has* no address yet. Reporting that as zero would invent a
    /// breakpoint on the null page.
    pub fn breakpoints(&self) -> Result<Vec<BreakpointInfo>, DbgEngError> {
        let count = unsafe { self.control.GetNumberBreakpoints() }.map_err(|source| {
            DbgEngError::Context {
                operation: "counting breakpoints".into(),
                source,
            }
        })?;
        let mut out = Vec::with_capacity(count as usize);
        for index in 0..count {
            let breakpoint =
                unsafe { self.control.GetBreakpointByIndex(index) }.map_err(|source| {
                    DbgEngError::Context {
                        operation: format!("reading breakpoint at index {index}"),
                        source,
                    }
                })?;
            // Never released, exactly as in [`Breakpoint`]: DbgEng owns breakpoint objects and
            // hands out borrowed interfaces, so letting the generated wrapper `Release()` one is
            // a call on an object this code does not own. There is nothing to leak — the engine
            // frees them with the session.
            let breakpoint = std::mem::ManuallyDrop::new(breakpoint);
            let id = unsafe { breakpoint.GetId() }.map_err(|source| DbgEngError::Context {
                operation: format!("reading the id of breakpoint {index}"),
                source,
            })?;
            let mut kind = 0u32;
            let mut _processor = 0u32;
            let kind = match unsafe { breakpoint.GetType(&mut kind, &mut _processor) } {
                Ok(()) => BreakpointKind::from_engine(kind),
                Err(_) => BreakpointKind::Other(DEBUG_ANY_ID),
            };
            let flags = unsafe { breakpoint.GetFlags() }.unwrap_or(0);
            // A deferred breakpoint answers `GetOffset` with an error, and one whose expression
            // resolved to nothing answers with `DEBUG_INVALID_OFFSET`. Both mean "no address
            // yet", and neither means address zero.
            let address = match unsafe { breakpoint.GetOffset() } {
                Ok(offset) if offset != DEBUG_INVALID_OFFSET => Some(offset),
                _ => None,
            };
            let expression = read_engine_string(|buffer, size| unsafe {
                breakpoint.GetOffsetExpression(buffer, size)
            })
            .ok()
            .filter(|text| !text.is_empty());
            let command =
                read_engine_string(|buffer, size| unsafe { breakpoint.GetCommand(buffer, size) })
                    .ok()
                    .filter(|text| !text.is_empty());
            let thread = unsafe { breakpoint.GetMatchThreadId() }
                .ok()
                .filter(|id| *id != DEBUG_ANY_ID);
            out.push(BreakpointInfo {
                id,
                kind,
                address,
                expression,
                command,
                thread,
                enabled: flags & DEBUG_BREAKPOINT_ENABLED != 0,
                deferred: flags & DEBUG_BREAKPOINT_DEFERRED != 0,
                one_shot: flags & DEBUG_BREAKPOINT_ONE_SHOT != 0,
                pass_count: unsafe { breakpoint.GetPassCount() }.unwrap_or(0),
                passes_remaining: unsafe { breakpoint.GetCurrentPassCount() }.unwrap_or(0),
            });
        }
        Ok(out)
    }

    /// Ensures the engine breaks at the initial (loader) breakpoint. A bare
    /// `DebugCreate` host defaults this event filter to "ignore", so a freshly
    /// launched/attached target would run free and the engine would never establish a
    /// current process/thread (register/stack commands then fail with `0x80040205`).
    fn enable_initial_break(&self) -> Result<(), DbgEngError> {
        // Unguarded on purpose: this runs *before* the target exists, which is exactly the state
        // `refuse_without_a_debuggee` refuses. See [`Self::execute_fixed_command`].
        self.execute_fixed_command("sxe ibp").map(|_| ())
    }

    /// Launches a new user-mode process under the debugger and waits for it to stop at
    /// its initial breakpoint, leaving a current process/thread ready to inspect.
    ///
    /// Fuses the launch with the initial-break wait, so a failure cannot say which half
    /// failed. Use [`Self::launch_process_begin`] when that matters.
    pub fn launch_process(&self, command_line: &str) -> Result<(), DbgEngError> {
        self.launch_process_begin(command_line)?.wait()
    }

    /// [`Self::launch_process`] up to — and not including — the initial-break wait.
    ///
    /// An `Ok` means the session is committed even though the process has not started yet:
    /// `CreateProcessWide` is deferred, so the spawn happens inside the wait, and from the
    /// caller's side a retry would spawn a second process. See [`PendingTarget`].
    pub fn launch_process_begin(
        &self,
        command_line: &str,
    ) -> Result<PendingTarget<'_>, DbgEngError> {
        // Before the spawn, so a pid the operating system is about to hand this process cannot
        // still be sitting in the record from an attach that ended. See `prune_dead_attachments`.
        self.prune_dead_attachments();
        self.enable_initial_break()?;
        let mut wide = to_wide(command_line);
        unsafe {
            self.client.CreateProcessWide(
                0,
                PWSTR::from_raw(wide.as_mut_ptr()),
                DEBUG_ONLY_THIS_PROCESS | CREATE_NEW_CONSOLE,
            )
        }
        .map_err(DbgEngError::OperationFailed)?;

        // `CreateProcessWide` is deferred: the engine doesn't actually spawn the process
        // until the next `WaitForEvent`, and it reads the command-line buffer (`wide`) at
        // that point — so `wide` moves into the guard, which owns it until the wait
        // returns. With the initial-breakpoint filter enabled above, that wait stops at
        // the loader breakpoint.
        self.retain_deferred_input(TargetInput::Wide(wide));
        Ok(PendingTarget::new(self, WaitKind::Live))
    }

    /// Attaches to an existing user-mode process by PID and waits for the break-in,
    /// leaving a current process/thread ready to inspect.
    ///
    /// Fuses the attach with the break-in wait, so a failure cannot say which half failed.
    /// Use [`Self::attach_process_begin`] when that matters.
    pub fn attach_process(&self, pid: u32) -> Result<(), DbgEngError> {
        self.attach_process_begin(pid)?.wait()
    }

    /// [`Self::attach_process`] up to — and not including — the break-in wait.
    ///
    /// An `Ok` means the debugger is attached to `pid`, so attaching again is no longer a
    /// clean retry — it attaches to the same process twice. See [`PendingTarget`].
    pub fn attach_process_begin(&self, pid: u32) -> Result<PendingTarget<'_>, DbgEngError> {
        self.enable_initial_break()?;
        unsafe { self.client.AttachProcess(0, pid, DEBUG_ATTACH_DEFAULT) }
            .map_err(DbgEngError::OperationFailed)?;
        // Recorded at the same moment the attach becomes irreversible, and for the same reason
        // this returns a guard: from here on the process is ours to let go of properly, whether
        // or not the break-in wait below ever succeeds. A wait that fails still leaves a debugger
        // attached to somebody else's process.
        self.prune_dead_attachments();
        self.claim_attached(pid);
        // The attach completes during `WaitForEvent`, which breaks the target in.
        Ok(PendingTarget::new(self, WaitKind::Live))
    }

    /// Opens a crash dump (`.dmp`) or a Time Travel Debugging trace (`.run`).
    /// Call [`Self::wait_for_event`] afterward to finish loading the target.
    pub fn open_dump(&self, path: &str) -> Result<(), DbgEngError> {
        let wide = to_wide(path);
        unsafe {
            self.client
                .OpenDumpFileWide(PCWSTR::from_raw(wide.as_ptr()), 0)
        }
        .map_err(DbgEngError::OperationFailed)?;
        self.forget_attachments();
        Ok(())
    }

    /// Opens a TTD trace (`.run`); alias for [`Self::open_dump`].
    pub fn open_trace(&self, path: &str) -> Result<(), DbgEngError> {
        self.open_dump(path)
    }

    /// Parks an input buffer for the life of the session, so DbgEng can still read it when
    /// it completes a deferred spawn or dial. See [`DebugEngine::deferred_inputs`].
    fn retain_deferred_input(&self, input: TargetInput) {
        self.deferred_inputs
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .push(input);
    }

    /// Releases the parked input buffers. Only sound once the session is over: until then
    /// the engine may still owe a deferred spawn or dial that reads them.
    fn release_deferred_inputs(&self) {
        self.deferred_inputs
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clear();
    }

    /// Records that `pid` is a process this engine attached to, so the teardown detaches from it
    /// instead of taking it.
    fn claim_attached(&self, pid: u32) {
        self.attached_processes
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .insert(pid);
    }

    /// Forgets recorded attachments this session no longer holds.
    ///
    /// **Called by the openers, and it is about pid reuse rather than tidiness.** A pid outlives
    /// the process it named, so an attached process that exits leaves a record that matches
    /// nothing — harmless, since the teardown walks the session and a pid it does not hold cannot
    /// match — right up until the operating system hands that number to a process this engine then
    /// **launches**. That process would be detached and left running by a session that is supposed
    /// to take it. Pruning at the opener is what closes it, and it has to prune rather than clear:
    /// a session can hold an attached process *and* be about to launch one, and clearing would
    /// forget the live attachment and kill somebody else's process to prevent an unlikely one.
    ///
    /// A session with no target holds nothing, so this correctly forgets everything there.
    ///
    /// **It narrows the window rather than closing it, which review asked about and which is
    /// declined on purpose.** `CreateProcessWide` is deferred, so the launched process gets its
    /// pid at the next `WaitForEvent`: an attached process that exits *after* this prune and
    /// whose number is then handed to that launch is still misread. Closing it needs something
    /// identifying the process **instance** rather than its number, and the one that would work is
    /// a retained handle — which also stops Windows reusing the pid at all, so it is the real
    /// answer if this is ever worth closing. It is not yet: reaching it needs an exit inside a
    /// window of milliseconds *and* an immediate reuse of that exact number, and what it costs is
    /// a launched process outliving its session — a stray process, where the bug this whole path
    /// exists for was killing somebody else's. Handle lifetimes across four teardown paths are a
    /// worse risk than that.
    fn prune_dead_attachments(&self) {
        let Ok(held) = self.session_processes() else {
            return;
        };
        self.attached_processes
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .retain(|pid| held.iter().any(|(_, held)| held == pid));
    }

    /// Forgets every recorded attach.
    ///
    /// Called when the session ends, and by the openers that **create** a target — a dump, a
    /// trace, a kernel connection. Those replace the session outright, so a pid recorded against
    /// the previous one is stale, and the one way a stale pid could matter is the one that would
    /// hurt: the operating system reusing it for a process this engine went on to launch, which
    /// would then be detached from and survive a session that is supposed to take it.
    fn forget_attachments(&self) {
        self.attached_processes
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clear();
    }

    /// Whether this engine holds a live user-mode process it **attached** to rather than
    /// launched — one [`Self::end_session`] will detach from and leave running.
    ///
    /// Exposed so a caller can *say* what its teardown is about to do. The teardown itself needs
    /// no help: `end_session` decides for itself, and so does `Drop`.
    ///
    /// **Asked of the session, not of the record**, and the difference is a wrong sentence rather
    /// than a wrong teardown: an attached process can leave on its own, so a pid recorded here is
    /// not proof the engine still holds it, and a caller reading this to describe what it did
    /// would say "detached and left running" about a session that launched and killed one.
    pub fn attached_to_a_live_process(&self) -> bool {
        let attached = self
            .attached_processes
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        !attached.is_empty()
            && self
                .session_processes()
                .is_ok_and(|held| held.iter().any(|(_, pid)| attached.contains(pid)))
    }

    /// Ends the current debug session without destroying the client, so it can be
    /// reused for another target.
    ///
    /// **What "ending" does to a target depends on where that target came from**, and the two
    /// exceptions are both about not destroying something this engine did not create:
    ///
    /// - a **live kernel** is resumed and actively detached, or it stays frozen at its last break;
    /// - every user-mode process this engine **attached** to is detached first and left running,
    ///   because a passive end destroys the debug port and the kernel then kills the debuggees
    ///   hanging off it (`DebugSetProcessKillOnExit` defaults to true);
    /// - everything else — a dump, a trace, a kernel dump, and any process this engine *launched*
    ///   — goes with the session.
    ///
    /// The first two are **per process**, not per session: DbgEng holds several user-mode targets
    /// at once (`|` lists them), so an engine can hold a service somebody else is running beside a
    /// program it launched itself, and each is let go of on its own terms.
    pub fn end_session(&self) -> Result<(), DbgEngError> {
        // The target is going away, so anything cached against it must not be reused for
        // whatever this engine holds next — nor by any other wrapper around this same client,
        // which is why the identity is recorded against the client rather than in this engine.
        reissue_identity(&self.client);
        // A live kernel left halted (at a break) and detached *passively* stays FROZEN —
        // one CPU halted, the rest spinning — because a passive detach never tells the
        // target to run. Resume it and actively detach instead, leaving it running.
        let ended = if self.is_live_kernel() {
            self.resume_and_detach_live_kernel()
        } else {
            // Detached one by one *before* the session ends, which is what makes a mixed session
            // come apart correctly: `EndSession` takes one flag for the whole session, so no
            // choice of flag can both keep an attached process and take a launched one. Anything
            // still in the session when the passive end runs is a target this engine created.
            let detached = self.detach_attached_processes();
            unsafe { self.client.EndSession(DEBUG_END_PASSIVE) }
                .map_err(DbgEngError::OperationFailed)
                .and(detached)
        };
        // Released only once the session is *confirmed* torn down: an outstanding deferred
        // spawn or dial dies with it, so nothing can read these buffers afterwards. A failed
        // teardown may leave the session live and still owing that read, so the buffers stay
        // — retaining a few bytes for the life of the engine beats a use-after-free.
        if ended.is_ok() {
            self.release_deferred_inputs();
        }
        ended
    }

    /// Detaches from a live kernel leaving it **running**, not frozen at the last break.
    /// Clears breakpoints (restoring their patched `int3` bytes), sets the target to run,
    /// then does an *active* detach — which, unlike a passive one, communicates with the
    /// target to resume it before disconnecting.
    fn resume_and_detach_live_kernel(&self) -> Result<(), DbgEngError> {
        let _ = self.execute_command("bc *");
        unsafe {
            let _ = self.control.SetExecutionStatus(DEBUG_STATUS_GO);
            self.client.EndSession(DEBUG_END_ACTIVE_DETACH)
        }
        .map_err(DbgEngError::OperationFailed)
    }

    /// Detaches from every user-mode process this engine **attached** to, leaving each running,
    /// and forgets them. Processes this engine created are left in the session for the passive
    /// end to take.
    ///
    /// `bc *` first, for a sharper version of the kernel reason: an `int3` this engine patched in
    /// stays patched in a process that goes on running, and the first thread to reach it takes an
    /// exception with no debugger left to handle it. A target that dies minutes after the session
    /// ended is worse than one that never survived it, because nothing connects the two. It is
    /// session-wide, so it also clears breakpoints in a process about to be taken — which costs
    /// nothing, since that process is about to be taken.
    ///
    /// No resume beside it, which is the one step the kernel path has and this does not: the
    /// kernel needs telling to run because its detach only disconnects, while
    /// `DetachCurrentProcess` resumes the threads the debug port suspended.
    ///
    /// **Best-effort per process, and the session ends either way.** This sits on a teardown that
    /// a client disconnect and a lease expiry both run, where a session that will not close is
    /// worse than a debuggee that was killed. It still **reports** the first failure, because a
    /// caller told "released" would have no reason to go and look at a process that had just been
    /// taken by the passive end instead.
    fn detach_attached_processes(&self) -> Result<(), DbgEngError> {
        let attached = std::mem::take(
            &mut *self
                .attached_processes
                .lock()
                .unwrap_or_else(|e| e.into_inner()),
        );
        if attached.is_empty() {
            return Ok(());
        }
        let _ = self.execute_command("bc *");
        let mut failure = None;
        // Walked by engine id rather than by the recorded pid, because `SetCurrentProcessId` takes
        // the engine's id and a pid this engine no longer holds — the process exited, a raw
        // `.detach` took it — is simply not in this list. So a stale entry costs nothing and needs
        // no separate check.
        for (id, pid) in self.session_processes()? {
            if !attached.contains(&pid) {
                continue;
            }
            if let Err(e) = unsafe {
                self.system_objects()?
                    .SetCurrentProcessId(id)
                    .and_then(|()| self.client.DetachCurrentProcess())
            } {
                failure.get_or_insert(DbgEngError::OperationFailed(e));
            }
        }
        failure.map_or(Ok(()), Err)
    }

    /// The user-mode processes in this session, as `(engine id, system pid)`.
    ///
    /// The engine id is what `SetCurrentProcessId` takes and the pid is what a caller knows a
    /// process by, and they are not the same number — `GetProcessIdsByIndex` is the one call that
    /// answers both, which is why this returns pairs rather than either alone.
    fn session_processes(&self) -> Result<Vec<(u32, u32)>, DbgEngError> {
        // An engine with no debuggee holds no processes, and answering that rather than asking is
        // not a shortcut: `GetNumberProcesses` fails `E_UNEXPECTED` ("Catastrophic failure") in
        // that state — measured — which would turn "the program had already finished" into a
        // failed teardown. `has_target` is the one call that answers reliably there; see its docs.
        if !self.has_target()? {
            return Ok(Vec::new());
        }
        let system = self.system_objects()?;
        let count =
            unsafe { system.GetNumberProcesses() }.map_err(|source| DbgEngError::Context {
                operation: "counting the processes in this session".into(),
                source,
            })? as usize;
        let mut ids = vec![0u32; count];
        let mut pids = vec![0u32; count];
        unsafe {
            system.GetProcessIdsByIndex(
                0,
                count as u32,
                Some(ids.as_mut_ptr()),
                Some(pids.as_mut_ptr()),
            )
        }
        .map_err(|source| DbgEngError::Context {
            operation: "listing the processes in this session".into(),
            source,
        })?;
        Ok(ids.into_iter().zip(pids).collect())
    }

    /// `IDebugSystemObjects` off this engine's client.
    fn system_objects(&self) -> Result<IDebugSystemObjects, DbgEngError> {
        self.client.cast().map_err(|source| DbgEngError::Context {
            operation: "querying IDebugSystemObjects".into(),
            source,
        })
    }
}

impl Drop for DebugEngine {
    fn drop(&mut self) {
        // Only tear down sessions we opened ourselves. Wrapping a borrowed WinDbg
        // client must not end the host's active session when the wrapper drops.
        if !self.owns_session {
            // That session outlives this wrapper, so it may still complete a deferred spawn
            // or dial and read the parked input buffers — and nothing will ever tell us when
            // that is over. Leak them rather than free memory the host's engine still holds a
            // pointer to; `end_session` is the only place a release can be justified, and a
            // borrowed client never reaches it. Costs nothing unless a `*_begin` opener was
            // actually used on a borrowed client.
            std::mem::forget(std::mem::take(
                &mut *self
                    .deferred_inputs
                    .lock()
                    .unwrap_or_else(|e| e.into_inner()),
            ));
            return;
        }
        // Don't leave a live kernel frozen at a break if we're torn down without an
        // explicit end_session (e.g. the process exits): resume + actively detach.
        if self.is_live_kernel() {
            let _ = self.resume_and_detach_live_kernel();
            return;
        }
        // And don't take somebody else's process down with us — the same asymmetry as the kernel
        // above, handled in the same place and for the same reason: a teardown that is nobody's
        // call to make still has to leave a target this engine did not create alive. Before the
        // end rather than instead of it: what this detaches is only the processes this engine
        // attached to, and the session still has to be ended for the rest.
        let _ = self.detach_attached_processes();
        // Best-effort teardown; ignore errors (e.g. when no session is active).
        unsafe {
            let _ = self.client.EndSession(DEBUG_END_PASSIVE);
        }
    }
}

/// Which initial-break wait completes a [`PendingTarget`].
#[derive(Clone, Copy)]
enum WaitKind {
    /// User-mode launch/attach: a finite `WaitForEvent`.
    Live,
    /// Kernel attach: the bounded INFINITE wait plus its INITIAL_BREAK bookkeeping.
    KernelBreakIn,
}

/// Input buffers DbgEng may still read *after* the target-creating call has returned,
/// held so the pointers handed to the engine stay valid across the seam.
///
/// `CreateProcessWide` is the documented case: the spawn is deferred until the next
/// `WaitForEvent`, and the engine reads the command line at that point. A kernel
/// connection string gets the same treatment, because the link it describes is likewise
/// only established during the wait — before the split its buffer stayed alive by accident
/// of scope, and freeing it early here would be a silent regression. Never read by this
/// crate; held only to own the allocation.
//
// The payloads are deliberately never read, so rustc reports them as dead and offers to
// replace them with `()`. Taking that suggestion would free the buffers at the end of the
// opener and hand DbgEng a dangling pointer during the wait — the exact bug this guards.
#[allow(dead_code)]
enum TargetInput {
    Wide(Vec<u16>),
    Ansi(CString),
}

/// A debug target that has been created or claimed, but not yet waited for.
///
/// Separates the two halves the openers otherwise fuse: the side effect that creates or
/// claims a target (`CreateProcessWide` / `AttachProcess` / `AttachKernel`) and the wait
/// for the resulting initial break. Fused, one `Err` covers both "nothing happened, the
/// slate is clean" and "the target exists and only the wait failed" — which need opposite
/// recovery, since re-running the first is correct and re-running the second spawns a
/// second process, attaches twice, or re-dials a live KD link.
///
/// Holding one of these means the side effect *succeeded*. A caller that tracks sessions
/// can commit that bookkeeping here, before a wait that may still fail or time out:
///
/// ```no_run
/// # use dbgscope::dbgeng::DebugEngine;
/// # fn commit(_: &str) {}
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let engine = DebugEngine::new();
/// let pending = engine.launch_process_begin("notepad.exe")?;
/// commit("session-1"); // the target is ours from here, even if the wait below fails
/// pending.wait()?;
/// # Ok(())
/// # }
/// ```
///
/// The type is what makes the ordering unforgeable: the guard cannot exist unless the side
/// effect returned `Ok`.
///
/// **Dropping the guard without calling [`wait`](Self::wait) is safe and cancels nothing.**
/// The engine has already been told to spawn or connect, and it completes that at the next
/// `WaitForEvent` from any source — `execute_and_wait` and `run_to_address` included —
/// reading the input buffers then. Those buffers live in the [`DebugEngine`] precisely so
/// this is sound whether or not the guard is waited on; dropping merely forfeits the
/// initial-break wait, leaving the target to materialize later.
///
/// There is deliberately no `Drop` impl. Driving the wait from one could hang without bound
/// on a kernel attach whose link is still coming up (`SetInterrupt` cannot cancel that wait),
/// and clearing that attach's `DEBUG_ENGOPT_INITIAL_BREAK` would half-cancel a request that
/// is still pending — the target would connect and keep *running* instead of stopping, which
/// is the one thing the attach asked for.
///
/// The cost, for an abandoned **kernel** guard only: `DEBUG_ENGOPT_INITIAL_BREAK` stays armed
/// for the session, since only [`Self::wait`] clears it. The pending attach still breaks in
/// as asked, but a later `go`/step can immediately re-break until something clears the
/// option. Abandoning a kernel attach is a poor way to change your mind; prefer `wait()` and
/// then `end_session`.
#[must_use = "the target was created but never waited for; call `wait()` to reach the initial break"]
pub struct PendingTarget<'a> {
    engine: &'a DebugEngine,
    kind: WaitKind,
}

impl<'a> PendingTarget<'a> {
    fn new(engine: &'a DebugEngine, kind: WaitKind) -> Self {
        Self { engine, kind }
    }

    /// Waits for the target's initial break, completing the open.
    ///
    /// For a kernel attach this can block **without bound** when the target never connects;
    /// see [`DebugEngine::attach_kernel`]. User-mode waits are bounded by `LIVE_WAIT_MS`.
    pub fn wait(self) -> Result<(), DbgEngError> {
        match self.kind {
            WaitKind::Live => self.engine.wait_for_event(LIVE_WAIT_MS),
            WaitKind::KernelBreakIn => self.engine.wait_for_kernel_break_in(),
        }
    }
}

/// Holds the [`Scope`] the engine was in, and puts it back when dropped.
///
/// From [`DebugEngine::scope_guard`]. The guard borrows the engine, so it cannot outlive it;
/// what it cannot promise is that the engine still holds the same *target* at drop time, and a
/// scope from a released target is refused rather than applied — see [`DebugEngine::set_scope`].
///
/// `Drop` cannot report anything, so a caller who needs to know the restore worked calls
/// [`Self::restore`] and reads the result; the drop afterwards then restores the same scope
/// again, which is a no-op the engine accepts.
#[must_use = "the scope is restored when this is dropped, so dropping it immediately restores nothing later"]
pub struct ScopeGuard<'a> {
    engine: &'a DebugEngine,
    saved: Scope,
}

impl ScopeGuard<'_> {
    /// The scope that will be restored — the engine's position when the guard was taken.
    pub fn saved(&self) -> &Scope {
        &self.saved
    }

    /// Restores the saved scope now, reporting whether it worked.
    pub fn restore(&self) -> Result<(), DbgEngError> {
        self.engine.set_scope(&self.saved)
    }
}

impl Drop for ScopeGuard<'_> {
    fn drop(&mut self) {
        // Best-effort: a failure here has nowhere to go, and this runs on unwind paths where
        // panicking would abort the process. A target that has gone away is the ordinary
        // failure, and it is refused inside `set_scope` rather than applied to its successor.
        let _ = self.engine.set_scope(&self.saved);
    }
}

// Output callbacks implementation to capture command output
#[windows::core::implement(
    windows::Win32::System::Diagnostics::Debug::Extensions::IDebugOutputCallbacks
)]
#[derive(Debug)]
pub struct OutputCallbacks {
    buffer: *mut Vec<u8>,
}

impl OutputCallbacks {
    fn new(buffer: &mut Vec<u8>) -> Self {
        Self {
            buffer: buffer as *mut Vec<u8>,
        }
    }
}

#[allow(non_snake_case)]
impl windows::Win32::System::Diagnostics::Debug::Extensions::IDebugOutputCallbacks_Impl
    for OutputCallbacks_Impl
{
    fn Output(&self, _mask: u32, text: &PCSTR) -> windows::core::Result<()> {
        // `self` (the generated `_Impl` wrapper) derefs to the inner `OutputCallbacks`,
        // so access the field directly. The previous `self as *const OutputCallbacks`
        // cast reinterpreted the COM wrapper's header as our struct (UB) — it read a
        // vtable pointer as `buffer` and corrupted memory.
        if text.is_null() {
            return Ok(());
        }
        let c_str = unsafe { std::ffi::CStr::from_ptr(text.0 as *const i8) };
        if let Ok(str_slice) = c_str.to_str() {
            // Append: DbgEng calls Output() once per chunk, so clearing here would
            // discard everything but the final chunk.
            unsafe {
                (*self.buffer).extend_from_slice(str_slice.as_bytes());
            }
        }
        Ok(())
    }
}

/// A breakpoint owned by a single operation and removed when that operation ends —
/// on success, on an early `?`, and on an unwind alike.
///
/// [`DebugEngine::run_to_address`] previously drove execution with WinDbg's one-shot
/// `g <addr>`, which DbgEng clears only when the breakpoint is *hit* and for which it hands
/// back no handle. Every other outcome therefore left it armed and unremovable, and a later
/// unrelated `g` passing `address` could stop there spuriously. Owning the handle is what
/// makes cleanup possible at all.
///
/// Distinct from [`Breakpoint`], which is a caller-managed handle with explicit
/// `enable`/`disable`/`remove` and no `Drop`.
struct ScopedBreakpoint<'a> {
    control: &'a IDebugControl4,
    breakpoint: std::mem::ManuallyDrop<IDebugBreakpoint2>,
}

impl<'a> ScopedBreakpoint<'a> {
    /// Adds an enabled code breakpoint at `address`.
    fn at(engine: &'a DebugEngine, address: u64) -> Result<Self, DbgEngError> {
        let breakpoint = unsafe {
            engine
                .control
                .AddBreakpoint2(DEBUG_BREAKPOINT_CODE, DEBUG_ANY_ID)
        }
        .map_err(DbgEngError::BreakpointFailed)?;
        // Wrapped before it is configured, so a failure below still removes it rather than
        // leaking a half-built breakpoint into the session.
        let scoped = Self {
            control: &engine.control,
            breakpoint: std::mem::ManuallyDrop::new(breakpoint),
        };
        unsafe {
            scoped
                .breakpoint
                .SetOffset(address)
                .map_err(DbgEngError::BreakpointFailed)?;
            scoped
                .breakpoint
                .AddFlags(DEBUG_BREAKPOINT_ENABLED)
                .map_err(DbgEngError::BreakpointFailed)?;
        }
        Ok(scoped)
    }
}

impl Drop for ScopedBreakpoint<'_> {
    fn drop(&mut self) {
        // Best-effort: a failure here has nowhere to go, and this runs on unwind paths where
        // panicking would abort the process.
        unsafe {
            let _ = self.control.RemoveBreakpoint2(&*self.breakpoint);
        }
        // `breakpoint` is deliberately not dropped. DbgEng owns breakpoint objects and
        // `RemoveBreakpoint2` destroys this one, so letting the generated wrapper `Release()`
        // it afterwards dereferences freed memory — observed as an access violation that took
        // down the host process, not as an error return. `ManuallyDrop` is what stops that.
    }
}

pub struct Breakpoint<'a> {
    control: &'a IDebugControl4,
    /// Never released by this wrapper: DbgEng owns breakpoint objects, and [`Self::remove`]
    /// destroys this one, so a `Release()` afterwards would be a use-after-free. See
    /// [`ScopedBreakpoint`], where the same hazard showed up as a host-process crash.
    breakpoint: std::mem::ManuallyDrop<IDebugBreakpoint>,
}

impl<'a> Breakpoint<'a> {
    pub fn new(engine: &'a DebugEngine) -> Result<Self, DbgEngError> {
        let breakpoint = unsafe {
            engine
                .control
                .AddBreakpoint(DEBUG_BREAKPOINT_CODE, DEBUG_ANY_ID)
        };

        if breakpoint.is_err() {
            return Err(DbgEngError::BreakpointFailed(breakpoint.err().unwrap()));
        }

        Ok(Self {
            breakpoint: std::mem::ManuallyDrop::new(breakpoint.unwrap()),
            control: &engine.control,
        })
    }

    pub fn set_offset_expression(&self, expression: &str) -> Result<(), DbgEngError> {
        // Mirror execute_command: return an error on malformed input rather than panic.
        let expr = CString::new(expression).map_err(|_| DbgEngError::InvalidCommand)?;

        unsafe {
            self.breakpoint
                .SetOffsetExpression(PCSTR::from_raw(expr.as_ptr() as *const u8))
                .map_err(DbgEngError::BreakpointFailed)?;
        }
        Ok(())
    }

    pub fn enable(&self) {
        unsafe {
            self.breakpoint
                .AddFlags(DEBUG_BREAKPOINT_ENABLED)
                .expect("[-] Failed to set breakpoint offset");
        }
    }

    pub fn disable(&self) {
        unsafe {
            self.breakpoint
                .RemoveFlags(DEBUG_BREAKPOINT_ENABLED)
                .expect("[-] Failed to remove breakpoint offset");
        }
    }

    pub fn remove(&self) {
        unsafe {
            self.control
                .RemoveBreakpoint(&*self.breakpoint)
                .expect("[-] Failed to remove breakpoint");
        }
    }
}

#[cfg(test)]
mod tests {
    use windows::Win32::System::Diagnostics::Debug::Extensions::{
        DEBUG_STATUS_BREAK, DEBUG_STATUS_IGNORE_EVENT, DEBUG_STATUS_NO_CHANGE,
        DEBUG_STATUS_OUT_OF_SYNC, DEBUG_STATUS_RESTART_REQUESTED, DEBUG_STATUS_TIMEOUT,
        DEBUG_STATUS_WAIT_INPUT, DEBUG_VALUE_0, DEBUG_VALUE_INVALID, DEBUG_VALUE_TYPES,
    };

    use super::*;

    /// The spelling a symbol server path uses, which is **not** the braced, dashed form `Debug`
    /// prints and not a byte-order-preserving dump either: the first three fields are written as
    /// the numbers they are, and only the trailing eight bytes are laid out in order.
    ///
    /// The value is `ntkrnlmp.pdb`'s for the ARM64 kernel in windbg-mcp's own sample dump, taken
    /// from the image's CodeView record — so this test pins the convention against a string that
    /// is known to fetch the right file rather than against a hand-built one.
    #[test]
    fn test_a_pdb_guid_is_spelled_the_way_a_symbol_server_path_is() {
        let guid = windows::core::GUID {
            data1: 0xFE3F_58BD,
            data2: 0xA39D,
            data3: 0x2FC1,
            data4: [0x3C, 0x37, 0x06, 0x18, 0xD1, 0xDB, 0xDF, 0x22],
        };
        assert_eq!(format_pdb_guid(&guid), "FE3F58BDA39D2FC13C370618D1DBDF22");
    }

    /// The engine renders one instruction as three columns. The split has to survive both
    /// architectures' padding, and it must take the address from the walk rather than from the
    /// line — the point of the record is that it is not a re-parse of a rendering.
    #[test]
    fn test_an_instruction_splits_into_its_encoding_and_its_mnemonic() {
        let x64 = split_instruction(
            0xfffff803_89201234,
            "fffff803`89201234 48895c2408      mov     qword ptr [rsp+8],rbx\n",
        );
        assert_eq!(x64.address, 0xfffff803_89201234);
        assert_eq!(x64.bytes, "48895c2408");
        assert_eq!(x64.text, "mov qword ptr [rsp+8],rbx");

        let arm64 = split_instruction(
            0xfffff803_89201234,
            "fffff803`89201234 a9bf7bfd     stp         fp,lr,[sp,#-0x10]!\n",
        );
        assert_eq!(arm64.bytes, "a9bf7bfd");
        assert_eq!(arm64.text, "stp fp,lr,[sp,#-0x10]!");
    }

    /// The address is the walk's, not the line's. Asserted against a line that disagrees, because
    /// agreeing lines cannot tell the two sources apart.
    #[test]
    fn test_an_instructions_address_comes_from_the_walk_not_the_rendering() {
        let one = split_instruction(0x1000, "deadbeef`deadbeef 90    nop");
        assert_eq!(one.address, 0x1000);
        assert_eq!(one.text, "nop");
    }

    /// An engine that renders a shape this does not know loses a column, never an instruction:
    /// the remainder is kept as text and nothing is presented as an encoding that is not one.
    #[test]
    fn test_an_unrecognised_line_keeps_its_text_rather_than_inventing_an_encoding() {
        let two_columns = split_instruction(0x1000, "fffff803`89201234 ????");
        assert!(two_columns.bytes.is_empty(), "{two_columns:?}");
        assert_eq!(two_columns.text, "????");

        let one_column = split_instruction(0x1000, "???");
        assert!(one_column.bytes.is_empty(), "{one_column:?}");
        assert_eq!(one_column.text, "???");
    }

    /// glslang/dbgscope#82: a borrowed engine's lifecycle used to die with the wrapper.
    ///
    /// The identity was the client pointer, so it was stable across the per-command wrappers an
    /// extension builds — which is what it was for — while an `end_session` bumped a field on a
    /// value dropped moments later. Rebuild the wrapper around the same client and the original
    /// pointer-derived identity came back, matching cache entries gathered from the target it
    /// had just let go of.
    ///
    /// One test rather than four: the registry is process-global, so separate tests could clear
    /// each other's entries through the cap below.
    #[test]
    fn test_a_clients_identity_outlives_the_wrapper_it_was_issued_to() {
        // Keys no real client pointer can collide with: an `IDebugClient6` is a heap
        // allocation, and these sit far below any address one lands at.
        let (client, other) = (0x11, 0x22);

        let first = identity_for(client);
        assert_eq!(
            identity_for(client),
            first,
            "a rebuilt wrapper keeps its caches"
        );
        assert_ne!(identity_for(other), first, "two clients are two targets");

        // The case that was lost: the wrapper that ends the session is gone by the time the
        // next one asks, so the bump has to be recorded against the client, not in the wrapper.
        let after_release = reissue_for(client);
        assert_ne!(after_release, first);
        assert_eq!(identity_for(client), after_release);

        // Forgetting an entry is safe by construction, and this is the claim that makes it so:
        // identities come from a counter that never repeats, so a dropped entry costs a re-walk
        // and can never resurrect a previous target's.
        for filler in 0..MAX_REMEMBERED_CLIENTS {
            identity_for(0x1000 + filler);
        }
        assert!(locked_identities().len() <= MAX_REMEMBERED_CLIENTS);
        assert!(
            identity_for(client) >= after_release,
            "a forgotten client is issued a later identity, never an earlier one"
        );

        // A client already known does not make room, because it does not need any. Clearing
        // before the lookup would take the identity of the very client being asked about — a
        // live one, mid-session — so the cap has to be reached with it present to see that.
        let mut identities = locked_identities();
        identities.clear();
        identities.insert(client, after_release);
        for filler in 1..MAX_REMEMBERED_CLIENTS {
            identities.insert(0x2000 + filler, next_target_identity());
        }
        assert_eq!(identities.len(), MAX_REMEMBERED_CLIENTS);
        drop(identities);
        assert_eq!(
            identity_for(client),
            after_release,
            "a client at the cap keeps the caches it is in the middle of using"
        );
        assert_eq!(locked_identities().len(), MAX_REMEMBERED_CLIENTS);

        // A client it has never seen is what makes room, and pays for it with everything.
        identity_for(0xbeef);
        assert!(locked_identities().len() < MAX_REMEMBERED_CLIENTS);
    }

    /// A `DEBUG_VALUE` carrying a value in the arm `type_code` names.
    fn tagged(type_code: u32, fill: impl FnOnce(&mut DEBUG_VALUE_0)) -> DEBUG_VALUE {
        let mut anonymous = DEBUG_VALUE_0::default();
        fill(&mut anonymous);
        DEBUG_VALUE {
            Anonymous: anonymous,
            TailOfRawBytes: 0,
            Type: type_code,
        }
    }

    /// The tag decides which arm is read, and nothing else does.
    ///
    /// Worth a test precisely because getting it wrong is invisible: every arm of the union
    /// occupies the same bytes, so a 32-bit register read as `I64` yields a number that looks
    /// like an answer. Each case below stores one arm and asserts the *other* interpretations do
    /// not leak into the result.
    #[test]
    fn a_register_value_is_read_by_the_arm_its_tag_names() {
        let int32 = tagged(DEBUG_VALUE_INT32, |v| v.I32 = 0xdead_beef);
        assert_eq!(
            RegisterValue::decode(&int32),
            RegisterValue::Int(0xdead_beef)
        );

        // The 64-bit arm of a value whose low half is the same bytes: read as I32 this would
        // silently drop the high half, which is the failure mode on every kernel pointer.
        let int64 = tagged(DEBUG_VALUE_INT64, |v| {
            v.Anonymous.I64 = 0xffff_8000_dead_beef
        });
        assert_eq!(
            RegisterValue::decode(&int64),
            RegisterValue::Int(0xffff_8000_dead_beef)
        );

        let byte = tagged(DEBUG_VALUE_INT8, |v| v.I8 = 0xff);
        assert_eq!(RegisterValue::decode(&byte), RegisterValue::Int(0xff));

        let float = tagged(DEBUG_VALUE_FLOAT64, |v| v.F64 = 1.5);
        assert_eq!(RegisterValue::decode(&float), RegisterValue::Float(1.5));
    }

    /// A vector register keeps all of its bytes, and an x87 one keeps its ten.
    ///
    /// The alternative — narrowing them to a scalar — is the one decoding choice that cannot be
    /// undone by the caller, so the width is pinned here.
    #[test]
    fn a_wide_register_keeps_every_byte() {
        let mut bytes = [0u8; 16];
        for (i, b) in bytes.iter_mut().enumerate() {
            *b = i as u8;
        }
        let vector = tagged(DEBUG_VALUE_VECTOR128, |v| v.VI8 = bytes);
        assert_eq!(
            RegisterValue::decode(&vector),
            RegisterValue::Bytes(bytes.to_vec())
        );

        let half = tagged(DEBUG_VALUE_VECTOR64, |v| v.VI8 = bytes);
        assert_eq!(
            RegisterValue::decode(&half),
            RegisterValue::Bytes(bytes[..8].to_vec())
        );

        let x87 = tagged(DEBUG_VALUE_FLOAT80, |v| v.F80Bytes = [7u8; 10]);
        assert_eq!(
            RegisterValue::decode(&x87),
            RegisterValue::Bytes(vec![7u8; 10])
        );
    }

    /// A type this build does not decode is reported as having no value, never as a number.
    #[test]
    fn an_undecodable_register_is_unavailable_rather_than_zero() {
        let unknown = tagged(DEBUG_VALUE_TYPES + 1, |v| {
            v.Anonymous.I64 = 0xdead_beef_dead_beef
        });
        assert_eq!(RegisterValue::decode(&unknown), RegisterValue::Unavailable);

        let invalid = tagged(DEBUG_VALUE_INVALID, |v| v.Anonymous.I64 = 1);
        assert_eq!(RegisterValue::decode(&invalid), RegisterValue::Unavailable);
    }

    /// A symbol type this build does not name keeps the engine's code instead of collapsing
    /// into `None` — which a caller would read as "this module has no symbols".
    #[test]
    fn an_unknown_symbol_type_is_not_reported_as_having_no_symbols() {
        assert_eq!(SymbolKind::from_engine(DEBUG_SYMTYPE_PDB), SymbolKind::Pdb);
        assert_eq!(
            SymbolKind::from_engine(DEBUG_SYMTYPE_DEFERRED),
            SymbolKind::Deferred
        );
        assert_eq!(
            SymbolKind::from_engine(DEBUG_SYMTYPE_NONE),
            SymbolKind::None
        );
        assert_eq!(SymbolKind::from_engine(4242), SymbolKind::Other(4242));
        assert!(SymbolKind::Pdb.has_type_info());
        assert!(SymbolKind::Dia.has_type_info());
        assert!(!SymbolKind::Export.has_type_info());
        assert!(!SymbolKind::Deferred.has_type_info());
    }

    #[test]
    fn a_breakpoint_type_keeps_an_unknown_code() {
        assert_eq!(
            BreakpointKind::from_engine(DEBUG_BREAKPOINT_CODE),
            BreakpointKind::Code
        );
        assert_eq!(
            BreakpointKind::from_engine(DEBUG_BREAKPOINT_DATA),
            BreakpointKind::Data
        );
        assert_eq!(BreakpointKind::from_engine(9), BreakpointKind::Other(9));
    }

    /// Engine buffers are fixed-size and NUL-terminated, so the tail past the NUL is whatever
    /// was there before — never part of the name.
    #[test]
    fn a_name_stops_at_the_nul_the_engine_wrote() {
        assert_eq!(nul_terminated(b"nt\0junkjunk"), "nt");
        assert_eq!(nul_terminated(b"\0"), "");
        assert_eq!(nul_terminated(b"no terminator"), "no terminator");
    }

    /// Connecting to a server that is not there is an **error**, not a panic and not a wait.
    ///
    /// Worth pinning because [`DebugEngine::connect`] is the one constructor whose failure comes
    /// from outside this process — the host may be absent, refusing, or running an engine the
    /// local one will not talk to — where the constructors beside it (`new`,
    /// `from_windbg_client`) answer that class of problem with `expect`. A caller that gets a
    /// panic here cannot report which server it failed to reach, and one that blocks cannot
    /// report anything at all.
    #[cfg(not(miri))]
    #[test]
    fn test_connecting_to_a_server_that_is_not_there_is_an_error() {
        // A pipe nothing publishes. This path creates no session — the connection fails before
        // there is one — so unlike the engine tests below it needs no serialization against the
        // process-wide debuggee.
        let options = "npipe:pipe=dbgscope-no-such-server-2f9c41d8,server=localhost";
        // `let else` rather than `expect_err`, which would want `DebugEngine: Debug`.
        let Err(err) = DebugEngine::connect(options) else {
            panic!("nothing is serving `{options}`, so connecting to it must fail");
        };
        // The connection string travels in the message. This is the one error whose cause is a
        // thing the caller named, and a log line that omits it says only that *a* server was
        // unreachable.
        assert!(err.to_string().contains(options), "{err}");
    }

    #[cfg(not(miri))]
    #[test]
    fn test_create_debug_engine() {
        // Serialized like every other engine test: this one's `Drop` ends the process-wide
        // debuggee session, which is not this process's to end while another test holds one.
        let _debuggee = one_debuggee();
        // Create new debug engine instance
        let _ = DebugEngine::new();

        println!("Debug engine created successfully");

        // DebugEngine's Drop impl will handle cleanup and detach
    }

    /// The half of glslang/dbgscope#82 that a registry alone does not close, and the reason the
    /// identity is not a field: two wrappers can be live around one client at once.
    ///
    /// With a copy in each, an `end_session` through one moves that one and the registry and
    /// leaves the other answering with an identity whose target is gone — so a snapshot or
    /// layout cached against it is served for whatever is opened next, which is the same stale
    /// read the issue was about arriving through a second wrapper instead of a later one.
    #[cfg(not(miri))]
    #[test]
    fn test_every_live_wrapper_sees_a_release_through_any_of_them() {
        // Serialized like every other engine test: this one's `Drop` ends the process-wide
        // debuggee session.
        let _debuggee = one_debuggee();
        let owner = DebugEngine::new();
        // A second wrapper around the *same* client, which is what an extension builds per
        // command. `clone` bumps the COM refcount and keeps the pointer, so both agree.
        let borrowed = DebugEngine::from_client_interface(owner.client.clone());
        let before = owner.target_identity();
        assert_eq!(borrowed.target_identity(), before);

        // There is no target to end, so the call itself fails. The identity moves before it
        // tries, which is the half this is about.
        let _ = owner.end_session();
        assert_ne!(
            owner.target_identity(),
            before,
            "a release moves the identity"
        );
        assert_eq!(
            borrowed.target_identity(),
            owner.target_identity(),
            "a wrapper that did not perform the release still has to observe it"
        );
    }

    /// Reads a debugger pseudo-register (`$t0`, …) as a number, via `? <expr>` — whose output
    /// is `Evaluate expression: <decimal> = <hex>`. `None` when no value came back.
    ///
    /// Fallible rather than panicking, because a read that fails is one of the outcomes these
    /// tests are here to observe: on an engine where a stale interrupt aborts the next
    /// command, this read can *be* that next command. Panicking would crash out of the
    /// measurement instead of recording it.
    #[cfg(not(miri))]
    fn read_pseudo_register_opt(e: &DebugEngine, expr: &str) -> Option<u64> {
        eval_expression(e, &format!("@{expr}"))
    }

    /// Evaluates a debugger expression — a symbol, an address, a pseudo-register — via
    /// `? <expr>`, whose output is `Evaluate expression: <decimal> = <hex>`. `None` when no
    /// value came back, for the same reason as [`read_pseudo_register_opt`].
    #[cfg(not(miri))]
    fn eval_expression(e: &DebugEngine, expr: &str) -> Option<u64> {
        let out = e.execute_command(&format!("? {expr}")).ok()?;
        let tail = out.split("Evaluate expression: ").nth(1)?;
        let digits: String = tail.chars().take_while(char::is_ascii_digit).collect();
        digits.parse().ok()
    }

    /// Breakpoints the engine currently holds, as `bl` lines. `None` when `bl` itself failed —
    /// which must not be read as "no breakpoints", since that is the answer these tests want.
    #[cfg(not(miri))]
    fn breakpoints(e: &DebugEngine) -> Option<Vec<String>> {
        let out = e.execute_command("bl").ok()?;
        Some(
            out.lines()
                .map(str::trim)
                // `DEBUG_EXECUTE_ECHO` puts the command itself in the buffer first.
                .filter(|line| !line.is_empty() && *line != "bl")
                .map(str::to_string)
                .collect(),
        )
    }

    /// [`read_pseudo_register_opt`] for call sites where a failed read means the test's own
    /// setup is broken rather than an observation — reading `$t0` after a command that is
    /// asserted to have run, for instance.
    #[cfg(not(miri))]
    fn read_pseudo_register(e: &DebugEngine, expr: &str) -> u64 {
        read_pseudo_register_opt(e, expr)
            .unwrap_or_else(|| panic!("could not read {expr} from the engine"))
    }

    /// Runs a command and reports whether it actually *took effect*, by having it stamp a
    /// sentinel into `$t1` and reading it back.
    ///
    /// Substring-matching the captured output cannot answer this. `execute_command` passes
    /// `DEBUG_EXECUTE_ECHO`, so DbgEng echoes the command text into the output buffer before
    /// running it, and [`OutputCallbacks`] appends every chunk unfiltered — a check like
    /// `output.contains("version")` therefore matches the echo alone and passes even when the
    /// command was aborted immediately after being echoed, which is precisely the failure
    /// these tests exist to catch.
    ///
    /// Every step is fallible and none of them panic. The clear below is itself a command, so
    /// on an engine where a stale interrupt does abort the next one, *this* is the command it
    /// aborts — panicking there would take out the measurement the caller is in the middle of,
    /// and the undrained case could never report the very behaviour it exists to report. A
    /// probe that cannot run at all is caught instead by the caller's baseline assertion,
    /// taken before anything is staged.
    #[cfg(not(miri))]
    fn command_took_effect(e: &DebugEngine, sentinel: u64) -> bool {
        // Clear first, so a value left by an earlier probe cannot pass for a fresh one.
        if e.execute_command("r $t1 = 0").is_err() || read_pseudo_register_opt(e, "$t1") != Some(0)
        {
            return false;
        }
        if e.execute_command(&format!("r $t1 = 0x{sentinel:x}"))
            .is_err()
        {
            return false;
        }
        read_pseudo_register_opt(e, "$t1") == Some(sentinel)
    }

    /// Every status the engine can be in while it is waiting to be pumped, and every one it
    /// cannot — pinned by value, because the whole point of asking the engine instead of reading
    /// the command is that this predicate is the only thing standing between a half-alive session
    /// and a settled one.
    #[test]
    fn every_go_and_step_status_is_a_running_one_and_nothing_else_is() {
        for status in [
            DEBUG_STATUS_GO,
            DEBUG_STATUS_GO_HANDLED,
            DEBUG_STATUS_GO_NOT_HANDLED,
            DEBUG_STATUS_STEP_OVER,
            DEBUG_STATUS_STEP_INTO,
            DEBUG_STATUS_STEP_BRANCH,
            DEBUG_STATUS_REVERSE_GO,
            DEBUG_STATUS_REVERSE_STEP_BRANCH,
            DEBUG_STATUS_REVERSE_STEP_OVER,
            DEBUG_STATUS_REVERSE_STEP_INTO,
        ] {
            assert!(
                is_running_status(status),
                "status {status} reads as stopped"
            );
        }
        for status in [
            DEBUG_STATUS_NO_CHANGE,
            DEBUG_STATUS_BREAK,
            DEBUG_STATUS_NO_DEBUGGEE,
            DEBUG_STATUS_IGNORE_EVENT,
            DEBUG_STATUS_RESTART_REQUESTED,
            DEBUG_STATUS_OUT_OF_SYNC,
            DEBUG_STATUS_WAIT_INPUT,
            DEBUG_STATUS_TIMEOUT,
        ] {
            assert!(
                !is_running_status(status),
                "status {status} reads as running"
            );
        }
    }

    /// A watchdog that is disarmed before its deadline returns **at once** and never fires.
    ///
    /// The "at once" is the assertion that matters, and it is a regression test rather than a
    /// tautology: both bounded paths here used to poll a flag on a 200/300ms sleep, so `join` sat
    /// out the rest of that interval on every call — the tax that made a finite `WaitForEvent`
    /// look like the cheaper option for user-mode targets, which is the bug this branch exists to
    /// fix. The bound is deliberately loose (a CI runner is not a bench) and still an order of
    /// magnitude under the old floor.
    #[cfg(not(miri))]
    #[test]
    fn a_watchdog_disarmed_before_its_deadline_costs_nothing() {
        let fires = Arc::new(AtomicU64::new(0));
        let counted = Arc::clone(&fires);
        let watchdog = Watchdog::arm(Duration::from_secs(30), move || {
            counted.fetch_add(1, Ordering::SeqCst);
        });
        let started = Instant::now();
        let fired = watchdog.disarm();
        let took = started.elapsed();
        assert!(!fired, "a watchdog 30s from its deadline reported firing");
        assert_eq!(fires.load(Ordering::SeqCst), 0);
        assert!(
            took < Duration::from_millis(50),
            "disarming took {took:?}; it waits for a wake-up, not for a poll interval"
        );
    }

    /// Past its deadline a watchdog fires, and keeps firing until it is disarmed.
    ///
    /// The repeat is not decoration: one `SetInterrupt` is a request the engine acts on at its
    /// next poll, and a busy operation can be between polls when it arrives.
    #[cfg(not(miri))]
    #[test]
    fn a_watchdog_past_its_deadline_keeps_raising_the_break() {
        let fires = Arc::new(AtomicU64::new(0));
        let counted = Arc::clone(&fires);
        // Zero means "no time at all", so the first raise is immediate.
        let watchdog = Watchdog::arm(Duration::ZERO, move || {
            counted.fetch_add(1, Ordering::SeqCst);
        });
        thread::sleep(WATCHDOG_REPEAT * 3);
        assert!(
            watchdog.disarm(),
            "a watchdog past its deadline reported not firing"
        );
        let fires = fires.load(Ordering::SeqCst);
        assert!(
            fires >= 2,
            "raised the break {fires} time(s) over three repeat intervals; it must repeat"
        );
    }

    /// A `go` that reaches no stop leaves the engine **usable** — the regression this branch is
    /// named for.
    ///
    /// Before it, `execute_and_wait` used a finite `WaitForEvent` for everything that was not a
    /// live kernel. On expiry that returns `S_FALSE` with the target still running and the engine
    /// holding no current process/thread, so this test's `command_took_effect` was `false` and
    /// stayed `false` for the life of the session — while the call itself reported success, which
    /// is what made it invisible. `run_to_address` has used the bounded wait for every target
    /// since it was written, and documents exactly this; only this path did not.
    ///
    /// Ignored: needs a live target; see the note above these tests.
    /// `cargo test --lib -- --ignored --nocapture --test-threads=1 a_go_that_never_stops`
    #[cfg(not(miri))]
    #[test]
    #[ignore = "needs a live debuggee; run manually with --ignored"]
    fn a_go_that_never_stops_is_reported_and_leaves_the_engine_usable() {
        let e = DebugEngine::new();
        e.launch_process("cmd.exe /c ping -n 30 127.0.0.1")
            .expect("launch failed");

        // No breakpoints, and a target that runs for half a minute: nothing will stop this.
        let run = e
            .execute_and_wait("g", 2_000)
            .expect("execute_and_wait errored");
        assert_eq!(
            run.cut_short,
            Some(Interruption::Deadline { after_ms: 2_000 }),
            "a `g` broken in at its own bound must say so rather than pass for a stop: {}",
            run.output
        );
        assert!(
            command_took_effect(&e, 0x67),
            "the engine is unusable after a `g` that did not stop — the target was left running \
             with no current process/thread"
        );
        let _ = e.end_session();
    }

    /// The same for the two step commands, which take the identical path and were identically
    /// broken. A step on a target that is about to spend thirty seconds inside one `ping` still
    /// completes, so this asserts the *shape*: the call reports what happened, and the engine is
    /// usable afterwards either way.
    ///
    /// Ignored: needs a live target; see the note above these tests.
    /// `cargo test --lib -- --ignored --nocapture --test-threads=1 stepping_leaves`
    #[cfg(not(miri))]
    #[test]
    #[ignore = "needs a live debuggee; run manually with --ignored"]
    fn stepping_leaves_the_engine_usable_whether_or_not_it_reaches_a_stop() {
        let e = DebugEngine::new();
        e.launch_process("cmd.exe /c ping -n 30 127.0.0.1")
            .expect("launch failed");

        for command in ["p", "t"] {
            let run = e
                .execute_and_wait(command, 2_000)
                .unwrap_or_else(|why| panic!("`{command}` errored: {why}"));
            assert!(
                !matches!(run.cut_short, Some(Interruption::OnRequest)),
                "`{command}` reported a break somebody asked for; nobody did"
            );
            assert!(
                command_took_effect(&e, 0x68),
                "the engine is unusable after `{command}`: {}",
                run.output
            );
        }
        let _ = e.end_session();
    }

    /// `settle` is the other half, and this is the reported bug end to end: a plain `Execute` of
    /// execution-control text sets the run state and returns, and until something pumps it the
    /// session refuses every later `g`/`p`/`t` with `0x80040205` while answering read-only
    /// commands normally.
    ///
    /// All three commands, because all three are doors to the same state and a fix that closed one
    /// would look identical from the outside. Asserted in the order that makes each step mean
    /// something: the engine reads as running *only* after the raw command, the pump reports what
    /// the target did, and execution control works again afterwards — which it does not without
    /// the settle.
    ///
    /// Ignored: needs a live target; see the note above these tests.
    /// `cargo test --lib -- --ignored --nocapture --test-threads=1 settle`
    #[cfg(not(miri))]
    #[test]
    #[ignore = "needs a live debuggee; run manually with --ignored"]
    fn settle_pumps_the_run_state_a_raw_command_left_behind() {
        let e = DebugEngine::new();
        e.launch_process("cmd.exe /c ping -n 30 127.0.0.1")
            .expect("launch failed");

        assert!(
            !e.is_running().expect("could not read the execution status"),
            "a freshly launched target is stopped at its initial breakpoint"
        );
        assert!(
            e.settle(2_000).expect("settle errored").is_none(),
            "settle pumped a target that was already stopped"
        );

        for (command, sentinel) in [("g", 0x67u64), ("p", 0x68), ("t", 0x69)] {
            // The bug, in one call: a plain `Execute` sets the run state and moves nothing.
            e.execute_command_bounded(command, 0).unwrap_or_else(|why| {
                panic!("the raw `{command}` itself should succeed — it is the pump that is missing: {why}")
            });
            assert!(
                e.is_running().expect("could not read the execution status"),
                "a raw `{command}` left the engine reading as stopped, so there is nothing here to settle"
            );

            let settled = e
                .settle(2_000)
                .expect("settle errored")
                .unwrap_or_else(|| panic!("settle found nothing to pump after a raw `{command}`"));
            assert!(
                !e.is_running().expect("could not read the execution status"),
                "settle returned with the engine still running after `{command}`: {}",
                settled.output
            );

            // The property the whole thing is for: execution control works again. Before the
            // settle this call fails with 0x80040205, and so does every one after it.
            let run = e.execute_and_wait("g", 2_000).unwrap_or_else(|why| {
                panic!("execution control is still refused after settling `{command}`: {why}")
            });
            assert!(
                command_took_effect(&e, sentinel),
                "the engine is unusable after settling `{command}` and running `g`: {}",
                run.output
            );
        }
        let _ = e.end_session();
    }

    // The `#[ignore]`d tests below each drive a real debuggee, and MUST be run with
    // `--test-threads=1`. dbgeng.dll holds one debuggee session per *process*, so two of them
    // running concurrently in the same test binary fight over the same session and fail in
    // ways that look like engine bugs. Individually they pass under the default harness; as a
    // group they do not.
    //
    // They are ignored rather than gated on an env var because CI has no target to give them
    // on any platform, so there is no configuration in which they would run there.

    /// A reachable address: `run_to_address` reports [`RunToOutcome::Hit`] and leaves no
    /// breakpoint behind.
    ///
    /// Ignored: needs a live target; see the note above these tests.
    /// `cargo test --lib -- --ignored --nocapture --test-threads=1 test_run_to_address_hit`
    #[cfg(not(miri))]
    #[test]
    #[ignore = "needs a live debuggee; run manually with --ignored"]
    fn test_run_to_address_hit_removes_its_breakpoint() {
        let e = DebugEngine::new();
        e.launch_process("cmd.exe /c ping -n 30 127.0.0.1")
            .expect("launch failed");
        assert_eq!(
            breakpoints(&e).expect("bl failed"),
            Vec::<String>::new(),
            "the target should start with no breakpoints"
        );

        // `cmd.exe` opens files as it starts up, so this is reached.
        let addr = eval_expression(&e, "ntdll!NtCreateFile").expect("could not resolve symbol");
        let res = e
            .run_to_address(addr, 20_000)
            .expect("run_to_address errored");
        assert_eq!(res.outcome, RunToOutcome::Hit, "output: {}", res.output);

        // Not vacuous: an `Ok` outcome means the breakpoint was successfully added, so an
        // empty `bl` here can only mean it was removed again. `breakpoints` returns None
        // rather than an empty list if `bl` itself fails.
        assert_eq!(
            breakpoints(&e).expect("bl failed"),
            Vec::<String>::new(),
            "run_to_address left its breakpoint armed after a hit"
        );
        let _ = e.end_session();
    }

    /// An address the target never reaches: `run_to_address` reports
    /// [`RunToOutcome::Timeout`], leaves no breakpoint behind, and leaves the engine usable.
    ///
    /// The last part is the regression that motivated the rewrite. Detecting the timeout from
    /// `GetExecutionStatus` did not work — an expired wait reports `DEBUG_STATUS_BREAK`, not
    /// `DEBUG_STATUS_GO`, and the engine has dropped the current process/thread by then — so
    /// this case used to fall through to a register read that failed with `0x8000FFFF`,
    /// returning a "Catastrophic failure" error and no usable session.
    ///
    /// Ignored: needs a live target; see the note above these tests.
    /// `cargo test --lib -- --ignored --nocapture --test-threads=1 test_run_to_address_timeout`
    #[cfg(not(miri))]
    #[test]
    #[ignore = "needs a live debuggee; run manually with --ignored"]
    fn test_run_to_address_timeout_removes_its_breakpoint() {
        let e = DebugEngine::new();
        e.launch_process("cmd.exe /c ping -n 30 127.0.0.1")
            .expect("launch failed");

        // Nothing in this target calls it.
        let addr = eval_expression(&e, "ntdll!NtShutdownSystem").expect("could not resolve symbol");
        let res = e
            .run_to_address(addr, 2_000)
            .expect("run_to_address errored");
        assert_eq!(res.outcome, RunToOutcome::Timeout, "output: {}", res.output);

        assert_eq!(
            breakpoints(&e).expect("bl failed"),
            Vec::<String>::new(),
            "run_to_address left its breakpoint armed after a timeout — a later `g` passing              that address would stop there spuriously"
        );
        assert!(
            command_took_effect(&e, 0x63),
            "the engine is unusable after a timeout — the target was left running, or the              current process/thread was never restored"
        );
        let _ = e.end_session();
    }

    /// Probes whether `GetInterrupt` *consumes* a pending `SetInterrupt`, which
    /// [`DebugEngine::execute_command_bounded`]'s stale-interrupt drain assumes. DbgEng
    /// documents `GetInterrupt` as a check (S_OK requested / S_FALSE not); whether it also
    /// clears is not documented, so it is measured rather than assumed.
    ///
    /// Ignored: needs a live target, which CI has no way to provide. See the note above these
    /// tests on why they must not run in parallel.
    /// `cargo test --lib -- --ignored --nocapture --test-threads=1 test_get_interrupt`
    #[cfg(not(miri))]
    #[test]
    #[ignore = "needs a live debuggee; run manually with --ignored"]
    fn test_get_interrupt_drain_semantics() {
        let e = DebugEngine::new();
        e.launch_process("cmd.exe /c exit").expect("launch failed");

        // Asserted, not just printed: this test is the record the production drain rests on,
        // so an engine that stopped clearing — or started counting — has to fail here rather
        // than quietly print a different vector on a manual run.
        const DRAINS_ON_FIRST_POLL: [bool; 5] = [true, false, false, false, false];

        // One request in.
        unsafe { e.control.SetInterrupt(DEBUG_INTERRUPT_ACTIVE) }.expect("SetInterrupt failed");
        let polls: Vec<bool> = (0..5).map(|_| e.interrupted().unwrap()).collect();
        println!("after 1x SetInterrupt, five GetInterrupt polls: {polls:?}");
        assert_eq!(
            polls, DRAINS_ON_FIRST_POLL,
            "GetInterrupt no longer clears the pending request on this engine"
        );

        // Several requests in, since the watchdog re-fires every 200ms while past its
        // deadline: does one poll clear them all, or one each?
        for _ in 0..3 {
            unsafe { e.control.SetInterrupt(DEBUG_INTERRUPT_ACTIVE) }.expect("SetInterrupt failed");
        }
        let polls: Vec<bool> = (0..5).map(|_| e.interrupted().unwrap()).collect();
        println!("after 3x SetInterrupt, five GetInterrupt polls: {polls:?}");
        assert_eq!(
            polls, DRAINS_ON_FIRST_POLL,
            "repeated SetInterrupt now accumulates; one drain no longer suffices"
        );

        let _ = e.end_session();
    }

    /// Forces the exact race the drain targets, which ordinary timing almost never hits: a
    /// `SetInterrupt` landing *after* `Execute` has returned, leaving a Ctrl+Break pending
    /// with no command running.
    ///
    /// Named for what it measures, not for a result: on the engine tested a stale interrupt
    /// does **not** abort the next command, short or long, so only the drained case is
    /// asserted. The undrained case prints its observation rather than asserting one, because
    /// pinning it down would encode "stale interrupts are harmless" as a requirement — the
    /// opposite of what this test exists to keep watching.
    ///
    /// Ignored: needs a live target; see the note above these tests.
    /// `cargo test --lib -- --ignored --nocapture --test-threads=1 test_stale_interrupt`
    #[cfg(not(miri))]
    #[test]
    #[ignore = "needs a live debuggee; run manually with --ignored"]
    fn test_stale_interrupt_effect_on_the_next_command() {
        let e = DebugEngine::new();
        e.launch_process("cmd.exe /c exit").expect("launch failed");

        // Baseline: the probe reports a healthy engine before anything is staged.
        assert!(
            command_took_effect(&e, 0xBA5E),
            "baseline command did not take effect; the probe is broken, not the engine"
        );

        // Undrained: stage the race, then run a command.
        unsafe { e.control.SetInterrupt(DEBUG_INTERRUPT_ACTIVE) }.expect("SetInterrupt failed");
        let undrained = command_took_effect(&e, 0xA11);
        println!("undrained next command took effect: {undrained}");

        // Drained: stage the same race, consume it, then run the same command.
        //
        // The drain's return value is asserted, not discarded. `Execute` resets the request
        // itself, so if the staged interrupt never registered — or `GetInterrupt` errored —
        // the `version` below would still succeed and this case would pass while draining
        // nothing. The assertion is what makes it the *drained* case rather than a second
        // undrained one, and it has to stand on its own here: this test is documented as
        // runnable by name, without `test_get_interrupt_drain_semantics` to catch it first.
        unsafe { e.control.SetInterrupt(DEBUG_INTERRUPT_ACTIVE) }.expect("SetInterrupt failed");
        assert!(
            e.interrupted().expect("GetInterrupt failed"),
            "staged interrupt was not pending — nothing was drained, so the case below is not \
             the drained one it claims to be"
        );
        let drained = command_took_effect(&e, 0xB22);
        println!("drained   next command took effect: {drained}");

        // A short command like `version` may simply never poll for the interrupt. The case
        // that matters is a *long* next command, which does — if a stale Ctrl+Break aborts
        // that, the drain is load-bearing; if not, it is a no-op.
        // Whether it *finished* is read from `$t0`, not inferred from the clock.
        const LONG_ITERS: u64 = 0x4_0000;
        let long = format!(".for (r $t0 = 0; @$t0 < 0x{LONG_ITERS:x}; r $t0 = @$t0 + 1) {{ }}");

        // Seed `$t0` with a value the loop cannot produce before *each* run. The loop's own
        // `r $t0 = 0` initializer is part of the command, so an abort landing before it leaves
        // `$t0` holding `LONG_ITERS` from the previous run — which would read as "completed"
        // and report the immediate abort, the very case this probe exists to catch, as "did
        // NOT abort". Seeding makes "never started" its own observable value.
        const UNSTARTED: u64 = 0xDEAD_BEEF;
        let seed = format!("r $t0 = 0x{UNSTARTED:x}");

        e.execute_command(&seed).expect("seeding $t0 failed");
        let clean_start = Instant::now();
        e.execute_command(&long).expect("long command failed");
        let clean = clean_start.elapsed();
        let clean_t0 = read_pseudo_register(&e, "$t0");
        assert_eq!(
            clean_t0, LONG_ITERS,
            "the uninterrupted run did not complete — the probe is broken, not the engine"
        );

        e.execute_command(&seed).expect("seeding $t0 failed");
        unsafe { e.control.SetInterrupt(DEBUG_INTERRUPT_ACTIVE) }.expect("SetInterrupt failed");
        let stale_start = Instant::now();
        let stale = e.execute_command(&long);
        let stale_elapsed = stale_start.elapsed();
        let stale_t0 = read_pseudo_register_opt(&e, "$t0");
        let stale_result = if stale.is_ok() { "Ok" } else { "Err" };
        println!("long command, clean:           {clean:?} (t0={clean_t0} of {LONG_ITERS})");
        println!(
            "long command, stale interrupt: {stale_elapsed:?} (t0={stale_t0:?} of {LONG_ITERS}, {stale_result})"
        );
        println!(
            "  -> stale interrupt {} the long command",
            match stale_t0 {
                None => "gave no readable $t0 after",
                Some(UNSTARTED) => "ABORTED, before the loop even started,",
                Some(t0) if t0 < LONG_ITERS => "ABORTED mid-loop",
                _ => "did NOT abort",
            }
        );
        let _ = e.interrupted();

        // Only the drained case is asserted; the undrained ones are the measurement.
        assert!(
            drained,
            "draining should leave the next command fully usable"
        );

        let _ = e.end_session();
    }

    /// The behaviour the drain exists to protect, end to end: after a bounded command is
    /// cut short by its watchdog, the *next* command must run normally rather than being
    /// aborted by a Ctrl+Break left pending behind it.
    ///
    /// Ignored: needs a live target; see the note above these tests.
    /// `cargo test --lib -- --ignored --nocapture --test-threads=1 test_next_command`
    #[cfg(not(miri))]
    #[test]
    #[ignore = "needs a live debuggee; run manually with --ignored"]
    fn test_next_command_survives_a_bounded_timeout() {
        let e = DebugEngine::new();
        e.launch_process("cmd.exe /c exit").expect("launch failed");

        // A deliberately runaway command. Note a broad `s` search does *not* work here: it
        // skips unmapped ranges, so even `L?0x7fffffffff` returns almost immediately. A tight
        // `.for` in the expression evaluator is genuinely CPU-bound and interruptible, and it
        // leaves its progress behind in `$t0` — which is what proves the interruption below.
        const ITERATIONS: u64 = 0x100_0000;
        const TIMEOUT_MS: u32 = 1_500;
        let started = Instant::now();
        let out = e
            .execute_command_bounded(
                &format!(".for (r $t0 = 0; @$t0 < 0x{ITERATIONS:x}; r $t0 = @$t0 + 1) {{ }}"),
                TIMEOUT_MS,
            )
            .expect("bounded command should return, not error");
        let elapsed = started.elapsed();

        // Proof of interruption is the loop counter, not the clock and not the diagnostic
        // note. The note is appended whenever the watchdog *attempted* `SetInterrupt`, so an
        // interrupt the engine ignored still produces it. A wall-clock bound is no better: it
        // has to be picked for this host, and on a faster machine or a cheaper `.for` the loop
        // could finish naturally inside the bound, passing both checks while the watchdog did
        // nothing. `$t0` is host-independent — short of `ITERATIONS`, the loop did not finish.
        let t0 = read_pseudo_register(&e, "$t0");
        println!("bounded command returned after {elapsed:?}, $t0 = {t0} of {ITERATIONS}");
        assert!(t0 > 0, "loop never started; $t0 = {t0}");
        assert!(
            t0 < ITERATIONS,
            "loop ran to completion ($t0 = {t0}) — the watchdog did not cut it short, so the \
             rest of this test would prove nothing"
        );
        assert_eq!(
            out.cut_short,
            Some(Interruption::Deadline {
                after_ms: TIMEOUT_MS
            }),
            "a loop that stopped short has to say a deadline stopped it"
        );

        // The command under test. If a stale interrupt survived, this aborts instead — so the
        // check has to be that it *took effect*, not that its text came back. `Execute` echoes
        // the command into the output buffer before running it, which makes any substring
        // check against the command name pass on the echo alone.
        assert!(
            command_took_effect(&e, 0x5A5E),
            "next command did not take effect — a stale interrupt aborted it"
        );

        let _ = e.end_session();
    }

    /// The same command, cut short by an [`InterruptHandle`] instead of by a deadline: the
    /// partial output comes back as `Ok`, without the watchdog's note, and the engine is left
    /// usable.
    ///
    /// The `Ok` is the whole point of the shared flag. `SetInterrupt` makes `Execute` fail, so
    /// without it an abort on request is a `CommandFailed` — the caller loses every line the
    /// command had already produced, which on an interrupted search is the only thing it was
    /// ever going to get. The absent note is the other half: a watchdog explains itself because
    /// nobody saw the deadline pass, whereas this caller is the one who asked.
    ///
    /// Ignored: needs a live target; see the note above these tests.
    /// `cargo test --lib -- --ignored --nocapture --test-threads=1 test_command_interrupted_on_request`
    #[cfg(not(miri))]
    #[test]
    #[ignore = "needs a live debuggee; run manually with --ignored"]
    fn test_command_interrupted_on_request_keeps_its_output() {
        let e = DebugEngine::new();
        e.launch_process("cmd.exe /c exit").expect("launch failed");

        // As in the watchdog test above: a genuinely CPU-bound `.for` that polls for the
        // interrupt and leaves its progress in `$t0`, which is what proves it was cut short.
        const ITERATIONS: u64 = 0x100_0000;
        let long = format!(".for (r $t0 = 0; @$t0 < 0x{ITERATIONS:x}; r $t0 = @$t0 + 1) {{ }}");

        // Raised from another thread while the command runs — the arrangement the handle exists
        // for. A delay rather than a handshake because there is nothing to hand shake with: the
        // engine thread is inside `Execute` and the only observable it publishes is the loop
        // counter this test reads afterwards.
        let handle = e.interrupt_handle();
        let asker = thread::spawn(move || {
            thread::sleep(Duration::from_millis(1_500));
            handle.interrupt().expect("SetInterrupt failed");
        });

        // No watchdog of its own (`0`), so anything that stops this command came from the thread
        // above and the result cannot be credited to the deadline path by accident.
        let out = e
            .execute_command_bounded(&long, 0)
            .expect("an interrupted command must return its partial output, not an error");
        asker.join().expect("the interrupting thread panicked");

        let t0 = read_pseudo_register(&e, "$t0");
        println!("command interrupted on request, $t0 = {t0} of {ITERATIONS}");
        assert!(t0 > 0, "loop never started; $t0 = {t0}");
        assert!(
            t0 < ITERATIONS,
            "loop ran to completion ($t0 = {t0}) — the interrupt never reached it, so the rest \
             of this test would prove nothing"
        );
        assert_eq!(
            out.cut_short,
            Some(Interruption::OnRequest),
            "the break came from the handle, not from a deadline — and which it was is what a \
             caller renders its advice from"
        );

        // And the next command is unaffected, which is what the drain is for.
        assert!(
            command_took_effect(&e, 0x1234),
            "next command did not take effect — the requested interrupt was left pending"
        );

        let _ = e.end_session();
    }

    /// Serializes the tests that build a [`DebugEngine`].
    ///
    /// dbgeng holds **one debuggee session per process** and `DebugEngine::drop` ends it, so
    /// two engine tests sharing a test binary either lose the race to open a target — the
    /// launch fails with `0x80004005` — or end each other's session on the way out.
    ///
    /// Nothing under `cargo nextest run`, which gives every test its own process and is what CI
    /// and this repo's instructions use. Load-bearing under plain `cargo test`, which the
    /// coverage workflow runs. (The `#[ignore]`d tests above have the same requirement, met the
    /// other way: they are documented as needing `--test-threads=1`.)
    #[cfg(not(miri))]
    static ONE_DEBUGGEE: Mutex<()> = Mutex::new(());

    #[cfg(not(miri))]
    fn one_debuggee() -> std::sync::MutexGuard<'static, ()> {
        // A test that panics while holding this poisons it. The next test still needs the
        // lock, and its own assertion is a better failure message than a poison error.
        ONE_DEBUGGEE.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Puts the session somewhere other than its default scope, and says what did it.
    ///
    /// `None` means nothing moved — which the scope tests below must treat as a failure rather
    /// than a pass, since a scope that never moved is restored by doing nothing at all.
    #[cfg(not(miri))]
    fn move_the_scope(e: &DebugEngine) -> Option<&'static str> {
        let before = e.scope().ok()?;
        for command in [".frame 1", ".frame 2", ".ecxr"] {
            let _ = e.execute_command(command);
            if e.scope().ok()? != before {
                return Some(command);
            }
        }
        None
    }

    #[test]
    #[cfg(not(miri))]
    fn a_scope_needs_a_target_to_be_read_from() {
        let _debuggee = one_debuggee();
        let e = DebugEngine::new();
        // Measured: `GetScope` answers `E_UNEXPECTED` with no target, for every buffer size
        // including none at all. So there is no scope to report as empty — only an error.
        let err = e
            .scope()
            .expect_err("an engine holding no target reported a scope");
        println!("scope() with no target: {err}");
    }

    #[test]
    #[cfg(not(miri))]
    fn a_saved_scope_is_the_one_restored() {
        let _debuggee = one_debuggee();
        let e = DebugEngine::new();
        e.launch_process("cmd.exe /c exit").expect("launch failed");

        let moved_by = move_the_scope(&e).expect("nothing moved the scope; the rest is vacuous");
        let saved = e.scope().expect("scope() failed");
        println!("scope moved by `{moved_by}`: {saved:?}");
        // The context is what makes this more than a frame number, and its buffer is sized by
        // walking `SCOPE_CONTEXT_SIZES`. A live target on any architecture the CI runs (x64 and
        // ARM64) must find its size in there.
        assert!(
            saved.has_context(),
            "no size in SCOPE_CONTEXT_SIZES covered this target's CONTEXT"
        );

        // Move again, so the restore has something to undo.
        e.execute_command(".frame 0").expect(".frame 0 failed");
        assert_ne!(
            e.scope().expect("scope() failed"),
            saved,
            "the second move did not move anything"
        );

        e.set_scope(&saved).expect("set_scope failed");
        assert_eq!(
            e.scope().expect("scope() failed"),
            saved,
            "the scope that came back is not the one that was saved"
        );
        let _ = e.end_session();
    }

    #[test]
    #[cfg(not(miri))]
    fn a_guard_restores_the_scope_even_when_the_caller_panics() {
        let _debuggee = one_debuggee();
        let e = DebugEngine::new();
        e.launch_process("cmd.exe /c exit").expect("launch failed");
        move_the_scope(&e).expect("nothing moved the scope; the rest is vacuous");
        let before = e.scope().expect("scope() failed");

        // The path a hand-written save/restore pair misses. `AssertUnwindSafe` because the
        // engine is deliberately shared across the boundary: whether it was left consistent is
        // the thing under test.
        let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _guard = e.scope_guard().expect("scope_guard() failed");
            e.execute_command(".frame 0").expect(".frame 0 failed");
            panic!("the guarded call gave up");
        }))
        .is_err();
        assert!(panicked, "the closure was supposed to panic");

        assert_eq!(
            e.scope().expect("scope() failed"),
            before,
            "the guard did not restore the scope while unwinding"
        );
        let _ = e.end_session();
    }

    #[test]
    #[cfg(not(miri))]
    fn a_scope_is_not_restored_onto_a_later_target() {
        let _debuggee = one_debuggee();
        let e = DebugEngine::new();
        e.launch_process("cmd.exe /c exit").expect("launch failed");
        let stale = e.scope().expect("scope() failed");
        let _ = e.end_session();

        // A second target in the same engine: the frame and context in `stale` describe a stack
        // that no longer exists, and pointing this session at it would be worse than refusing.
        e.launch_process("cmd.exe /c exit")
            .expect("second launch failed");
        let err = e
            .set_scope(&stale)
            .expect_err("a scope from the previous target was applied to this one");
        assert!(
            matches!(err, DbgEngError::ScopeFromAnotherTarget),
            "wrong error for a stale scope: {err}"
        );

        // The refusal is about *that* scope, not about the engine: this target's own still works.
        let fresh = e.scope().expect("scope() failed");
        e.set_scope(&fresh)
            .expect("set_scope failed on a fresh scope");
        let _ = e.end_session();
    }

    /// A debuggee that runs to completion during a `go` is an **ending**, not a catastrophe —
    /// and what the run captured on the way survives it.
    ///
    /// Before this, the `E_UNEXPECTED` `WaitForEvent` answers once the target is gone was
    /// propagated verbatim: `Debug command failed: Catastrophic failure (0x8000FFFF)` for a
    /// program exiting normally, the captured output discarded with it, and the *next* call
    /// saying "No active debuggee" — the accurate half, one call late.
    ///
    /// The tail is the chain that made the session read as wedged rather than finished: `k`
    /// answering a bare `0x80040205` while `.echo` still worked.
    #[test]
    #[cfg(not(miri))]
    fn test_a_target_that_exits_during_a_go_is_an_ending_rather_than_a_catastrophe() {
        let _debuggee = one_debuggee();
        let e = DebugEngine::new();
        e.launch_process("cmd.exe /c exit").expect("launch failed");

        let run = e
            .execute_and_wait("g", 30_000)
            .expect("a target running to completion was reported as a failure");
        assert!(
            run.target_gone,
            "the target is gone and the run does not say so: {run:?}"
        );
        assert!(
            run.cut_short.is_none(),
            "nothing interrupted this run — the target simply ended: {run:?}"
        );
        // What the `Err` path used to throw away. *That* it arrived, not which lines it holds:
        // which modules a `cmd.exe` loads on its way out is the host's business, while the echo
        // `DEBUG_EXECUTE_ECHO` puts at the front is always there.
        assert!(
            !run.output.is_empty(),
            "the run captured nothing, so the ending discarded it after all"
        );
        println!("captured across the ending: {:?}", run.output);

        // The chain, now that the engine holds nothing: one error naming the state, on every
        // road in, instead of `0x80040205` from the commands that need a thread and success
        // from the ones that do not.
        for command in ["k 3", "r", "lm", ".echo alive"] {
            assert!(
                matches!(
                    e.execute_command_bounded(command, 5_000),
                    Err(DbgEngError::NoDebuggee)
                ),
                "`{command}` did not answer that there is no debuggee"
            );
        }
        assert!(
            matches!(e.execute_and_wait("g", 5_000), Err(DbgEngError::NoDebuggee)),
            "a second resume was not refused"
        );
        // And the session is still the caller's to end, which is the only thing left to do.
        e.end_session()
            .expect("end_session failed after the ending");
    }

    /// The same ending reached through [`DebugEngine::settle`], which is the corner
    /// [windbg-mcp#226]'s fix left open: a raw `Execute` sets the run state, and the pump that
    /// recovers it is where the target runs out.
    ///
    /// The pump's buffer is the whole of what is at stake here — the command itself printed only
    /// its own echo, and everything the run produced (module loads, a breakpoint banner, an
    /// embedded script's prints) arrives during the wait this used to fail. It is printed rather
    /// than asserted on: what a `cmd.exe` prints on its way out belongs to the host, while the
    /// answer being `Ok(Some(_))` at all is the fix.
    ///
    /// [windbg-mcp#226]: https://github.com/glslang/windbg-mcp/issues/226
    #[test]
    #[cfg(not(miri))]
    fn test_a_target_that_exits_during_the_settle_pump_reports_the_ending_with_its_output() {
        let _debuggee = one_debuggee();
        let e = DebugEngine::new();
        e.launch_process("cmd.exe /c exit").expect("launch failed");

        e.execute_command_bounded("g", 0)
            .expect("the raw `g` itself should succeed — it is the pump that follows it");
        assert!(
            e.is_running().expect("could not read the execution status"),
            "a raw `g` left the engine reading as stopped, so there is nothing here to settle"
        );

        let settled = e
            .settle(30_000)
            .expect("the pump reported the target's ending as a failure")
            .expect("settle found nothing to pump after a raw `g`");
        assert!(
            settled.target_gone,
            "the pump ended because the target did, and did not say so: {settled:?}"
        );
        println!("captured by the pump: {:?}", settled.output);

        // Settling again finds nothing rather than pumping a target that is not there.
        assert!(
            e.settle(5_000).expect("a second settle errored").is_none(),
            "settle pumped an engine that holds no target"
        );
        e.end_session()
            .expect("end_session failed after the ending");
    }

    /// A command can take the target away *itself*, and the two that do it differ in a way worth
    /// pinning: `.detach` leaves nothing behind at once, while `.kill` leaves a target that is
    /// still readable and goes away on the **next** resume.
    ///
    /// Both measured on dbgeng 10.0.26100.1 (ARM64), and the asymmetry is the reason
    /// [`CommandRun::target_gone`] is answered from the engine's state after every command rather
    /// than from a list of command names: a list would have to put `.detach` and `q` on it and
    /// leave `.kill` off, and be re-derived for every engine version.
    #[test]
    #[cfg(not(miri))]
    fn test_a_command_that_takes_the_target_away_says_so_and_kill_is_not_one_of_them() {
        let _debuggee = one_debuggee();

        // `.kill`: the target is terminated but the exit events have not been pumped, so the
        // engine still holds it and a stack still reads.
        let e = DebugEngine::new();
        e.launch_process("cmd.exe /c ping -n 30 127.0.0.1")
            .expect("launch failed");
        let killed = e
            .execute_command_bounded(".kill", 10_000)
            .expect("`.kill` failed");
        assert!(
            !killed.target_gone,
            "`.kill` reported the target gone, but the exit events have not been pumped yet: \
             {killed:?}"
        );
        assert!(
            e.execute_command_bounded("k 3", 5_000).is_ok(),
            "the target should still be readable after `.kill`"
        );
        let resumed = e
            .execute_and_wait("g", 30_000)
            .expect("the resume after `.kill` was reported as a failure");
        assert!(
            resumed.target_gone,
            "the resume after `.kill` is where the target goes away: {resumed:?}"
        );
        e.end_session().expect("end_session failed after `.kill`");

        // `.detach`: gone the moment the command returns, with nothing left to pump — so if this
        // were left to `settle` it would be reported by nobody.
        let e = DebugEngine::new();
        e.launch_process("cmd.exe /c ping -n 30 127.0.0.1")
            .expect("launch failed");
        let detached = e
            .execute_command_bounded(".detach", 10_000)
            .expect("`.detach` failed");
        assert!(
            detached.target_gone,
            "`.detach` did not report that it took the target away: {detached:?}"
        );
        assert!(
            e.settle(5_000).expect("settle errored").is_none(),
            "there is nothing to pump after a detach"
        );
        assert!(
            matches!(
                e.execute_command_bounded("k 3", 5_000),
                Err(DbgEngError::NoDebuggee)
            ),
            "a command after a detach was not refused"
        );
        e.end_session().expect("end_session failed after `.detach`");
    }

    /// A long-lived process to attach to, so a teardown test has something it did not create.
    ///
    /// `ping` rather than `cmd.exe /c ping`, which every launch test here uses: those want a
    /// debuggee and do not care what happens to the `ping` underneath it, while this has to ask
    /// afterwards whether *the process the engine attached to* is still alive — and through a
    /// `cmd` the answer would be about the parent either way round.
    #[cfg(not(miri))]
    fn a_process_to_attach_to() -> std::process::Child {
        std::process::Command::new("ping")
            .args(["-n", "30", "127.0.0.1"])
            .stdout(std::process::Stdio::null())
            .spawn()
            .expect("could not start a process to attach to")
    }

    /// `STILL_ACTIVE` — what `GetExitCodeProcess` answers for a process that has not exited. The
    /// `windows` crate has it as an `NTSTATUS`, which is not the `u32` that call writes.
    #[cfg(not(miri))]
    const STILL_RUNNING: u32 = 259;

    /// What became of `pid`, asked the way a bystander has to ask it — there is no `Child` for a
    /// process DbgEng created, and `Child::try_wait` is the wrong question even where there is
    /// one. **Measured**: a debuggee the kernel kills at `EndSession` has its exit status set
    /// before the call returns, while its process object is not signalled yet, so `try_wait`
    /// answers `Ok(None)` — "still running" — for a process that is already dead.
    ///
    /// `None` when the pid cannot be opened at all, which the callers below treat as a failure
    /// rather than as an answer: both of them want to know *which* ending happened.
    #[cfg(not(miri))]
    fn exit_code_of(pid: u32) -> Option<u32> {
        use windows::Win32::Foundation::CloseHandle;
        use windows::Win32::System::Threading::{
            GetExitCodeProcess, OpenProcess, PROCESS_QUERY_INFORMATION,
        };
        unsafe {
            let handle = OpenProcess(PROCESS_QUERY_INFORMATION, false, pid).ok()?;
            let mut code = 0u32;
            let read = GetExitCodeProcess(handle, &mut code).is_ok();
            let _ = CloseHandle(handle);
            read.then_some(code)
        }
    }

    /// **Ending a session must not take a process this engine did not create.**
    ///
    /// The bug this pins, found on windbg-mcp's benches on 2026-08-27: attach to a running
    /// process, end the session, and the process is *gone* — not suspended, not detached,
    /// terminated. Two defaults meeting, neither wrong on its own: `end_session` ended passively,
    /// which disconnects without detaching, and a debuggee whose debug port is destroyed is killed
    /// by the kernel, because `DebugSetProcessKillOnExit` defaults to true.
    ///
    /// **The kill is synchronous with `end_session`**, which is worth knowing because it is not
    /// what the report assumed (it read as the *debugger's* exit doing it, one step later) and
    /// because it is what lets this be a test at all: measured on dbgeng 10.0.26100.1 (ARM64),
    /// the exit code is `0xC0000354` — `STATUS_DEBUGGER_INACTIVE` — the moment the call returns,
    /// against `STILL_ACTIVE` with the detach in place. Ten runs each way, no overlap, so there
    /// is no poll loop here: a bound would only make a failure slower.
    ///
    /// What is **not** a discriminator, and would look like the obvious one:
    /// `CheckRemoteDebuggerPresent` reads `false` after either ending. The passive end does tear
    /// the debug port down — that is precisely why the process dies — so "is it still being
    /// debugged" cannot tell the two apart. Only the target's own fate can.
    #[test]
    #[cfg(not(miri))]
    fn test_ending_a_session_detaches_from_a_process_it_attached_to_rather_than_killing_it() {
        let _debuggee = one_debuggee();
        let mut target = a_process_to_attach_to();
        let pid = target.id();

        let e = DebugEngine::new();
        e.attach_process(pid).expect("attach failed");
        assert!(
            e.attached_to_a_live_process(),
            "the engine attached to a process and does not know it"
        );
        // A target that is really there to be let go of, rather than one that ended under us and
        // would pass this by having had nothing left to kill.
        assert!(
            e.execute_command_bounded("k 3", 5_000).is_ok(),
            "the attached process should be readable before the session ends"
        );

        e.end_session().expect("end_session failed after an attach");
        assert!(
            !e.attached_to_a_live_process(),
            "the engine still believes it holds the process it just let go of"
        );
        assert_eq!(
            exit_code_of(pid),
            Some(STILL_RUNNING),
            "`end_session` did not leave the process it attached to running"
        );

        target.kill().expect("could not clean up the target");
        let _ = target.wait();
    }

    /// The other half of the same rule, and the reason it is a rule about the **opener** rather
    /// than about live user-mode targets: a process the engine *created* still goes with the
    /// session.
    ///
    /// Not symmetry for its own sake — it is the half that says the fix above is a change of
    /// *policy* and not of mechanism. A launch whose debuggee outlived it would leave a process
    /// nobody holds a handle to, started by a debugger that is gone; a caller who wants one kept
    /// is asking for something this crate has no way to be told.
    #[test]
    #[cfg(not(miri))]
    fn test_a_process_the_engine_launched_still_goes_with_its_session() {
        let _debuggee = one_debuggee();

        let e = DebugEngine::new();
        e.launch_process("cmd.exe /c ping -n 30 127.0.0.1")
            .expect("launch failed");
        assert!(
            !e.attached_to_a_live_process(),
            "a launched process is not one this engine attached to"
        );
        // Read out of the engine rather than tracked from outside: `CreateProcessWide` is the
        // engine's own spawn, so this is the only side that ever knows the pid.
        let pid = eval_expression(&e, "@$tpid").expect("could not read the launched process id");

        e.end_session().expect("end_session failed after a launch");
        // The status is not pinned, only the ending: `STATUS_DEBUGGER_INACTIVE` is what this
        // engine writes today, and what matters is that the process did not survive its session.
        assert_ne!(
            exit_code_of(pid as u32),
            Some(STILL_RUNNING),
            "the process this engine launched (pid {pid}) outlived its session"
        );
    }

    /// **An engine is reusable, so where its target came from is answered by the last opener and
    /// not by the last attach** — the gap review found in the first version of the fix above
    /// ([glslang/dbgscope#121](https://github.com/glslang/dbgscope/pull/121)).
    ///
    /// The sequence is reachable without a teardown anywhere in it: attach, lose the target (here
    /// a raw `.detach`, which takes it the moment the command returns; a process exiting on its
    /// own does the same), then launch something else on the same engine. With only
    /// `attach_process_begin` recording anything, the flag was still set, and the *launched*
    /// process took the detach branch and survived a session that is supposed to take it.
    ///
    /// Two claims, and the second is the one that generalises: the launched process goes, and the
    /// engine no longer believes it is holding an attached one.
    #[test]
    #[cfg(not(miri))]
    fn test_a_launch_after_a_lost_attach_is_still_a_launch() {
        let _debuggee = one_debuggee();
        let mut target = a_process_to_attach_to();

        let e = DebugEngine::new();
        e.attach_process(target.id()).expect("attach failed");
        let detached = e
            .execute_command_bounded(".detach", 10_000)
            .expect("`.detach` failed");
        assert!(
            detached.target_gone,
            "`.detach` left a target behind, so this is not the state under test: {detached:?}"
        );

        e.launch_process("cmd.exe /c ping -n 30 127.0.0.1")
            .expect("launch after a lost attach failed");
        assert!(
            !e.attached_to_a_live_process(),
            "the engine still believes it holds an attached process after launching one"
        );
        // **And the record itself was pruned**, which the assertion above cannot see — it asks the
        // session, so a stale pid naming nothing reads as "no attachment" either way. What the
        // pruning is for is the coincidence that cannot be staged in a test: Windows handing the
        // dead process's number to the one this engine just launched, which would then be detached
        // and left running. Reading the field directly is the only way to say the record is clean
        // rather than merely unmatched.
        assert!(
            e.attached_processes
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .is_empty(),
            "the launch left a dead process's pid in the record, where a reused pid can alias it"
        );
        let launched = eval_expression(&e, "@$tpid").expect("could not read the launched pid");

        e.end_session().expect("end_session failed");
        assert_ne!(
            exit_code_of(launched as u32),
            Some(STILL_RUNNING),
            "the process this engine launched (pid {launched}) outlived its session, because the \
             engine was still carrying the previous attach"
        );

        let _ = target.kill();
        let _ = target.wait();
    }

    /// **A target that leaves on its own does not turn its teardown into an error.**
    ///
    /// The other half of the same finding, and the one with a caller-visible cost: an attached
    /// process can exit under the debugger, and if the active detach then failed, ending that
    /// session would report "the debugger reported an error releasing the target" for a program
    /// that had simply finished.
    ///
    /// **It does not fail** — measured on dbgeng 10.0.26100.1 (ARM64): `EndSession` with
    /// `DEBUG_END_ACTIVE_DETACH` succeeds on an engine holding no debuggee. That is why
    /// `end_session` does *not* check `has_target` before taking this branch: the check was
    /// written, measured to change nothing, and removed. This test is what stands in its place —
    /// an engine that ever does refuse fails here, and the guard is one line away.
    ///
    /// `.detach` stands in for the process exiting because it is instantaneous and leaves the
    /// engine in the same state (`DEBUG_STATUS_NO_DEBUGGEE`); what the teardown meets is that
    /// state, not how the target came to be missing.
    #[test]
    #[cfg(not(miri))]
    fn test_ending_a_session_whose_attached_target_already_left_is_not_an_error() {
        let _debuggee = one_debuggee();
        let mut target = a_process_to_attach_to();

        let e = DebugEngine::new();
        e.attach_process(target.id()).expect("attach failed");
        assert!(
            e.execute_command_bounded(".detach", 10_000)
                .expect("`.detach` failed")
                .target_gone,
            "`.detach` left a target behind, so this is not the state under test"
        );
        // And the engine says so, because this asks the session rather than the record: the pid
        // is still written down, and the process it named is gone.
        assert!(
            !e.attached_to_a_live_process(),
            "the engine reports holding an attached process after that process has gone"
        );

        e.end_session()
            .expect("end_session failed on a session whose attached target had already gone");

        let _ = target.kill();
        let _ = target.wait();
    }

    /// The system pids of the processes in this session, read by **selecting each one in turn**.
    ///
    /// `@$tpid` answers for whichever process is *current*, and which process that is after a
    /// launch is not something to assume: measured, a fresh engine leaves the process it just
    /// created current, while one that has held a target before leaves the earlier process
    /// current — so a test reading `@$tpid` straight after a launch gets the launched pid or the
    /// attached one depending on what ran before it in the same binary. That cost a whole round of
    /// "the fix does not work" against a fix that did.
    #[cfg(not(miri))]
    fn session_pids(e: &DebugEngine, count: usize) -> Vec<u64> {
        (0..count)
            .filter_map(|index| {
                e.execute_command(&format!("|{index}s")).ok()?;
                eval_expression(e, "@$tpid")
            })
            .collect()
    }

    /// **A session holding both kinds of process comes apart by where each one came from.**
    ///
    /// The second thing review found, and the one that made the record a set of pids: DbgEng keeps
    /// several user-mode targets in one session — `|` lists them and says `attach` or `create`
    /// against each — so an engine can hold somebody's running service *and* a program it launched
    /// itself. `EndSession` takes one flag for the whole session, so **no choice of flag is
    /// right**: a passive end kills the attached process, an active detach lets the launched one
    /// survive. Detaching the attached ones first, one at a time, is what makes both true at once.
    ///
    /// Both orderings, because what the first version got wrong was an ordering: with one
    /// session-wide flag written by whichever opener ran last, attach-then-launch killed the
    /// service and launch-then-attach let the launched program outlive its session.
    #[test]
    #[cfg(not(miri))]
    fn test_a_mixed_session_comes_apart_by_where_each_process_came_from() {
        let _debuggee = one_debuggee();

        for attach_first in [true, false] {
            let mut theirs = a_process_to_attach_to();
            let e = DebugEngine::new();
            if attach_first {
                e.attach_process(theirs.id()).expect("attach failed");
                e.launch_process("cmd.exe /c ping -n 30 127.0.0.1")
                    .expect("launch failed");
            } else {
                e.launch_process("cmd.exe /c ping -n 30 127.0.0.1")
                    .expect("launch failed");
                e.attach_process(theirs.id()).expect("attach failed");
            }

            // The state under test is a session holding two processes; if the second opener did
            // not add one, this test is asserting about something else entirely.
            let listed = e.execute_command("|").expect("`|` failed");
            let pids = session_pids(&e, 2);
            assert_eq!(
                pids.len(),
                2,
                "attach_first={attach_first}: this is not a two-process session:\n{listed}"
            );
            // Identified by elimination rather than by asking which is current, for the reason
            // `session_pids` gives.
            let ours = *pids
                .iter()
                .find(|pid| **pid != u64::from(theirs.id()))
                .unwrap_or_else(|| {
                    panic!(
                        "attach_first={attach_first}: the launched process is not here: {pids:?}"
                    )
                });

            e.end_session()
                .expect("end_session failed on a mixed session");
            assert_eq!(
                exit_code_of(theirs.id()),
                Some(STILL_RUNNING),
                "attach_first={attach_first}: the session's end killed the process it had only \
                 attached to"
            );
            assert_ne!(
                exit_code_of(ours as u32),
                Some(STILL_RUNNING),
                "attach_first={attach_first}: the process this engine launched (pid {ours}) \
                 outlived its session"
            );

            let _ = theirs.kill();
            let _ = theirs.wait();
        }
    }

    /// Execution control with no debuggee is **refused**, because letting it reach DbgEng takes
    /// the process down.
    ///
    /// Measured before this guard existed, on dbgeng 10.0.26100.1 (ARM64): a raw `g` through
    /// `execute_command_bounded` exits the process with `STATUS_ACCESS_VIOLATION` — both on an
    /// engine whose debuggee had just exited *and* on this one, which has never held a target.
    /// The second case is why the guard is keyed on the missing debuggee rather than on the
    /// departure, and why it sits in the primitive rather than in the caller that met it first.
    ///
    /// A structured exception is not a panic, so there is no `#[should_panic]` shape for the
    /// regression: what this test asserts by *returning at all* is that the fault is gone. Under
    /// `cargo nextest`, which gives each test its own process, a regression takes this one down
    /// and nothing else.
    #[test]
    #[cfg(not(miri))]
    fn test_execution_control_with_no_debuggee_is_refused_rather_than_faulting_the_process() {
        let _debuggee = one_debuggee();
        let e = DebugEngine::new();
        assert!(
            matches!(e.has_target(), Ok(false)),
            "a fresh engine is supposed to be holding no target"
        );

        // Four spellings of one thing, and the point is that the guard reads none of them: an
        // alias and a `.if` branch reach execution without saying so, which is why the check is
        // on the engine's state rather than on the text.
        for command in ["g", "p", "t", ".if (1) { g }"] {
            assert!(
                matches!(
                    e.execute_command_bounded(command, 5_000),
                    Err(DbgEngError::NoDebuggee)
                ),
                "`{command}` was not refused on the bounded path"
            );
            assert!(
                matches!(e.execute_command(command), Err(DbgEngError::NoDebuggee)),
                "`{command}` was not refused on the unbounded path"
            );
        }

        // The two typed paths, one of which had the guard already. Named here so all three ways
        // in are pinned in one place rather than one of them being covered by a target's exit.
        assert!(
            matches!(e.execute_and_wait("g", 5_000), Err(DbgEngError::NoDebuggee)),
            "execute_and_wait was not refused"
        );
        assert!(
            matches!(
                e.run_to_address(0x1000, 5_000),
                Err(DbgEngError::NoDebuggee)
            ),
            "run_to_address was not refused"
        );
    }
}

#[windows::core::implement(
    windows::Win32::System::Diagnostics::Debug::Extensions::IDebugEventContextCallbacks
)]
pub struct DebugEventContextCallbacks {
    callback: Option<BreakpointCallback>,
}

impl DebugEventContextCallbacks {
    pub fn new(callback: Option<BreakpointCallback>) -> Self {
        Self { callback }
    }
}

#[allow(non_snake_case)]
impl windows::Win32::System::Diagnostics::Debug::Extensions::IDebugEventContextCallbacks_Impl
    for DebugEventContextCallbacks_Impl
{
    fn GetInterestMask(&self) -> windows::core::Result<u32> {
        Ok(DEBUG_EVENT_BREAKPOINT)
    }

    fn Breakpoint(
        &self,
        bp: windows::core::Ref<'_, IDebugBreakpoint2>,
        _context: *const std::ffi::c_void,
        _flags: u32,
    ) -> windows::core::Result<()> {
        if let Some(callback) = &self.callback {
            let _ = callback(bp.as_ref().unwrap(), _context, _flags);
        }
        Ok(())
    }

    fn Exception(
        &self,
        _exception: *const windows::Win32::System::Diagnostics::Debug::EXCEPTION_RECORD64,
        _first_chance: u32,
        _context: *const std::ffi::c_void,
        _flags: u32,
    ) -> windows::core::Result<()> {
        Ok(())
    }

    fn CreateThread(
        &self,
        _handle: u64,
        _data_offset: u64,
        _start_offset: u64,
        _context: *const std::ffi::c_void,
        _flags: u32,
    ) -> windows::core::Result<()> {
        Ok(())
    }

    fn ExitThread(
        &self,
        _exit_code: u32,
        _context: *const std::ffi::c_void,
        _flags: u32,
    ) -> windows::core::Result<()> {
        Ok(())
    }

    fn CreateProcessA(
        &self,
        _image_file_handle: u64,
        _handle: u64,
        _base_offset: u64,
        _module_size: u32,
        _module_name: &PCWSTR,
        _image_name: &PCWSTR,
        _checksum: u32,
        _timestamp: u32,
        _initial_thread_handle: u64,
        _thread_data_offset: u64,
        _start_offset: u64,
        _context: *const std::ffi::c_void,
        _flags: u32,
    ) -> windows::core::Result<()> {
        Ok(())
    }

    fn ExitProcess(
        &self,
        _exit_code: u32,
        _context: *const std::ffi::c_void,
        _flags: u32,
    ) -> windows::core::Result<()> {
        Ok(())
    }

    fn LoadModule(
        &self,
        _image_file_handle: u64,
        _base_offset: u64,
        _module_size: u32,
        _module_name: &PCWSTR,
        _image_name: &PCWSTR,
        _checksum: u32,
        _timestamp: u32,
        _context: *const std::ffi::c_void,
        _flags: u32,
    ) -> windows::core::Result<()> {
        Ok(())
    }

    fn UnloadModule(
        &self,
        _image_base_name: &PCWSTR,
        _base_offset: u64,
        _context: *const std::ffi::c_void,
        _flags: u32,
    ) -> windows::core::Result<()> {
        Ok(())
    }

    fn SystemError(
        &self,
        _error: u32,
        _level: u32,
        _context: *const std::ffi::c_void,
        _flags: u32,
    ) -> windows::core::Result<()> {
        Ok(())
    }

    fn SessionStatus(&self, _status: u32) -> windows::core::Result<()> {
        Ok(())
    }

    fn ChangeDebuggeeState(
        &self,
        _flags: u32,
        _argument: u64,
        _context: *const std::ffi::c_void,
        _flags2: u32,
    ) -> windows::core::Result<()> {
        Ok(())
    }

    fn ChangeEngineState(
        &self,
        _flags: u32,
        _argument: u64,
        _context: *const std::ffi::c_void,
        _flags2: u32,
    ) -> windows::core::Result<()> {
        Ok(())
    }

    fn ChangeSymbolState(&self, _flags: u32, _argument: u64) -> windows::core::Result<()> {
        Ok(())
    }
}