ntoseye 0.28.0

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

use iced_x86::{Code, Decoder, DecoderOptions, Mnemonic};
use single_instance::SingleInstance;

use std::sync::Arc;

use crate::backend::MemoryOps;
use crate::bugchecks::{CURRENT_KERNEL_RELOAD_WINDOW, looks_like_kernel_pointer};
use crate::dbg_backend::{
    BackendCapability, BugcheckInfo, ContinueDisposition, DebugBackend, DebugCapability,
    DebugOutputPage, HW_BREAKPOINT_SLOTS, HwBreakpointAccess, LastEvent, StopEvent,
    WatchpointAccess,
};
use crate::disasm::{DisasmRow, decode_rows, decode_rows_arm64, disasm_formatter};
use crate::dmp::DmpBackend;
use crate::error::{Error, Result};
use crate::gdb::breakpoints::{Breakpoint, BreakpointConfig};
use crate::gdb::{
    BreakpointHitDisposition, BreakpointHitResult, BreakpointManager, GdbClient, RegisterMap,
};
use crate::guest::{ModuleSymbolLoadReport, ProcessInfo};
use crate::kd::{KdBackend, KdMemorySource, hwbp, trace_enabled};
use crate::memory::DTB_IDENTITY;
use crate::memory_backend::MemoryBackend;
use crate::phys::PhysMem;
use crate::target::{ReloadReport, SelectedFrame, Target, ThreadInfo};
#[cfg(test)]
use crate::triage::{TriageBlock, make_triage_dump};
use crate::types::{Arch, VirtAddr};
use crate::unwind::{
    RecoveredStackTrace, StackTrace, ThreadStackTrace, build_parked_thread_recovered_stack,
    build_parked_thread_stack, build_stacktrace, build_stacktrace_with_context, preferred_code_dtb,
    resolve_thread_trace_context,
};
use crate::{Backend, TargetSpec};
#[cfg(test)]
use std::sync::atomic::AtomicU64;

/// Trace reload classification (lines prefixed `reload:`), gated on
/// `NTOSEYE_KD_TRACE` like the KD packet trace so one capture correlates both.
/// Off by default; pure output.
macro_rules! reload_trace {
    ($($arg:tt)*) => {
        if trace_enabled() {
            eprintln!("reload: {}", format_args!($($arg)*));
        }
    };
}

/// How [`Session::continue_until_break`] returned: a stop worth surfacing, or a
/// timeout with the VM still running (the caller polls again). Hosts render it.
#[derive(Debug, Clone)]
pub enum ContinueOutcome {
    /// A scoped breakpoint hit (its condition, if any, held).
    Breakpoint {
        id: u32,
        address: u64,
        symbol: Option<String>,
        temporary: bool,
        /// Optional frontend command action attached to the breakpoint.
        action: Option<String>,
        rip: u64,
        /// Runtime condition failure. The stop is surfaced rather than skipped.
        condition_error: Option<String>,
    },
    /// The guest is processing a bugcheck (BSOD). `info` carries the code +
    /// parameters when the backend decoded them from the KD stream; otherwise
    /// read `nt!KiBugCheckData` from memory with
    /// [`crate::bugchecks::current_bugcheck`].
    Bugcheck {
        rip: Option<u64>,
        info: Option<BugcheckInfo>,
    },
    /// A non-breakpoint stop (exception, or a manual interrupt).
    Stopped {
        rip: u64,
        exception_code: Option<u32>,
        first_chance: Option<bool>,
        exception_address: Option<u64>,
    },
    /// A single-step / step-over / step-out completed and landed at `rip`
    /// (no user breakpoint was hit en route).
    Step { rip: u64 },
    /// The guest rebooted (KD stream reset) and debugger state was rebuilt.
    /// Surfaced exactly once per reboot, as early as possible: normally at the
    /// earliest post-reboot stop where the new kernel is discoverable
    /// (`coherent: false`, matching the REPL's early-boot break; process/module
    /// enumeration unavailable, and the later rediscovery completion is silent).
    /// If the rebuild failed at that detection stop, the notification falls back
    /// to the completion instead (`coherent: true`, system already up).
    /// `kernel_base` is the rediscovered `nt` base. All prior addresses are
    /// stale and must be re-queried either way.
    TargetReloaded {
        kernel_base: Option<u64>,
        coherent: bool,
    },
    /// The timeout elapsed and the VM is still running; call again to keep
    /// waiting.
    Running,
    /// A non-resuming wait found the VM already halted with nothing pending: it
    /// is parked at `rip` and no new stop can arrive without a resume. Returned
    /// only by [`Self::wait_for_stop_bounded`] (the run-and-wait helpers resume
    /// first, so they never see it); lets a caller distinguish "still stopped
    /// where you left it" from "running" instead of spinning the whole timeout.
    Halted { rip: u64 },
}

/// A "where am I" snapshot for the read-only status surface: whether the guest
/// is running, and if halted, the current stop site and inspection scope.
/// `coherent` is false after a reboot until kernel rediscovery finishes (the
/// loaded-module list is up), so a host knows process/module enumeration is not
/// yet meaningful and it should keep waiting rather than read stale state.
#[derive(Debug, Clone)]
pub struct RunStatus {
    pub running: bool,
    pub current_thread: String,
    /// Current instruction pointer when halted (None while running).
    pub rip: Option<u64>,
    /// Nearest symbol to `rip` when halted.
    pub symbol: Option<String>,
    /// Attached process inspection scope, if any. This is where `dt`, `dq` and
    /// friends read from; it is chosen with `.process` and survives resumes,
    /// so it is not necessarily what the guest is executing.
    pub attached_process: Option<ProcessInfo>,
    /// The process whose page tables the stopped vCPU has loaded (from CR3).
    /// Refreshed at every stop.
    pub stopped_process: Option<ProcessInfo>,
    /// The Windows thread the stopped vCPU is running, walked from its KPRCB
    /// at this stop. Its owner can differ from `stopped_process`: a thread
    /// attached to another address space with `KeStackAttachProcess` runs on
    /// borrowed page tables.
    pub stopped_thread: Option<ThreadInfo>,
    pub coherent: bool,
    /// Rediscovered `nt` base. A host caches it to detect a reboot (the base
    /// changes) and invalidate stale addresses without parsing prose.
    pub kernel_base: u64,
}

/// How [`Session::classify_reload_stop`] classified a freshly observed stop:
/// real stop, reboot artifact, or transport noise. A host decides whether to
/// surface or absorb each case (the REPL prints boot phases inline;
/// `continue_until_break` surfaces reload detection and completion as
/// [`ContinueOutcome::TargetReloaded`] and absorbs the noise in between).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReloadDisposition {
    /// Not reboot/assist related; handle it as an ordinary stop (breakpoint,
    /// exception, manual pause).
    Ordinary,
    /// The guest rebooted and guest state was rebuilt. `coherent` is true once
    /// the loaded-module list is available (introspection usable); false means
    /// the reload happened but the system is still very early in boot (module
    /// and process enumeration unavailable until a later stop completes
    /// rediscovery). Hosts surface both: this is the earliest meaningful
    /// post-reboot stop.
    Reloaded { coherent: bool },
    /// Rediscovery completed for a reload that was never surfaced (the rebuild
    /// failed at the detection stop, so the host has not been told the guest
    /// rebooted). Surface it as the reload notification, the fallback that
    /// guarantees one notification per reboot. When the reload *was* surfaced
    /// at detection, completion is silent instead: noise stops classify as
    /// [`Self::ResumePastAssist`], real stops as [`Self::Ordinary`].
    ReloadCompleted,
    /// A reboot was observed but the kernel image isn't discoverable yet; resume
    /// and keep retrying (the assist break-ins retry the reload until it lands,
    /// which then surfaces as [`Self::Reloaded`]).
    PendingRediscovery,
    /// A debugger-induced KD reconnect/refresh break-in (or any mid-reboot stop
    /// before the module list is available): resume past it, don't surface.
    ResumePastAssist,
}

/// The plan for a step-over of the current instruction: either a plain
/// single-step, or run to an address (the instruction after a `call`).
#[derive(Debug, Clone, Copy)]
pub enum StepKind {
    /// The current instruction isn't a call; just single-step it.
    Single,
    /// Run to this address (the return site of a `call`, or a caller frame).
    RunTo(VirtAddr),
}

/// Architecture-neutral summary of the instruction at the program counter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CurrentInstruction {
    /// Whether the instruction is a call (`call` on AMD64, `bl`/`blr` on ARM64).
    pub is_call: bool,
    /// Address of the following instruction.
    pub next_ip: u64,
}

/// How a stop landed relative to our breakpoints, decided by
/// [`Session::resolve_breakpoint_stop`]. Cases a host shouldn't surface (a
/// wrong-process hit on a shared-page int3, or a false conditional breakpoint)
/// are stepped over and resumed inside the resolver; the host only reacts to the
/// verdict. Shared by the core loop and the REPL so the two can't drift.
#[derive(Debug, Clone)]
pub enum BreakpointStopAction {
    /// A breakpoint the caller should surface (its condition, if any, held).
    /// Enabled breakpoints have already been re-armed.
    Hit {
        breakpoint: Breakpoint,
        /// Runtime condition failure. The stop is surfaced rather than skipped.
        condition_error: Option<String>,
    },
    /// The stop was absorbed: a wrong-process shared-page int3 or a false
    /// conditional breakpoint. It has been stepped over and the VM resumed, so
    /// the caller should keep waiting.
    Resumed,
    /// `rip` is not one of our breakpoints (a genuine exception or manual pause).
    NotBreakpoint,
}

/// Disposition of a data-watch stop after backend status, inspection context,
/// and an optional condition have been handled.
#[derive(Debug, Clone)]
pub enum WatchpointStopAction {
    /// A watchpoint whose condition held or failed to evaluate.
    Hit {
        breakpoint: Breakpoint,
        condition_error: Option<String>,
    },
    /// A false conditional hit was resumed in place.
    Resumed,
    /// The stop was not raised by one of our watchpoints.
    NotBreakpoint,
}

/// Complete core classification of one raw backend stop. Frontends render
/// surfaced stops and execute frontend-owned breakpoint/exception commands;
/// they never repeat backend acknowledgment, reload, scope, or trap handling.
#[derive(Debug, Clone)]
pub enum StopResolution {
    /// Debugger noise or a filtered breakpoint was handled and execution resumed.
    Resumed,
    /// A kernel module load/unload notification was reconciled and resumed.
    ModulesChanged,
    /// A software or hardware breakpoint worth surfacing.
    Breakpoint {
        breakpoint: Breakpoint,
        event: StopEvent,
        rip: u64,
        condition_error: Option<String>,
    },
    /// The guest entered a bugcheck.
    Bugcheck { event: StopEvent },
    /// The guest rebooted and target state was rebuilt.
    TargetReloaded { event: StopEvent, coherent: bool },
    /// A genuine non-breakpoint stop, including a user interrupt.
    Stopped { event: StopEvent, rip: u64 },
}

fn update_target_context_from_registers(
    target: &mut Target,
    register_map: &RegisterMap,
    registers: Result<Vec<u8>>,
) {
    target.selected_frame = None;
    let Ok(registers) = registers else {
        target.registers = None;
        target.clear_context_dtb_override();
        return;
    };
    target.registers = Some(register_map.to_hashmap(&registers));
    match register_map.read_u64(target.arch().dtb_register(), &registers) {
        // For triage dumps all modules are loaded with DTB_IDENTITY and
        // memory reads use identity mapping, so the context DTB from the
        // CONTEXT
        // record is meaningless.  Setting it here would cause a DTB
        // mismatch that makes symbol lookup, type resolution, and eval
        // fail.
        Ok(dtb) if dtb != 0 && target.guest.is_some() && target.kernel_dtb() != DTB_IDENTITY => {
            target.set_context_dtb_override(dtb)
        }
        _ => target.clear_context_dtb_override(),
    }
}

/// A backend execution context (vCPU) and the guest code it is currently
/// running. `symbol` is `None` when nothing resolves (render the raw `rip`);
/// `error` is set when the vCPU's register context couldn't be read at all.
#[derive(Debug, Clone)]
pub struct VcpuInfo {
    /// Backend thread/vCPU id (e.g. `p1.1`).
    pub id: String,
    /// Instruction pointer, or `None` if the register context was unreadable.
    pub rip: Option<u64>,
    /// The address space the vCPU is executing in: `"kernel"`, a process name,
    /// or `"unknown"`. Empty when the context could not be determined.
    pub context: String,
    /// Nearest symbol to `rip` (`module!name+0x..`), if one resolved.
    pub symbol: Option<String>,
    /// Why the vCPU context was unavailable, if it was.
    pub error: Option<String>,
}

/// The low bits of a CR3/DTB that select the page-directory base physical
/// frame (PCID and reserved/canonical bits masked out), for comparing the
/// address space a vCPU runs in against a process's DTB.
/// How often the run-control poll loop wakes to check for a stop.
const CONTINUE_POLL_INTERVAL: Duration = Duration::from_millis(200);

/// How many noise stops [`Session::interrupt`] resumes past before surfacing
/// whatever the target is doing.
const INTERRUPT_MAX_RESUMES: usize = 8;

/// How long [`Session::halt_for_exit`] gives an already-pending stop to land
/// before breaking in.
const EXIT_STOP_POLL: Duration = Duration::from_millis(200);

/// How long a background `service_idle` pass spends absorbing caught stops before
/// returning to the actor's job queue. Small so a real tool call is never held off
/// for long; one buffered stop is drained immediately regardless, this only bounds
/// the brief wait for any follow-on hit in a burst.
const SERVICE_IDLE_BUDGET: Duration = Duration::from_millis(5);

/// `STATUS_BREAKPOINT`, the NTSTATUS an `int3` raises (e.g. `nt!DbgBreakPoint`).
const STATUS_BREAKPOINT: u32 = 0x8000_0003;

/// `STATUS_SINGLE_STEP`, the NTSTATUS a trap-flag single-step raises. During a
/// run-control loop (continue / run-to) nobody is intentionally single-stepping;
/// `si` steps via [`step_one_and_clear_tf`] directly, not the loop, so a
/// single-step that isn't at a user breakpoint is a debugger artifact (see
/// [`stop_is_stray_single_step`]).
const STATUS_SINGLE_STEP: u32 = 0x8000_0004;

/// The root owner of a live debugging session: the introspection context, the
/// backend that drives the target, and the session state layered on top.
pub struct Session {
    /// Process-unique session id, assigned at construction from a monotonic
    /// counter. Hosts use it as a stable identity token for handles they hand
    /// out (e.g. the Python `Breakpoint`/`StopOutcome` session guard) without
    /// reasoning about pointer reuse across reattach.
    id: usize,
    pub target: Target,
    pub backend: Box<dyn DebugBackend>,
    pub breakpoints: BreakpointManager,
    pub register_map: RegisterMap,
    pub current_thread: String,
    /// ETHREAD selected for stack-only inspection while the backend remains on
    /// `current_thread`. Its register file does not exist as a coherent snapshot.
    parked_windows_thread: Option<VirtAddr>,
    /// Whether a guest reload is mid-flight with the loaded-module list not yet
    /// available (very early boot). Carried across `continue_until_break` calls
    /// so the post-reboot KD-reconnect dance runs to completion; when the list
    /// appears, [`Self::try_complete_pending_reload`] finishes rediscovery and
    /// stops the backend's reconnect-assist poking. The single owner of that
    /// state; hosts read it rather than reimplement it.
    pub reload_module_list_pending: bool,
    /// Whether a detected reload has not yet been surfaced to the host: the
    /// guest-state rebuild failed at the detection stop, so no
    /// [`ContinueOutcome::TargetReloaded`] went out. While set, the eventual
    /// rediscovery completion is surfaced in its place (the fallback "the guest
    /// rebooted" notification); once a reload has been surfaced, the completion
    /// is silent. Guarantees exactly one reload notification per reboot.
    reload_surface_pending: bool,
    /// A real execution stop the background `service_idle` caught and processed
    /// while the host was idle (a breakpoint/non-bp stop/bugcheck the host didn't
    /// actively `wait_for_stop` for). The VM is halted at it; the next
    /// `wait_for_stop` returns this as the proper event instead of a bare
    /// "halted", and `resume` clears it. `None` whenever the host is up to date.
    parked_stop: Option<ContinueOutcome>,
    /// The most recent per-stop module refresh report, retained so the REPL can
    /// render its existing module-symbol summary after the core reconciles
    /// breakpoints. Other hosts simply leave it unconsumed.
    module_refresh_report: Option<ModuleSymbolLoadReport>,
    /// Most recently observed backend stop and the disposition used when it was
    /// subsequently continued.
    pub last_event: Option<LastEvent>,
    /// Per-target single-instance lock, held for the session's lifetime so a
    /// second ntoseye can't attach to the same backend resource. `Some` via
    /// [`Self::connect`] (every host's attach path), `None` via the unguarded
    /// [`Self::new`].
    _instance_guard: Option<InstanceGuard>,
}

