ntoseye 0.27.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
use std::{
    collections::{HashMap, HashSet},
    sync::Arc,
};

use pelite::pe64::{Pe, PeView, image::IMAGE_SCN_MEM_EXECUTE};

use crate::backend::MemoryOps;
use crate::dbg_backend::{
    DebugBackend, DebugCapability, HwBreakpointAccess, WatchpointAccess, validate_hw_breakpoint,
};
use crate::error::{Error, Result};
use crate::expr::Expr;
use crate::guest::{ModuleInfo, ProcessInfo, read_pe_header_page};
use crate::target::Target;
use crate::types::{Arch, Dtb, VirtAddr};

/// A hardware (debug-register) breakpoint's parameters: the access it traps on,
/// the watch width in bytes, and which physical debug slot it occupies.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HardwareBreakpoint {
    pub access: HwBreakpointAccess,
    pub len: u8,
    pub slot: u8,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BreakpointSpec {
    Symbol(String),
    Source {
        raw: String,
        file: String,
        line: u32,
        address_index: usize,
    },
}

impl BreakpointSpec {
    pub fn source(raw: &str, address_index: usize) -> Option<Self> {
        let (file, line) = raw.rsplit_once(':')?;
        let line = line.parse().ok()?;
        (!file.is_empty()).then(|| Self::Source {
            raw: raw.to_string(),
            file: file.to_string(),
            line,
            address_index,
        })
    }

    pub fn label(&self) -> &str {
        match self {
            Self::Symbol(symbol) => symbol,
            Self::Source { raw, .. } => raw,
        }
    }

    fn resolve(&self, debugger: &Target, dtb: Dtb) -> Result<Option<VirtAddr>> {
        match self {
            Self::Symbol(symbol) => debugger.symbols.find_symbol_across_modules(dtb, symbol),
            Self::Source {
                file,
                line,
                address_index,
                ..
            } => Ok(debugger
                .symbols
                .source_addresses(dtb, file, *line)
                .get(*address_index)
                .copied()),
        }
    }
}

#[derive(Debug, Clone)]
pub struct Breakpoint {
    pub id: u32,
    /// Last resolved address. Use [`Self::resolved_address`] when deciding
    /// whether a backend breakpoint is currently installed.
    pub address: VirtAddr,
    pub enabled: bool,
    /// Display name for the current resolution.
    pub symbol: Option<String>,
    /// Original deferred specification (`bu`/`bm`), kept across re-resolution.
    pub spec: Option<BreakpointSpec>,
    pub resolved: bool,
    pub scope: BreakpointScope,
    /// Whether `scope` was inferred from the resolved address and the process
    /// selected when this breakpoint was created. Explicit `/p` scopes remain
    /// fixed across symbol re-resolution.
    automatic_scope: bool,
    pub condition: Option<String>,
    pub condition_expr: Option<Arc<Expr>>,
    /// Requested hit number. Zero and one both mean "break on the first hit".
    pub pass_count: u64,
    pub hit_count: u64,
    pub remaining_pass_count: u64,
    pub one_shot: bool,
    pub action: Option<String>,
    pub temporary: bool,
    /// Transport-specific breakpoint state; hosts use [`Self::watchpoint`] for
    /// the semantic data-watch metadata.
    pub hardware: Option<HardwareBreakpoint>,
    backend: BreakpointBackend,
}

impl Breakpoint {
    pub fn resolved_address(&self) -> Option<VirtAddr> {
        self.resolved.then_some(self.address)
    }

    pub fn deferred(&self) -> bool {
        self.spec.is_some() && !self.resolved
    }

    pub fn specification(&self) -> Option<&str> {
        self.spec.as_ref().map(BreakpointSpec::label)
    }

    fn should_evaluate_after_hit(&self) -> bool {
        self.remaining_pass_count == 0
    }

    /// Data-watch semantics for this stop point. Execute-only debug-register
    /// breakpoints remain code breakpoints and deliberately return `None`.
    pub fn watchpoint(&self) -> Option<(WatchpointAccess, u8)> {
        let hardware = self.hardware?;
        let access = match hardware.access {
            HwBreakpointAccess::Write => WatchpointAccess::Write,
            HwBreakpointAccess::ReadWrite => WatchpointAccess::ReadWrite,
            HwBreakpointAccess::Execute => return None,
        };
        Some((access, hardware.len))
    }