fn prepare_backend_after_cleanup(
    backend: &mut dyn DebugBackend,
    cleanup: Result<()>,
) -> Result<()> {
    match cleanup {
        Ok(()) => backend.prepare_for_exit(true),
        Err(cleanup_error) => match backend.prepare_for_exit(false) {
            Ok(()) => Err(cleanup_error),
            Err(teardown_error) => Err(Error::DebugInfo(format!(
                "{cleanup_error}; backend teardown also failed: {teardown_error}"
            ))),
        },
    }
}

impl Session {
    /// Attach per `spec`: open a dump, or connect the chosen live backend.
    /// The one construction path shared by the CLI, MCP, and Python hosts, so
    /// backend selection, endpoint defaults, and instance locking cannot
    /// drift between them.
    ///
    /// kd/kdnet/gdb take a per-target instance lock before building the
    /// backend, so a second attach against the same resource fails fast rather
    /// than racing on the handshake; dumps and passive memory are read-only
    /// and coexist with anything.
    pub fn open(spec: &TargetSpec) -> Result<Self> {
        spec.validate().map_err(Error::DebugInfo)?;
        match spec {
            TargetSpec::Dump(path) => {
                let phys = Arc::new(PhysMem::dmp(path)?);
                let info = phys
                    .dmp_info()
                    .expect("dmp_info must be Some for DMP backend")
                    .clone();
                Self::connect(phys, None, || Ok(Box::new(DmpBackend::new(&info))))
            }
            TargetSpec::Live {
                backend: backend @ (Backend::Kd | Backend::KdNet),
                kdnet_key,
                memory_source,
                ..
            } => {
                let endpoint = spec.endpoint().expect("KD/KDNET always have an endpoint");
                Self::connect_kd(endpoint, *memory_source, || match backend {
                    Backend::Kd => KdBackend::connect(endpoint),
                    Backend::KdNet => {
                        let key = kdnet_key.as_deref().expect("validated above");
                        KdBackend::connect_net(endpoint, key)
                    }
                    Backend::Gdb | Backend::Memory => unreachable!("matched KD above"),
                })
            }
            TargetSpec::Live { backend, .. } => {
                let phys = Arc::new(PhysMem::live()?);
                let endpoint = spec.endpoint();
                Self::connect(phys, endpoint, || {
                    Ok(match backend {
                        Backend::Gdb => Box::new(GdbClient::connect(
                            endpoint.expect("gdb always has an endpoint"),
                        )?),
                        Backend::Memory => Box::new(MemoryBackend::new()),
                        Backend::Kd | Backend::KdNet => unreachable!("matched above"),
                    })
                })
            }
        }
    }

    /// Acquire the single-instance lock for `target` (`None` for read-only
    /// backends that are safe to share), then connect a backend via
    /// `make_backend` and build the owned session.
    pub fn connect<F>(phys: Arc<PhysMem>, target: Option<&str>, make_backend: F) -> Result<Self>
    where
        F: FnOnce() -> Result<Box<dyn DebugBackend>>,
    {
        let guard = target.map(acquire_instance_guard).transpose()?;
        let backend = make_backend()?;
        let mut session = Self::new(phys, backend)?;
        session._instance_guard = guard;
        Ok(session)
    }

    /// Connect KD/KDNET, select a validated memory source, and build the
    /// session. `Auto` prefers matching host VM memory and safely falls back to
    /// target-mediated KD physical-memory requests.
    pub fn connect_kd<F>(
        resource: &str,
        memory_source: KdMemorySource,
        make_backend: F,
    ) -> Result<Self>
    where
        F: FnOnce() -> Result<KdBackend>,
    {
        let guard = Some(acquire_instance_guard(resource)?);
        let mut backend = make_backend()?;
        let hints = backend.target_hints()?;

        let host_phys: Option<PhysMem> = match memory_source {
            KdMemorySource::Kd => None,
            KdMemorySource::Host => {
                let phys = PhysMem::live().map_err(|error| {
                    Error::Kd(format!("host memory source unavailable: {error}"))
                })?;
                backend.validate_host_memory(&phys, hints)?;
                Some(phys)
            }
            KdMemorySource::Auto => match PhysMem::live() {
                Ok(phys) => match backend.validate_host_memory(&phys, hints) {
                    Ok(()) => Some(phys),
                    Err(error) => {
                        eprintln!(
                            "{}: host memory rejected ({error}); falling back to KD memory",
                            backend.name()
                        );
                        None
                    }
                },
                Err(error) => {
                    eprintln!(
                        "{}: host memory unavailable ({error}); falling back to KD memory",
                        backend.name()
                    );
                    None
                }
            },
        };

        let backend_name = backend.name();
        let (target, backend): (Target, Box<dyn DebugBackend>) = match host_phys {
            Some(host) => {
                eprintln!("{backend_name}: memory source host (validated VM-process memory)");
                // Host reads can bypass KD, but writes must preserve guest protection,
                // copy-on-write, and residency handling.
                let (backend, memory) = backend.into_remote_memory();
                let phys = Arc::new(host.with_mediated_writes(memory));
                (
                    Target::with_remote_phys(
                        phys,
                        hints.kernel_dtb,
                        hints.kernel_base,
                        hints.arch,
                    )?,
                    Box::new(backend),
                )
            }
            None => {
                let (backend, memory) = backend.into_remote_memory();
                eprintln!("{}", kd_memory_source_notice(backend_name));
                let phys = Arc::new(PhysMem::remote(memory));
                (
                    Target::with_remote_phys(
                        phys,
                        hints.kernel_dtb,
                        hints.kernel_base,
                        hints.arch,
                    )?,
                    Box::new(backend),
                )
            }
        };
        let mut session = Self::new_with_target(target, backend)?;
        session._instance_guard = guard;
        Ok(session)
    }

    /// Build a session around an already-connected backend and physical-memory
    /// source. Hosts normally use [`Self::connect`] or [`Self::connect_kd`].
    pub fn new(phys: Arc<PhysMem>, backend: Box<dyn DebugBackend>) -> Result<Self> {
        let target = Target::with_phys(phys)?;
        Self::new_with_target(target, backend)
    }

    fn new_with_target(mut target: Target, mut backend: Box<dyn DebugBackend>) -> Result<Self> {
        let debugger_data_hint = backend.target_debugger_data_hint().ok().flatten();
        target.refresh_debugger_data(debugger_data_hint);
        backend.initialize_from_target(&target);
        // ARM64 register snapshots expose TTBR1 via the synthetic `cr3` slot;
        // hand the resolved kernel root to the backend so it can fill it.
        backend.set_kernel_dtb(target.kernel_dtb());
        let register_map = backend.register_map().clone();

        // Seed the selected thread from the backend when it exposes register
        // context; otherwise default to the first processor.
        let has_register_context = backend
            .capabilities()
            .iter()
            .any(|c| c.capability == DebugCapability::ReadRegisters && c.supported);
        let current_thread = if has_register_context {
            backend
                .stopped_thread_id()
                .unwrap_or_else(|_| "1".to_string())
        } else {
            "1".to_string()
        };

        static NEXT_SESSION_ID: AtomicUsize = AtomicUsize::new(1);

        let mut session = Self {
            id: NEXT_SESSION_ID.fetch_add(1, Ordering::Relaxed),
            target,
            backend,
            breakpoints: BreakpointManager::new(),
            register_map,
            current_thread,
            parked_windows_thread: None,
            reload_module_list_pending: false,
            reload_surface_pending: false,
            parked_stop: None,
            module_refresh_report: None,
            last_event: None,
            _instance_guard: None,
        };

        // Populate target.registers so register names resolve in expressions
        // (important for dump sessions where no stop event fires).
        if has_register_context {
            session.refresh_context_for_current_thread();
        }

        Ok(session)
    }

    /// Single-step one instruction on the currently selected thread. If RIP sits
    /// on one of our breakpoints, do the disable/step/enable dance; otherwise
    /// plain step + trap-flag clear. Afterward re-arm enabled breakpoints (the
    /// stub can drop non-hit ones on a stop) and re-select the landed-on thread.
    /// The full "step one instruction", shared by the REPL (`si`) and the SDK.
    pub fn step(&mut self) -> Result<()> {
        self.require_live_register_context()?;
        self.target.selected_frame = None;
        // Advancing the VM spends any stop `service_idle` parked, so drop it (the
        // other advance paths clear it via `resume`; a bare single-step doesn't).
        self.parked_stop = None;
        self.backend.set_current_thread(&self.current_thread)?;
        if !step_over_current_breakpoint(
            self.backend.as_mut(),
            &self.register_map,
            &self.target,
            &mut self.breakpoints,
        )? {
            step_one_and_clear_tf(self.backend.as_mut(), &self.register_map)?;
        }
        for id in self.breakpoints.one_shot_hit_ids() {
            self.breakpoints
                .remove(self.backend.as_mut(), &self.target, id)?;
        }

        // Re-arm breakpoints the stub may have lost when the VM stopped, then
        // adopt whatever thread we ended up on.
        if let Err(error) = self
            .breakpoints
            .refresh_enabled(self.backend.as_mut(), &self.target)
        {
            eprintln!("failed to re-arm breakpoints after the step: {error}");
        }
        if let Ok(tid) = self.backend.stopped_thread_id() {
            self.current_thread = tid;
        }
        self.refresh_context_for_current_thread();
        Ok(())
    }

    /// Select `id` as the current inspection thread (e.g. a vCPU id), so
    /// registers/backtrace/step operate on it. Validates the id against the
    /// backend. Shared by the REPL's `thread`/`vcpu` commands and the SDKs.
    pub fn set_current_thread(&mut self, id: &str) -> Result<()> {
        self.backend.set_current_thread(id)?;
        self.target.selected_frame = None;
        self.current_thread = id.to_string();
        self.parked_windows_thread = None;
        self.target.clear_current_windows_thread_context();
        self.refresh_context_for_current_thread();
        Ok(())
    }

    /// Select a non-running Windows thread for metadata and stack inspection
    /// without changing the backend vCPU. This deliberately does not attempt to
    /// manufacture a register context for the parked thread.
    pub fn select_parked_windows_thread(&mut self, thread: &ThreadInfo) {
        self.target.selected_frame = None;
        self.parked_windows_thread = Some(thread.ethread);
        self.target.set_parked_windows_thread(thread.clone());
    }

    /// Install a debugger-selected frame/context as the inspection context:
    /// its recovered registers shadow the live ones and its address space
    /// becomes the expression/memory scope. Shared by the REPL's `.frame` /
    /// `.cxr` / `.trap` and the DAP frame selection so the two can't drift.
    pub fn select_frame(&mut self, selected: SelectedFrame) {
        self.target.registers = Some(selected.registers.clone());
        if let Some(cr3) = selected.registers.get("cr3").copied()
            && cr3 != 0
            && self.target.guest.is_some()
            && self.target.kernel_dtb() != DTB_IDENTITY
        {
            self.target.set_context_dtb_override(cr3);
        } else {
            self.target.clear_context_dtb_override();
        }
        self.target.selected_frame = Some(selected);
    }

    pub fn parked_windows_thread(&self) -> Option<&ThreadInfo> {
        let ethread = self.parked_windows_thread?;
        self.target
            .windows_thread_selection
            .as_ref()
            .filter(|thread| thread.ethread == ethread)
    }

    fn require_live_register_context(&self) -> Result<()> {
        if self.parked_windows_thread().is_some() {
            return Err(Error::DebugInfo(
                "selected Windows thread is parked; registers and execution control require a live vCPU context (use `vcpu <id>`)".into(),
            ));
        }
        Ok(())
    }

    /// Record a raw backend stop for `.lastevent` and typed hosts. REPL paths
    /// that own their richer wait loop call this at the same boundary as the
    /// session wait helpers.
    pub fn record_stop_event(&mut self, event: &StopEvent) {
        self.last_event = Some(LastEvent::new(event.clone()));
    }

    fn record_visible_stop(&mut self, resolution: &StopResolution) {
        let event = match resolution {
            StopResolution::Breakpoint { event, .. }
            | StopResolution::Bugcheck { event }
            | StopResolution::TargetReloaded { event, .. }
            | StopResolution::Stopped { event, .. } => event,
            StopResolution::Resumed | StopResolution::ModulesChanged => return,
        };
        // `$exr_code` follows the same boundary as host-visible stop events;
        // absorbed transport noise must not overwrite it.
        self.target.last_exception_code = event.exception_code;
    }

    /// Attach the acknowledgment chosen for the current stop. A successful
    /// continuation calls this after the backend accepts the request.
    pub fn record_continuation_disposition(&mut self, disposition: ContinueDisposition) {
        if let Some(last_event) = &mut self.last_event {
            last_event.disposition = Some(disposition);
        }
    }

    fn continue_outcome_from_resolution(&self, resolution: StopResolution) -> ContinueOutcome {
        match resolution {
            StopResolution::Breakpoint {
                breakpoint,
                rip,
                condition_error,
                ..
            } => ContinueOutcome::Breakpoint {
                id: breakpoint.id,
                address: breakpoint.address.0,
                symbol: breakpoint.symbol,
                temporary: breakpoint.temporary,
                action: breakpoint.action,
                rip,
                condition_error,
            },
            StopResolution::Bugcheck { event } => ContinueOutcome::Bugcheck {
                rip: event.program_counter,
                info: event.bugcheck,
            },
            StopResolution::TargetReloaded { coherent, .. } => ContinueOutcome::TargetReloaded {
                kernel_base: self.target.kernel_base().map(|address| address.0),
                coherent,
            },
            StopResolution::Stopped { event, rip } => ContinueOutcome::Stopped {
                rip,
                exception_code: event.exception_code,
                first_chance: event.first_chance,
                exception_address: event.exception_address,
            },
            StopResolution::Resumed | StopResolution::ModulesChanged => {
                unreachable!("absorbed stop cannot be parked")
            }
        }
    }

    fn interrupt_classified(&mut self) -> Result<(StopResolution, bool)> {
        let mut resumed = 0;
        loop {
            let stop_was_pending = self.backend.has_pending_stop();
            let event = self.backend.interrupt()?;
            let resolution = self.classify_stop_event(event)?;
            match resolution {
                StopResolution::Resumed => {
                    resumed += 1;
                    if resumed < INTERRUPT_MAX_RESUMES {
                        continue;
                    }
                    // Surface a generic stop after the bounded noise budget.
                    let stop_was_pending = self.backend.has_pending_stop();
                    let event = self.backend.interrupt()?;
                    let resolution = StopResolution::Stopped {
                        rip: event.program_counter.unwrap_or(0),
                        event,
                    };
                    return Ok((resolution, !stop_was_pending));
                }
                StopResolution::ModulesChanged => continue,
                resolution => return Ok((resolution, !stop_was_pending)),
            }
        }
    }

    /// Pause the VM and return the first meaningful stop. Every raw event routes
    /// through [`Self::classify_stop_event`], so an interrupt that races with a
    /// filtered breakpoint or reconnect-assist stop cannot bypass core state.
    ///
    /// Bounded: while the guest is rebooting (reconnect assist) or hammering a
    /// wrong-process breakpoint, every break-in can classify as noise and be
    /// resumed; after [`INTERRUPT_MAX_RESUMES`] of those the last stop is
    /// surfaced as-is rather than spinning forever (the ^D exit path lives on
    /// this).
    pub fn interrupt(&mut self) -> Result<StopEvent> {
        self.interrupt_classified()
            .map(|(resolution, _)| match resolution {
                StopResolution::Breakpoint { event, .. }
                | StopResolution::Bugcheck { event }
                | StopResolution::TargetReloaded { event, .. }
                | StopResolution::Stopped { event, .. } => event,
                StopResolution::Resumed | StopResolution::ModulesChanged => {
                    unreachable!("absorbed stop cannot be returned")
                }
            })
    }

    /// Run `edit` with the target halted, restoring the previous run state.
    /// If the target is already halted, `edit` runs directly and neither
    /// interrupts nor resumes the backend. If it is running, this method breaks
    /// in, runs `edit`, and resumes afterward unless the interrupt exposed a
    /// genuine pending stop. Such a stop is left halted and parked for the next
    /// [`Self::wait_for_stop_bounded`], while an edit error still resumes an
    /// otherwise ordinary break-in before returning the error. This primitive is
    /// shared by hosts that edit breakpoint state; it emits no notifications.
    pub fn with_target_halted<T>(
        &mut self,
        edit: impl FnOnce(&mut Session) -> Result<T>,
    ) -> Result<T> {
        let interrupt_supported = self.backend.capabilities().iter().any(|capability| {
            capability.capability == DebugCapability::InterruptTarget && capability.supported
        });
        if !self.backend.is_running() || !interrupt_supported {
            return edit(self);
        }

        let (resolution, own_breakin_candidate) = self.interrupt_classified()?;
        let (exception_code, program_counter) = match &resolution {
            StopResolution::Stopped { event, .. } => (event.exception_code, event.program_counter),
            _ => (None, None),
        };
        // The KD break-in rule is the same status/non-managed-address split
        // used by `stop_is_assisted_refresh_breakin`: a STATUS_BREAKPOINT that
        // classified as an ordinary stop and is not on one of our sites is the
        // break-in we requested. A backend-reported pending stop wins even if
        // it carries the same status; any other resolution is parked conservatively.
        let own_breakin = own_breakin_candidate
            && exception_code == Some(STATUS_BREAKPOINT)
            && matches!(&resolution, StopResolution::Stopped { .. })
            && program_counter
                .is_none_or(|pc| self.breakpoints.breakpoint_id_at_address(pc).is_none());

        if !own_breakin {
            self.parked_stop = Some(self.continue_outcome_from_resolution(resolution));
            return edit(self);
        }

        let result = edit(self);
        let resume = self.resume();
        match (result, resume) {
            (Ok(value), Ok(())) => Ok(value),
            (Err(error), Ok(())) => Err(error),
            (Ok(_), Err(error)) => Err(error),
            (Err(edit_error), Err(resume_error)) => Err(Error::DebugInfo(format!(
                "{edit_error}; failed to resume target: {resume_error}"
            ))),
        }
    }
    /// Bring the target to a real halt before teardown: consume a stop that is
    /// already pending if it is meaningful, else break in. The REPL's ^D path.
    pub fn halt_for_exit(&mut self) -> Result<()> {
        if let Some(event) = self.backend.try_wait_for_stop(EXIT_STOP_POLL)?
            && !matches!(
                self.classify_stop_event(event)?,
                StopResolution::Resumed | StopResolution::ModulesChanged
            )
        {
            return Ok(());
        }
        self.interrupt().map(drop)
    }

    /// Align the inspection context to the currently selected thread's address
    /// space: when halted, read that thread's registers and set
    /// `target.registers` and `context_dtb_override` from its CR3 (or ARM64
    /// TTBR0), so reads,
    /// steps, and breakpoint installs scope to the focused thread rather than
    /// an earlier stop on another thread. Called from the thread-selection entry
    /// points; `continue_until_break` establishes the same context inline. Best-
    /// effort and a no-op while the guest runs (no coherent register file).
    fn refresh_context_for_current_thread(&mut self) {
        self.parked_windows_thread = None;
        if self.backend.is_running() {
            return;
        }
        let registers = self
            .backend
            .set_current_thread(&self.current_thread)
            .and_then(|_| self.backend.read_registers());
        update_target_context_from_registers(&mut self.target, &self.register_map, registers);
    }

    /// Decode the instruction at the current thread's program counter, masking
    /// any software-breakpoint patch and reading through the thread's preferred
    /// code DTB. Selects the current thread first; the VM must be halted.
    pub fn current_instruction(&mut self) -> Result<CurrentInstruction> {
        self.require_live_register_context()?;
        self.backend.set_current_thread(&self.current_thread)?;
        let regs = self.backend.read_registers()?;
        let pc = self.register_map.read_u64("rip", &regs)?;
        let dtb = self
            .register_map
            .read_u64(self.target.arch().dtb_register(), &regs)
            .unwrap_or(0);
        let trace = resolve_thread_trace_context(&self.target, dtb);
        let code_dtb = preferred_code_dtb(&trace, pc);
        let memory = self.target.address_space(code_dtb);
        let mut bytes = [0u8; 16];
        memory.read_bytes(VirtAddr(pc), &mut bytes)?;
        self.breakpoints
            .mask_breakpoint_bytes(VirtAddr(pc), &mut bytes, trace.active_dtb);

        if self.target.arch() == Arch::Arm64 {
            let word = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
            let Ok(instruction) = bad64::decode(word, pc) else {
                return Err(Error::DebugInfo(format!(
                    "failed to decode instruction at {pc:#x}"
                )));
            };
            let mnem = instruction.op().mnem();
            // `bl`/`blr` are the call forms; AArch64 instructions are 4 bytes.
            return Ok(CurrentInstruction {
                is_call: mnem == "bl" || mnem == "blr",
                next_ip: pc.wrapping_add(4),
            });
        }

        let mut decoder = Decoder::with_ip(64, &bytes, pc, DecoderOptions::NONE);
        let instruction = decoder.decode();
        if instruction.code() == Code::INVALID {
            return Err(Error::DebugInfo(format!(
                "failed to decode instruction at {pc:#x}"
            )));
        }
        Ok(CurrentInstruction {
            is_call: instruction.mnemonic() == Mnemonic::Call,
            next_ip: instruction.next_ip(),
        })
    }

    /// Compute the step-over plan for the current instruction: run to the
    /// instruction *after* a `call`, otherwise a plain single-step. The shared
    /// decision used by the REPL `p` and [`Self::step_over`].
    pub fn step_over_target(&mut self) -> Result<StepKind> {
        let instruction = self.current_instruction()?;
        if instruction.is_call {
            Ok(StepKind::RunTo(VirtAddr(instruction.next_ip)))
        } else {
            Ok(StepKind::Single)
        }
    }

    /// The current frame's caller return address (the step-out target). Walks a
    /// few frames of the current thread's stack and returns the second frame's
    /// IP. Shared by the REPL `gu` and [`Self::step_out`].
    pub fn step_out_target(&mut self) -> Result<VirtAddr> {
        self.require_live_register_context()?;
        self.backend.set_current_thread(&self.current_thread)?;
        let regs = self.backend.read_registers()?;
        let trace = build_stacktrace(&self.target, &self.register_map, &regs, 4);
        let caller = trace
            .frames
            .get(1)
            .ok_or_else(|| Error::DebugInfo("could not find caller return address".to_string()))?;
        if caller.ip == 0 {
            return Err(Error::DebugInfo(
                "caller return address is null".to_string(),
            ));
        }
        Ok(VirtAddr(caller.ip))
    }

    /// Run until `address` is reached. If a breakpoint is already set there in
    /// the current context this is a plain [`Self::continue_until_break`];
    /// otherwise it installs a temporary breakpoint, runs to it, removes it, and
    /// reports reaching it as [`ContinueOutcome::Step`]. A *different* breakpoint,
    /// bugcheck, or exception en route is surfaced as-is. Blocks until a stop
    /// (checking `cancel` between polls); on cancel it halts, removes the temp
    /// breakpoint, and returns [`ContinueOutcome::Running`]. The run-to-address
    /// primitive behind [`Self::step_over`] / [`Self::step_out`].
    pub fn run_to(&mut self, address: VirtAddr, cancel: &AtomicBool) -> Result<ContinueOutcome> {
        // Already breakpointed here → just continue; the existing bp will report.
        if self
            .breakpoints
            .enabled_breakpoint_id_for_current_context(&self.target, address)
            .is_some()
        {
            return self.continue_until_break(None, cancel);
        }

        let temp_id =
            self.breakpoints
                .add_temporary_code(self.backend.as_mut(), &self.target, address)?;
        let outcome = self.continue_until_break(None, cancel);

        // Removing a breakpoint writes guest memory, so halt first if a cancel
        // left the VM running. A target reload already cleared the manager, so
        // the remove may be a no-op, ignore its error.
        if self.backend.is_running() {
            let _ = self.interrupt();
        }
        let _ = self
            .breakpoints
            .remove(self.backend.as_mut(), &self.target, temp_id);

        match outcome? {
            ContinueOutcome::Breakpoint { id, rip, .. } if id == temp_id => {
                Ok(ContinueOutcome::Step { rip })
            }
            other => Ok(other),
        }
    }

    /// Step over the current instruction: single-step it, or, if it's a `call`,
    /// run to the instruction after it ([`ContinueOutcome::Step`] on completion).
    /// Shared by the REPL `p` (target only) and the SDKs.
    pub fn step_over(&mut self, cancel: &AtomicBool) -> Result<ContinueOutcome> {
        match self.step_over_target()? {
            StepKind::Single => {
                self.step()?;
                Ok(ContinueOutcome::Step {
                    rip: self.current_rip(),
                })
            }
            StepKind::RunTo(addr) => self.run_to(addr, cancel),
        }
    }

    /// Step out of the current function: run to the caller's return address.
    pub fn step_out(&mut self, cancel: &AtomicBool) -> Result<ContinueOutcome> {
        let target = self.step_out_target()?;
        self.run_to(target, cancel)
    }

    /// Best-effort current RIP of the selected thread (0 if unreadable).
    fn current_rip(&mut self) -> u64 {
        self.backend
            .read_registers()
            .ok()
            .and_then(|r| self.register_map.read_u64("rip", &r).ok())
            .unwrap_or(0)
    }

    /// Read the selected live vCPU register file. A parked Windows thread is a
    /// stack-only inspection target and must never fall through to the backend's
    /// unrelated live register context.
    pub fn read_registers(&mut self) -> Result<Vec<u8>> {
        self.require_live_register_context()?;
        if self.backend.is_running() {
            return Err(Error::TargetRunning);
        }
        self.backend.set_current_thread(&self.current_thread)?;
        self.backend.read_registers()
    }

    /// Set a single register on the current thread by name, as a read-modify-
    /// write of the register file (read all, patch the one, write back).
    pub fn write_register(&mut self, name: &str, value: u64) -> Result<()> {
        self.require_live_register_context()?;
        if self.backend.is_running() {
            return Err(Error::TargetRunning);
        }
        if !self
            .backend
            .capabilities()
            .iter()
            .any(|entry| entry.capability == DebugCapability::WriteRegisters && entry.supported)
        {
            return Err(Error::RegisterWriteUnsupported);
        }
        let mut regs = self.read_registers()?;
        self.register_map.write_u64(name, &mut regs, value)?;
        self.backend.write_registers(&regs)?;
        self.target.registers = Some(self.register_map.to_hashmap(&regs));
        Ok(())
    }

    /// The backend's capability matrix (what the current transport supports), so
    /// a host can report unsupported operations up front instead of by failure.
    pub fn capabilities(&self) -> Vec<BackendCapability> {
        self.backend.capabilities()
    }

    /// Read captured guest debug output (DbgPrint) at or after `since_seq`.
    /// Snapshot+cursor: pass the previous page's `next_seq` to poll only new
    /// lines. Empty on backends without a native debug stream (gdb/memory); see
    /// [`DebugCapability::DebugOutput`].
    pub fn read_debug_output(&self, since_seq: u64) -> DebugOutputPage {
        self.backend.read_debug_output(since_seq)
    }

    /// Whether kernel structures are safe to read: the loaded-module list is
    /// populated (not early boot / mid-rediscovery) and the kernel base still
    /// reads `MZ` (no undetected reboot).
    pub fn kernel_coherent(&self) -> bool {
        !self.reload_module_list_pending && self.target.current_kernel_mapping_is_valid()
    }

    /// Drain a stop the background servicer has already caught without advancing
    /// to a later event. This makes a physically halted VM visible even while
    /// `is_running()` still holds stale running state.
    ///
    /// Debugger-generated noise is still absorbed so read/status surfaces match
    /// normal run control. Reload stops keep their deferred `TargetReloaded`
    /// notification for the next wait surface.
    pub fn settle_pending_stop(&mut self) -> Result<()> {
        if !self.backend.has_pending_stop() {
            return Ok(());
        }
        let event = self.backend.wait_for_stop()?;
        if matches!(
            self.classify_stop_event(event)?,
            StopResolution::TargetReloaded { .. }
        ) {
            // Settling is intentionally non-surfacing. Preserve the single
            // reboot notification for the next explicit wait.
            self.reload_surface_pending = true;
        }
        Ok(())
    }

    /// Service the guest while the host is otherwise idle: absorb a stop the
    /// background servicer caught but no tool call has drained (chiefly a
    /// wrong-process hit on a shared-page breakpoint), so the guest is not left
    /// frozen between tool calls. Noise is resumed; a real stop is parked for
    /// the next `wait_for_stop`.
    pub fn service_idle(&mut self) {
        if self.parked_stop.is_some() || !self.backend.has_pending_stop() {
            return;
        }
        let never_cancel = AtomicBool::new(false);
        match self.wait_for_stop_bounded(Some(SERVICE_IDLE_BUDGET), &never_cancel) {
            Ok(ContinueOutcome::Running) | Err(_) => {}
            Ok(ContinueOutcome::TargetReloaded { .. }) => {
                self.reload_surface_pending = true;
            }
            Ok(outcome) => {
                self.parked_stop = Some(outcome);
            }
        }
    }

    /// Resolve the stopped vCPU's process and Windows thread from the target.
    /// Select that thread for inspection. The attached process scope is separate
    /// and persists across resumes.
    pub fn stopped_context(&mut self) -> (Option<ProcessInfo>, Option<ThreadInfo>) {
        let mask = self.target.arch().dtb_page_mask();
        let dtb_register = self.target.arch().dtb_register();
        let stopped_process = self
            .backend
            .read_registers()
            .ok()
            .and_then(|regs| self.register_map.read_u64(dtb_register, &regs).ok())
            .and_then(|cr3| self.target.process_for_cr3(cr3 & mask));
        let current_thread = self.current_thread.clone();
        let stopped_thread =
            refresh_windows_thread_context_for_backend_thread(&mut self.target, &current_thread);
        (stopped_process, stopped_thread)
    }

    /// A read-only run-control snapshot for the "where am I" surface (see
    /// [`RunStatus`]). When halted, selects the current thread and resolves
    /// rip+symbol (best-effort); while running, leaves those None. Reports
    /// `coherent: false` while a post-reboot rediscovery is still pending so a
    /// host waits instead of enumerating stale state.
    pub fn run_status(&mut self) -> RunStatus {
        // On failure `has_pending_stop` stays true and the snapshot reports
        // halted with no location.
        let _ = self.settle_pending_stop();
        self.try_finish_rediscovery_from_memory();
        // The snapshot carries `kernel_base` + `coherent`, so it is the reload
        // notification.
        self.clear_deferred_reload_surface();
        let pending_stop = self.backend.has_pending_stop();
        let running = self.backend.is_running() && !pending_stop;
        let (rip, symbol, stopped_process, stopped_thread) = if running || pending_stop {
            (None, None, None, None)
        } else {
            let _ = self.backend.set_current_thread(&self.current_thread);
            let registers = self.backend.read_registers().ok();
            let rip = registers
                .as_ref()
                .and_then(|regs| self.register_map.read_u64("rip", regs).ok());
            let symbol = rip.and_then(|r| self.target.closest_symbol_current_context(VirtAddr(r)));
            let (stopped_process, stopped_thread) = self.stopped_context();
            (rip, symbol, stopped_process, stopped_thread)
        };
        RunStatus {
            running,
            current_thread: self.current_thread.clone(),
            rip,
            symbol,
            attached_process: self.target.current_process_info.clone(),
            stopped_process,
            stopped_thread,
            coherent: self.kernel_coherent(),
            kernel_base: self.target.kernel_base().map(|a| a.0).unwrap_or(0),
        }
    }

    /// Set a code breakpoint at `addr`. Returns the breakpoint id.
    pub fn add_breakpoint(&mut self, addr: VirtAddr) -> Result<u32> {
        self.add_breakpoint_with(addr, None, BreakpointConfig::default())
    }

    /// Set a code breakpoint at `addr` with an optional break condition
    /// (re-evaluated each hit; the run-control loop steps over and keeps running
    /// when it is false). The breakpoint's scope is derived from the current
    /// inspection context at install time. Returns the breakpoint id.
    pub fn add_breakpoint_with_condition(
        &mut self,
        addr: VirtAddr,
        condition: Option<String>,
    ) -> Result<u32> {
        self.add_breakpoint_with(
            addr,
            None,
            BreakpointConfig {
                condition,
                ..BreakpointConfig::default()
            },
        )
    }

    /// Set a code breakpoint at `addr` with an optional display `symbol` and
    /// explicit configuration (pass count, one-shot, and command action).
    pub fn add_breakpoint_with(
        &mut self,
        addr: VirtAddr,
        symbol: Option<String>,
        config: BreakpointConfig,
    ) -> Result<u32> {
        self.breakpoints
            .add_configured(self.backend.as_mut(), &self.target, addr, symbol, config)
    }