    /// The watched access name (`"write"`/`"read_write"`), or `None` for a
    /// code breakpoint. Presentation surfaces share this instead of
    /// destructuring [`Self::watchpoint`] themselves.
    pub fn watch_access_name(&self) -> Option<&'static str> {
        self.watchpoint().map(|(access, _)| access.name())
    }

    /// The watched byte width, or `None` for a code breakpoint.
    pub fn watch_length(&self) -> Option<u8> {
        self.watchpoint().map(|(_, length)| length)
    }

    /// Evaluate the condition compiled when this breakpoint was installed.
    /// Unconditional breakpoints always hold.
    pub fn evaluate_condition(&self, target: &Target) -> Result<bool> {
        match &self.condition_expr {
            Some(expr) => Ok(expr.resolve(target)?.0 != 0),
            None => Ok(true),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BreakpointScope {
    Kernel,
    Process { pid: u64, dtb: Dtb, name: String },
}

impl BreakpointScope {
    pub fn process(process: &ProcessInfo) -> Self {
        Self::Process {
            pid: process.pid,
            dtb: process.dtb,
            name: process.name.clone(),
        }
    }

    pub fn matches_cr3(&self, cr3: u64) -> bool {
        // Mask out the PCID (bits 0..11) and reserved/canonical bits
        // (52..63), leaving only the page-directory base physical frame.
        match self {
            Self::Kernel => true,
            Self::Process { dtb, .. } => {
                let mask = Arch::Amd64.dtb_page_mask();
                (cr3 & mask) == (*dtb & mask)
            }
        }
    }

    pub fn label(&self) -> String {
        match self {
            Self::Kernel => "global".to_string(),
            Self::Process { pid, name, .. } => format!("{name} ({pid})"),
        }
    }
}

/// Who owns the patched instruction for a breakpoint.
///
/// * `Kernel`: written through the target's debugger API
///   (`DbgKdWriteBreakPointApi` / gdb `Z0`). The target tracks the original
///   instruction and handles step-over.
/// * `GuestMemoryPatch`: the user-process path writes the architecture's
///   breakpoint instruction (`int3` on AMD64 or `brk #0xF000` on AArch64)
///   through the live VM memory handle against a specific process page table.
///   KD has no per-process breakpoint primitive: its API uses the current
///   address-space root. Writing the physical frame bypasses copy-on-write, so
///   every process mapping that frame sees the trap; the address-space filter
///   discards wrong-process hits, though those processes still pay for the
///   exception.
/// * `Hardware`: an architecture debug-register watch (`ba`). No memory is
///   modified —
///   the CPU traps on the linear address — so there is no displaced byte and no
///   step-over dance. The DR slot and watch parameters live on
///   [`Breakpoint::hardware`]; hits are identified by DR6, not by RIP, so
///   hardware breakpoints stay out of the int3-hit predicates.
#[derive(Debug, Clone, Copy)]
struct BreakpointPatch {
    bytes: [u8; 4],
    len: u8,
}

impl BreakpointPatch {
    fn new(len: usize) -> Self {
        debug_assert!((1..=4).contains(&len));
        Self {
            bytes: [0; 4],
            len: len as u8,
        }
    }

    #[cfg(test)]
    fn single(byte: u8) -> Self {
        let mut patch = Self::new(1);
        patch.bytes[0] = byte;
        patch
    }

    fn as_slice(&self) -> &[u8] {
        &self.bytes[..self.len as usize]
    }

    fn as_mut_slice(&mut self) -> &mut [u8] {
        let len = self.len as usize;
        &mut self.bytes[..len]
    }
}

#[derive(Debug, Clone)]
enum BreakpointBackend {
    Kernel { original: BreakpointPatch },
    GuestMemoryPatch { original: BreakpointPatch },
    Hardware,
    Deferred,
}

/// The software breakpoint instruction we patch into guest code: x86 `int3`
/// (one byte) or AArch64 `brk #0xF000` (four bytes, little-endian), the same
/// opcode the kernel debugger uses so the guest reports it as a KD break.
const fn breakpoint_opcode(arch: Arch) -> &'static [u8] {
    match arch {
        Arch::Amd64 => &[0xcc],
        // 0xD43E0000 little-endian.
        Arch::Arm64 => &[0x00, 0x00, 0x3E, 0xD4],
    }
}

impl BreakpointBackend {
    /// The instruction bytes we displaced with the breakpoint, so display
    /// paths can overlay them and never show our own patch (1 byte for an
    /// x86 `int3`, 4 for an AArch64 `brk #0xF000`). Hardware breakpoints
    /// displace nothing (they never reach the masking path).
    fn original_bytes(&self) -> &[u8] {
        match self {
            Self::Kernel { original } | Self::GuestMemoryPatch { original } => original.as_slice(),
            Self::Hardware | Self::Deferred => &[],
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BreakpointHitDisposition {
    SkipPass,
    Evaluate,
}
#[derive(Debug, Clone, Default)]
pub struct BreakpointConfig {
    pub condition: Option<String>,
    pub condition_expr: Option<Arc<Expr>>,
    pub pass_count: u64,
    pub one_shot: bool,
    pub action: Option<String>,
    pub scope: Option<BreakpointScope>,
}

#[derive(Default)]
pub struct BreakpointManager {
    breakpoints: HashMap<u32, Breakpoint>,
    one_shot_hits: HashSet<u32>,
    next_id: u32,
}

impl BreakpointManager {
    pub fn new() -> Self {
        Self {
            breakpoints: HashMap::new(),
            one_shot_hits: HashSet::new(),
            next_id: 0,
        }
    }

    /// Test-only: register a breakpoint directly, bypassing backend
    /// installation. `hardware: Some(..)` makes a DR breakpoint; `None` a
    /// kernel int3 with a dummy displaced byte.
    #[cfg(test)]
    pub fn insert_for_test(
        &mut self,
        id: u32,
        address: VirtAddr,
        enabled: bool,
        hardware: Option<HardwareBreakpoint>,
    ) {
        let backend = match hardware {
            Some(_) => BreakpointBackend::Hardware,
            None => BreakpointBackend::Kernel {
                original: BreakpointPatch::single(0x90),
            },
        };
        self.breakpoints.insert(
            id,
            Breakpoint {
                id,
                address,
                enabled,
                symbol: None,
                spec: None,
                resolved: true,
                scope: BreakpointScope::Kernel,
                automatic_scope: false,
                condition: None,
                condition_expr: None,
                pass_count: 0,
                hit_count: 0,
                remaining_pass_count: 0,
                one_shot: false,
                action: None,
                temporary: false,
                hardware,
                backend,
            },
        );
    }

    pub fn add(
        &mut self,
        client: &mut dyn DebugBackend,
        debugger: &Target,
        address: VirtAddr,
        symbol: Option<String>,
        condition: Option<String>,
    ) -> Result<u32> {
        let condition_expr = Self::compile_condition(condition.as_deref())?;
        self.add_code_configured(
            client,
            debugger,
            Some(address),
            symbol,
            None,
            false,
            BreakpointConfig {
                condition,
                condition_expr,
                ..BreakpointConfig::default()
            },
        )
    }

    pub fn add_configured(
        &mut self,
        client: &mut dyn DebugBackend,
        debugger: &Target,
        address: VirtAddr,
        symbol: Option<String>,
        config: BreakpointConfig,
    ) -> Result<u32> {
        self.add_code_configured(client, debugger, Some(address), symbol, None, false, config)
    }

    pub fn add_symbolic(
        &mut self,
        client: &mut dyn DebugBackend,
        debugger: &Target,
        symbol: String,
        config: BreakpointConfig,
    ) -> Result<u32> {
        let spec = BreakpointSpec::Symbol(symbol.clone());
        let dtb = Self::resolution_dtb(debugger, config.scope.as_ref());
        let address = spec.resolve(debugger, dtb)?;
        self.add_code_configured(
            client,
            debugger,
            address,
            Some(symbol),
            Some(spec),
            false,
            config,
        )
    }

    /// Add one deferred identity per currently known address for `file:line`.
    /// If no module currently supplies source mappings, retain one unresolved
    /// identity (index zero) for a later symbol/module refresh. The batch is
    /// transactional: if any location fails, every location installed by this
    /// call is removed before the error is returned.
    pub fn add_source(
        &mut self,
        client: &mut dyn DebugBackend,
        debugger: &Target,
        source: String,
        config: BreakpointConfig,
    ) -> Result<Vec<u32>> {
        let Some(first_spec) = BreakpointSpec::source(&source, 0) else {
            return Err(Error::Rsp(format!("invalid source breakpoint: {source}")));
        };
        let dtb = Self::resolution_dtb(debugger, config.scope.as_ref());
        let address_count = match &first_spec {
            BreakpointSpec::Source { file, line, .. } => {
                debugger.symbols.source_addresses(dtb, file, *line).len()
            }
            BreakpointSpec::Symbol(_) => unreachable!(),
        };
        let count = address_count.max(1);
        let mut ids = Vec::with_capacity(count);
        for index in 0..count {
            let result = (|| {
                let spec = BreakpointSpec::source(&source, index)
                    .ok_or_else(|| Error::Rsp(format!("invalid source breakpoint: {source}")))?;
                let address = spec.resolve(debugger, dtb)?;
                self.add_code_configured(
                    client,
                    debugger,
                    address,
                    Some(source.clone()),
                    Some(spec),
                    false,
                    config.clone(),
                )
            })();

            match result {
                Ok(id) => ids.push(id),
                Err(error) => {
                    if let Err(rollback_error) =
                        self.remove_ids(client, debugger, ids.iter().rev().copied())
                    {
                        return Err(Error::Rsp(format!(
                            "failed to add source breakpoint '{source}': {error}; rollback incomplete: {rollback_error}"
                        )));
                    }
                    return Err(error);
                }
            }
        }
        Ok(ids)
    }

    fn resolution_dtb(debugger: &Target, scope: Option<&BreakpointScope>) -> Dtb {
        match scope {
            Some(BreakpointScope::Process { dtb, .. }) => *dtb,
            Some(BreakpointScope::Kernel) => debugger.kernel_dtb(),
            None => debugger.current_dtb(),
        }
    }

    pub fn add_temporary_code(
        &mut self,
        client: &mut dyn DebugBackend,
        debugger: &Target,
        address: VirtAddr,
    ) -> Result<u32> {
        self.add_code_configured(
            client,
            debugger,
            Some(address),
            None,
            None,
            true,
            BreakpointConfig::default(),
        )
    }

    fn add_code_configured(
        &mut self,
        client: &mut dyn DebugBackend,
        debugger: &Target,
        address: Option<VirtAddr>,
        symbol: Option<String>,
        spec: Option<BreakpointSpec>,
        temporary: bool,
        config: BreakpointConfig,
    ) -> Result<u32> {
        let automatic_scope = config.scope.is_none();
        let fallback_scope = config
            .scope
            .unwrap_or_else(|| Self::scope_for_current_context(debugger));
        let scope = if automatic_scope {
            address
                .map(|address| Self::scope_for_address(debugger, address, &fallback_scope))
                .unwrap_or(fallback_scope)
        } else {
            fallback_scope
        };
        Self::validate_scope_capability(client, &scope)?;

        let (address, resolved, backend) = match address {
            Some(address) => {
                self.ensure_site_available(address, false, None)?;
                Self::validate_breakpoint_target(debugger, address, &scope)?;
                let backend = Self::install_breakpoint(client, debugger, address, &scope)?;
                (address, true, backend)
            }
            None => (VirtAddr(0), false, BreakpointBackend::Deferred),
        };
        let pass_count = config.pass_count;
        let id = self.next_id;
        self.next_id += 1;
        self.breakpoints.insert(
            id,
            Breakpoint {
                id,
                address,
                enabled: true,
                symbol,
                spec,
                resolved,
                scope,
                automatic_scope,
                condition: config.condition,
                condition_expr: config.condition_expr,
                pass_count,
                hit_count: 0,
                remaining_pass_count: pass_count.saturating_sub(1),
                one_shot: config.one_shot,
                action: config.action,
                temporary,
                hardware: None,
                backend,
            },
        );
        Ok(id)
    }

    fn validate_scope_capability(client: &dyn DebugBackend, scope: &BreakpointScope) -> Result<()> {
        let capability = match scope {
            BreakpointScope::Kernel => DebugCapability::KernelBreakpoints,
            BreakpointScope::Process { .. } => DebugCapability::UserModeBreakpoints,
        };
        if client
            .capabilities()
            .iter()
            .any(|c| c.capability == capability && c.supported)
        {
            Ok(())
        } else {
            Err(Error::NotSupported)
        }
    }

    /// Set a hardware (debug-register) breakpoint. String conditions use the
    /// core decimal expression contract.
    pub fn add_hardware(
        &mut self,
        client: &mut dyn DebugBackend,
        debugger: &Target,
        address: VirtAddr,
        access: HwBreakpointAccess,
        len: u8,
        symbol: Option<String>,
        condition: Option<String>,
    ) -> Result<u32> {
        let condition_expr = Self::compile_condition(condition.as_deref())?;
        self.add_hardware_configured(
            client,
            debugger,
            address,
            access,
            len,
            symbol,
            BreakpointConfig {
                condition,
                condition_expr,
                ..BreakpointConfig::default()
            },
        )
    }

    pub fn add_hardware_configured(
        &mut self,
        client: &mut dyn DebugBackend,
        debugger: &Target,
        address: VirtAddr,
        access: HwBreakpointAccess,
        len: u8,
        symbol: Option<String>,
        config: BreakpointConfig,
    ) -> Result<u32> {
        if !client.supports_watchpoints() {
            return Err(Error::NotSupported);
        }
        validate_hw_breakpoint(access, len, address.0)?;
        self.ensure_site_available(address, true, None)?;
        let slot = self.free_hardware_slot(client, access)?;
        let automatic_scope = config.scope.is_none();
        let fallback_scope = config
            .scope
            .unwrap_or_else(|| Self::scope_for_current_context(debugger));
        let scope = if automatic_scope {
            Self::scope_for_address(debugger, address, &fallback_scope)
        } else {
            fallback_scope
        };
        client.set_hardware_breakpoint(slot, address.0, access, len)?;

        let id = self.next_id;
        self.next_id += 1;
        let pass_count = config.pass_count;
        self.breakpoints.insert(
            id,
            Breakpoint {
                id,
                address,
                enabled: true,
                symbol,
                spec: None,
                resolved: true,
                scope,
                automatic_scope,
                condition: config.condition,
                condition_expr: config.condition_expr,
                pass_count,
                hit_count: 0,
                remaining_pass_count: pass_count.saturating_sub(1),
                one_shot: config.one_shot,
                action: config.action,
                temporary: false,
                hardware: Some(HardwareBreakpoint { access, len, slot }),
                backend: BreakpointBackend::Hardware,
            },
        );
        Ok(id)
    }

    fn compile_condition(condition: Option<&str>) -> Result<Option<Arc<Expr>>> {
        condition
            .map(Expr::parse)
            .transpose()
            .map(|expr| expr.map(Arc::new))
    }

    /// The lowest physical slot not already claimed by a hardware breakpoint.
    /// ARM64 uses one global ID space with separate WVR/WCR data and BVR/BCR
    /// execute ranges supplied by the backend. Disabled hardware breakpoints
    /// keep their slot reserved, matching WinDbg's fixed architectural slots.
    fn free_hardware_slot(
        &self,
        client: &dyn DebugBackend,
        access: HwBreakpointAccess,
    ) -> Result<u8> {
        let mut slots = client.hardware_slot_range(access);
        let kind = if matches!(access, HwBreakpointAccess::Execute) {
            "execute"
        } else {
            "watchpoint"
        };
        slots
            .find(|slot| {
                !self
                    .breakpoints
                    .values()
                    .any(|bp| bp.hardware.is_some_and(|hw| hw.slot == *slot))
            })
            .ok_or_else(|| Error::Rsp(format!("all {kind} hardware breakpoint slots are in use")))
    }

    pub fn remove(
        &mut self,
        client: &mut dyn DebugBackend,
        debugger: &Target,
        id: u32,
    ) -> Result<()> {
        self.remove_if_uninstalled(id, |bp| Self::uninstall_breakpoint(client, debugger, bp))
    }

    fn remove_ids(
        &mut self,
        client: &mut dyn DebugBackend,
        debugger: &Target,
        ids: impl IntoIterator<Item = u32>,
    ) -> Result<()> {
        self.remove_ids_if_uninstalled(ids, |bp| Self::uninstall_breakpoint(client, debugger, bp))
    }

    pub fn remove_all(&mut self, client: &mut dyn DebugBackend, debugger: &Target) -> Result<()> {
        let ids = self.managed_ids();
        self.remove_ids(client, debugger, ids)
    }

    fn remove_if_uninstalled(
        &mut self,
        id: u32,
        uninstall: impl FnOnce(&Breakpoint) -> Result<()>,
    ) -> Result<()> {
        let bp = self
            .breakpoints
            .get(&id)
            .cloned()
            .ok_or(Error::BPNotFound(id))?;

        if bp.enabled && bp.resolved {
            uninstall(&bp)?;
        }
        self.breakpoints.remove(&id);
        self.one_shot_hits.remove(&id);

        if self.breakpoints.is_empty() {
            self.next_id = 0;
        }

        Ok(())
    }

    fn remove_ids_if_uninstalled(
        &mut self,
        ids: impl IntoIterator<Item = u32>,
        mut uninstall: impl FnMut(&Breakpoint) -> Result<()>,
    ) -> Result<()> {
        let mut failures = Vec::new();
        for id in ids {
            if let Err(error) = self.remove_if_uninstalled(id, |bp| uninstall(bp)) {
                failures.push(format!("#{id}: {error}"));
            }
        }

        if failures.is_empty() {
            Ok(())
        } else {
            Err(Error::Rsp(format!(
                "failed to uninstall breakpoints: {}",
                failures.join("; ")
            )))
        }
    }

    /// Forget a breakpoint whose site can no longer be restored (its address
    /// space is gone). The backend is told so it stops treating a hit at the
    /// stale address as ours.
    pub fn discard(&mut self, client: &mut dyn DebugBackend, id: u32) -> Result<Breakpoint> {
        let bp = self.breakpoints.remove(&id).ok_or(Error::BPNotFound(id))?;
        Self::forget_backend_site(client, &bp);
        self.one_shot_hits.remove(&id);
        if self.breakpoints.is_empty() {
            self.next_id = 0;
        }
        Ok(bp)
    }

    /// Rename a managed breakpoint without changing its installed backend
    /// site.  Breakpoint IDs are the user-facing handles, so one-shot state
    /// must move with the entry as well.
    pub fn renumber(&mut self, id: u32, new_id: u32) -> Result<()> {
        if id == new_id {
            if self.breakpoints.contains_key(&id) {
                return Ok(());
            }
            return Err(Error::BPNotFound(id));
        }
        if self.breakpoints.contains_key(&new_id) {
            return Err(Error::Rsp(format!(
                "breakpoint ID {new_id} is already in use"
            )));
        }
        let mut bp = self.breakpoints.remove(&id).ok_or(Error::BPNotFound(id))?;
        bp.id = new_id;
        self.breakpoints.insert(new_id, bp);
        if self.one_shot_hits.remove(&id) {
            self.one_shot_hits.insert(new_id);
        }
        self.next_id = self.next_id.max(new_id.saturating_add(1));
        Ok(())
    }

    /// Drop the backend's bookkeeping for a host-patched site that is being
    /// abandoned rather than restored (KD classifies stops by that set).
    fn forget_backend_site(client: &mut dyn DebugBackend, bp: &Breakpoint) {
        if matches!(bp.backend, BreakpointBackend::GuestMemoryPatch { .. }) {
            client.note_breakpoint_uninstalled(bp.address.0);
        }
    }

    pub fn enable(
        &mut self,
        client: &mut dyn DebugBackend,
        debugger: &Target,
        id: u32,
    ) -> Result<()> {
        let snapshot = self
            .breakpoints
            .get(&id)
            .cloned()
            .ok_or(Error::BPNotFound(id))?;
        if snapshot.enabled {
            return Ok(());
        }
        if snapshot.resolved {
            self.ensure_site_available(snapshot.address, snapshot.hardware.is_some(), Some(id))?;
            let backend = if matches!(snapshot.backend, BreakpointBackend::Deferred) {
                Some(Self::install_breakpoint(
                    client,
                    debugger,
                    snapshot.address,
                    &snapshot.scope,
                )?)
            } else {
                Self::install_existing_breakpoint(client, debugger, &snapshot)?;
                None
            };
            if let Some(backend) = backend {
                self.breakpoints
                    .get_mut(&id)
                    .ok_or(Error::BPNotFound(id))?
                    .backend = backend;
            }
        }
        self.breakpoints
            .get_mut(&id)
            .ok_or(Error::BPNotFound(id))?
            .enabled = true;
        Ok(())
    }

    pub fn disable(
        &mut self,
        client: &mut dyn DebugBackend,
        debugger: &Target,
        id: u32,
    ) -> Result<()> {
        let bp = self.breakpoints.get_mut(&id).ok_or(Error::BPNotFound(id))?;

        if !bp.enabled {
            return Ok(());
        }
        if bp.resolved {
            Self::uninstall_breakpoint(client, debugger, bp)?;
        }
        bp.enabled = false;
        Ok(())
    }

    pub fn disable_guest_memory_patch_in_address_space(
        &mut self,
        client: &mut dyn DebugBackend,
        debugger: &Target,
        id: u32,
        dtb: Dtb,
    ) -> Result<()> {
        let bp = self.breakpoints.get_mut(&id).ok_or(Error::BPNotFound(id))?;

        if !bp.enabled {
            return Ok(());
        }

        match &bp.backend {
            BreakpointBackend::GuestMemoryPatch { original } => {
                let memory = debugger.address_space(dtb);
                memory.write_bytes(bp.address, original.as_slice())?;
                client.note_breakpoint_uninstalled(bp.address.0);
                bp.enabled = false;
                Ok(())
            }
            BreakpointBackend::Kernel { .. } => Err(Error::Rsp(
                "cannot address-space-disable a kernel breakpoint".into(),
            )),
            BreakpointBackend::Hardware => Err(Error::Rsp(
                "cannot address-space-disable a hardware breakpoint".into(),
            )),
            BreakpointBackend::Deferred => {
                bp.enabled = false;
                Ok(())
            }
        }
    }
    pub fn managed_ids(&self) -> Vec<u32> {
        let mut ids = self.breakpoints.keys().copied().collect::<Vec<_>>();
        ids.sort_unstable();
        ids
    }

    pub fn list(&self) -> Vec<&Breakpoint> {
        let mut bps: Vec<_> = self
            .breakpoints
            .values()
            .filter(|bp| !self.one_shot_hits.contains(&bp.id))
            .collect();
        bps.sort_by_key(|bp| bp.id);
        bps
    }

    pub fn has_enabled_breakpoints(&self) -> bool {
        self.breakpoints
            .values()
            .any(|bp| bp.enabled && bp.resolved)
    }

    /// Whether any enabled hardware (DR) breakpoint exists — the cheap gate the
    /// stop path checks before reading DR6 on a single-step.
    pub fn has_enabled_hardware_breakpoints(&self) -> bool {
        self.breakpoints
            .values()
            .any(|bp| bp.enabled && bp.hardware.is_some())
    }

    /// The enabled hardware breakpoint occupying DR slot `slot`, if any — used
    /// to map a DR6 status bit back to the breakpoint that fired.
    pub fn hardware_breakpoint_for_slot(&self, slot: u8) -> Option<Breakpoint> {
        self.breakpoints
            .values()
            .find(|bp| bp.enabled && bp.hardware.is_some_and(|hw| hw.slot == slot))
            .cloned()
    }

    /// Best-effort release of every DR slot held by a hardware breakpoint
    /// (enabled or not), so a target reload leaves no orphaned watches.
    pub fn clear_hardware_slots(&self, client: &mut dyn DebugBackend) {
        for bp in self.breakpoints.values() {
            if let Some(hw) = bp.hardware {
                let _ = client.clear_hardware_breakpoint(hw.slot);
            }
        }
    }

    pub fn refresh_enabled(&self, client: &mut dyn DebugBackend, debugger: &Target) -> Result<()> {
        let mut enabled: Vec<_> = self
            .breakpoints
            .values()
            .filter(|bp| bp.enabled && bp.resolved && bp.hardware.is_none())
            .collect();
        enabled.sort_by_key(|bp| bp.id);

        for bp in enabled {
            let _ = Self::uninstall_breakpoint(client, debugger, bp);
            Self::install_existing_breakpoint(client, debugger, bp)?;
        }

        Ok(())
    }

    /// Record a physical hit before pass-count and condition handling.
    pub fn record_hit(&mut self, id: u32) -> Result<BreakpointHitDisposition> {
        let bp = self.breakpoints.get_mut(&id).ok_or(Error::BPNotFound(id))?;
        bp.hit_count = bp.hit_count.saturating_add(1);
        if bp.remaining_pass_count > 0 {
            bp.remaining_pass_count -= 1;
            Ok(BreakpointHitDisposition::SkipPass)
        } else {
            debug_assert!(bp.should_evaluate_after_hit());
            Ok(BreakpointHitDisposition::Evaluate)
        }
    }

    pub fn set_pass_count(&mut self, id: u32, pass_count: u64) -> Result<()> {
        let bp = self.breakpoints.get_mut(&id).ok_or(Error::BPNotFound(id))?;
        bp.pass_count = pass_count;
        bp.remaining_pass_count = pass_count.saturating_sub(1);
        Ok(())
    }

    pub fn set_one_shot(&mut self, id: u32, one_shot: bool) -> Result<()> {
        self.breakpoints
            .get_mut(&id)
            .ok_or(Error::BPNotFound(id))?
            .one_shot = one_shot;
        Ok(())
    }

    pub fn set_action(&mut self, id: u32, action: Option<String>) -> Result<()> {
        self.breakpoints
            .get_mut(&id)
            .ok_or(Error::BPNotFound(id))?
            .action = action;
        Ok(())
    }
    pub fn mark_one_shot_hit(&mut self, id: u32) -> Result<()> {
        let bp = self.breakpoints.get(&id).ok_or(Error::BPNotFound(id))?;
        if bp.one_shot {
            self.one_shot_hits.insert(id);
        }
        Ok(())
    }

    pub fn one_shot_hit_ids(&self) -> Vec<u32> {
        self.one_shot_hits.iter().copied().collect()
    }

    pub fn set_condition(
        &mut self,
        id: u32,
        condition: Option<String>,
        condition_expr: Option<Arc<Expr>>,
    ) -> Result<()> {
        let bp = self.breakpoints.get_mut(&id).ok_or(Error::BPNotFound(id))?;
        bp.condition = condition;
        bp.condition_expr = condition_expr;
        Ok(())
    }

    /// Keep symbolic code breakpoints across a target rebuild while dropping
    /// every backend installation and all target-specific numeric/watch points.
    pub fn prepare_target_reload(&mut self, client: &mut dyn DebugBackend) -> usize {
        self.clear_hardware_slots(client);
        let before = self.breakpoints.len();
        let fired_one_shots = std::mem::take(&mut self.one_shot_hits);
        self.breakpoints.retain(|id, bp| {
            !fired_one_shots.contains(id) && bp.hardware.is_none() && bp.spec.is_some()
        });
        for bp in self.breakpoints.values_mut() {
            bp.resolved = false;
            bp.backend = BreakpointBackend::Deferred;
        }
        if self.breakpoints.is_empty() {
            self.next_id = 0;
        }
        before - self.breakpoints.len()
    }

    /// Resolve every symbolic breakpoint against the current symbol store.
    /// IDs, counters, conditions, actions, and enabled state survive address
    /// changes. Unavailable symbols remain deferred without backend state.
    fn expand_source_specs(&mut self, debugger: &Target) {
        let roots: Vec<Breakpoint> = self
            .breakpoints
            .values()
            .filter(|bp| {
                matches!(
                    bp.spec,
                    Some(BreakpointSpec::Source {
                        address_index: 0,
                        ..
                    })
                )
            })
            .cloned()
            .collect();
        for root in roots {
            let Some(BreakpointSpec::Source {
                raw, file, line, ..
            }) = root.spec.as_ref()
            else {
                continue;
            };
            let dtb = Self::resolution_dtb(debugger, Some(&root.scope));
            let count = debugger.symbols.source_addresses(dtb, file, *line).len();
            for address_index in 1..count {
                let already_exists = self.breakpoints.values().any(|bp| {
                    matches!(
                        bp.spec.as_ref(),
                        Some(BreakpointSpec::Source {
                            raw: other,
                            address_index: other_index,
                            ..
                        }) if other == raw && *other_index == address_index
                    )
                });
                if already_exists {
                    continue;
                }
                let id = self.next_id;
                self.next_id += 1;
                let mut bp = root.clone();
                bp.id = id;
                bp.address = VirtAddr(0);
                bp.spec = BreakpointSpec::source(raw, address_index);
                bp.resolved = false;
                bp.backend = BreakpointBackend::Deferred;
                self.breakpoints.insert(id, bp);
            }
        }
    }

    fn defer_symbolic_sites_if(
        &mut self,
        client: &mut dyn DebugBackend,
        mut site_is_unloaded: impl FnMut(&Breakpoint) -> bool,
    ) -> usize {
        let ids = self
            .breakpoints
            .values()
            .filter(|bp| {
                bp.resolved && bp.spec.is_some() && bp.hardware.is_none() && site_is_unloaded(bp)
            })
            .map(|bp| bp.id)
            .collect::<Vec<_>>();

        for id in &ids {
            let bp = self
                .breakpoints
                .get_mut(id)
                .expect("collected breakpoint exists");
            // The module mapping is already gone. Do not send a removal request
            // for its stale address: it may be unmapped or reused by now.
            Self::forget_backend_site(client, bp);
            bp.resolved = false;
            bp.backend = BreakpointBackend::Deferred;
        }
        ids.len()
    }

    /// Reconcile symbolic breakpoints after the live module set changes.
    ///
    /// Sites whose owning module disappeared become deferred without touching
    /// their stale target address. Newly available specifications are then
    /// resolved and installed normally.
    pub fn reconcile_symbolic_after_module_refresh(
        &mut self,
        client: &mut dyn DebugBackend,
        debugger: &Target,
    ) -> Result<usize> {
        self.defer_symbolic_sites_if(client, |bp| {
            let dtb = Self::resolution_dtb(debugger, Some(&bp.scope));
            debugger
                .symbols
                .find_module_for_address(dtb, bp.address)
                .is_none()
        });
        self.resolve_symbolic(client, debugger)
    }

    pub fn resolve_symbolic(
        &mut self,
        client: &mut dyn DebugBackend,
        debugger: &Target,
    ) -> Result<usize> {
        self.expand_source_specs(debugger);
        let mut ids: Vec<u32> = self
            .breakpoints
            .values()
            .filter(|bp| bp.spec.is_some() && bp.hardware.is_none())
            .map(|bp| bp.id)
            .collect();
        ids.sort_unstable();

        let mut resolved_count = 0;
        for id in ids {
            let snapshot = self
                .breakpoints
                .get(&id)
                .cloned()
                .ok_or(Error::BPNotFound(id))?;
            let spec = snapshot
                .spec
                .as_ref()
                .ok_or_else(|| Error::Rsp(format!("breakpoint {id} lost its specification")))?;
            let dtb = Self::resolution_dtb(debugger, Some(&snapshot.scope));
            let resolved = spec.resolve(debugger, dtb)?;
            let scope = resolved
                .filter(|_| snapshot.automatic_scope)
                .map(|address| Self::scope_for_address(debugger, address, &snapshot.scope))
                .unwrap_or_else(|| snapshot.scope.clone());

            if snapshot.resolved && resolved == Some(snapshot.address) && scope == snapshot.scope {
                resolved_count += 1;
                continue;
            }

            if let Some(address) = resolved {
                Self::validate_scope_capability(client, &scope)?;
                Self::validate_breakpoint_target(debugger, address, &scope)?;
                self.ensure_site_available(address, false, Some(id))?;
            }

            if snapshot.resolved && snapshot.enabled {
                Self::uninstall_breakpoint(client, debugger, &snapshot)?;
            }

            let backend = match resolved {
                Some(address) if snapshot.enabled => {
                    match Self::install_breakpoint(client, debugger, address, &scope) {
                        Ok(backend) => backend,
                        Err(install_error) => {
                            if snapshot.resolved
                                && let Err(rollback_error) =
                                    Self::install_existing_breakpoint(client, debugger, &snapshot)
                            {
                                return Err(Error::Rsp(format!(
                                    "failed to move breakpoint {id}: {install_error}; restoring its previous installation also failed: {rollback_error}"
                                )));
                            }
                            return Err(install_error);
                        }
                    }
                }
                _ => BreakpointBackend::Deferred,
            };

            let bp = self.breakpoints.get_mut(&id).ok_or(Error::BPNotFound(id))?;
            match resolved {
                Some(address) => {
                    bp.address = address;
                    bp.resolved = true;
                    bp.scope = scope;
                    bp.backend = backend;
                    bp.symbol = Some(spec.label().to_string());
                    resolved_count += 1;
                }
                None => {
                    bp.resolved = false;
                    bp.backend = BreakpointBackend::Deferred;
                }
            }
        }
        Ok(resolved_count)
    }

    pub fn check_breakpoint_hit(&self, rip: u64, cr3: u64) -> BreakpointHitResult {
        for bp in self.breakpoints.values() {
            if !self.one_shot_hits.contains(&bp.id)
                && bp.resolved
                && bp.hardware.is_none()
                && bp.address.0 == rip
                && bp.enabled
                && bp.scope.matches_cr3(cr3)
            {
                return BreakpointHitResult::Hit(bp.clone());
            }
        }

        BreakpointHitResult::NotBreakpoint
    }

    pub fn enabled_breakpoint_id_for_current_context(
        &self,
        debugger: &Target,
        address: VirtAddr,
    ) -> Option<u32> {
        let cr3 = debugger.current_dtb();
        self.breakpoints
            .values()
            .filter(|bp| {
                bp.resolved
                    && bp.enabled
                    && bp.hardware.is_none()
                    && bp.address == address
                    && bp.scope.matches_cr3(cr3)
            })
            .map(|bp| bp.id)
            .min()
    }

    #[cfg(test)]
    fn enabled_software_breakpoint_id(
        &self,
        scope: &BreakpointScope,
        address: VirtAddr,
    ) -> Option<u32> {
        self.breakpoints
            .values()
            .filter(|bp| {
                bp.resolved
                    && bp.enabled
                    && bp.hardware.is_none()
                    && bp.address == address
                    && &bp.scope == scope
            })
            .map(|bp| bp.id)
            .min()
    }

    /// Overlay our breakpoints' original bytes onto a buffer read for display,
    /// so no view ever shows the int3 we injected. `start` is the buffer's
    /// guest VA; `cr3` scopes process breakpoints to the address space the
    /// bytes were read from (kernel breakpoints are global).
    pub fn mask_breakpoint_bytes(&self, start: VirtAddr, buf: &mut [u8], cr3: u64) {
        let end = start.0.wrapping_add(buf.len() as u64);
        for bp in self.breakpoints.values() {
            if !bp.resolved || !bp.enabled || bp.hardware.is_some() || !bp.scope.matches_cr3(cr3) {
                continue;
            }
            if bp.address.0 < start.0 || bp.address.0 >= end {
                continue;
            }
            let offset = (bp.address.0 - start.0) as usize;
            let bytes = bp.backend.original_bytes();
            if offset + bytes.len() <= buf.len() {
                buf[offset..offset + bytes.len()].copy_from_slice(bytes);
            }
        }
    }

    /// Find a BP at `rip` regardless of its scope; "is this int3 owned by us?"
    pub fn breakpoint_id_at_address(&self, rip: u64) -> Option<u32> {
        self.breakpoints
            .values()
            .find(|bp| bp.resolved && bp.enabled && bp.hardware.is_none() && bp.address.0 == rip)
            .map(|bp| bp.id)
    }

    fn ensure_site_available(
        &self,
        address: VirtAddr,
        hardware: bool,
        exclude_id: Option<u32>,
    ) -> Result<()> {
        if let Some(existing) = self.breakpoints.values().find(|bp| {
            Some(bp.id) != exclude_id
                && bp.resolved
                && bp.address == address
                && bp.hardware.is_some() == hardware
        }) {
            let kind = if hardware { "hardware" } else { "software" };
            return Err(Error::Rsp(format!(
                "{kind} breakpoint {} already owns address {:#x}",
                existing.id, address.0
            )));
        }
        Ok(())
    }

    fn scope_for_current_context(debugger: &Target) -> BreakpointScope {
        match &debugger.current_process_info {
            Some(ProcessInfo { pid, name, dtb, .. }) => BreakpointScope::Process {
                pid: *pid,
                dtb: *dtb,
                name: name.clone(),
            },
            None => BreakpointScope::Kernel,
        }
    }

    fn scope_for_address(
        debugger: &Target,
        address: VirtAddr,
        fallback: &BreakpointScope,
    ) -> BreakpointScope {
        const WINDOWS_X64_KERNEL_START: u64 = 0xffff_8000_0000_0000;
        if address.0 >= WINDOWS_X64_KERNEL_START
            || Self::find_kernel_module_containing_address(debugger, address).is_some()
        {
            BreakpointScope::Kernel
        } else {
            fallback.clone()
        }
    }

    fn install_breakpoint(
        client: &mut dyn DebugBackend,
        debugger: &Target,
        address: VirtAddr,
        scope: &BreakpointScope,
    ) -> Result<BreakpointBackend> {
        match scope {
            BreakpointScope::Kernel => {
                // Capture the displaced instruction before the kernel writes
                // the breakpoint, so display paths can mask it back out. x86
                // `int3` displaces one byte; AArch64 `brk #0xF000` displaces
                // four. Kernel code is read through the kernel's own tables: an
                // attached process's (KVA-shadow) CR3 need not map it.
                let memory = debugger.address_space(debugger.kernel_dtb());
                let mut original = BreakpointPatch::new(breakpoint_opcode(debugger.arch()).len());
                memory.read_bytes(address, original.as_mut_slice())?;
                client.set_breakpoint(address.0)?;
                Ok(BreakpointBackend::Kernel { original })
            }
            BreakpointScope::Process { dtb, .. } => {
                let memory = debugger.address_space(*dtb);
                let opcode = breakpoint_opcode(debugger.arch());
                let mut original = BreakpointPatch::new(opcode.len());
                memory.read_bytes(address, original.as_mut_slice())?;
                memory.write_bytes(address, opcode)?;
                // The kernel does not know about a breakpoint patched through
                // host memory, so update the backend's stop bookkeeping.
                client.note_breakpoint_installed(address.0);
                Ok(BreakpointBackend::GuestMemoryPatch { original })
            }
        }
    }

    fn install_existing_breakpoint(
        client: &mut dyn DebugBackend,
        debugger: &Target,
        bp: &Breakpoint,
    ) -> Result<()> {
        match (&bp.scope, &bp.backend) {
            (BreakpointScope::Kernel, BreakpointBackend::Kernel { .. }) => {
                client.set_breakpoint(bp.address.0)
            }
            (BreakpointScope::Process { dtb, .. }, BreakpointBackend::GuestMemoryPatch { .. }) => {
                let memory = debugger.address_space(*dtb);
                memory.write_bytes(bp.address, breakpoint_opcode(debugger.arch()))?;
                client.note_breakpoint_installed(bp.address.0);
                Ok(())
            }
            (_, BreakpointBackend::Hardware) => match bp.hardware {
                Some(hw) => {
                    client.set_hardware_breakpoint(hw.slot, bp.address.0, hw.access, hw.len)
                }
                None => Err(Error::Rsp("hardware breakpoint missing parameters".into())),
            },
            _ => Err(Error::Rsp("breakpoint backend/scope mismatch".into())),
        }
    }

    fn uninstall_breakpoint(
        client: &mut dyn DebugBackend,
        debugger: &Target,
        bp: &Breakpoint,
    ) -> Result<()> {
        match (&bp.scope, &bp.backend) {
            (BreakpointScope::Kernel, BreakpointBackend::Kernel { .. }) => {
                client.remove_breakpoint(bp.address.0)
            }
            (
                BreakpointScope::Process { dtb, .. },
                BreakpointBackend::GuestMemoryPatch { original },
            ) => {
                let memory = debugger.address_space(*dtb);
                memory.write_bytes(bp.address, original.as_slice())?;
                client.note_breakpoint_uninstalled(bp.address.0);
                Ok(())
            }
            (_, BreakpointBackend::Hardware) => match bp.hardware {
                Some(hw) => client.clear_hardware_breakpoint(hw.slot),
                None => Err(Error::Rsp("hardware breakpoint missing parameters".into())),
            },
            _ => Err(Error::Rsp("breakpoint backend/scope mismatch".into())),
        }
    }

    fn validate_breakpoint_target(
        debugger: &Target,
        address: VirtAddr,
        scope: &BreakpointScope,
    ) -> Result<()> {
        let module = Self::find_kernel_module_containing_address(debugger, address);
        let dtb = match scope {
            BreakpointScope::Kernel => debugger.kernel_dtb(),
            BreakpointScope::Process { dtb, .. } => *dtb,
        };
        let memory = debugger.address_space(dtb);
        let translation = memory
            .virt_to_phys(address)?
            .ok_or(Error::BadVirtualAddress(address))?;

        // AArch64 table-level execute restrictions depend on TCR_EL1
        // hierarchical-permission controls, which passive memory inspection
        // does not capture. Do not reject a TTBR1 address solely from descriptor
        // bits; known kernel modules are still checked against PE executable
        // sections below. TTBR0 user pages can be classified by effective UXN.
        let nx = match (debugger.arch(), address.0 & (1 << 55) != 0) {
            (Arch::Arm64, true) => false,
            (Arch::Arm64, false) => translation.uxn,
            _ => translation.nx,
        };

        if nx {
            let context = module
                .as_ref()
                .map(|module| module.short_name.as_str())
                .unwrap_or("unknown");
            return Err(Error::Breakpoint(format!(
                "refusing breakpoint at {:#x}: target page is non-executable ({})",
                address.0, context
            )));
        }

        if let Some(module) = module {
            let headers = read_pe_header_page(module.base_address, &memory)?;
            let view = PeView::from_bytes(&headers)?;
            let rva = address.0.saturating_sub(module.base_address.0) as u32;
            let in_executable_section = view.section_headers().iter().any(|section| {
                let size = section.VirtualSize.max(section.SizeOfRawData);
                size != 0
                    && section.Characteristics & IMAGE_SCN_MEM_EXECUTE != 0
                    && rva >= section.VirtualAddress
                    && rva < section.VirtualAddress.saturating_add(size)
            });

            if !in_executable_section {
                return Err(Error::Breakpoint(format!(
                    "refusing breakpoint at {:#x}: address falls in non-executable section of {}",
                    address.0, module.short_name
                )));
            }
        }

        Ok(())
    }

    fn find_kernel_module_containing_address(
        debugger: &Target,
        address: VirtAddr,
    ) -> Option<ModuleInfo> {
        debugger
            .kernel_modules()
            .ok()?
            .into_iter()
            .find(|module| module.contains_address(address))
    }
}

#[derive(Debug)]
pub enum BreakpointHitResult {
    /// Breakpoint hit
    Hit(Breakpoint),
    /// Program counter does not match any breakpoint.
    NotBreakpoint,
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::{
        Breakpoint, BreakpointBackend, BreakpointHitDisposition, BreakpointHitResult,
        BreakpointManager, BreakpointPatch, BreakpointScope, BreakpointSpec, HardwareBreakpoint,
    };
    use crate::dbg_backend::{DebugBackend, HwBreakpointAccess, StopEvent};
    use crate::error::{Error, Result};
    use crate::gdb::RegisterMap;
    use crate::types::VirtAddr;

    #[test]
    fn failed_uninstall_keeps_breakpoint_managed_for_retry() {
        let mut manager = BreakpointManager::new();
        manager.insert_for_test(
            7,
            VirtAddr(0x1000),
            true,
            Some(HardwareBreakpoint {
                access: HwBreakpointAccess::Execute,
                len: 1,
                slot: 0,
            }),
        );

        let result = manager.remove_if_uninstalled(7, |_| {
            Err(Error::Kd("injected hardware clear failure".into()))
        });
        assert!(result.is_err());
        assert_eq!(manager.list().len(), 1);
        assert_eq!(manager.list()[0].id, 7);
        assert!(manager.has_enabled_hardware_breakpoints());
    }

    #[test]
    fn renumber_moves_breakpoint_and_preserves_one_shot_state() {
        let mut manager = BreakpointManager::new();
        manager.insert_for_test(2, VirtAddr(0x2000), true, None);
        manager.breakpoints.get_mut(&2).unwrap().one_shot = true;
        manager.mark_one_shot_hit(2).unwrap();

        manager.renumber(2, 7).unwrap();

        assert!(!manager.breakpoints.contains_key(&2));
        assert_eq!(manager.breakpoints.get(&7).unwrap().id, 7);
        assert_eq!(manager.one_shot_hit_ids(), vec![7]);
        assert!(manager.renumber(7, 7).is_ok());
        manager.insert_for_test(8, VirtAddr(0x8000), true, None);
        assert!(manager.renumber(7, 8).is_err());
        assert!(manager.breakpoints.contains_key(&7));
    }

    #[test]
    fn source_batch_rollback_removes_only_locations_added_by_the_batch() {
        let mut manager = BreakpointManager::new();
        manager.insert_for_test(1, VirtAddr(0x1000), true, None);
        manager.insert_for_test(2, VirtAddr(0x2000), true, None);
        manager.insert_for_test(9, VirtAddr(0x9000), true, None);

        manager
            .remove_ids_if_uninstalled([2, 1], |_| Ok(()))
            .unwrap();

        let ids: Vec<_> = manager.list().into_iter().map(|bp| bp.id).collect();
        assert_eq!(ids, vec![9]);
    }

    #[test]
    fn source_batch_rollback_reports_failed_uninstall_and_keeps_it_managed() {
        let mut manager = BreakpointManager::new();
        manager.insert_for_test(1, VirtAddr(0x1000), true, None);
        manager.insert_for_test(2, VirtAddr(0x2000), true, None);
        manager.insert_for_test(9, VirtAddr(0x9000), true, None);

        let error = manager
            .remove_ids_if_uninstalled([2, 1], |bp| {
                if bp.id == 2 {
                    Err(Error::Kd("injected rollback failure".into()))
                } else {
                    Ok(())
                }
            })
            .unwrap_err();

        assert!(error.to_string().contains("#2"));
        assert!(error.to_string().contains("injected rollback failure"));
        let ids: Vec<_> = manager.list().into_iter().map(|bp| bp.id).collect();
        assert_eq!(ids, vec![2, 9]);
    }

    #[test]
    fn detects_breakpoint_hit_at_exact_rip() {
        let mut manager = BreakpointManager::new();
        manager.breakpoints.insert(
            0,
            Breakpoint {
                id: 0,
                address: VirtAddr(0x1000),
                enabled: true,
                symbol: None,
                spec: None,
                resolved: true,
                scope: BreakpointScope::Kernel,
                automatic_scope: false,
                condition: None,
                condition_expr: None,
                pass_count: 0,
                hit_count: 0,
                remaining_pass_count: 0,
                one_shot: false,
                action: None,
                temporary: false,
                hardware: None,
                backend: BreakpointBackend::Kernel {
                    original: BreakpointPatch::single(0x90),
                },
            },
        );

        match manager.check_breakpoint_hit(0x1000, 0) {
            BreakpointHitResult::Hit(bp) => assert_eq!(bp.id, 0),
            other => panic!("unexpected result: {:?}", other),
        }
    }

    #[test]
    fn process_breakpoint_hit_requires_matching_cr3() {
        let mut manager = BreakpointManager::new();
        manager.breakpoints.insert(
            0,
            Breakpoint {
                id: 0,
                address: VirtAddr(0x7ff7_1234_1000),
                enabled: true,
                symbol: None,
                spec: None,
                resolved: true,
                scope: BreakpointScope::Process {
                    pid: 42,
                    dtb: 0x1234_5000,
                    name: "user.exe".to_string(),
                },
                automatic_scope: false,
                condition: None,
                condition_expr: None,
                pass_count: 0,
                hit_count: 0,
                remaining_pass_count: 0,
                one_shot: false,
                action: None,
                temporary: false,
                hardware: None,
                backend: BreakpointBackend::GuestMemoryPatch {
                    original: BreakpointPatch::single(0x90),
                },
            },
        );

        assert!(matches!(
            manager.check_breakpoint_hit(0x7ff7_1234_1000, 0x1234_5000),
            BreakpointHitResult::Hit(_)
        ));
        assert!(matches!(
            manager.check_breakpoint_hit(0x7ff7_1234_1000, 0x1234_5fff),
            BreakpointHitResult::Hit(_)
        ));
        assert!(matches!(
            manager.check_breakpoint_hit(0x7ff7_1234_1000, 0x9999_9000),
            BreakpointHitResult::NotBreakpoint
        ));
        assert!(matches!(
            manager.check_breakpoint_hit(0x7ff7_1234_1000, 0x1234_4000),
            BreakpointHitResult::NotBreakpoint
        ));
    }

    #[test]
    fn hardware_breakpoint_is_ignored_by_int3_hit_predicates() {
        let mut manager = BreakpointManager::new();
        manager.insert_for_test(
            0,
            VirtAddr(0x2000),
            true,
            Some(HardwareBreakpoint {
                access: HwBreakpointAccess::Write,
                len: 4,
                slot: 1,
            }),
        );

        assert!(matches!(
            manager.check_breakpoint_hit(0x2000, 0),
            BreakpointHitResult::NotBreakpoint
        ));
        assert_eq!(manager.breakpoint_id_at_address(0x2000), None);
    }

    #[test]
    fn has_enabled_hardware_breakpoints_tracks_enabled_hw_bps() {
        let mut manager = BreakpointManager::new();

        manager.insert_for_test(0, VirtAddr(0x1000), true, None);
        assert!(!manager.has_enabled_hardware_breakpoints());

        manager.insert_for_test(
            1,
            VirtAddr(0x2000),
            true,
            Some(HardwareBreakpoint {
                access: HwBreakpointAccess::Write,
                len: 4,
                slot: 1,
            }),
        );
        assert!(manager.has_enabled_hardware_breakpoints());

        manager.breakpoints.get_mut(&1).unwrap().enabled = false;
        assert!(!manager.has_enabled_hardware_breakpoints());
    }

    #[test]
    fn hardware_breakpoint_for_slot_resolves_enabled_slot_only() {
        let mut manager = BreakpointManager::new();
        manager.insert_for_test(
            7,
            VirtAddr(0x3000),
            true,
            Some(HardwareBreakpoint {
                access: HwBreakpointAccess::ReadWrite,
                len: 8,
                slot: 1,
            }),
        );

        let found = manager
            .hardware_breakpoint_for_slot(1)
            .expect("slot 1 hw bp");
        assert_eq!(found.id, 7);
        assert_eq!(found.hardware.expect("hw params").slot, 1);

        assert!(manager.hardware_breakpoint_for_slot(0).is_none());

        manager.insert_for_test(
            8,
            VirtAddr(0x4000),
            false,
            Some(HardwareBreakpoint {
                access: HwBreakpointAccess::Write,
                len: 2,
                slot: 0,
            }),
        );
        assert!(manager.hardware_breakpoint_for_slot(0).is_none());
    }

    #[test]
    fn software_and_hardware_breakpoint_coexist_at_same_address() {
        let mut manager = BreakpointManager::new();
        let addr = 0x5000;

        manager.insert_for_test(0, VirtAddr(addr), true, None);
        manager.insert_for_test(
            1,
            VirtAddr(addr),
            true,
            Some(HardwareBreakpoint {
                access: HwBreakpointAccess::Write,
                len: 4,
                slot: 1,
            }),
        );

        match manager.check_breakpoint_hit(addr, 0) {
            BreakpointHitResult::Hit(bp) => {
                assert_eq!(bp.id, 0);
                assert!(bp.hardware.is_none());
            }
            other => panic!("expected software hit, got {:?}", other),
        }
        assert_eq!(manager.breakpoint_id_at_address(addr), Some(0));
        assert_eq!(
            manager.enabled_software_breakpoint_id(&BreakpointScope::Kernel, VirtAddr(addr)),
            Some(0)
        );

        manager.breakpoints.remove(&0);
        assert_eq!(
            manager.enabled_software_breakpoint_id(&BreakpointScope::Kernel, VirtAddr(addr)),
            None
        );
    }

    #[test]
    fn pass_count_records_every_hit_and_surfaces_requested_hit() {
        let mut manager = BreakpointManager::new();
        manager.insert_for_test(3, VirtAddr(0x1000), true, None);
        manager.set_pass_count(3, 3).unwrap();

        assert_eq!(
            manager.record_hit(3).unwrap(),
            BreakpointHitDisposition::SkipPass
        );
        assert_eq!(
            manager.record_hit(3).unwrap(),
            BreakpointHitDisposition::SkipPass
        );
        assert_eq!(
            manager.record_hit(3).unwrap(),
            BreakpointHitDisposition::Evaluate
        );
        let bp = manager.list()[0];
        assert_eq!(bp.hit_count, 3);
        assert_eq!(bp.remaining_pass_count, 0);
    }

    #[test]
    fn one_shot_is_hidden_after_surface_but_remains_available_for_safe_step_over() {
        let mut manager = BreakpointManager::new();
        manager.insert_for_test(4, VirtAddr(0x2000), true, None);
        manager.set_one_shot(4, true).unwrap();
        manager.mark_one_shot_hit(4).unwrap();

        assert!(manager.list().is_empty());
        assert_eq!(manager.breakpoint_id_at_address(0x2000), Some(4));
        assert_eq!(manager.one_shot_hit_ids(), vec![4]);
        manager.discard(&mut SlotRecorder::new(), 4).unwrap();
        assert!(manager.one_shot_hit_ids().is_empty());
    }

    #[test]
    fn target_reload_keeps_symbolic_identity_deferred_and_drops_numeric_points() {
        let mut manager = BreakpointManager::new();
        manager.insert_for_test(1, VirtAddr(0x1000), true, None);
        manager.insert_for_test(7, VirtAddr(0x2000), true, None);
        {
            let symbolic = manager.breakpoints.get_mut(&7).unwrap();
            symbolic.symbol = Some("driver!Entry".into());
            symbolic.spec = Some(BreakpointSpec::Symbol("driver!Entry".into()));
        }
        let mut backend = SlotRecorder::new();
        assert_eq!(manager.prepare_target_reload(&mut backend), 1);
        let bp = manager.list()[0];
        assert_eq!(bp.id, 7);
        assert!(bp.deferred());
        assert_eq!(bp.address, VirtAddr(0x2000));
        assert!(matches!(bp.backend, BreakpointBackend::Deferred));
    }

    #[test]
    fn unloaded_symbolic_site_becomes_deferred_without_dropping_identity() {
        let mut manager = BreakpointManager::new();
        manager.insert_for_test(3, VirtAddr(0x3000), true, None);
        manager.insert_for_test(4, VirtAddr(0x4000), true, None);
        manager.breakpoints.get_mut(&3).unwrap().spec = Some(BreakpointSpec::Source {
            raw: "probe.c:35".into(),
            file: "probe.c".into(),
            line: 35,
            address_index: 0,
        });

        assert_eq!(
            manager.defer_symbolic_sites_if(&mut SlotRecorder::new(), |bp| bp.id == 3),
            1
        );

        let deferred = manager.breakpoints.get(&3).unwrap();
        assert!(deferred.enabled);
        assert!(deferred.deferred());
        assert_eq!(deferred.address, VirtAddr(0x3000));
        assert!(matches!(deferred.backend, BreakpointBackend::Deferred));
        assert!(manager.breakpoints.get(&4).unwrap().resolved);
        assert!(matches!(
            manager.check_breakpoint_hit(0x3000, 0),
            BreakpointHitResult::NotBreakpoint
        ));
    }

    #[test]
    fn physical_breakpoint_sites_reject_same_kind_collisions() {
        let mut manager = BreakpointManager::new();
        let address = VirtAddr(0x4000);
        manager.insert_for_test(2, address, false, None);

        let error = manager
            .ensure_site_available(address, false, None)
            .expect_err("disabled breakpoints still own their physical site");
        assert!(error.to_string().contains("breakpoint 2 already owns"));
        assert!(manager.ensure_site_available(address, true, None).is_ok());
    }

    /// Backend stub that records which DR slots `clear_hardware_breakpoint`
    /// releases; every other operation is out of scope for these tests.
    struct SlotRecorder {
        register_map: RegisterMap,
        cleared: Vec<u8>,
    }

    impl SlotRecorder {
        fn new() -> Self {
            Self {
                register_map: RegisterMap::default(),
                cleared: Vec::new(),
            }
        }
    }

    impl DebugBackend for SlotRecorder {
        fn register_map(&self) -> &RegisterMap {
            &self.register_map
        }
        fn read_registers(&mut self) -> Result<Vec<u8>> {
            Err(Error::NotSupported)
        }
        fn write_registers(&mut self, _data: &[u8]) -> Result<()> {
            Err(Error::NotSupported)
        }
        fn set_breakpoint(&mut self, _addr: u64) -> Result<()> {
            Err(Error::NotSupported)
        }
        fn remove_breakpoint(&mut self, _addr: u64) -> Result<()> {
            Err(Error::NotSupported)
        }
        fn clear_hardware_breakpoint(&mut self, slot: u8) -> Result<()> {
            self.cleared.push(slot);
            Ok(())
        }
        fn continue_execution(&mut self) -> Result<()> {
            Err(Error::NotSupported)
        }
        fn step(&mut self) -> Result<()> {
            Err(Error::NotSupported)
        }
        fn interrupt(&mut self) -> Result<StopEvent> {
            Err(Error::NotSupported)
        }
        fn wait_for_stop(&mut self) -> Result<StopEvent> {
            Err(Error::NotSupported)
        }
        fn try_wait_for_stop(&mut self, _timeout: Duration) -> Result<Option<StopEvent>> {
            Ok(None)
        }
        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 {
            false
        }
    }

    #[test]
    fn clear_hardware_slots_releases_every_hw_slot_and_skips_software() {
        let mut manager = BreakpointManager::new();
        manager.insert_for_test(
            0,
            VirtAddr(0x1000),
            true,
            Some(HardwareBreakpoint {
                access: HwBreakpointAccess::Write,
                len: 4,
                slot: 2,
            }),
        );
        manager.insert_for_test(
            1,
            VirtAddr(0x2000),
            false,
            Some(HardwareBreakpoint {
                access: HwBreakpointAccess::Execute,
                len: 1,
                slot: 0,
            }),
        );
        manager.insert_for_test(2, VirtAddr(0x3000), true, None);

        let mut backend = SlotRecorder::new();
        manager.clear_hardware_slots(&mut backend);

        let mut cleared = backend.cleared.clone();
        cleared.sort_unstable();
        assert_eq!(cleared, vec![0, 2]);
    }
}