    /// Set a symbol-identity breakpoint that survives module unload/reload and
    /// may remain deferred until matching symbols are loaded.
    pub fn add_symbol_breakpoint(
        &mut self,
        symbol: String,
        condition: Option<String>,
    ) -> Result<u32> {
        self.add_symbol_breakpoint_with(
            symbol,
            BreakpointConfig {
                condition,
                ..BreakpointConfig::default()
            },
        )
    }

    /// Set a symbol-identity breakpoint with an explicit configuration (pass
    /// count, one-shot, command action). Hosts that expose the full breakpoint
    /// grammar (the REPL, DAP) use this instead of the condition-only form.
    pub fn add_symbol_breakpoint_with(
        &mut self,
        symbol: String,
        config: BreakpointConfig,
    ) -> Result<u32> {
        self.breakpoints
            .add_symbolic(self.backend.as_mut(), &self.target, symbol, config)
    }

    /// Set one source identity for every address matching `file:line`, or one
    /// deferred identity when no matching module is currently loaded.
    pub fn add_source_breakpoint(
        &mut self,
        source: String,
        condition: Option<String>,
    ) -> Result<Vec<u32>> {
        self.add_source_breakpoint_with(
            source,
            BreakpointConfig {
                condition,
                ..BreakpointConfig::default()
            },
        )
    }

    /// Set source-line breakpoints with an explicit configuration. Returns one
    /// id per matching address (or a single deferred id).
    pub fn add_source_breakpoint_with(
        &mut self,
        source: String,
        config: BreakpointConfig,
    ) -> Result<Vec<u32>> {
        self.breakpoints
            .add_source(self.backend.as_mut(), &self.target, source, config)
    }

    /// Watch data accesses at `addr`. Watches are global across guest address
    /// spaces. Returns the stop-point id.
    pub fn add_watchpoint(
        &mut self,
        addr: VirtAddr,
        access: WatchpointAccess,
        len: u8,
    ) -> Result<u32> {
        self.add_watchpoint_with(addr, access, len, None, BreakpointConfig::default())
    }

    /// Watch data accesses with an optional condition evaluated on each hit.
    pub fn add_watchpoint_with_condition(
        &mut self,
        addr: VirtAddr,
        access: WatchpointAccess,
        len: u8,
        condition: Option<String>,
    ) -> Result<u32> {
        self.add_watchpoint_with(
            addr,
            access,
            len,
            None,
            BreakpointConfig {
                condition,
                ..BreakpointConfig::default()
            },
        )
    }

    /// Watch data accesses while retaining an optional host-resolved display
    /// symbol and explicit configuration. Hosts choose write or read/write
    /// behavior while the backend implementation remains private.
    pub fn add_watchpoint_with(
        &mut self,
        addr: VirtAddr,
        access: WatchpointAccess,
        len: u8,
        symbol: Option<String>,
        config: BreakpointConfig,
    ) -> Result<u32> {
        self.breakpoints.add_hardware_configured(
            self.backend.as_mut(),
            &self.target,
            addr,
            access.into(),
            len,
            symbol,
            config,
        )
    }

    /// Remove a breakpoint by id.
    pub fn remove_breakpoint(&mut self, id: u32) -> Result<()> {
        self.breakpoints
            .remove(self.backend.as_mut(), &self.target, id)
    }

    /// Re-arm a disabled breakpoint (re-patch its `int3`).
    pub fn enable_breakpoint(&mut self, id: u32) -> Result<()> {
        self.breakpoints
            .enable(self.backend.as_mut(), &self.target, id)
    }

    /// Disable a breakpoint (restore the original byte) without forgetting it,
    /// so it can be re-enabled later.
    pub fn disable_breakpoint(&mut self, id: u32) -> Result<()> {
        self.breakpoints
            .disable(self.backend.as_mut(), &self.target, id)
    }

    /// List all breakpoints.
    pub fn list_breakpoints(&self) -> Vec<&Breakpoint> {
        self.breakpoints.list()
    }

    /// This session's process-unique identity (see the `id` field).
    pub fn id(&self) -> usize {
        self.id
    }

    /// Return one breakpoint by id.
    pub fn breakpoint(&self, id: u32) -> Option<&Breakpoint> {
        self.breakpoints.list().into_iter().find(|bp| bp.id == id)
    }

    /// Inspect every backend execution context (vCPU): its RIP, the address space
    /// it is running in (kernel / a process / unknown), and the nearest symbol.
    /// Selects each vCPU in turn to read its register file, then restores the
    /// originally-stopped one. The VM must be halted.
    pub fn vcpus(&mut self) -> Result<Vec<VcpuInfo>> {
        let original = self.backend.stopped_thread_id()?;
        let threads = self.backend.thread_list()?;
        let processes = self
            .target
            .guest
            .as_ref()
            .and_then(|g| g.enumerate_processes().ok())
            .unwrap_or_default();
        let dtb_mask = self.target.arch().dtb_page_mask();
        let kernel_dtb_masked = self
            .target
            .guest
            .as_ref()
            .map(|g| g.ntoskrnl.dtb() & dtb_mask);

        let mut out = Vec::with_capacity(threads.len());
        for thread in &threads {
            let regs = self
                .backend
                .set_current_thread(thread)
                .and_then(|_| self.backend.read_registers());
            let regs = match regs {
                Ok(regs) => regs,
                Err(e) => {
                    out.push(VcpuInfo {
                        id: thread.clone(),
                        rip: None,
                        context: String::new(),
                        symbol: None,
                        error: Some(e.to_string()),
                    });
                    continue;
                }
            };
            let (Ok(rip), Ok(dtb)) = (
                self.register_map.read_u64("rip", &regs),
                self.register_map
                    .read_u64(self.target.arch().dtb_register(), &regs),
            ) else {
                out.push(VcpuInfo {
                    id: thread.clone(),
                    rip: None,
                    context: String::new(),
                    symbol: None,
                    error: None,
                });
                continue;
            };

            // RIP=0 means the dump did not capture this CPU's context
            if rip == 0 {
                out.push(VcpuInfo {
                    id: thread.clone(),
                    rip: Some(0),
                    context: "no context".to_string(),
                    symbol: None,
                    error: None,
                });
                continue;
            }

            let dtb_masked = dtb & dtb_mask;
            let (context, symbol) = if kernel_dtb_masked.is_some_and(|k| dtb_masked == k) {
                let sym = self
                    .target
                    .guest
                    .as_ref()
                    .and_then(|g| g.ntoskrnl.closest_symbol(VirtAddr(rip)).ok())
                    .map(|(s, o)| format!("{s}+{o:#x}"));
                ("kernel".to_string(), sym)
            } else {
                match processes.iter().find(|p| (p.dtb & dtb_mask) == dtb_masked) {
                    Some(proc) => {
                        let sym = self
                            .target
                            .symbols
                            .format_closest_symbol_for_address(proc.dtb, VirtAddr(rip));
                        (proc.name.clone(), sym)
                    }
                    None => {
                        let sym = self.target.closest_symbol_current_context(VirtAddr(rip));
                        let ctx = if sym.is_some() { "kernel" } else { "unknown" };
                        (ctx.to_string(), sym)
                    }
                }
            };

            out.push(VcpuInfo {
                id: thread.clone(),
                rip: Some(rip),
                context,
                symbol,
                error: None,
            });
        }

        let _ = self.backend.set_current_thread(&original);
        Ok(out)
    }

    /// Map each *active* Windows thread (one currently scheduled on a vCPU) to
    /// the vCPU running it and its [`ThreadInfo`], keyed by `ETHREAD` address.
    /// Walks every backend vCPU, resolves the Windows thread it is executing,
    /// and restores the originally-stopped vCPU. Best-effort (empty map if the
    /// backend can't enumerate vCPUs).
    pub fn active_thread_map(&mut self) -> HashMap<u64, (String, ThreadInfo)> {
        let Ok(original) = self.backend.stopped_thread_id() else {
            return HashMap::new();
        };
        let Ok(vcpus) = self.backend.thread_list() else {
            return HashMap::new();
        };

        let mut active = HashMap::new();
        for vcpu in &vcpus {
            if self.backend.set_current_thread(vcpu).is_err() {
                continue;
            }
            let Some(processor) = processor_index_from_backend_thread_id(vcpu) else {
                continue;
            };
            if let Ok(thread) = self.target.current_windows_thread_for_processor(processor) {
                active.insert(thread.ethread.0, (vcpu.clone(), thread));
            }
        }

        let _ = self.backend.set_current_thread(&original);
        active
    }

    /// Enumerate all Windows threads, merged with the currently-active threads
    /// (so a thread scheduled on a vCPU but absent from the walk is still
    /// included), sorted by `(pid, tid)`. Returns the threads plus a map of
    /// `ETHREAD -> vCPU id` for those currently running; hosts apply their own
    /// filtering/rendering.
    pub fn windows_threads(&mut self) -> Result<(Vec<ThreadInfo>, HashMap<u64, String>)> {
        let active = self.active_thread_map();
        let mut threads = self.target.enumerate_threads()?;
        for (_, thread) in active.values() {
            if !threads.iter().any(|known| known.ethread == thread.ethread) {
                threads.push(thread.clone());
            }
        }
        threads.sort_by_key(|thread| (thread.pid.unwrap_or(u64::MAX), thread.tid));
        let active_vcpus = active
            .into_iter()
            .map(|(ethread, (vcpu, _))| (ethread, vcpu))
            .collect();
        Ok((threads, active_vcpus))
    }

    /// Read guest virtual memory in the current inspection context with our
    /// own breakpoint patch bytes masked back to the original code, so every
    /// host (REPL, MCP, SDK) sees the same bytes the guest would run.
    pub fn read_masked(&self, addr: VirtAddr, buf: &mut [u8]) -> Result<()> {
        let process = self.target.current_process()?;
        process.memory().read_bytes(addr, buf)?;
        self.breakpoints
            .mask_breakpoint_bytes(addr, buf, process.dtb());
        Ok(())
    }

    /// Disassemble `count` instructions starting at `addr` in the current
    /// address space. Our own breakpoint `int3` bytes are masked back to the
    /// original opcode, and branch / rip-relative targets get symbol comments.
    pub fn disassemble(&self, addr: VirtAddr, count: usize) -> Result<Vec<DisasmRow>> {
        let process = self.target.current_process()?;
        let dtb = process.dtb();

        // x86-64 instructions are at most 15 bytes; ARM64 is fixed 4 bytes.
        // Over-read so `count` decode.
        let overread = match self.target.arch() {
            Arch::Amd64 => count * 16,
            Arch::Arm64 => count * 4,
        };
        let mut buf = vec![0u8; overread];
        self.read_masked(addr, &mut buf)?;

        let symbols = &self.target.symbols;
        let resolve = |target: u64| {
            symbols
                .format_closest_symbol_for_address(dtb, VirtAddr(target))
                .unwrap_or_default()
        };
        match self.target.arch() {
            Arch::Amd64 => {
                let mut formatter = disasm_formatter();
                Ok(decode_rows(
                    &buf,
                    addr.0,
                    Some(count),
                    &mut formatter,
                    resolve,
                ))
            }
            Arch::Arm64 => Ok(decode_rows_arm64(&buf, addr.0, Some(count), resolve)),
        }
    }

    /// The current backend context's call stack with the sparse registers
    /// recovered for every frame, plus the seed register file the walk started
    /// from. A parked Windows thread is walked from its saved context without
    /// touching the backend vCPU.
    pub fn recovered_backtrace(
        &mut self,
        limit: usize,
    ) -> Result<(RecoveredStackTrace, HashMap<String, u64>)> {
        if let Some(thread) = self.parked_windows_thread() {
            let recovered = build_parked_thread_recovered_stack(&self.target, thread, limit)?;
            // The walk's own first frame is the only register context a parked
            // thread has; there is no live file to seed from.
            let seed = recovered
                .stacktrace
                .frames
                .first()
                .map(|frame| frame.registers.clone())
                .unwrap_or_default();
            return Ok((recovered.stacktrace, seed));
        }

        let registers = self.read_registers()?;
        let seed = self.register_map.to_hashmap(&registers);
        let recovered =
            build_stacktrace_with_context(&self.target, &self.register_map, &registers, limit);
        Ok((recovered, seed))
    }

    /// Walk the currently selected backend context's call stack, returning up to
    /// `limit` frames. A parked Windows thread uses stack-only recovery without
    /// touching the backend vCPU.
    pub fn backtrace(&mut self, limit: usize) -> Result<StackTrace> {
        let (recovered, _) = self.recovered_backtrace(limit)?;
        Ok(StackTrace {
            frames: recovered
                .frames
                .into_iter()
                .map(|frame| frame.frame)
                .collect(),
            truncated: recovered.truncated,
        })
    }

    /// Unwind a specified non-running Windows thread in its owning process
    /// address space without selecting it or mutating the backend vCPU.
    pub fn backtrace_thread(&self, thread: &ThreadInfo, limit: usize) -> Result<ThreadStackTrace> {
        build_parked_thread_stack(&self.target, thread, limit)
    }

    /// Uninstall every breakpoint. Successful removals are forgotten; failed
    /// removals remain managed so callers can retry and must not resume the
    /// target as if cleanup had succeeded.
    pub fn remove_all_breakpoints(&mut self) -> Result<()> {
        self.breakpoints
            .remove_all(self.backend.as_mut(), &self.target)
    }

    /// Leave the target in a usable state when a frontend exits: halt first if
    /// needed, restore every debugger-owned breakpoint site, and resume only
    /// when both operations succeed. Any failure explicitly prepares the
    /// backend to leave the target halted.
    pub fn cleanup_for_exit(&mut self) -> Result<()> {
        let halted = if self.backend.is_running() {
            self.interrupt().map(|_| ())
        } else {
            Ok(())
        };
        if halted.is_err() {
            return prepare_backend_after_cleanup(self.backend.as_mut(), halted);
        }

        let cleanup = self.remove_all_breakpoints();
        prepare_backend_after_cleanup(self.backend.as_mut(), cleanup)
    }

    /// Resume the VM. If sitting on one of our breakpoints, step past it first
    /// (otherwise the `int3` at RIP re-fires immediately), re-arm enabled
    /// breakpoints, then continue and drop the now-stale inspection caches.
    /// The canonical resume prologue, shared by the REPL and the SDK.
    ///
    /// Does not poll for Ctrl+C or handle KD target-reload/reconnect the way the
    /// REPL's continue loop does; those remain REPL concerns.
    pub fn resume(&mut self) -> Result<()> {
        self.resume_with_disposition(ContinueDisposition::Handled)
    }

    /// Clear every inspection cache that cannot survive a crash/reboot command
    /// before the shared wait loop re-establishes the next stop.
    pub fn clear_resume_state(&mut self) {
        self.target.selected_frame = None;
        self.target.registers = None;
        self.target.clear_context_dtb_override();
        self.target.clear_current_windows_thread_context();
        self.target.last_exception_code = None;
        self.parked_windows_thread = None;
        self.parked_stop = None;
        self.module_refresh_report = None;
    }

    /// Resume with an explicit exception acknowledgment while preserving the
    /// same breakpoint step-over and cache invalidation prologue as [`Self::resume`].
    pub fn resume_with_disposition(&mut self, disposition: ContinueDisposition) -> Result<()> {
        self.target.selected_frame = None;
        self.module_refresh_report = None;
        if self.parked_windows_thread().is_some() {
            self.parked_windows_thread = None;
            self.target.clear_current_windows_thread_context();
            self.refresh_context_for_current_thread();
        }
        // The VM is moving on, so any stop `service_idle` parked for the host to
        // observe is now spent; drop it so a later `wait_for_stop` doesn't replay
        // a stale event.
        self.parked_stop = None;
        // If a post-reboot rediscovery is still pending only because the module
        // list wasn't up yet, finish it from memory before continuing. We are
        // halted, so the next `continue` starts the pump with the reconnect-assist
        // poking already off, instead of resuming into another forced break-in.
        self.try_finish_rediscovery_from_memory();
        if self.breakpoints.has_enabled_breakpoints() {
            self.backend.set_current_thread(&self.current_thread)?;
            step_over_current_breakpoint(
                self.backend.as_mut(),
                &self.register_map,
                &self.target,
                &mut self.breakpoints,
            )?;
        }
        for id in self.breakpoints.one_shot_hit_ids() {
            self.breakpoints
                .remove(self.backend.as_mut(), &self.target, id)?;
        }

        self.breakpoints
            .refresh_enabled(self.backend.as_mut(), &self.target)?;
        self.backend
            .continue_execution_with_disposition(disposition)?;
        self.record_continuation_disposition(disposition);

        self.target.registers = None;
        self.target.clear_context_dtb_override();
        self.target.clear_current_windows_thread_context();
        self.parked_windows_thread = None;
        Ok(())
    }

    /// Classify a freshly observed stop at (`rip`, `cr3`) against our breakpoints,
    /// performing the absorb actions the caller shouldn't have to: a false
    /// conditional breakpoint or a wrong-process hit on a shared-page int3 is
    /// stepped over and resumed, returning [`BreakpointStopAction::Resumed`]. A
    /// real hit re-arms enabled breakpoints (the stub can drop non-hit ones on a
    /// stop) and returns its details. The caller must have read registers and
    /// established (`rip`, `cr3`) for the stopped thread first.
    ///
    /// Shared by [`Self::continue_until_break`] and the REPL's continue loop so
    /// they can't drift on which int3 hits surface and which are silently resumed.
    pub fn resolve_breakpoint_stop(&mut self, rip: u64, cr3: u64) -> Result<BreakpointStopAction> {
        match self.breakpoints.check_breakpoint_hit(rip, cr3) {
            BreakpointHitResult::Hit(bp) => {
                // Count every scoped physical hit before pass-count and
                // condition evaluation. A pass skip uses the same canonical
                // step-over/resume path as a false condition.
                if self.breakpoints.record_hit(bp.id)? == BreakpointHitDisposition::SkipPass {
                    step_over_current_breakpoint(
                        self.backend.as_mut(),
                        &self.register_map,
                        &self.target,
                        &mut self.breakpoints,
                    )?;
                    self.backend.continue_execution()?;
                    return Ok(BreakpointStopAction::Resumed);
                }
                // A false condition is absorbed. Evaluation errors fail safe:
                // surface the stop and carry the error to every host.
                let condition_error = match bp.evaluate_condition(&self.target) {
                    Ok(false) => {
                        step_over_current_breakpoint(
                            self.backend.as_mut(),
                            &self.register_map,
                            &self.target,
                            &mut self.breakpoints,
                        )?;
                        self.backend.continue_execution()?;
                        return Ok(BreakpointStopAction::Resumed);
                    }
                    Ok(true) => None,
                    Err(error) => Some(error.to_string()),
                };

                // The stub can drop non-hit breakpoints when the VM stops; re-arm
                // so they survive the next resume.
                if let Err(error) = self
                    .breakpoints
                    .refresh_enabled(self.backend.as_mut(), &self.target)
                {
                    eprintln!("failed to re-arm breakpoints at this stop: {error}");
                }

                self.breakpoints.mark_one_shot_hit(bp.id)?;
                Ok(BreakpointStopAction::Hit {
                    breakpoint: bp,
                    condition_error,
                })
            }
            BreakpointHitResult::NotBreakpoint => {
                // Wrong-process hit on a shared-page int3 (the BP is scoped to a
                // different address space): silently step over so the wrong
                // process keeps running, then resume waiting for the right one.
                if self.breakpoints.breakpoint_id_at_address(rip).is_some() {
                    step_over_current_breakpoint(
                        self.backend.as_mut(),
                        &self.register_map,
                        &self.target,
                        &mut self.breakpoints,
                    )?;
                    self.backend.continue_execution()?;
                    return Ok(BreakpointStopAction::Resumed);
                }

                Ok(BreakpointStopAction::NotBreakpoint)
            }
        }
    }

    /// Consult and clear the module-change signals, reconciling symbolic
    /// breakpoints when the module set moved. Returns whether it moved. The KD
    /// event signal and the per-stop module-list refresh are joined here so all
    /// hosts share the same deferred-breakpoint behavior; refresh and
    /// reconciliation failures are logged and do not discard the stop.
    pub fn refresh_modules_on_stop(&mut self) -> bool {
        let event_changed = self.backend.take_modules_changed();
        let symbols_changed = match self.target.refresh_kernel_module_symbols() {
            Ok(report) => {
                let changed = report.loaded != 0 || report.unloaded != 0;
                if changed {
                    self.module_refresh_report = Some(report);
                }
                changed
            }
            Err(error) => {
                eprintln!("failed to refresh module symbols after module change: {error}");
                false
            }
        };
        let modules_changed = event_changed || symbols_changed;
        if modules_changed
            && let Err(error) = self
                .breakpoints
                .reconcile_symbolic_after_module_refresh(self.backend.as_mut(), &self.target)
        {
            eprintln!("failed to reconcile breakpoints after module refresh: {error}");
        }
        modules_changed
    }

    /// Take the latest module-symbol report for the REPL's existing summary.
    /// The report is private to the REPL's summary path.
    pub fn take_module_refresh_report(&mut self) -> Option<ModuleSymbolLoadReport> {
        self.module_refresh_report.take()
    }

    /// Classify one raw backend stop and perform every core-owned transition.
    ///
    /// This is the only stop-ingestion state machine. REPL, MCP, Python, and
    /// idle servicing may differ in polling and presentation, but must route
    /// raw events here so reload handling, DR acknowledgment, scope checks,
    /// `int3` rewind, conditions, and auto-resume behavior cannot drift.
    pub fn classify_stop_event(&mut self, mut event: StopEvent) -> Result<StopResolution> {
        self.target.selected_frame = None;
        self.record_stop_event(&event);
        set_current_thread_from_stop(self.backend.as_mut(), &event, &mut self.current_thread);

        if event.is_bugcheck && !event.target_reloaded {
            self.target.registers = None;
            let resolution = StopResolution::Bugcheck { event };
            self.record_visible_stop(&resolution);
            return Ok(resolution);
        }

        match self.classify_reload_stop(&mut event)? {
            disposition @ (ReloadDisposition::Reloaded { .. }
            | ReloadDisposition::ReloadCompleted) => {
                let coherent =
                    !matches!(disposition, ReloadDisposition::Reloaded { coherent: false });
                self.refresh_context_for_current_thread();
                let resolution = StopResolution::TargetReloaded { event, coherent };
                self.record_visible_stop(&resolution);
                return Ok(resolution);
            }
            ReloadDisposition::PendingRediscovery | ReloadDisposition::ResumePastAssist => {
                self.backend.continue_execution()?;
                return Ok(StopResolution::Resumed);
            }
            ReloadDisposition::Ordinary => {}
        }

        if event.modules_changed {
            self.refresh_modules_on_stop();
            self.backend.continue_execution()?;
            return Ok(StopResolution::ModulesChanged);
        }

        match resolve_watchpoint_stop(
            self.backend.as_mut(),
            &self.register_map,
            &mut self.breakpoints,
            &mut self.target,
            &mut self.current_thread,
            &event,
        )? {
            WatchpointStopAction::Hit {
                breakpoint,
                condition_error,
            } => {
                let rip = self
                    .target
                    .registers
                    .as_ref()
                    .and_then(|registers| registers.get("rip").copied())
                    .unwrap_or(0);
                let resolution = StopResolution::Breakpoint {
                    breakpoint,
                    event,
                    rip,
                    condition_error,
                };
                self.record_visible_stop(&resolution);
                return Ok(resolution);
            }
            WatchpointStopAction::Resumed => return Ok(StopResolution::Resumed),
            WatchpointStopAction::NotBreakpoint => {}
        }

        if stop_is_stray_single_step(&event, &self.breakpoints) {
            let _ = clear_trap_flag(self.backend.as_mut(), &self.register_map);
            self.backend.continue_execution()?;
            return Ok(StopResolution::Resumed);
        }

        if event.exception_code == Some(STATUS_BREAKPOINT)
            && self.breakpoints.has_enabled_breakpoints()
        {
            rewind_thread_off_breakpoint(
                self.backend.as_mut(),
                &self.register_map,
                &self.breakpoints,
                self.target.arch(),
            );
        }

        let registers = self.backend.read_registers()?;
        let rip = self.register_map.read_u64("rip", &registers).unwrap_or(0);
        let cr3 = self
            .register_map
            .read_u64(self.target.arch().dtb_register(), &registers)
            .unwrap_or(0);
        update_target_context_from_registers(&mut self.target, &self.register_map, Ok(registers));

        let resolution = match self.resolve_breakpoint_stop(rip, cr3)? {
            BreakpointStopAction::Hit {
                breakpoint,
                condition_error,
            } => StopResolution::Breakpoint {
                breakpoint,
                event,
                rip,
                condition_error,
            },
            BreakpointStopAction::Resumed => StopResolution::Resumed,
            BreakpointStopAction::NotBreakpoint => StopResolution::Stopped { event, rip },
        };
        self.record_visible_stop(&resolution);
        Ok(resolution)
    }

    /// Resume the VM (unless already running) and wait up to `timeout` for a
    /// meaningful stop; wrong-process int3 hits and false conditional
    /// breakpoints are stepped over silently. `None` waits indefinitely;
    /// `cancel` or an elapsed timeout returns [`ContinueOutcome::Running`] with
    /// the VM left running. Non-resuming observation is
    /// [`Self::wait_for_stop_bounded`].
    pub fn continue_until_break(
        &mut self,
        timeout: Option<Duration>,
        cancel: &AtomicBool,
    ) -> Result<ContinueOutcome> {
        self.continue_until_break_with_disposition(timeout, cancel, ContinueDisposition::Handled)
    }

    /// Resume with an explicit exception acknowledgment, then wait for a
    /// meaningful stop. When already running, no acknowledgment is sent.
    pub fn continue_until_break_with_disposition(
        &mut self,
        timeout: Option<Duration>,
        cancel: &AtomicBool,
        disposition: ContinueDisposition,
    ) -> Result<ContinueOutcome> {
        if !self.backend.is_running() {
            self.resume_with_disposition(disposition)?;
        }
        self.wait_for_stop_bounded(timeout, cancel)
    }

    /// Wait up to `timeout` for the next meaningful stop **without resuming**:
    /// drains a held stop, drives the reboot / breakpoint classification, absorbs
    /// debugger noise (assist break-ins, stray single-steps, wrong-process and
    /// false-condition hits), and returns the stop worth surfacing (or
    /// [`ContinueOutcome::Running`] on timeout/cancel). Because it never resumes, a
    /// caller already halted at an interesting site (e.g. the early-boot reload)
    /// observes it in place instead of blowing past it; that separation is why
    /// the MCP surface splits resume from wait.
    pub fn wait_for_stop_bounded(
        &mut self,
        timeout: Option<Duration>,
        cancel: &AtomicBool,
    ) -> Result<ContinueOutcome> {
        // A stop `service_idle` caught and parked while the host was idle is
        // the proper event for this wait: surface it before waiting for a new
        // one, so every host (not just one) sees it as its real event.
        if let Some(parked) = self.parked_stop.take() {
            return Ok(parked);
        }
        let deadline = timeout.map(|t| Instant::now() + t);
        loop {
            if cancel.load(Ordering::Relaxed) {
                return Ok(ContinueOutcome::Running);
            }
            // Wait one poll interval at a time so `cancel` and the deadline stay
            // responsive; an indefinite wait (`deadline == None`) just keeps going.
            let poll = match deadline {
                Some(dl) => {
                    let remaining = dl.saturating_duration_since(Instant::now());
                    if remaining.is_zero() {
                        return Ok(ContinueOutcome::Running);
                    }
                    remaining.min(CONTINUE_POLL_INTERVAL)
                }
                None => CONTINUE_POLL_INTERVAL,
            };

            let event = match self.backend.try_wait_for_stop(poll)? {
                Some(event) => event,
                None => {
                    // Halted with nothing pending: report the park instead of
                    // spinning out the timeout.
                    if !self.backend.is_running() {
                        // Flush a reload nobody surfaced before reporting a plain halt.
                        if self.reload_surface_pending {
                            self.reload_surface_pending = false;
                            return Ok(ContinueOutcome::TargetReloaded {
                                kernel_base: self.target.kernel_base().map(|a| a.0),
                                coherent: self.kernel_coherent(),
                            });
                        }
                        let rip = self
                            .backend
                            .read_registers()
                            .ok()
                            .and_then(|regs| self.register_map.read_u64("rip", &regs).ok())
                            .unwrap_or(0);
                        return Ok(ContinueOutcome::Halted { rip });
                    }
                    continue;
                }
            };
            match self.classify_stop_event(event)? {
                StopResolution::Resumed | StopResolution::ModulesChanged => continue,
                resolution @ StopResolution::TargetReloaded { coherent, .. } => {
                    reload_trace!(
                        "continue: SURFACE target_reloaded base={} coherent={}",
                        self.target.kernel_base().map_or_else(
                            || "none".to_string(),
                            |address| format!("{:#x}", address.0)
                        ),
                        coherent,
                    );
                    return Ok(self.continue_outcome_from_resolution(resolution));
                }
                resolution => return Ok(self.continue_outcome_from_resolution(resolution)),
            }
        }
    }

    /// Block until the backend produces a meaningful stop, routing every raw
    /// event through [`Self::classify_stop_event`]. Filtered breakpoint hits and
    /// debugger noise are resumed internally.
    pub fn wait_for_stop(&mut self) -> Result<StopEvent> {
        loop {
            let event = self.backend.wait_for_stop()?;
            match self.classify_stop_event(event)? {
                StopResolution::Resumed | StopResolution::ModulesChanged => continue,
                StopResolution::Breakpoint { event, .. }
                | StopResolution::Bugcheck { event }
                | StopResolution::TargetReloaded { event, .. }
                | StopResolution::Stopped { event, .. } => return Ok(event),
            }
        }
    }

    /// Rebuild guest state using an optional kernel-base hint through the shared
    /// [`perform_target_reload`] action.
    pub fn reload_with_hint(&mut self, hint: Option<VirtAddr>) -> Result<()> {
        self.target.last_exception_code = None;
        self.module_refresh_report = None;
        let outcome = perform_target_reload(
            self.backend.as_mut(),
            &mut self.target,
            &mut self.breakpoints,
            hint,
        );
        self.reload_module_list_pending = !outcome
            .report
            .as_ref()
            .map(reload_report_has_loaded_module_list)
            .unwrap_or(false);
        if let Some(error) = outcome.breakpoint_error {
            return Err(error);
        }
        outcome.report.map(|_| ())
    }

    /// Rebuild guest state, auto-discovering the kernel base.
    pub fn reload(&mut self) -> Result<()> {
        self.reload_with_hint(None)
    }

    /// If a module-list reload is pending and the loaded-module list has now
    /// appeared, finish rediscovery: reload the kernel module symbols, tell the
    /// backend rediscovery completed (stopping its reconnect-assist poking), and
    /// clear the pending flag. Returns whether it completed on this call. The
    /// REPL layers cache refresh and progress printing on the same condition.
    pub fn try_complete_pending_reload(&mut self) -> Result<bool> {
        if !self.reload_module_list_pending {
            return Ok(false);
        }
        let startup = match self.target.startup_message_data() {
            Ok(startup) => startup,
            Err(error) => {
                reload_trace!("try_complete: startup read failed: {error}");
                return Ok(false);
            }
        };
        reload_trace!("try_complete: psmods={:#x}", startup.loaded_module_list.0);
        if startup.loaded_module_list.is_zero() {
            return Ok(false);
        }
        self.target.refresh_kernel_module_symbols()?;
        self.breakpoints
            .resolve_symbolic(self.backend.as_mut(), &self.target)?;
        self.backend.note_target_rediscovery_complete();
        self.reload_module_list_pending = false;
        Ok(true)
    }

    /// Try to finish module-list rediscovery by reading `PsLoadedModuleList` from
    /// guest memory instead of forcing a stop. Skips while a reload notification
    /// is still owed, so completion cannot silently swallow the one
    /// `TargetReloaded` event.
    pub fn try_finish_rediscovery_from_memory(&mut self) {
        if !self.reload_surface_pending {
            let _ = self.try_complete_pending_reload();
        }
    }

    /// Clear a deferred reboot notification once the host has already observed
    /// or acted on the rebuilt target. Leave it pending if the current kernel
    /// mapping still looks stale, so a later wait can surface the real reload.
    pub fn clear_deferred_reload_surface(&mut self) {
        if self.target.current_kernel_mapping_is_valid() {
            self.reload_surface_pending = false;
        }
    }

    /// Advance the reboot / KD-reconnect state machine for a freshly observed
    /// `event`, returning how a host should treat it (see [`ReloadDisposition`]).
    /// On a detected reload it drops stale breakpoints, rebuilds guest state, and
    /// records whether the module list is available yet (setting
    /// [`Self::reload_module_list_pending`]); on a later stop it tries to complete
    /// a pending rediscovery; otherwise it recognizes transport assist break-ins.
    /// Mutates `event.target_reloaded` to match. `continue_until_break` consumes
    /// it; the REPL shares its predicates so they can't drift.
    pub fn classify_reload_stop(&mut self, event: &mut StopEvent) -> Result<ReloadDisposition> {
        reload_trace!(
            "classify: pc={} exc={} assisted={} reloaded={} bugcheck={} pending={}",
            event
                .program_counter
                .map_or_else(|| "none".to_string(), |p| format!("{p:#x}")),
            event
                .exception_code
                .map_or_else(|| "none".to_string(), |c| format!("{c:#x}")),
            event.assisted_breakin,
            event.target_reloaded,
            event.is_bugcheck,
            self.reload_module_list_pending,
        );

        if stop_event_requires_target_reload(&self.target, event) {
            event.target_reloaded = true;
            let TargetReloadOutcome {
                report,
                hint,
                breakpoint_error,
            } = perform_target_reload(
                self.backend.as_mut(),
                &mut self.target,
                &mut self.breakpoints,
                event.target_kernel_base_hint,
            );
            if let Some(error) = breakpoint_error {
                return Err(error);
            }
            return Ok(match report {
                Ok(report) => {
                    let coherent = reload_report_has_loaded_module_list(&report);
                    self.reload_module_list_pending = !coherent;
                    // The host surfaces this verdict, so the reboot has been
                    // reported; the eventual completion stays silent.
                    self.reload_surface_pending = false;
                    reload_trace!(
                        "classify: reload ok hint={} new_base={} psmods={} coherent={}",
                        hint.map_or_else(|| "none".to_string(), |value| format!("{:#x}", value.0)),
                        self.target.kernel_base().map_or_else(
                            || "none".to_string(),
                            |address| format!("{:#x}", address.0)
                        ),
                        report.startup.as_ref().map_or_else(
                            || "none".to_string(),
                            |startup| format!("{:#x}", startup.loaded_module_list.0),
                        ),
                        coherent,
                    );
                    ReloadDisposition::Reloaded { coherent }
                }
                Err(error) => {
                    self.reload_module_list_pending = true;
                    self.reload_surface_pending = true;
                    reload_trace!("classify: reload err={error} -> pending_rediscovery");
                    ReloadDisposition::PendingRediscovery
                }
            });
        }

        // A pending reload whose module list just became available completes here
        // (and turns off the reconnect-assist poking). If the reload itself was
        // never surfaced (the rebuild failed at the detection stop), surface the
        // completion as the one reload notification for this reboot; otherwise
        // the completion is silent; absorb debugger noise, and let a real stop
        // (e.g. an early-boot breakpoint hit) be handled normally below.
        if self.try_complete_pending_reload()? {
            if self.reload_surface_pending {
                self.reload_surface_pending = false;
                reload_trace!(
                    "classify: pending reload COMPLETED (unsurfaced) -> reload_completed"
                );
                return Ok(ReloadDisposition::ReloadCompleted);
            }
            if stop_is_assisted_refresh_breakin(&self.breakpoints, event) {
                reload_trace!("classify: pending reload COMPLETED silently -> resume_past_assist");
                return Ok(ReloadDisposition::ResumePastAssist);
            }
            reload_trace!("classify: pending reload COMPLETED silently at a real stop");
            return Ok(ReloadDisposition::Ordinary);
        }

        // KD refresh/reconnect/debugger break-in (including the boot-time assist
        // pokes while a reload is still pending): resume past it. Real stops,
        // notably hits on breakpoints set at the early-boot reload stop, fall
        // through and surface even while the module list is still pending.
        if stop_is_assisted_refresh_breakin(&self.breakpoints, event) {
            reload_trace!("classify: assisted refresh break-in -> resume_past_assist");
            return Ok(ReloadDisposition::ResumePastAssist);
        }

        reload_trace!("classify: ordinary");
        Ok(ReloadDisposition::Ordinary)
    }
}

/// Per-target guard that one ntoseye session owns a given backend resource at a
/// time; a second attach against the same target would corrupt both. Held
/// inside [`Session`] for its lifetime (see [`Session::connect`]); dropping it
/// releases the lock.
struct InstanceGuard(#[allow(dead_code)] SingleInstance);

/// Take the single-instance lock for `target`, or [`Error::AlreadyRunning`] if
/// another ntoseye already holds it. `target` is the backend resource identifier
/// (socket path, address, dump file) so instances on *different* targets can
/// coexist. Internal to [`Session::connect`], which calls it before connecting
/// a backend so a second instance fails fast rather than racing on the transport
/// handshake.
fn acquire_instance_guard(target: &str) -> Result<InstanceGuard> {
    let canonical = canonicalize_target(target);
    let key = format!("ntoseye-{:016x}", fnv1a_64(canonical.as_bytes()));
    // macOS backs the lock with a flock file at this path; keep it out of cwd.
    #[cfg(target_os = "macos")]
    let key = std::env::temp_dir().join(&key).display().to_string();
    let instance = SingleInstance::new(&key).map_err(|err| {
        Error::DebugInfo(format!("failed to create single-instance guard: {err:?}"))
    })?;
    if !instance.is_single() {
        return Err(Error::AlreadyRunning(canonical));
    }
    Ok(InstanceGuard(instance))
}

/// Normalize a target identifier for lock-key stability: equivalent targets
/// must produce the same canonical string. Existing filesystem entries
/// (sockets, files) are resolved first so that different relative paths to
/// the same socket produce the same key.
fn canonicalize_target(target: &str) -> String {
    if let Some(normalized) = normalize_host_port(target) {
        return normalized;
    }
    let path = std::path::Path::new(target);
    if let Ok(canon) = std::fs::canonicalize(path) {
        return canon.to_string_lossy().into_owned();
    }
    let full = if path.is_relative() {
        std::env::current_dir().unwrap_or_default().join(path)
    } else {
        path.to_path_buf()
    };
    let mut out = std::path::PathBuf::new();
    for component in full.components() {
        match component {
            std::path::Component::RootDir => out.push("/"),
            std::path::Component::CurDir => {}
            std::path::Component::ParentDir => {
                out.pop();
            }
            std::path::Component::Normal(s) => out.push(s),
            _ => {}
        }
    }
    out.to_string_lossy().into_owned()
}

/// Detect `host:port` targets and normalize the host component so that
/// `localhost:1234` and `127.0.0.1:1234` map to the same lock key.
fn normalize_host_port(target: &str) -> Option<String> {
    let (host, port_str) = target.rsplit_once(':')?;
    if host.contains('/') {
        return None;
    }
    // Reject bare (unbracketed) IPv6 because the host part would contain extra
    // colons (e.g. "fe80:" from "fe80::5678").
    if host.contains(':') && !host.starts_with('[') {
        return None;
    }
    let _port: u16 = port_str.parse().ok()?;
    let host = host
        .trim_start_matches('[')
        .trim_end_matches(']')
        .to_ascii_lowercase();
    let host = match host.as_str() {
        "localhost" | "ip6-localhost" | "::1" => "127.0.0.1",
        other => other,
    };
    Some(format!("{host}:{port_str}"))
}

fn fnv1a_64(data: &[u8]) -> u64 {
    let mut hash: u64 = 0xcbf29ce484222325;
    for &byte in data {
        hash ^= byte as u64;
        hash = hash.wrapping_mul(0x100000001b3);
    }
    hash
}

/// What to tell the operator when every memory access goes over KD. An
/// emulated UART hands the guest one byte per hypervisor main-loop iteration,
/// so every request costs milliseconds; KDNET has no such floor.
fn kd_memory_source_notice(backend_name: &str) -> String {
    match backend_name {
        "kdnet" => "kdnet: memory source kd; remote reads may be slow.".to_string(),
        name => format!(
            "{name}: memory source kd; prefer --memory-source host if the VM is local, or KDNET"
        ),
    }
}

/// Parse a backend vCPU/thread id (`p1.<one-based-hex>`) into a zero-based
/// processor index. Returns `None` for ids that aren't processor contexts.
/// Shared by the REPL (re-exported from `repl::stop`) and `Session`.
pub fn processor_index_from_backend_thread_id(thread_id: &str) -> Option<u16> {
    let stripped = thread_id.strip_prefix("p1.")?;
    let one_based = u16::from_str_radix(stripped, 16).ok()?;
    one_based.checked_sub(1)
}

/// Adopt the Windows thread a backend vCPU is running as the inspection
/// context, walked from that processor's KPRCB. Returns it, or `None` when the
/// id is not a processor context or the walk fails, clearing the stale
/// selection either way.
///
/// Every host has to do this at every stop: the selection is what `!thread`
/// reports and what the `$thread`/`$proc` pseudo-registers read, and a resume
/// clears it. Shared by the REPL (re-exported from `repl::stop`) and
/// [`Session::run_status`] so the two cannot report different threads.
pub fn refresh_windows_thread_context_for_backend_thread(
    debugger: &mut Target,
    thread_id: &str,
) -> Option<ThreadInfo> {
    let thread = processor_index_from_backend_thread_id(thread_id).and_then(|processor| {
        debugger
            .current_windows_thread_for_processor(processor)
            .ok()
    });
    match thread.clone() {
        Some(thread) => debugger.set_current_windows_thread_context(thread),
        None => debugger.clear_current_windows_thread_context(),
    }
    thread
}

/// Whether a guest-reload report found the loaded-module list (i.e. kernel
/// rediscovery completed). Single definition shared with the REPL.
pub fn reload_report_has_loaded_module_list(report: &ReloadReport) -> bool {
    report
        .startup
        .as_ref()
        .is_some_and(|startup| !startup.loaded_module_list.is_zero())
}

/// The result of [`perform_target_reload`]: the guest-reload outcome plus the
/// resolved kernel-base hint the reload was guided by. `report` is `Ok` when the
/// new kernel image was rediscovered (possibly before its module list is up;
/// check [`reload_report_has_loaded_module_list`]) and `Err` when it isn't
/// discoverable yet (very early boot). `hint` is the base used (from the stop
/// event, else queried from the backend), which the REPL rebases symbols against
/// while rediscovery is pending.
pub struct TargetReloadOutcome {
    pub report: Result<ReloadReport>,
    pub hint: Option<VirtAddr>,
    /// Symbolic breakpoint re-resolution failed after the target itself reloaded.
    pub breakpoint_error: Option<Error>,
}

/// Rebuild guest state after a detected reboot: drop the now-stale breakpoints,
/// resolve a kernel-base hint (preferring the stop event's, else the backend's),
/// reload the guest image, and tell the backend whether rediscovery completed so
/// it stops (or keeps) its reconnect-assist poking. The shared reload *action*
/// behind [`Session::classify_reload_stop`] and the REPL's
/// `apply_target_reload_if_needed`; callers layer their own state/caches/output
/// on top of the returned outcome.
pub fn perform_target_reload(
    backend: &mut dyn DebugBackend,
    target: &mut Target,
    breakpoints: &mut BreakpointManager,
    event_hint: Option<VirtAddr>,
) -> TargetReloadOutcome {
    // Target-specific numeric breakpoints and hardware slots cannot survive a
    // rebuild. Symbolic code breakpoints retain identity and become deferred.
    breakpoints.prepare_target_reload(backend);
    let hint = event_hint.or_else(|| backend.target_kernel_base_hint().ok().flatten());
    let report = target.reload_guest_with_kernel_base_hint(hint);
    // The attach-time identity check only proved the host mapping matched the
    // kernel that was running then. Re-check it against the rebuilt target
    // before anything reads through it again.
    if report.is_ok()
        && let Err(error) = backend.revalidate_host_memory(&target.phys)
    {
        eprintln!(
            "host memory no longer matches the target after the reload ({error}); every read \
             through it is now suspect - reattach with --memory-source kd"
        );
    }
    let breakpoint_error = if report.is_ok() {
        let debugger_data_hint = backend.target_debugger_data_hint().ok().flatten();
        target.refresh_debugger_data(debugger_data_hint);
        breakpoints.resolve_symbolic(backend, target).err()
    } else {
        None
    };
    match &report {
        // Once the kernel image is rediscovered, stop reconnect-assist pokes. The
        // remaining module-list completion is polled from live memory; forced
        // break-ins here would freeze early boot and delay the list we're waiting on.
        Ok(_) => backend.note_target_rediscovery_complete(),
        // Kernel not discoverable at all (no base to read): the assist poke is the
        // only way to force a stop where the rebuild can be retried, so keep it.
        Err(_) => backend.note_target_rediscovery_pending(),
    }
    TargetReloadOutcome {
        report,
        hint,
        breakpoint_error,
    }
}

/// Whether `event` reflects a guest reboot into a new kernel image (so debugger
/// state must be rebuilt), rather than an ordinary stop in the current one.
/// Trusts the transport's explicit reload flag, then falls back to heuristics: a
/// kernel-space PC that lands in no known module, an invalidated current-kernel
/// mapping, or a rediscovered kernel whose identity changed, while treating a
/// near-base bugcheck as the *same* image. Used by
/// [`Session::classify_reload_stop`] and re-exported for the REPL.
pub fn stop_event_requires_target_reload(debugger: &Target, event: &StopEvent) -> bool {
    if event.target_reloaded {
        return true;
    }

    let Some(pc) = event.program_counter else {
        return false;
    };
    if !looks_like_kernel_pointer(pc) {
        return false;
    }

    if !debugger.current_kernel_mapping_is_valid() {
        return true;
    }

    let current_dtb = debugger.kernel_dtb();
    if debugger
        .symbols
        .find_module_for_address(current_dtb, VirtAddr(pc))
        .is_some()
    {
        return false;
    }

    if !event.is_bugcheck
        && debugger
            .kernel_base()
            .is_some_and(|base| pc.abs_diff(base.0) < CURRENT_KERNEL_RELOAD_WINDOW)
    {
        return false;
    }

    debugger
        .rediscovered_kernel_identity_changed()
        .unwrap_or(false)
}

/// Whether `event` is a debugger-generated KD refresh/reconnect break-in
/// rather than a user break or genuine target exception, i.e. a stop to resume
/// past, not surface. KD marks reconnect-assist break-ins explicitly via the
/// `assisted_breakin` flag; user-initiated break-ins (e.g. via Ctrl+C) always
/// surface as real stops regardless of where the kernel hits. Used by
/// [`Session::classify_reload_stop`].
pub fn stop_is_assisted_refresh_breakin(
    breakpoints: &BreakpointManager,
    event: &StopEvent,
) -> bool {
    if event.bugcheck.is_some() || event.exception_code != Some(STATUS_BREAKPOINT) {
        return false;
    }

    if event
        .program_counter
        .is_some_and(|pc| breakpoints.breakpoint_id_at_address(pc).is_some())
    {
        return false;
    }

    event.assisted_breakin
}

/// Whether `event` is a *stray* single-step: a `STATUS_SINGLE_STEP` trap that
/// isn't sitting on a user breakpoint. In a run-control loop (continue / run-to)
/// nobody is intentionally single-stepping, so this is a debugger artifact; a
/// managed step-over's single-step that leaked out because KD single-steps the
/// whole machine and another processor's break was reported first. The loop
/// absorbs it (clear `TF`, resume) rather than surfacing it as a stop. Used by
/// [`Session::continue_until_break`] and the REPL's continue loop.
pub fn stop_is_stray_single_step(event: &StopEvent, breakpoints: &BreakpointManager) -> bool {
    event.exception_code == Some(STATUS_SINGLE_STEP)
        && !event.is_bugcheck
        && event
            .program_counter
            .is_none_or(|pc| breakpoints.breakpoint_id_at_address(pc).is_none())
}

/// If `event` is a hardware-debug stop, return the breakpoint that fired.
/// AMD64 maps DR6 status bits and clears them; ARM64 uses the stopped PC/FAR
/// together with BCR/WCR enable and address-select fields. `None` means a
/// plain single-step or a backend without hardware-stop state. Must run before
/// [`stop_is_stray_single_step`].
pub fn hardware_breakpoint_hit(
    backend: &mut dyn DebugBackend,
    register_map: &RegisterMap,
    breakpoints: &BreakpointManager,
    event: &StopEvent,
) -> Result<Option<Breakpoint>> {
    if event.exception_code != Some(STATUS_SINGLE_STEP)
        || event.is_bugcheck
        || !breakpoints.has_enabled_hardware_breakpoints()
    {
        return Ok(None);
    }

    let mut regs = backend.read_registers()?;
    let Ok(dr6) = register_map.read_u64("dr6", &regs) else {
        return arm64_hardware_breakpoint_hit(register_map, breakpoints, event, &regs);
    };

    let hit = (0..HW_BREAKPOINT_SLOTS)
        .filter(|slot| dr6 & (1u64 << slot) != 0)
        .find_map(|slot| breakpoints.hardware_breakpoint_for_slot(slot));

    let mut dirty = false;
    // Clear the B0-B3 status bits so the next single-step is unambiguous; the
    // CPU never clears them itself, but leave the rest of DR6 intact.
    let cleared = dr6 & !0b1111u64;
    if cleared != dr6 {
        register_map.write_u64("dr6", &mut regs, cleared)?;
        dirty = true;
    }
    if hit
        .as_ref()
        .and_then(|bp| bp.hardware)
        .is_some_and(|hw| hw.access == HwBreakpointAccess::Execute)
    {
        let eflags = register_map.read_u64("eflags", &regs)?;
        const RF: u64 = 1 << 16;
        if eflags & RF == 0 {
            register_map.write_u64("eflags", &mut regs, eflags | RF)?;
            dirty = true;
        }
    }

    if dirty {
        backend.write_registers(&regs)?;
    }

    Ok(hit)
}

fn arm64_hardware_breakpoint_hit(
    register_map: &RegisterMap,
    breakpoints: &BreakpointManager,
    event: &StopEvent,
    regs: &[u8],
) -> Result<Option<Breakpoint>> {
    let pc = register_map
        .read_u64("pc", regs)
        .or_else(|_| register_map.read_u64("rip", regs))
        .unwrap_or_else(|_| event.program_counter.unwrap_or(0));
    let far = register_map.read_u64("far", regs).unwrap_or(0);
    let mut hit = None;

    // ARM64 WVR values are granule-aligned and WCR.BAS identifies the bytes
    // that caused the data watchpoint. Require FAR as evidence: without it a
    // plain single-step must not be mistaken for a data breakpoint.
    if far != 0 {
        for slot in hwbp::ARM64_WATCHPOINT_SLOTS {
            let Some(bp) = breakpoints.hardware_breakpoint_for_slot(slot) else {
                continue;
            };
            let Some(hw) = bp.hardware else { continue };
            if hw.access == HwBreakpointAccess::Execute {
                continue;
            }
            let control = register_map
                .read_u64(format!("wcr{slot}"), regs)
                .unwrap_or(0);
            let value = register_map
                .read_u64(format!("wvr{slot}"), regs)
                .unwrap_or(0);
            if control & 1 == 0 || value != far & !7 {
                continue;
            }
            let bas = ((control >> 5) & 0xff) as u8;
            let far_bit = 1u8 << (far & 7);
            let in_requested_range = bp
                .address
                .0
                .checked_add(hw.len as u64)
                .is_some_and(|end| far >= bp.address.0 && far < end);
            if bas & far_bit != 0 && in_requested_range {
                hit = Some(bp);
                break;
            }
        }
    }

    if hit.is_none() {
        for slot in hwbp::ARM64_BREAKPOINT_SLOTS {
            let Some(bp) = breakpoints.hardware_breakpoint_for_slot(slot) else {
                continue;
            };
            let Some(hw) = bp.hardware else { continue };
            if hw.access != HwBreakpointAccess::Execute {
                continue;
            }
            let index = slot - hwbp::ARM64_BREAKPOINT_SLOTS.start;
            let control = register_map
                .read_u64(format!("bcr{index}"), regs)
                .unwrap_or(0);
            let value = register_map
                .read_u64(format!("bvr{index}"), regs)
                .unwrap_or(0);
            if control & 1 != 0 && value == pc & !3 && bp.address.0 == pc {
                hit = Some(bp);
                break;
            }
        }
    }

    Ok(hit)
}

/// Resolve one stop against the watchpoint manager. This owns the behavior
/// common to every host: claim and acknowledge backend status, adopt the
/// stopped thread, refresh register/CR3 context before condition evaluation,
/// and resume a pass-count or false conditional hit. Condition errors fail
/// safe by surfacing the hit with error metadata.
pub fn resolve_watchpoint_stop(
    backend: &mut dyn DebugBackend,
    register_map: &RegisterMap,
    breakpoints: &mut BreakpointManager,
    target: &mut Target,
    current_thread: &mut String,
    event: &StopEvent,
) -> Result<WatchpointStopAction> {
    let Some(breakpoint) = hardware_breakpoint_hit(backend, register_map, breakpoints, event)?
    else {
        return Ok(WatchpointStopAction::NotBreakpoint);
    };

    set_current_thread_from_stop(backend, event, current_thread);
    let registers = backend.read_registers()?;
    let scope_dtb = register_map
        .read_u64(target.arch().dtb_register(), &registers)
        .unwrap_or(0);
    update_target_context_from_registers(target, register_map, Ok(registers));
    if !breakpoint.scope.matches_cr3(scope_dtb) {
        backend.continue_execution()?;
        return Ok(WatchpointStopAction::Resumed);
    }
    if breakpoints.record_hit(breakpoint.id)? == BreakpointHitDisposition::SkipPass {
        backend.continue_execution()?;
        return Ok(WatchpointStopAction::Resumed);
    }

    let condition_error = match breakpoint.evaluate_condition(target) {
        Ok(false) => {
            backend.continue_execution()?;
            return Ok(WatchpointStopAction::Resumed);
        }
        Ok(true) => None,
        Err(error) => Some(error.to_string()),
    };
    if breakpoint.one_shot {
        breakpoints.remove(backend, target, breakpoint.id)?;
    }

    Ok(WatchpointStopAction::Hit {
        breakpoint,
        condition_error,
    })
}

/// Rewind the reporting thread back onto the breakpoint address when it is
/// parked one byte past one of ours.
///
/// An `int3` advances RIP by one when it executes, so a thread that hit a
/// breakpoint the target does not own reports `addr + 1`; the breakpoint-hit
/// check matches on the exact address, so this realignment must happen first.
///
/// Only the thread that reported the stop is touched, and only for a
/// breakpoint exception. Every other vCPU is frozen wherever it happened to
/// be, which may legitimately be one byte past a breakpoint, and moving a PC
/// back there would re-execute a byte that already ran. A thread that did hit
/// the same `int3` reports it as its own stop later, and is realigned then.
/// Best-effort: a backend that cannot read or write the context is left alone.
pub fn rewind_thread_off_breakpoint(
    backend: &mut dyn DebugBackend,
    register_map: &RegisterMap,
    breakpoints: &BreakpointManager,
    arch: Arch,
) {
    if arch == Arch::Arm64 {
        return;
    }
    let Ok(regs) = backend.read_registers() else {
        return;
    };
    let rip = register_map.read_u64("rip", &regs).unwrap_or(0);
    let cr3 = register_map
        .read_u64(arch.dtb_register(), &regs)
        .unwrap_or(0);
    let Some(prev) = rip.checked_sub(register_map.breakpoint_step_size() as u64) else {
        return;
    };
    if !matches!(
        breakpoints.check_breakpoint_hit(prev, cr3),
        BreakpointHitResult::Hit(_)
    ) {
        return;
    }
    let mut adjusted = regs.clone();
    if register_map.write_u64("rip", &mut adjusted, prev).is_err() {
        return;
    }
    let _ = backend.write_registers(&adjusted);
}

/// Adopt the thread reported by a stop event (falling back to the backend's
/// stopped-thread query) as the current thread, and select it on the backend.
pub fn set_current_thread_from_stop(
    backend: &mut dyn DebugBackend,
    event: &StopEvent,
    current: &mut String,
) {
    let stopped_tid = event
        .thread_id
        .clone()
        .or_else(|| backend.stopped_thread_id().ok());
    if let Some(tid) = stopped_tid {
        *current = tid;
        let _ = backend.set_current_thread(current);
    }
}

/// Single-step the current thread and clear `TF` afterward (KVM leaves it set).
/// A fault or bugcheck instead of the step trap is returned as an error.
pub fn step_one_and_clear_tf(
    backend: &mut dyn DebugBackend,
    register_map: &RegisterMap,
) -> Result<()> {
    backend.step()?;
    let event = backend.wait_for_stop()?;
    clear_trap_flag(backend, register_map)?;
    if event.is_bugcheck {
        return Err(Error::DebugInfo(
            "target bugchecked while single-stepping".into(),
        ));
    }
    if let Some(code) = event
        .exception_code
        .filter(|&code| code != STATUS_SINGLE_STEP && code != STATUS_BREAKPOINT)
    {
        return Err(Error::DebugInfo(format!(
            "target raised exception {code:#x} while single-stepping"
        )));
    }
    Ok(())
}

/// Clear the trap flag (`TF`, RFLAGS bit 8) and DR6's B0-B3 status bits on the
/// currently selected thread, best-effort, so an absorbed single-step leaves
/// no residue for the next resume. ARM64 has neither x86 field, so its
/// single-step state is acknowledged by KD's ARM64 continue request instead.
pub fn clear_trap_flag(backend: &mut dyn DebugBackend, register_map: &RegisterMap) -> Result<()> {
    if let Ok(mut regs) = backend.read_registers() {
        let mut dirty = false;
        if let Ok(eflags) = register_map.read_u64("eflags", &regs) {
            let cleared = eflags & !(1u64 << 8);
            if cleared != eflags && register_map.write_u64("eflags", &mut regs, cleared).is_ok() {
                dirty = true;
            }
        }
        if let Ok(dr6) = register_map.read_u64("dr6", &regs) {
            let cleared = dr6 & !0b1111u64;
            if cleared != dr6 && register_map.write_u64("dr6", &mut regs, cleared).is_ok() {
                dirty = true;
            }
        }
        if dirty {
            backend.write_registers(&regs)?;
        }
    }

    Ok(())
}

/// If RIP sits on one of our enabled breakpoints, disable it, step the
/// underlying instruction, then re-enable; returns whether a step was
/// performed. A stale breakpoint (its address space gone) is silently
/// discarded. Callers must have selected the desired thread first. Shared by the
/// REPL and [`Session::step`].
pub fn step_over_current_breakpoint(
    backend: &mut dyn DebugBackend,
    register_map: &RegisterMap,
    debugger: &Target,
    breakpoints: &mut BreakpointManager,
) -> Result<bool> {
    let regs = backend.read_registers()?;
    let rip = register_map.read_u64("rip", &regs)?;
    // Only the shared-page fallback below needs the address space; a stub
    // without its DTB register still gets the plain step-over.
    let cr3 = register_map
        .read_u64(debugger.arch().dtb_register(), &regs)
        .ok();

    // Scope-agnostic: a wrong-process hit on a shared-page BP still needs the
    // disable/step/enable dance so the wrong process can make forward progress.
    let Some(bp_id) = breakpoints.breakpoint_id_at_address(rip) else {
        return Ok(false);
    };

    // KD removes and reinstalls its own breakpoint sites around stops.
    // Host-side step-over would temporarily leave the site untracked.
    if backend.target_manages_breakpoint_sites() && breakpoints.target_owns_site(bp_id) {
        return Ok(false);
    }

    match (breakpoints.disable(backend, debugger, bp_id), cr3) {
        (Ok(()), _) => {}
        (Err(Error::BadVirtualAddress(_) | Error::AddressNotInDump(_)), Some(cr3)) => {
            breakpoints
                .disable_guest_memory_patch_in_address_space(backend, debugger, bp_id, cr3)?;
        }
        (Err(err), _) => return Err(err),
    }

    let stepped = step_one_and_clear_tf(backend, register_map);

    // Re-arm whether or not the step worked: a failed step must not leave the
    // site unpatched with the manager still believing it is enabled.
    match breakpoints.enable(backend, debugger, bp_id) {
        Ok(()) => {}
        Err(Error::BadVirtualAddress(_) | Error::AddressNotInDump(_)) => {
            // Address space no longer exists; drop the breakpoint and move on.
            breakpoints.discard(backend, bp_id)?;
        }
        Err(err) => return stepped.and(Err(err)),
    }
    stepped.map(|()| true)
}

/// Open a session over a synthetic triage dump whose only memory region is
/// `memory`, mapped at `base`.
#[cfg(test)]
pub fn session_over_memory(base: u64, memory: &[u8]) -> Session {
    let block = TriageBlock {
        address: base,
        offset: 0,
        size: memory.len() as u32,
    };
    let dump = make_triage_dump(&[block], &[(base, memory)]);
    static SEQUENCE: AtomicU64 = AtomicU64::new(0);
    let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed);
    let path = temp_dir().join(format!("ntoseye-session-{sequence}-{}.dmp", id(),));
    write(&path, dump).unwrap();
    let session = Session::open(&TargetSpec::Dump(path.clone())).unwrap();
    remove_file(path).unwrap();
    session
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::gdb::breakpoints::HardwareBreakpoint;
    use crate::kd::context::{REGISTER_BUFFER_SIZE, build_register_map};
    use std::collections::VecDeque;
    use std::sync::atomic::AtomicUsize;

    /// DR6.BS (bit 14): a status bit outside B0-B3 that the functions under
    /// test must leave untouched.
    const DR6_BS: u64 = 1 << 14;
    /// RFLAGS.RF (bit 16), the resume flag an execute hit must set.
    const RF: u64 = 1 << 16;
    /// RFLAGS.TF (bit 8), the trap flag `clear_trap_flag` clears.
    const TF: u64 = 1 << 8;
    /// An eflags value with a few innocent bits (IF | reserved bit 1) that
    /// must survive every rewrite.
    const EFLAGS_BASE: u64 = 0x202;

    /// Minimal register-file backend: a KD-layout register buffer the map's
    /// offsets index into, plus a write counter for no-op assertions. Every
    /// non-register operation is out of scope for these tests.
    struct MockBackend {
        register_map: RegisterMap,
        regs: Vec<u8>,
        writes: usize,
        fail_writes: bool,
        allow_breakpoints: bool,
        exit_requests: Vec<bool>,
        fail_exit: bool,
        running: bool,
        interrupts: Arc<AtomicUsize>,
        continues: Arc<AtomicUsize>,
        interrupt_events: VecDeque<StopEvent>,
        modules_changed: bool,
        target_manages_sites: bool,
    }

    impl MockBackend {
        fn new() -> Self {
            Self {
                register_map: build_register_map(),
                regs: vec![0u8; REGISTER_BUFFER_SIZE],
                writes: 0,
                fail_writes: false,
                allow_breakpoints: false,
                exit_requests: Vec::new(),
                fail_exit: false,
                running: false,
                interrupts: Arc::new(AtomicUsize::new(0)),
                continues: Arc::new(AtomicUsize::new(0)),
                interrupt_events: VecDeque::new(),
                modules_changed: false,
                target_manages_sites: false,
            }
        }

        fn running(mut self) -> Self {
            self.running = true;
            self
        }

        /// Model a target that owns its breakpoint table (KD), not a stub
        /// that leaves our patched byte in place across a stop.
        fn target_managed_sites(mut self) -> Self {
            self.target_manages_sites = true;
            self
        }

        fn queue_interrupt(&mut self, event: StopEvent) {
            self.interrupt_events.push_back(event);
        }

        fn set(&mut self, name: &str, value: u64) {
            self.register_map
                .write_u64(name, &mut self.regs, value)
                .unwrap();
        }

        fn get(&self, name: &str) -> u64 {
            self.register_map.read_u64(name, &self.regs).unwrap()
        }
    }

    impl DebugBackend for MockBackend {
        fn register_map(&self) -> &RegisterMap {
            &self.register_map
        }
        fn read_registers(&mut self) -> Result<Vec<u8>> {
            Ok(self.regs.clone())
        }
        fn write_registers(&mut self, data: &[u8]) -> Result<()> {
            self.writes += 1;
            if self.fail_writes {
                return Err(Error::Kd("injected register write failure".into()));
            }
            self.regs = data.to_vec();
            Ok(())
        }
        fn set_breakpoint(&mut self, _addr: u64) -> Result<()> {
            if self.allow_breakpoints {
                Ok(())
            } else {
                Err(Error::NotSupported)
            }
        }
        fn remove_breakpoint(&mut self, _addr: u64) -> Result<()> {
            if self.allow_breakpoints {
                Ok(())
            } else {
                Err(Error::NotSupported)
            }
        }
        fn target_manages_breakpoint_sites(&self) -> bool {
            self.target_manages_sites
        }
        fn continue_execution(&mut self) -> Result<()> {
            self.continues.fetch_add(1, Ordering::Relaxed);
            self.running = true;
            Ok(())
        }
        fn step(&mut self) -> Result<()> {
            Err(Error::NotSupported)
        }
        fn interrupt(&mut self) -> Result<StopEvent> {
            self.interrupts.fetch_add(1, Ordering::Relaxed);
            let event = self
                .interrupt_events
                .pop_front()
                .ok_or(Error::NotSupported)?;
            self.running = false;
            Ok(event)
        }
        fn wait_for_stop(&mut self) -> Result<StopEvent> {
            let event = self
                .interrupt_events
                .pop_front()
                .ok_or(Error::NotSupported)?;
            self.running = false;
            Ok(event)
        }
        fn try_wait_for_stop(&mut self, _timeout: Duration) -> Result<Option<StopEvent>> {
            let event = self.interrupt_events.pop_front();
            if event.is_some() {
                self.running = false;
            }
            Ok(event)
        }
        fn thread_list(&mut self) -> Result<Vec<String>> {
            Err(Error::NotSupported)
        }
        fn set_current_thread(&mut self, _thread_id: &str) -> Result<()> {
            Err(Error::NotSupported)
        }
        fn stopped_thread_id(&mut self) -> Result<String> {
            Err(Error::NotSupported)
        }
        fn is_running(&self) -> bool {
            self.running
        }

        fn take_modules_changed(&mut self) -> bool {
            take(&mut self.modules_changed)
        }
        fn prepare_for_exit(&mut self, leave_running: bool) -> Result<()> {
            self.exit_requests.push(leave_running);
            if self.fail_exit {
                Err(Error::Kd("injected backend teardown failure".into()))
            } else {
                Ok(())
            }
        }
    }

    fn single_step_event() -> StopEvent {
        StopEvent {
            thread_id: None,
            exception_code: Some(STATUS_SINGLE_STEP),
            first_chance: Some(true),
            exception_address: None,
            program_counter: None,
            is_bugcheck: false,
            bugcheck: None,
            target_reloaded: false,
            target_kernel_base_hint: None,
            modules_changed: false,
            assisted_breakin: false,
        }
    }

    fn breakpoint_event(pc: u64) -> StopEvent {
        StopEvent {
            thread_id: None,
            exception_code: Some(STATUS_BREAKPOINT),
            first_chance: Some(true),
            exception_address: Some(pc),
            program_counter: Some(pc),
            is_bugcheck: false,
            bugcheck: None,
            target_reloaded: false,
            target_kernel_base_hint: None,
            modules_changed: false,
            assisted_breakin: false,
        }
    }

    fn module_change_event() -> StopEvent {
        StopEvent {
            thread_id: None,
            exception_code: None,
            first_chance: None,
            exception_address: None,
            program_counter: None,
            is_bugcheck: false,
            bugcheck: None,
            target_reloaded: false,
            target_kernel_base_hint: None,
            modules_changed: true,
            assisted_breakin: false,
        }
    }

    fn session_with_mock(backend: MockBackend) -> Session {
        let mut session = session_over_memory(0x1000, &[0; 0x100]);
        session.backend = Box::new(backend);
        session.register_map = build_register_map();
        session
    }

    #[test]
    fn with_target_halted_runs_directly_when_already_halted() {
        let backend = MockBackend::new();
        let interrupts = Arc::clone(&backend.interrupts);
        let continues = Arc::clone(&backend.continues);
        let mut session = session_with_mock(backend);
        let value = session.with_target_halted(|_| Ok(7u32)).unwrap();

        assert_eq!(value, 7);
        assert_eq!(interrupts.load(Ordering::Relaxed), 0);
        assert_eq!(continues.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn with_target_halted_interrupts_edits_and_resumes_running_target() {
        let mut backend = MockBackend::new().running();
        let interrupts = Arc::clone(&backend.interrupts);
        let continues = Arc::clone(&backend.continues);
        backend.queue_interrupt(breakpoint_event(0x2000));
        let mut session = session_with_mock(backend);

        session.with_target_halted(|_| Ok(())).unwrap();

        assert_eq!(interrupts.load(Ordering::Relaxed), 1);
        assert_eq!(continues.load(Ordering::Relaxed), 1);
        assert!(session.backend.is_running());
    }

    #[test]
    fn with_target_halted_resumes_after_edit_error() {
        let mut backend = MockBackend::new().running();
        let continues = Arc::clone(&backend.continues);
        backend.queue_interrupt(breakpoint_event(0x2000));
        let mut session = session_with_mock(backend);

        let error = session
            .with_target_halted(|_| Err::<(), _>(Error::DebugInfo("edit failed".into())))
            .unwrap_err();

        assert!(error.to_string().contains("edit failed"));
        assert_eq!(continues.load(Ordering::Relaxed), 1);
        assert!(session.backend.is_running());
    }

    #[test]
    fn with_target_halted_parks_a_genuine_pending_breakpoint() {
        let mut backend = MockBackend::new().running();
        backend.set("rip", 0x1000);
        let continues = Arc::clone(&backend.continues);
        backend.queue_interrupt(breakpoint_event(0x1000));
        let mut session = session_with_mock(backend);
        session
            .breakpoints
            .insert_for_test(1, VirtAddr(0x1000), true, None);

        session.with_target_halted(|_| Ok(())).unwrap();

        assert_eq!(continues.load(Ordering::Relaxed), 0);
        assert!(!session.backend.is_running());
        let cancel = AtomicBool::new(false);
        assert!(matches!(
            session.wait_for_stop_bounded(Some(Duration::ZERO), &cancel),
            Ok(ContinueOutcome::Breakpoint { id: 1, .. })
        ));
    }

    #[test]
    fn load_symbols_stop_reconciles_and_resumes_as_modules_changed() {
        let mut backend = MockBackend::new().running();
        backend.modules_changed = true;
        backend.allow_breakpoints = true;
        let continues = Arc::clone(&backend.continues);
        let mut session = session_with_mock(backend);
        let id = session
            .add_symbol_breakpoint("driver!DeferredFn".into(), None)
            .unwrap();
        assert!(
            session
                .breakpoints
                .list()
                .into_iter()
                .find(|breakpoint| breakpoint.id == id)
                .is_some_and(|breakpoint| !breakpoint.resolved)
        );

        let dtb = session.target.current_dtb();
        session.target.symbols.inject_source_lines_for_test(
            1,
            dtb,
            VirtAddr(0x1000),
            0x100,
            "driver.c",
            &[],
        );
        session
            .target
            .symbols
            .inject_module_for_test(1, Vec::new(), &[("DeferredFn", 0x10)]);

        let resolution = session.classify_stop_event(module_change_event()).unwrap();

        assert!(matches!(resolution, StopResolution::ModulesChanged));
        assert_eq!(continues.load(Ordering::Relaxed), 1);
        let breakpoint = session
            .breakpoints
            .list()
            .into_iter()
            .find(|breakpoint| breakpoint.id == id)
            .unwrap();
        assert!(breakpoint.resolved);
        assert_eq!(breakpoint.address, VirtAddr(0x1010));
    }

    #[test]
    fn breakpoint_rewind_realigns_the_reporting_thread_without_thread_enumeration() {
        let mut backend = MockBackend::new();
        assert!(backend.thread_list().is_err(), "precondition");
        backend.set("rip", 0x1001);
        let mut manager = BreakpointManager::new();
        manager.insert_for_test(1, VirtAddr(0x1000), true, None);
        let register_map = backend.register_map().clone();

        rewind_thread_off_breakpoint(&mut backend, &register_map, &manager, Arch::Amd64);

        assert_eq!(backend.get("rip"), 0x1000);
    }

    #[test]
    fn breakpoint_rewind_leaves_an_unrelated_program_counter_alone() {
        let mut backend = MockBackend::new();
        backend.set("rip", 0x2001);
        let mut manager = BreakpointManager::new();
        manager.insert_for_test(1, VirtAddr(0x1000), true, None);
        let register_map = backend.register_map().clone();

        rewind_thread_off_breakpoint(&mut backend, &register_map, &manager, Arch::Amd64);

        assert_eq!(backend.get("rip"), 0x2001);
        assert_eq!(backend.writes, 0);
    }

    #[test]
    fn a_target_owned_breakpoint_is_left_for_the_target_to_step_over() {
        let session = session_over_memory(0x1000, &[0u8; 0x80]);
        let mut backend = MockBackend::new().target_managed_sites();
        // A dance would succeed here, so only the ownership check can stop it.
        backend.allow_breakpoints = true;
        backend.set("rip", 0x1000);
        let mut manager = BreakpointManager::new();
        manager.insert_for_test(1, VirtAddr(0x1000), true, None);
        let register_map = backend.register_map().clone();

        let stepped = step_over_current_breakpoint(
            &mut backend,
            &register_map,
            &session.target,
            &mut manager,
        )
        .unwrap();

        assert!(!stepped, "host stepped a site the target owns");
        assert!(
            manager.list()[0].enabled,
            "the site was disowned across the resume"
        );
        assert_eq!(backend.writes, 0, "the guest context was rewritten");
    }

    fn manager_with_hw(slot: u8, access: HwBreakpointAccess, enabled: bool) -> BreakpointManager {
        let mut manager = BreakpointManager::new();
        let len = match access {
            HwBreakpointAccess::Execute => 1,
            _ => 4,
        };
        manager.insert_for_test(
            7,
            VirtAddr(0x1000),
            enabled,
            Some(HardwareBreakpoint { access, len, slot }),
        );
        manager
    }

    #[test]
    fn backend_default_rejects_not_handled_continuation() {
        let mut backend = MockBackend::new();
        assert!(matches!(
            backend.continue_execution_with_disposition(ContinueDisposition::NotHandled),
            Err(Error::ExceptionDispositionUnsupported)
        ));
    }

    #[test]
    fn successful_breakpoint_cleanup_requests_running_exit() {
        let mut backend = MockBackend::new();

        prepare_backend_after_cleanup(&mut backend, Ok(())).unwrap();

        assert_eq!(backend.exit_requests, vec![true]);
    }

    #[test]
    fn failed_breakpoint_cleanup_requests_halted_exit() {
        let mut backend = MockBackend::new();

        let error = prepare_backend_after_cleanup(
            &mut backend,
            Err(Error::Kd("injected breakpoint removal failure".into())),
        )
        .unwrap_err();

        assert!(error.to_string().contains("breakpoint removal failure"));
        assert_eq!(backend.exit_requests, vec![false]);
    }

    #[test]
    fn cleanup_reports_breakpoint_and_backend_teardown_failures() {
        let mut backend = MockBackend::new();
        backend.fail_exit = true;

        let error = prepare_backend_after_cleanup(
            &mut backend,
            Err(Error::Kd("injected breakpoint removal failure".into())),
        )
        .unwrap_err();

        let message = error.to_string();
        assert!(message.contains("breakpoint removal failure"));
        assert!(message.contains("backend teardown failure"));
        assert_eq!(backend.exit_requests, vec![false]);
    }

    #[test]
    fn hardware_breakpoint_hit_claims_matching_dr6_bit_and_clears_status() {
        let manager = manager_with_hw(2, HwBreakpointAccess::Write, true);
        let mut backend = MockBackend::new();
        backend.set("dr6", (1 << 2) | DR6_BS);
        backend.set("eflags", EFLAGS_BASE);

        let map = build_register_map();
        let hit = hardware_breakpoint_hit(&mut backend, &map, &manager, &single_step_event())
            .expect("register update must succeed")
            .expect("slot 2 #DB must be claimed by the registered watch");
        assert_eq!(hit.id, 7);
        assert_eq!(hit.hardware.expect("hw params").slot, 2);

        assert_eq!(backend.get("dr6"), DR6_BS);
        assert_eq!(backend.writes, 1);
        assert_eq!(backend.get("eflags"), EFLAGS_BASE);
    }

    #[test]
    fn hardware_breakpoint_hit_sets_resume_flag_only_for_execute_watches() {
        for (access, want_rf) in [
            (HwBreakpointAccess::Execute, true),
            (HwBreakpointAccess::Write, false),
            (HwBreakpointAccess::ReadWrite, false),
        ] {
            let manager = manager_with_hw(0, access, true);
            let mut backend = MockBackend::new();
            backend.set("dr6", 1);
            backend.set("eflags", EFLAGS_BASE);

            let map = build_register_map();
            let hit = hardware_breakpoint_hit(&mut backend, &map, &manager, &single_step_event())
                .unwrap();
            assert!(hit.is_some(), "{access:?} hit must be claimed");

            let eflags = backend.get("eflags");
            assert_eq!(eflags & RF != 0, want_rf, "{access:?}: RF mismatch");
            assert_eq!(eflags & !RF, EFLAGS_BASE, "{access:?}: eflags clobbered");
            assert_eq!(backend.get("dr6"), 0, "{access:?}: B0 not cleared");
        }
    }

    #[test]
    fn hardware_breakpoint_hit_propagates_required_register_write_failure() {
        let manager = manager_with_hw(0, HwBreakpointAccess::Execute, true);
        let mut backend = MockBackend::new();
        backend.set("dr6", 1);
        backend.set("eflags", EFLAGS_BASE);
        backend.fail_writes = true;

        let map = build_register_map();
        assert!(
            hardware_breakpoint_hit(&mut backend, &map, &manager, &single_step_event()).is_err()
        );
        assert_eq!(backend.get("dr6"), 1);
        assert_eq!(backend.get("eflags"), EFLAGS_BASE);
        assert_eq!(backend.writes, 1);
    }

    #[test]
    fn hardware_breakpoint_hit_ignores_non_single_step_stops() {
        let manager = manager_with_hw(0, HwBreakpointAccess::Write, true);
        let mut backend = MockBackend::new();
        backend.set("dr6", 1); // would match slot 0 if the gate were open
        let before = backend.regs.clone();
        let map = build_register_map();

        let mut event = single_step_event();
        event.exception_code = Some(0x8000_0003);
        assert!(
            hardware_breakpoint_hit(&mut backend, &map, &manager, &event)
                .unwrap()
                .is_none()
        );

        event.exception_code = None;
        assert!(
            hardware_breakpoint_hit(&mut backend, &map, &manager, &event)
                .unwrap()
                .is_none()
        );

        event.exception_code = Some(STATUS_SINGLE_STEP);
        event.is_bugcheck = true;
        assert!(
            hardware_breakpoint_hit(&mut backend, &map, &manager, &event)
                .unwrap()
                .is_none()
        );

        assert_eq!(backend.writes, 0);
        assert_eq!(backend.regs, before);
    }

    #[test]
    fn hardware_breakpoint_hit_requires_an_enabled_hardware_breakpoint() {
        let map = build_register_map();
        let mut backend = MockBackend::new();
        backend.set("dr6", 1);
        let before = backend.regs.clone();

        let empty = BreakpointManager::new();
        assert!(
            hardware_breakpoint_hit(&mut backend, &map, &empty, &single_step_event())
                .unwrap()
                .is_none()
        );
        assert_eq!(backend.writes, 0);
        assert_eq!(backend.regs, before);

        let manager = manager_with_hw(0, HwBreakpointAccess::Write, false);
        assert!(
            hardware_breakpoint_hit(&mut backend, &map, &manager, &single_step_event())
                .unwrap()
                .is_none()
        );
        assert_eq!(backend.writes, 0);
        assert_eq!(backend.regs, before);
    }

    #[test]
    fn hardware_breakpoint_hit_clears_stale_dr6_bits_for_unregistered_slots() {
        let manager = manager_with_hw(1, HwBreakpointAccess::Write, true);
        let mut backend = MockBackend::new();
        backend.set("dr6", (1 << 3) | DR6_BS);

        let map = build_register_map();
        assert!(
            hardware_breakpoint_hit(&mut backend, &map, &manager, &single_step_event())
                .unwrap()
                .is_none()
        );
        assert_eq!(backend.get("dr6"), DR6_BS);
        assert_eq!(backend.writes, 1);
    }

    #[test]
    fn clear_trap_flag_clears_tf_and_dr6_status_in_one_write() {
        let mut backend = MockBackend::new();
        backend.set("eflags", TF | EFLAGS_BASE);
        backend.set("dr6", 0b1011 | DR6_BS);

        let map = build_register_map();
        clear_trap_flag(&mut backend, &map).unwrap();

        assert_eq!(backend.get("eflags"), EFLAGS_BASE);
        assert_eq!(backend.get("dr6"), DR6_BS);
        assert_eq!(backend.writes, 1);
    }

    #[test]
    fn clear_trap_flag_skips_the_write_when_nothing_is_set() {
        let mut backend = MockBackend::new();
        backend.set("eflags", EFLAGS_BASE);
        backend.set("dr6", DR6_BS);
        let before = backend.regs.clone();

        let map = build_register_map();
        clear_trap_flag(&mut backend, &map).unwrap();

        assert_eq!(backend.writes, 0);
        assert_eq!(backend.regs, before);
    }
}