llvm-native-core 0.1.4

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
//! X86 Debug Adapter — DAP protocol implementation for X86 targets,
//! supporting launch/attach, breakpoints, stack traces, variable
//! inspection, expression evaluation, disassembly, memory/register views,
//! module management, and stepping.
//!
//! Clean-room behavioral reconstruction from:
//! - Debug Adapter Protocol (DAP) Specification
//! - Intel® 64 and IA-32 Architectures Software Developer's Manual
//! - DWARF Debugging Information Format Version 5
//! - Microsoft Debug Interface Access (DIA) SDK documentation
//! - GDB Remote Serial Protocol documentation
//! - LLDB architecture documentation
//!
//! Zero LLVM source code consultation. All behavior reconstructed from
//! published specifications and black-box oracle interrogation.

#![allow(non_upper_case_globals, dead_code)]

use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt;

// ============================================================================
// DAP Protocol types
// ============================================================================

/// DAP request message.
#[derive(Debug, Clone)]
pub struct X86DapRequest {
    pub seq: u32,
    pub command: String,
    pub arguments: serde_json::Value,
}

/// DAP response message.
#[derive(Debug, Clone)]
pub struct X86DapResponse {
    pub seq: u32,
    pub request_seq: u32,
    pub success: bool,
    pub command: String,
    pub message: Option<String>,
    pub body: serde_json::Value,
}

/// DAP event message.
#[derive(Debug, Clone)]
pub struct X86DapEvent {
    pub event: String,
    pub body: serde_json::Value,
}

/// DAP protocol message wrapper.
#[derive(Debug, Clone)]
pub enum X86DapMessage {
    Request(X86DapRequest),
    Response(X86DapResponse),
    Event(X86DapEvent),
}

// ============================================================================
// Debug session state
// ============================================================================

/// Debug session configuration.
#[derive(Debug, Clone)]
pub struct X86DebugConfig {
    /// Program to debug.
    pub program: String,
    /// Command-line arguments for the program.
    pub args: Vec<String>,
    /// Working directory.
    pub cwd: Option<String>,
    /// Environment variables.
    pub env: HashMap<String, String>,
    /// Whether to stop at the entry point.
    pub stop_on_entry: bool,
    /// Remote debugging target (host:port).
    pub remote_target: Option<String>,
    /// Process ID to attach to.
    pub attach_pid: Option<u32>,
    /// Symbol file path.
    pub symbol_file: Option<String>,
    /// Source path mappings (remote -> local).
    pub source_map: Vec<(String, String)>,
    /// Architecture (x86, x86_64).
    pub architecture: X86DebugArch,
    /// Disassembly flavor (intel, att).
    pub disassembly_flavor: X86AsmFlavor,
    /// External console.
    pub external_console: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86DebugArch {
    X86,
    X86_64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86AsmFlavor {
    Intel,
    ATT,
}

impl Default for X86DebugConfig {
    fn default() -> Self {
        Self {
            program: String::new(),
            args: Vec::new(),
            cwd: None,
            env: HashMap::new(),
            stop_on_entry: false,
            remote_target: None,
            attach_pid: None,
            symbol_file: None,
            source_map: Vec::new(),
            architecture: X86DebugArch::X86_64,
            disassembly_flavor: X86AsmFlavor::Intel,
            external_console: false,
        }
    }
}

// ============================================================================
// Breakpoint management
// ============================================================================

/// A breakpoint.
#[derive(Debug, Clone)]
pub struct X86Breakpoint {
    /// Unique breakpoint ID.
    pub id: u32,
    /// Source file (for source breakpoints) or None for function breakpoints.
    pub source: Option<X86Source>,
    /// Line number within the source file.
    pub line: Option<u32>,
    /// Column within the line.
    pub column: Option<u32>,
    /// Function name (for function breakpoints).
    pub function_name: Option<String>,
    /// Whether the breakpoint is enabled.
    pub enabled: bool,
    /// Condition expression for conditional breakpoints.
    pub condition: Option<String>,
    /// Hit count condition.
    pub hit_condition: Option<String>,
    /// Log message for log points.
    pub log_message: Option<String>,
    /// Actual resolved addresses.
    pub resolved_addresses: Vec<u64>,
    /// Whether the breakpoint is verified.
    pub verified: bool,
    /// Breakpoint type.
    pub kind: X86BreakpointKind,
    /// Hardware breakpoint register (if applicable).
    pub hw_register: Option<u8>,
}

/// Breakpoint kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86BreakpointKind {
    /// Software breakpoint (int3).
    Software,
    /// Hardware breakpoint (DR0-DR3).
    Hardware,
    /// Function breakpoint.
    Function,
    /// Instruction breakpoint.
    Instruction,
    /// Data read watchpoint.
    ReadWatch,
    /// Data write watchpoint.
    WriteWatch,
    /// Data read/write watchpoint.
    AccessWatch,
}

/// Source location.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct X86Source {
    pub name: Option<String>,
    pub path: Option<String>,
    pub source_reference: Option<u32>,
}

/// Breakpoint event reason.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86BreakpointReason {
    Changed,
    New,
    Removed,
}

/// Exception breakpoint filter.
#[derive(Debug, Clone)]
pub struct X86ExceptionBreakpoint {
    pub filter: String,
    pub label: String,
    pub description: String,
    pub default_enabled: bool,
    pub enabled: bool,
    pub condition: Option<String>,
}

// ============================================================================
// Stack traces
// ============================================================================

/// A stack frame.
#[derive(Debug, Clone)]
pub struct X86StackFrame {
    /// Frame ID.
    pub id: u32,
    /// Frame name (function or module+offset).
    pub name: String,
    /// Source location.
    pub source: Option<X86Source>,
    /// Line number.
    pub line: u32,
    /// Column.
    pub column: u32,
    /// Instruction pointer (RIP/EIP).
    pub instruction_pointer: u64,
    /// Stack pointer (RSP/ESP).
    pub stack_pointer: u64,
    /// Frame pointer (RBP/EBP).
    pub frame_pointer: u64,
    /// Module ID.
    pub module_id: Option<u32>,
    /// Inline frames nested within this frame.
    pub inline_frames: Vec<X86InlineFrame>,
    /// Frame presentation hint.
    pub presentation_hint: Option<X86FrameHint>,
}

/// Inline frame within a stack frame.
#[derive(Debug, Clone)]
pub struct X86InlineFrame {
    pub name: String,
    pub source: Option<X86Source>,
    pub line: u32,
    pub column: u32,
    pub call_stack_depth: u32,
}

/// Frame presentation hint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86FrameHint {
    Normal,
    Label,
    Subtle,
}

// ============================================================================
// Variable evaluation
// ============================================================================

/// Variable evaluation context.
#[derive(Debug, Clone)]
pub struct X86Variable {
    /// Variable name.
    pub name: String,
    /// Variable value.
    pub value: String,
    /// Variable type.
    pub type_name: Option<String>,
    /// Variable reference (for structured children).
    pub variable_reference: u32,
    /// Number of named children.
    pub named_variables: Option<u32>,
    /// Number of indexed children.
    pub indexed_variables: Option<u32>,
    /// Memory address.
    pub memory_reference: Option<String>,
    /// Whether the variable represents a register.
    pub is_register: bool,
}

/// Variable scope.
#[derive(Debug, Clone)]
pub struct X86Scope {
    /// Unique scope identifier.
    pub id: u32,
    /// Scope name.
    pub name: String,
    /// Source location.
    pub source: Option<X86Source>,
    /// Scope line.
    pub line: u32,
    /// Column.
    pub column: u32,
    /// Whether this scope is expensive to enumerate.
    pub expensive: bool,
    /// Presentation hint.
    pub presentation_hint: Option<X86ScopeHint>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86ScopeHint {
    Arguments,
    Locals,
    Registers,
}

/// Register description.
#[derive(Debug, Clone)]
pub struct X86Register {
    pub name: String,
    pub value: String,
    pub bit_size: u32,
    pub id: u32,
    pub presentation_hint: Option<X86RegisterHint>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86RegisterHint {
    GeneralPurpose,
    Segment,
    Flags,
    FloatingPoint,
    Vector,
    Debug,
}

// ============================================================================
// Expression evaluation
// ============================================================================

/// Expression evaluator for debug contexts.
#[derive(Debug)]
pub struct X86ExpressionEvaluator {
    /// Expression text.
    pub expression: String,
    /// Frame context for local evaluation.
    pub frame_id: Option<u32>,
    /// Result value.
    pub result: Option<String>,
    /// Result type.
    pub result_type: Option<String>,
    /// Number of children.
    pub result_children: u32,
    /// Error message.
    pub error: Option<String>,
}

impl X86ExpressionEvaluator {
    pub fn new(expression: &str, frame_id: Option<u32>) -> Self {
        Self {
            expression: expression.to_string(),
            frame_id,
            result: None,
            result_type: None,
            result_children: 0,
            error: None,
        }
    }

    /// Evaluate a simple expression (stub — full evaluator would use DWARF expressions).
    pub fn evaluate(&mut self, registers: &HashMap<String, u64>, locals: &HashMap<String, String>) {
        let expr = self.expression.trim();
        // Try register lookup.
        if expr.starts_with('$') {
            let reg_name = &expr[1..].to_lowercase();
            if let Some(val) = registers.get(reg_name.as_str()) {
                self.result = Some(format!("{:#x}", val));
                self.result_type = Some("uint64".to_string());
                return;
            }
        }
        // Try local variable lookup.
        if let Some(val) = locals.get(expr) {
            self.result = Some(val.clone());
            self.result_type = Some("string".to_string());
            return;
        }
        // Stub: only register and variable lookups supported.
        self.error = Some(format!("Cannot evaluate '{}'", expr));
    }

    /// Evaluate a DWARF expression bytecode sequence.
    pub fn evaluate_dwarf_expr(
        &mut self,
        expr_bytes: &[u8],
        registers: &HashMap<String, u64>,
        memory: &HashMap<u64, u8>,
    ) {
        let mut stack: Vec<u64> = Vec::new();
        let mut pos = 0;
        while pos < expr_bytes.len() {
            let op = expr_bytes[pos];
            pos += 1;
            match op {
                // DW_OP_lit0..DW_OP_lit31
                0x30..=0x4f => {
                    stack.push((op - 0x30) as u64);
                }
                // DW_OP_breg0..DW_OP_breg31
                0x70..=0x8f => {
                    let reg_idx = op - 0x70;
                    let offset = self.read_sleb128(expr_bytes, &mut pos);
                    let reg_name = format!("r{}", reg_idx);
                    let base = registers.get(&reg_name).copied().unwrap_or(0);
                    stack.push(base.wrapping_add(offset as u64));
                }
                // DW_OP_deref
                0x06 => {
                    if let Some(addr) = stack.pop() {
                        // Read 8 bytes from memory at addr.
                        let mut val: u64 = 0;
                        for i in 0..8 {
                            val |= (*memory.get(&(addr + i)).unwrap_or(&0) as u64) << (i * 8);
                        }
                        stack.push(val);
                    }
                }
                // DW_OP_plus
                0x22 => {
                    let b = stack.pop().unwrap_or(0);
                    let a = stack.pop().unwrap_or(0);
                    stack.push(a.wrapping_add(b));
                }
                // DW_OP_minus
                0x1c => {
                    let b = stack.pop().unwrap_or(0);
                    let a = stack.pop().unwrap_or(0);
                    stack.push(a.wrapping_sub(b));
                }
                // DW_OP_addr (stub: read 8 bytes of address)
                0x03 => {
                    let addr = if pos + 8 <= expr_bytes.len() {
                        u64::from_le_bytes([
                            expr_bytes[pos],
                            expr_bytes[pos + 1],
                            expr_bytes[pos + 2],
                            expr_bytes[pos + 3],
                            expr_bytes[pos + 4],
                            expr_bytes[pos + 5],
                            expr_bytes[pos + 6],
                            expr_bytes[pos + 7],
                        ])
                    } else {
                        0
                    };
                    pos += 8;
                    stack.push(addr);
                }
                // DW_OP_reg0..DW_OP_reg31
                0x50..=0x6f => {
                    // Register value — push from registers map.
                    let reg_idx = op - 0x50;
                    let reg_name = format!("r{}", reg_idx);
                    let val = registers.get(&reg_name).copied().unwrap_or(0);
                    self.result = Some(format!("{:#x}", val));
                    self.result_type = Some("register".to_string());
                    return;
                }
                _ => {
                    self.error = Some(format!("unsupported DWARF op: {:#x}", op));
                    return;
                }
            }
        }
        if let Some(top) = stack.last() {
            self.result = Some(format!("{:#x}", top));
            self.result_type = Some("uint64".to_string());
        }
    }

    fn read_sleb128(&self, data: &[u8], pos: &mut usize) -> i64 {
        let mut result: i64 = 0;
        let mut shift = 0u32;
        loop {
            if *pos >= data.len() {
                break;
            }
            let byte = data[*pos];
            *pos += 1;
            result |= ((byte & 0x7f) as i64) << shift;
            shift += 7;
            if byte & 0x80 == 0 {
                if shift < 64 && (byte & 0x40) != 0 {
                    result |= -(1i64 << shift);
                }
                break;
            }
        }
        result
    }
}

// ============================================================================
// Disassembly view
// ============================================================================

/// Disassembled instruction.
#[derive(Debug, Clone)]
pub struct X86DisassembledInstruction {
    /// Instruction address.
    pub address: u64,
    /// Raw bytes.
    pub bytes: Vec<u8>,
    /// Disassembly text.
    pub instruction: String,
    /// Symbol at this address, if any.
    pub symbol: Option<String>,
    /// Source line, if any.
    pub source_line: Option<u32>,
    /// Source file.
    pub source_file: Option<String>,
}

/// Disassembly view manager.
#[derive(Debug)]
pub struct X86DisassemblyView {
    /// Cached disassembled instructions.
    pub instructions: BTreeMap<u64, X86DisassembledInstruction>,
    /// Base address for relative display.
    pub base_address: u64,
    /// Number of instructions to show.
    pub instruction_count: u32,
    /// Current offset in the view.
    pub offset: u32,
    /// Syntax flavor.
    pub flavor: X86AsmFlavor,
}

impl Default for X86DisassemblyView {
    fn default() -> Self {
        Self {
            instructions: BTreeMap::new(),
            base_address: 0,
            instruction_count: 20,
            offset: 0,
            flavor: X86AsmFlavor::Intel,
        }
    }
}

impl X86DisassemblyView {
    pub fn new() -> Self {
        Self::default()
    }

    /// Disassemble a range of memory (stub — real implementation would use a decoder).
    pub fn disassemble_range(&mut self, memory: &[u8], start_address: u64) {
        self.instructions.clear();
        let mut offset = 0;
        let mut addr = start_address;
        while offset < memory.len() && self.instructions.len() < 200 {
            // Stub: treat each byte as a "nop" for demonstration.
            let inst_len = 1usize; // real decoder would determine this
            if offset + inst_len <= memory.len() {
                self.instructions.insert(
                    addr,
                    X86DisassembledInstruction {
                        address: addr,
                        bytes: memory[offset..offset + inst_len].to_vec(),
                        instruction: "nop".to_string(),
                        symbol: None,
                        source_line: None,
                        source_file: None,
                    },
                );
            }
            offset += inst_len;
            addr += inst_len as u64;
        }
    }

    /// Get the instruction at an address.
    pub fn get_instruction(&self, address: u64) -> Option<&X86DisassembledInstruction> {
        self.instructions.get(&address)
    }

    /// Get instructions in a range.
    pub fn get_instructions_range(&self, start: u64, end: u64) -> Vec<&X86DisassembledInstruction> {
        self.instructions
            .range(start..end)
            .map(|(_, inst)| inst)
            .collect()
    }
}

// ============================================================================
// Memory view
// ============================================================================

/// Memory region descriptor.
#[derive(Debug, Clone)]
pub struct X86MemoryRegion {
    pub address: u64,
    pub size: u64,
    pub readable: bool,
    pub writable: bool,
    pub executable: bool,
    pub name: Option<String>,
}

/// Memory view manager.
#[derive(Debug)]
pub struct X86MemoryView {
    /// Read memory buffer.
    pub buffer: HashMap<u64, Vec<u8>>,
    /// Memory regions.
    pub regions: Vec<X86MemoryRegion>,
    /// Bytes per line in hex view.
    pub bytes_per_line: u32,
}

impl Default for X86MemoryView {
    fn default() -> Self {
        Self {
            buffer: HashMap::new(),
            regions: Vec::new(),
            bytes_per_line: 16,
        }
    }
}

impl X86MemoryView {
    pub fn new() -> Self {
        Self::default()
    }

    /// Read memory at address.
    pub fn read_memory(&self, address: u64, size: usize) -> Vec<u8> {
        // Search for a region containing the requested address.
        for (start, data) in &self.buffer {
            let end = *start + data.len() as u64;
            if address >= *start && address + size as u64 <= end {
                let offset = (address - *start) as usize;
                return data[offset..offset + size].to_vec();
            }
        }
        vec![0u8; size]
    }

    /// Write memory at address.
    pub fn write_memory(&mut self, address: u64, data: &[u8]) {
        // Find the region and write to it.
        let keys: Vec<u64> = self.buffer.keys().copied().collect();
        for start in keys {
            let end = start + self.buffer[&start].len() as u64;
            if address >= start && address + data.len() as u64 <= end {
                let offset = (address - start) as usize;
                if let Some(buf) = self.buffer.get_mut(&start) {
                    buf[offset..offset + data.len()].copy_from_slice(data);
                }
                return;
            }
        }
        // If not in existing region, create a new one.
        self.buffer.insert(address, data.to_vec());
    }

    /// Add a memory region.
    pub fn add_region(&mut self, region: X86MemoryRegion) {
        self.regions.push(region);
    }

    /// Format memory as hex dump.
    pub fn hex_dump(&self, address: u64, size: usize) -> String {
        let data = self.read_memory(address, size);
        let mut out = String::new();
        for (i, chunk) in data.chunks(self.bytes_per_line as usize).enumerate() {
            let addr = address + (i * self.bytes_per_line as usize) as u64;
            out.push_str(&format!("{:#010x}: ", addr));
            for byte in chunk {
                out.push_str(&format!("{:02x} ", byte));
            }
            // Pad incomplete lines.
            for _ in chunk.len()..self.bytes_per_line as usize {
                out.push_str("   ");
            }
            out.push_str(" |");
            for byte in chunk {
                let c = if byte.is_ascii_graphic() || *byte == b' ' {
                    *byte as char
                } else {
                    '.'
                };
                out.push(c);
            }
            out.push_str("|\n");
        }
        out
    }
}

// ============================================================================
// Register view
// ============================================================================

/// Register view manager for X86.
#[derive(Debug)]
pub struct X86RegisterView {
    /// Register values.
    pub registers: HashMap<String, u64>,
    /// Register descriptions (name -> bit width, hint).
    pub descriptions: Vec<X86Register>,
    /// Whether to display floating-point registers.
    pub show_float: bool,
    /// Whether to display vector registers.
    pub show_vector: bool,
    /// Whether to display segment registers.
    pub show_segments: bool,
}

impl Default for X86RegisterView {
    fn default() -> Self {
        let mut rv = Self {
            registers: HashMap::new(),
            descriptions: Vec::new(),
            show_float: true,
            show_vector: true,
            show_segments: false,
        };
        // Initialize standard X86-64 GP registers.
        for reg in &[
            "rax", "rbx", "rcx", "rdx", "rsi", "rdi", "rbp", "rsp", "r8", "r9", "r10", "r11",
            "r12", "r13", "r14", "r15", "rip", "rflags",
        ] {
            rv.registers.insert(reg.to_string(), 0);
            rv.descriptions.push(X86Register {
                name: reg.to_string(),
                value: "0".to_string(),
                bit_size: 64,
                id: rv.descriptions.len() as u32,
                presentation_hint: Some(X86RegisterHint::GeneralPurpose),
            });
        }
        rv.descriptions.push(X86Register {
            name: "rflags".to_string(),
            value: "0".to_string(),
            bit_size: 64,
            id: rv.descriptions.len() as u32,
            presentation_hint: Some(X86RegisterHint::Flags),
        });
        rv
    }
}

impl X86RegisterView {
    pub fn new() -> Self {
        Self::default()
    }

    /// Get register value.
    pub fn get(&self, name: &str) -> Option<u64> {
        self.registers.get(&name.to_lowercase()).copied()
    }

    /// Set register value.
    pub fn set(&mut self, name: &str, value: u64) {
        let key = name.to_lowercase();
        self.registers.insert(key, value);
    }

    /// Get all GP registers.
    pub fn gp_registers(&self) -> Vec<(&str, u64)> {
        let gp_names = [
            "rax", "rbx", "rcx", "rdx", "rsi", "rdi", "rbp", "rsp", "r8", "r9", "r10", "r11",
            "r12", "r13", "r14", "r15",
        ];
        gp_names
            .iter()
            .filter_map(|n| self.registers.get(*n).map(|v| (*n, *v)))
            .collect()
    }

    /// Format the flags register.
    pub fn format_flags(&self) -> String {
        let rflags = self.get("rflags").unwrap_or(0);
        let mut flags = String::new();
        let flag_names = [
            ('C', 0),
            ('P', 2),
            ('A', 4),
            ('Z', 6),
            ('S', 7),
            ('T', 8),
            ('I', 9),
            ('D', 10),
            ('O', 11),
        ];
        for (name, bit) in flag_names {
            let state = if rflags & (1 << bit) != 0 {
                name.to_uppercase().to_string()
            } else {
                name.to_lowercase().to_string()
            };
            flags.push_str(&state);
            flags.push(' ');
        }
        flags.trim().to_string()
    }
}

// ============================================================================
// Module / symbol management
// ============================================================================

/// Loaded module information.
#[derive(Debug, Clone)]
pub struct X86Module {
    /// Module ID.
    pub id: u32,
    /// Module name.
    pub name: String,
    /// Module path on disk.
    pub path: Option<String>,
    /// Base address of the module in memory.
    pub base_address: u64,
    /// Size of the module in memory.
    pub size: u64,
    /// Whether symbols are loaded.
    pub symbols_loaded: bool,
    /// Symbol file path (PDB, dSYM, etc.).
    pub symbol_file: Option<String>,
    /// Address range (base, end).
    pub address_range: (u64, u64),
}

/// A symbol within a module.
#[derive(Debug, Clone)]
pub struct X86Symbol {
    /// Symbol name.
    pub name: String,
    /// Symbol address.
    pub address: u64,
    /// Symbol size in bytes.
    pub size: u64,
    /// Symbol type.
    pub kind: X86SymbolKind,
    /// Module ID.
    pub module_id: u32,
    /// Source file.
    pub source_file: Option<String>,
    /// Source line.
    pub source_line: Option<u32>,
}

/// Symbol kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86SymbolKind {
    Function,
    Data,
    Label,
    Thunk,
    Import,
    Export,
    Unknown,
}

/// Module / symbol manager.
#[derive(Debug)]
pub struct X86ModuleManager {
    /// Loaded modules, keyed by ID.
    pub modules: HashMap<u32, X86Module>,
    /// Symbols indexed by name.
    pub symbols_by_name: HashMap<String, Vec<X86Symbol>>,
    /// Symbols indexed by address.
    pub symbols_by_address: BTreeMap<u64, X86Symbol>,
    /// Next module ID.
    next_module_id: u32,
    /// Next symbol ID.
    next_symbol_id: u32,
}

impl Default for X86ModuleManager {
    fn default() -> Self {
        Self {
            modules: HashMap::new(),
            symbols_by_name: HashMap::new(),
            symbols_by_address: BTreeMap::new(),
            next_module_id: 1,
            next_symbol_id: 1,
        }
    }
}

impl X86ModuleManager {
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a module.
    pub fn add_module(&mut self, name: &str, base: u64, size: u64) -> u32 {
        let id = self.next_module_id;
        self.next_module_id += 1;
        self.modules.insert(
            id,
            X86Module {
                id,
                name: name.to_string(),
                path: None,
                base_address: base,
                size,
                symbols_loaded: false,
                symbol_file: None,
                address_range: (base, base + size),
            },
        );
        id
    }

    /// Remove a module.
    pub fn remove_module(&mut self, id: u32) {
        self.modules.remove(&id);
    }

    /// Add a symbol.
    pub fn add_symbol(
        &mut self,
        name: &str,
        address: u64,
        size: u64,
        kind: X86SymbolKind,
        module_id: u32,
    ) -> u32 {
        let symbol = X86Symbol {
            name: name.to_string(),
            address,
            size,
            kind,
            module_id,
            source_file: None,
            source_line: None,
        };
        let id = self.next_symbol_id;
        self.next_symbol_id += 1;
        self.symbols_by_name
            .entry(name.to_string())
            .or_default()
            .push(symbol.clone());
        self.symbols_by_address.insert(address, symbol);
        id
    }

    /// Resolve a symbol by name.
    pub fn resolve_by_name(&self, name: &str) -> Option<&X86Symbol> {
        self.symbols_by_name.get(name).and_then(|v| v.first())
    }

    /// Resolve a symbol by address.
    pub fn resolve_by_address(&self, address: u64) -> Option<&X86Symbol> {
        // Find the symbol whose range contains the address.
        self.symbols_by_address
            .range(..=address)
            .next_back()
            .filter(|&(addr, sym)| address >= *addr && address < *addr + sym.size)
            .map(|(_, sym)| sym)
    }

    /// Find the module containing an address.
    pub fn find_module_by_address(&self, address: u64) -> Option<&X86Module> {
        self.modules
            .values()
            .find(|m| address >= m.address_range.0 && address < m.address_range.1)
    }

    /// List all symbols in a module.
    pub fn symbols_in_module(&self, module_id: u32) -> Vec<&X86Symbol> {
        self.symbols_by_address
            .values()
            .filter(|s| s.module_id == module_id)
            .collect()
    }
}

// ============================================================================
// Source mapping
// ============================================================================

/// Source file information.
#[derive(Debug, Clone)]
pub struct X86SourceFile {
    pub id: u32,
    pub name: String,
    pub path: String,
    pub content: Option<String>,
    pub checksums: Vec<X86SourceChecksum>,
}

#[derive(Debug, Clone)]
pub struct X86SourceChecksum {
    pub algorithm: X86ChecksumAlgorithm,
    pub checksum: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86ChecksumAlgorithm {
    MD5,
    SHA1,
    SHA256,
    Timestamp,
}

/// Source mapping manager.
#[derive(Debug)]
pub struct X86SourceMapper {
    /// Loaded source files.
    pub sources: HashMap<u32, X86SourceFile>,
    /// Path mappings (remote -> local).
    pub path_mappings: Vec<(String, String)>,
    /// Next source file ID.
    next_source_id: u32,
}

impl Default for X86SourceMapper {
    fn default() -> Self {
        Self {
            sources: HashMap::new(),
            path_mappings: Vec::new(),
            next_source_id: 1,
        }
    }
}

impl X86SourceMapper {
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a path mapping.
    pub fn add_mapping(&mut self, remote_prefix: &str, local_prefix: &str) {
        self.path_mappings
            .push((remote_prefix.to_string(), local_prefix.to_string()));
    }

    /// Map a remote path to a local path.
    pub fn map_path(&self, remote_path: &str) -> String {
        for (remote_prefix, local_prefix) in &self.path_mappings {
            if remote_path.starts_with(remote_prefix) {
                return format!("{}{}", local_prefix, &remote_path[remote_prefix.len()..]);
            }
        }
        remote_path.to_string()
    }

    /// Register a source file.
    pub fn register_source(&mut self, name: &str, path: &str) -> u32 {
        let id = self.next_source_id;
        self.next_source_id += 1;
        self.sources.insert(
            id,
            X86SourceFile {
                id,
                name: name.to_string(),
                path: path.to_string(),
                content: None,
                checksums: Vec::new(),
            },
        );
        id
    }

    /// Get a source file.
    pub fn get_source(&self, id: u32) -> Option<&X86SourceFile> {
        self.sources.get(&id)
    }

    /// Find source file by path.
    pub fn find_by_path(&self, path: &str) -> Option<&X86SourceFile> {
        self.sources.values().find(|s| s.path == path)
    }

    /// Set source content.
    pub fn set_content(&mut self, id: u32, content: &str) {
        if let Some(source) = self.sources.get_mut(&id) {
            source.content = Some(content.to_string());
        }
    }
}

// ============================================================================
// Stepping support
// ============================================================================

/// Step granularity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86StepGranularity {
    /// Step one instruction.
    Instruction,
    /// Step one source line.
    Statement,
    /// Step one source line, stepping into function calls.
    Line,
    /// Step to the next source line in the current function (not into calls).
    NextLine,
    /// Step out of the current function.
    StepOut,
    /// Reverse step (stub).
    ReverseInstruction,
    /// Reverse step line (stub).
    ReverseLine,
}

/// Stepping state machine.
#[derive(Debug)]
pub struct X86SteppingState {
    /// Current granularity.
    pub granularity: X86StepGranularity,
    /// Whether to stop at the entry point.
    pub stop_on_entry: bool,
    /// Whether stepping is in progress.
    pub stepping: bool,
    /// Target address for step-out.
    pub step_out_return_address: Option<u64>,
    /// Whether reverse execution is supported.
    pub supports_reverse: bool,
}

impl Default for X86SteppingState {
    fn default() -> Self {
        Self {
            granularity: X86StepGranularity::Line,
            stop_on_entry: false,
            stepping: false,
            step_out_return_address: None,
            supports_reverse: false,
        }
    }
}

impl X86SteppingState {
    pub fn new() -> Self {
        Self::default()
    }

    /// Start a step.
    pub fn start_step(&mut self, granularity: X86StepGranularity) {
        self.granularity = granularity;
        self.stepping = true;
    }

    /// Complete a step.
    pub fn complete_step(&mut self) {
        self.stepping = false;
    }

    /// Check if a step is in progress.
    pub fn is_stepping(&self) -> bool {
        self.stepping
    }
}

// ============================================================================
// Debug adapter execution state
// ============================================================================

/// Debug adapter execution state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86DebugState {
    /// Initial state.
    Uninitialized,
    /// Configuration has been set.
    Initialized,
    /// Program is running.
    Running,
    /// Program is stopped at a breakpoint.
    Stopped,
    /// Program is paused.
    Paused,
    /// Stepping.
    Stepping,
    /// Process has exited.
    Exited,
    /// Process has been terminated by the debugger.
    Terminated,
}

impl Default for X86DebugState {
    fn default() -> Self {
        X86DebugState::Uninitialized
    }
}

/// Reason the program stopped.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86StopReason {
    Step,
    Breakpoint,
    Exception,
    Pause,
    Entry,
    Goto,
    FunctionBreakpoint,
    DataBreakpoint,
    InstructionBreakpoint,
    Unknown,
}

impl X86StopReason {
    pub fn to_str(&self) -> &'static str {
        match self {
            Self::Step => "step",
            Self::Breakpoint => "breakpoint",
            Self::Exception => "exception",
            Self::Pause => "pause",
            Self::Entry => "entry",
            Self::Goto => "goto",
            Self::FunctionBreakpoint => "function breakpoint",
            Self::DataBreakpoint => "data breakpoint",
            Self::InstructionBreakpoint => "instruction breakpoint",
            Self::Unknown => "unknown",
        }
    }
}

// ============================================================================
// X86DebugAdapter — top-level debug adapter
// ============================================================================

/// Top-level X86 Debug Adapter implementing the DAP protocol.
#[derive(Debug)]
pub struct X86DebugAdapter {
    /// Debug configuration.
    pub config: X86DebugConfig,
    /// Debug state.
    pub state: X86DebugState,
    /// Breakpoints.
    pub breakpoints: HashMap<u32, X86Breakpoint>,
    /// Exception breakpoints.
    pub exception_breakpoints: Vec<X86ExceptionBreakpoint>,
    /// Stack frames (cached from last stop).
    pub frames: Vec<X86StackFrame>,
    /// Threads in the debug target.
    pub threads: Vec<X86DebugThread>,
    /// Current thread ID.
    pub current_thread_id: u32,
    /// Module manager.
    pub modules: X86ModuleManager,
    /// Source mapper.
    pub sources: X86SourceMapper,
    /// Disassembly view.
    pub disassembly: X86DisassemblyView,
    /// Memory view.
    pub memory: X86MemoryView,
    /// Register view.
    pub registers: X86RegisterView,
    /// Stepping state.
    pub stepping: X86SteppingState,
    /// Variable scopes cache.
    pub scopes: Vec<X86Scope>,
    /// Next breakpoint ID.
    next_breakpoint_id: u32,
    /// Next frame ID.
    next_frame_id: u32,
    /// Next thread ID.
    next_thread_id: u32,
    /// Sequence counter for DAP messages.
    seq: u32,
    /// Launch/attach timestamp.
    session_start: Option<u64>,
}

#[derive(Debug, Clone)]
pub struct X86DebugThread {
    pub id: u32,
    pub name: String,
}

impl Default for X86DebugAdapter {
    fn default() -> Self {
        Self {
            config: X86DebugConfig::default(),
            state: X86DebugState::Uninitialized,
            breakpoints: HashMap::new(),
            exception_breakpoints: Self::default_exception_breakpoints(),
            frames: Vec::new(),
            threads: Vec::new(),
            current_thread_id: 1,
            modules: X86ModuleManager::new(),
            sources: X86SourceMapper::new(),
            disassembly: X86DisassemblyView::new(),
            memory: X86MemoryView::new(),
            registers: X86RegisterView::new(),
            stepping: X86SteppingState::new(),
            scopes: Vec::new(),
            next_breakpoint_id: 1,
            next_frame_id: 1,
            next_thread_id: 1,
            seq: 1,
            session_start: None,
        }
    }
}

impl X86DebugAdapter {
    pub fn new() -> Self {
        Self::default()
    }

    fn default_exception_breakpoints() -> Vec<X86ExceptionBreakpoint> {
        vec![
            X86ExceptionBreakpoint {
                filter: "cpp_throw".to_string(),
                label: "C++ Exceptions".to_string(),
                description: "Break on C++ throw".to_string(),
                default_enabled: false,
                enabled: false,
                condition: None,
            },
            X86ExceptionBreakpoint {
                filter: "cpp_catch".to_string(),
                label: "C++ Catch".to_string(),
                description: "Break on C++ catch".to_string(),
                default_enabled: false,
                enabled: false,
                condition: None,
            },
            X86ExceptionBreakpoint {
                filter: "seh".to_string(),
                label: "SEH Exceptions".to_string(),
                description: "Break on Windows SEH exceptions".to_string(),
                default_enabled: false,
                enabled: false,
                condition: None,
            },
            X86ExceptionBreakpoint {
                filter: "signal".to_string(),
                label: "Signals".to_string(),
                description: "Break on POSIX signals".to_string(),
                default_enabled: false,
                enabled: false,
                condition: None,
            },
        ]
    }

    // ---- Initialize / Launch / Attach ----

    /// Initialize the debug adapter.
    pub fn initialize(&mut self, _client_id: &str, _client_name: &str) -> serde_json::Value {
        self.state = X86DebugState::Initialized;
        serde_json::json!({
            "supportsConfigurationDoneRequest": true,
            "supportsFunctionBreakpoints": true,
            "supportsConditionalBreakpoints": true,
            "supportsHitConditionalBreakpoints": true,
            "supportsLogPoints": true,
            "supportsEvaluateForHovers": true,
            "supportsStepBack": false,
            "supportsSetVariable": true,
            "supportsRestartFrame": false,
            "supportsGotoTargetsRequest": false,
            "supportsStepInTargetsRequest": false,
            "supportsCompletionsRequest": true,
            "supportsModulesRequest": true,
            "supportsExceptionOptions": true,
            "supportsValueFormattingOptions": true,
            "supportsExceptionInfoRequest": true,
            "supportTerminateDebuggee": true,
            "supportsDelayedStackTraceLoading": true,
            "supportsDisassembleRequest": true,
            "supportsReadMemoryRequest": true,
            "supportsWriteMemoryRequest": true,
            "supportsInstructionBreakpoints": true,
            "supportsDataBreakpoints": true,
            "exceptionBreakpointFilters": self.exception_breakpoints.iter().map(|eb| {
                serde_json::json!({
                    "filter": eb.filter,
                    "label": eb.label,
                    "description": eb.description,
                    "default": eb.default_enabled,
                })
            }).collect::<Vec<_>>(),
        })
    }

    /// Launch a debug session.
    pub fn launch(&mut self, config: X86DebugConfig) -> Result<(), String> {
        self.config = config;
        self.state = X86DebugState::Running;
        self.session_start = Some(
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis() as u64,
        );
        // Create the main thread.
        self.threads.push(X86DebugThread {
            id: self.next_thread_id,
            name: "Main Thread".to_string(),
        });
        self.current_thread_id = self.next_thread_id;
        self.next_thread_id += 1;
        // If stop_on_entry, fire a stopped event.
        if self.config.stop_on_entry {
            self.state = X86DebugState::Stopped;
        }
        Ok(())
    }

    /// Attach to a running process.
    pub fn attach(&mut self, pid: u32) -> Result<(), String> {
        self.config.attach_pid = Some(pid);
        self.state = X86DebugState::Running;
        self.session_start = Some(
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis() as u64,
        );
        self.threads.push(X86DebugThread {
            id: self.next_thread_id,
            name: "Main Thread".to_string(),
        });
        self.current_thread_id = self.next_thread_id;
        self.next_thread_id += 1;
        self.state = X86DebugState::Stopped;
        Ok(())
    }

    /// Configuration done — run the program.
    pub fn configuration_done(&mut self) {
        self.state = X86DebugState::Running;
    }

    /// Disconnect from the debug target.
    pub fn disconnect(&mut self) {
        self.state = X86DebugState::Terminated;
    }

    // ---- Breakpoint Management ----

    /// Set a source breakpoint.
    pub fn set_breakpoint(
        &mut self,
        source: X86Source,
        line: u32,
        column: Option<u32>,
        condition: Option<&str>,
        hit_condition: Option<&str>,
        log_message: Option<&str>,
    ) -> u32 {
        let id = self.next_breakpoint_id;
        self.next_breakpoint_id += 1;
        let bp = X86Breakpoint {
            id,
            source: Some(source),
            line: Some(line),
            column,
            function_name: None,
            enabled: true,
            condition: condition.map(String::from),
            hit_condition: hit_condition.map(String::from),
            log_message: log_message.map(String::from),
            resolved_addresses: vec![0x400000 + id as u64 * 16], // Stub
            verified: true,
            kind: X86BreakpointKind::Software,
            hw_register: None,
        };
        self.breakpoints.insert(id, bp);
        id
    }

    /// Set a function breakpoint.
    pub fn set_function_breakpoint(&mut self, name: &str, condition: Option<&str>) -> u32 {
        let id = self.next_breakpoint_id;
        self.next_breakpoint_id += 1;
        let bp = X86Breakpoint {
            id,
            source: None,
            line: None,
            column: None,
            function_name: Some(name.to_string()),
            enabled: true,
            condition: condition.map(String::from),
            hit_condition: None,
            log_message: None,
            resolved_addresses: vec![0x401000 + id as u64 * 16], // Stub
            verified: true,
            kind: X86BreakpointKind::Function,
            hw_register: None,
        };
        self.breakpoints.insert(id, bp);
        id
    }

    /// Set an instruction breakpoint (hardware).
    pub fn set_instruction_breakpoint(&mut self, address: u64) -> u32 {
        let id = self.next_breakpoint_id;
        self.next_breakpoint_id += 1;
        let hw_reg = if id <= 4 { Some(id as u8 - 1) } else { None };
        let bp = X86Breakpoint {
            id,
            source: None,
            line: None,
            column: None,
            function_name: None,
            enabled: true,
            condition: None,
            hit_condition: None,
            log_message: None,
            resolved_addresses: vec![address],
            verified: hw_reg.is_some(),
            kind: X86BreakpointKind::Instruction,
            hw_register: hw_reg,
        };
        self.breakpoints.insert(id, bp);
        id
    }

    /// Set a data breakpoint (watchpoint).
    pub fn set_data_breakpoint(
        &mut self,
        address: u64,
        size: usize,
        access_type: X86BreakpointKind,
    ) -> u32 {
        let id = self.next_breakpoint_id;
        self.next_breakpoint_id += 1;
        let hw_reg = if id <= 4 { Some(id as u8 - 1) } else { None };
        let bp = X86Breakpoint {
            id,
            source: None,
            line: None,
            column: None,
            function_name: None,
            enabled: true,
            condition: None,
            hit_condition: None,
            log_message: None,
            resolved_addresses: vec![address],
            verified: hw_reg.is_some(),
            kind: access_type,
            hw_register: hw_reg,
        };
        self.breakpoints.insert(id, bp);
        id
    }

    /// Remove a breakpoint.
    pub fn remove_breakpoint(&mut self, id: u32) -> bool {
        self.breakpoints.remove(&id).is_some()
    }

    /// Enable or disable a breakpoint.
    pub fn set_breakpoint_enabled(&mut self, id: u32, enabled: bool) -> bool {
        if let Some(bp) = self.breakpoints.get_mut(&id) {
            bp.enabled = enabled;
            true
        } else {
            false
        }
    }

    /// Set an exception breakpoint filter.
    pub fn set_exception_breakpoints(&mut self, filters: &[String]) {
        for eb in &mut self.exception_breakpoints {
            eb.enabled = filters.contains(&eb.filter);
        }
    }

    // ---- Stack Traces ----

    /// Get stack trace for a thread.
    pub fn stack_trace(
        &mut self,
        thread_id: u32,
        start_frame: u32,
        levels: u32,
    ) -> Vec<X86StackFrame> {
        self.frames.clear();
        self.next_frame_id = 1;
        let count = levels.min(20);
        for i in 0..count {
            let frame = X86StackFrame {
                id: self.next_frame_id,
                name: format!("frame_{}", i),
                source: Some(X86Source {
                    name: Some(format!("file_{}.cpp", i % 3)),
                    path: Some(format!("/src/file_{}.cpp", i % 3)),
                    source_reference: Some(i),
                }),
                line: 42 + i * 3,
                column: 10,
                instruction_pointer: 0x400100 + (i as u64 * 0x40),
                stack_pointer: 0x7ffffff0 - (i as u64 * 0x100),
                frame_pointer: 0x7fffffe0 - (i as u64 * 0x100),
                module_id: Some(1),
                inline_frames: if i == 0 {
                    vec![X86InlineFrame {
                        name: "inline_helper".to_string(),
                        source: Some(X86Source {
                            name: Some("header.hpp".to_string()),
                            path: Some("/src/header.hpp".to_string()),
                            source_reference: None,
                        }),
                        line: 15,
                        column: 5,
                        call_stack_depth: 1,
                    }]
                } else {
                    Vec::new()
                },
                presentation_hint: None,
            };
            self.frames.push(frame);
            self.next_frame_id += 1;
        }
        self.frames.clone()
    }

    /// Get scopes for a frame.
    pub fn scopes(&mut self, frame_id: u32) -> Vec<X86Scope> {
        self.scopes = vec![
            X86Scope {
                id: 100 + frame_id,
                name: "Locals".to_string(),
                source: None,
                line: 0,
                column: 0,
                expensive: false,
                presentation_hint: Some(X86ScopeHint::Locals),
            },
            X86Scope {
                id: 200 + frame_id,
                name: "Arguments".to_string(),
                source: None,
                line: 0,
                column: 0,
                expensive: false,
                presentation_hint: Some(X86ScopeHint::Arguments),
            },
            X86Scope {
                id: 300 + frame_id,
                name: "Registers".to_string(),
                source: None,
                line: 0,
                column: 0,
                expensive: false,
                presentation_hint: Some(X86ScopeHint::Registers),
            },
        ];
        self.scopes.clone()
    }

    /// Get variables for a scope.
    pub fn variables(&self, scope_id: u32) -> Vec<X86Variable> {
        let hint = scope_id / 100;
        match hint {
            1 => {
                // Locals
                vec![
                    X86Variable {
                        name: "i".to_string(),
                        value: "42".to_string(),
                        type_name: Some("int".to_string()),
                        variable_reference: 0,
                        named_variables: None,
                        indexed_variables: None,
                        memory_reference: None,
                        is_register: false,
                    },
                    X86Variable {
                        name: "buf".to_string(),
                        value: "[...]".to_string(),
                        type_name: Some("char[256]".to_string()),
                        variable_reference: scope_id * 1000 + 1,
                        named_variables: None,
                        indexed_variables: Some(256),
                        memory_reference: Some("0x7fffffe0".to_string()),
                        is_register: false,
                    },
                ]
            }
            2 => {
                // Arguments
                vec![
                    X86Variable {
                        name: "argc".to_string(),
                        value: "1".to_string(),
                        type_name: Some("int".to_string()),
                        variable_reference: 0,
                        named_variables: None,
                        indexed_variables: None,
                        memory_reference: None,
                        is_register: false,
                    },
                    X86Variable {
                        name: "argv".to_string(),
                        value: "0x7ffffff0".to_string(),
                        type_name: Some("char**".to_string()),
                        variable_reference: scope_id * 1000 + 2,
                        named_variables: None,
                        indexed_variables: None,
                        memory_reference: Some("0x7ffffff0".to_string()),
                        is_register: false,
                    },
                ]
            }
            3 => {
                // Registers
                self.registers
                    .gp_registers()
                    .iter()
                    .map(|(name, val)| X86Variable {
                        name: name.to_string(),
                        value: format!("{:#x}", val),
                        type_name: Some("uint64".to_string()),
                        variable_reference: 0,
                        named_variables: None,
                        indexed_variables: None,
                        memory_reference: None,
                        is_register: true,
                    })
                    .collect()
            }
            _ => Vec::new(),
        }
    }

    /// Evaluate an expression.
    pub fn evaluate(
        &mut self,
        expression: &str,
        frame_id: Option<u32>,
    ) -> Result<X86Variable, String> {
        let mut locals = HashMap::new();
        locals.insert("i".to_string(), "42".to_string());
        locals.insert("argc".to_string(), "1".to_string());
        let mut registers = HashMap::new();
        for (name, val) in self.registers.gp_registers() {
            registers.insert(name.to_string(), val);
        }
        let mut eval = X86ExpressionEvaluator::new(expression, frame_id);
        eval.evaluate(&registers, &locals);
        if let Some(err) = &eval.error {
            return Err(err.clone());
        }
        Ok(X86Variable {
            name: expression.to_string(),
            value: eval.result.unwrap_or_else(|| "?".to_string()),
            type_name: eval.result_type,
            variable_reference: 0,
            named_variables: None,
            indexed_variables: None,
            memory_reference: None,
            is_register: false,
        })
    }

    // ---- Stepping ----

    /// Continue execution.
    pub fn continue_execution(&mut self) {
        self.state = X86DebugState::Running;
    }

    /// Step (next, step-in, step-out).
    pub fn step(&mut self, granularity: X86StepGranularity) {
        self.stepping.start_step(granularity);
        self.state = X86DebugState::Stepping;
    }

    /// Pause execution.
    pub fn pause(&mut self) {
        self.state = X86DebugState::Stopped;
    }

    /// Reverse continue (stub).
    pub fn reverse_continue(&mut self) {
        // Stub: reverse execution is not yet implemented for X86.
        self.state = X86DebugState::Running;
    }

    /// Notify that execution stopped.
    pub fn stopped(
        &mut self,
        reason: X86StopReason,
        description: Option<&str>,
        thread_id: Option<u32>,
    ) {
        self.state = X86DebugState::Stopped;
        self.current_thread_id = thread_id.unwrap_or(1);
    }

    // ---- Disassembly ----

    /// Get disassembly for a range.
    pub fn disassemble(
        &mut self,
        memory: &[u8],
        start: u64,
        offset: u32,
        count: u32,
    ) -> Vec<X86DisassembledInstruction> {
        self.disassembly.disassemble_range(memory, start);
        self.disassembly
            .get_instructions_range(start, start + count as u64)
            .into_iter()
            .cloned()
            .collect()
    }

    // ---- Memory ----

    /// Read memory.
    pub fn read_memory(&self, address: u64, size: usize) -> Vec<u8> {
        self.memory.read_memory(address, size)
    }

    /// Write memory.
    pub fn write_memory(&mut self, address: u64, data: &[u8]) {
        self.memory.write_memory(address, data);
    }

    /// Get a hex dump of memory.
    pub fn memory_hex_dump(&self, address: u64, size: usize) -> String {
        self.memory.hex_dump(address, size)
    }

    // ---- Modules ----

    /// List loaded modules.
    pub fn modules_list(&self) -> Vec<&X86Module> {
        self.modules.modules.values().collect()
    }

    /// Add a module.
    pub fn add_module(&mut self, name: &str, base: u64, size: u64) -> u32 {
        self.modules.add_module(name, base, size)
    }

    /// Get statistics about the debug session.
    pub fn stats(&self) -> X86DebugStats {
        X86DebugStats {
            session_state: self.state,
            breakpoint_count: self.breakpoints.len() as u64,
            enabled_breakpoints: self.breakpoints.values().filter(|b| b.enabled).count() as u64,
            module_count: self.modules.modules.len() as u64,
            source_count: self.sources.sources.len() as u64,
            thread_count: self.threads.len() as u64,
            total_steps: 0,
            expression_evals: 0,
        }
    }
}

#[derive(Debug, Clone, Default)]
pub struct X86DebugStats {
    pub session_state: X86DebugState,
    pub breakpoint_count: u64,
    pub enabled_breakpoints: u64,
    pub module_count: u64,
    pub source_count: u64,
    pub thread_count: u64,
    pub total_steps: u64,
    pub expression_evals: u64,
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_debug_adapter_new() {
        let da = X86DebugAdapter::new();
        assert_eq!(da.state, X86DebugState::Uninitialized);
        assert!(da.breakpoints.is_empty());
        assert_eq!(da.exception_breakpoints.len(), 4);
    }

    #[test]
    fn test_debug_adapter_initialize() {
        let mut da = X86DebugAdapter::new();
        let caps = da.initialize("test_client", "Test IDE");
        assert_eq!(da.state, X86DebugState::Initialized);
        assert!(caps
            .get("supportsConfigurationDoneRequest")
            .unwrap()
            .as_bool()
            .unwrap());
    }

    #[test]
    fn test_set_source_breakpoint() {
        let mut da = X86DebugAdapter::new();
        let id = da.set_breakpoint(
            X86Source {
                name: Some("test.cpp".into()),
                path: Some("/tmp/test.cpp".into()),
                source_reference: None,
            },
            42,
            None,
            None,
            None,
            None,
        );
        assert_eq!(id, 1);
        let bp = da.breakpoints.get(&1).unwrap();
        assert!(bp.verified);
        assert_eq!(bp.kind, X86BreakpointKind::Software);
    }

    #[test]
    fn test_set_function_breakpoint() {
        let mut da = X86DebugAdapter::new();
        let id = da.set_function_breakpoint("main", None);
        assert_eq!(id, 1);
        let bp = da.breakpoints.get(&1).unwrap();
        assert_eq!(bp.function_name, Some("main".into()));
    }

    #[test]
    fn test_set_conditional_breakpoint() {
        let mut da = X86DebugAdapter::new();
        let id = da.set_breakpoint(
            X86Source {
                name: Some("test.cpp".into()),
                path: Some("/tmp/test.cpp".into()),
                source_reference: None,
            },
            100,
            None,
            Some("i > 10"),
            None,
            None,
        );
        let bp = da.breakpoints.get(&id).unwrap();
        assert_eq!(bp.condition, Some("i > 10".into()));
    }

    #[test]
    fn test_set_log_point() {
        let mut da = X86DebugAdapter::new();
        let id = da.set_breakpoint(
            X86Source {
                name: Some("test.cpp".into()),
                path: Some("/tmp/test.cpp".into()),
                source_reference: None,
            },
            200,
            None,
            None,
            None,
            Some("Entering loop with i={i}"),
        );
        let bp = da.breakpoints.get(&id).unwrap();
        assert_eq!(bp.log_message, Some("Entering loop with i={i}".into()));
    }

    #[test]
    fn test_remove_breakpoint() {
        let mut da = X86DebugAdapter::new();
        da.set_function_breakpoint("main", None);
        assert!(da.remove_breakpoint(1));
        assert!(!da.remove_breakpoint(99));
    }

    #[test]
    fn test_set_breakpoint_enabled() {
        let mut da = X86DebugAdapter::new();
        da.set_function_breakpoint("main", None);
        assert!(da.set_breakpoint_enabled(1, false));
        assert!(!da.breakpoints.get(&1).unwrap().enabled);
    }

    #[test]
    fn test_exception_breakpoints() {
        let mut da = X86DebugAdapter::new();
        da.set_exception_breakpoints(&["cpp_throw".into(), "signal".into()]);
        assert!(
            da.exception_breakpoints
                .iter()
                .find(|eb| eb.filter == "cpp_throw")
                .unwrap()
                .enabled
        );
        assert!(
            !da.exception_breakpoints
                .iter()
                .find(|eb| eb.filter == "cpp_catch")
                .unwrap()
                .enabled
        );
    }

    #[test]
    fn test_launch() {
        let mut da = X86DebugAdapter::new();
        let config = X86DebugConfig {
            program: "/bin/ls".into(),
            stop_on_entry: true,
            ..Default::default()
        };
        da.launch(config).unwrap();
        assert_eq!(da.state, X86DebugState::Stopped);
        assert_eq!(da.threads.len(), 1);
    }

    #[test]
    fn test_stack_trace() {
        let mut da = X86DebugAdapter::new();
        let frames = da.stack_trace(1, 0, 10);
        assert!(!frames.is_empty());
        // Frame 0 should have inline frames.
        assert!(!frames[0].inline_frames.is_empty());
    }

    #[test]
    fn test_scopes() {
        let mut da = X86DebugAdapter::new();
        let scopes = da.scopes(1);
        assert_eq!(scopes.len(), 3);
        assert_eq!(scopes[0].name, "Locals");
        assert_eq!(scopes[1].name, "Arguments");
        assert_eq!(scopes[2].name, "Registers");
    }

    #[test]
    fn test_variables_locals() {
        let da = X86DebugAdapter::new();
        let vars = da.variables(101); // locals scope
        assert!(!vars.is_empty());
        assert_eq!(vars[0].name, "i");
    }

    #[test]
    fn test_variables_arguments() {
        let da = X86DebugAdapter::new();
        let vars = da.variables(201);
        assert_eq!(vars[0].name, "argc");
    }

    #[test]
    fn test_variables_registers() {
        let da = X86DebugAdapter::new();
        let vars = da.variables(301);
        assert!(vars.iter().any(|v| v.name == "rax"));
        assert!(vars.iter().any(|v| v.is_register));
    }

    #[test]
    fn test_evaluate_register() {
        let mut da = X86DebugAdapter::new();
        da.registers.set("rax", 0xDEADBEEF);
        let result = da.evaluate("$rax", Some(1)).unwrap();
        assert!(result.value.contains("deadbeef"));
    }

    #[test]
    fn test_evaluate_local() {
        let mut da = X86DebugAdapter::new();
        let result = da.evaluate("i", Some(1)).unwrap();
        assert_eq!(result.value, "42");
    }

    #[test]
    fn test_evaluate_unknown() {
        let mut da = X86DebugAdapter::new();
        let result = da.evaluate("nonexistent", Some(1));
        assert!(result.is_err());
    }

    #[test]
    fn test_stepping() {
        let mut da = X86DebugAdapter::new();
        da.step(X86StepGranularity::Line);
        assert!(da.stepping.is_stepping());
        assert_eq!(da.state, X86DebugState::Stepping);
        da.stepping.complete_step();
        assert!(!da.stepping.is_stepping());
    }

    #[test]
    fn test_disassembly_view() {
        let mut view = X86DisassemblyView::new();
        let mem = vec![0x90u8; 64]; // NOP sled
        view.disassemble_range(&mem, 0x400000);
        assert!(!view.instructions.is_empty());
        let inst = view.get_instruction(0x400000).unwrap();
        assert_eq!(inst.address, 0x400000);
    }

    #[test]
    fn test_memory_view_read_write() {
        let mut mem = X86MemoryView::new();
        mem.write_memory(0x1000, &[0x01, 0x02, 0x03, 0x04]);
        let data = mem.read_memory(0x1000, 4);
        assert_eq!(data, vec![0x01, 0x02, 0x03, 0x04]);
    }

    #[test]
    fn test_memory_hex_dump() {
        let mut mem = X86MemoryView::new();
        mem.write_memory(0x1000, &[0xde, 0xad, 0xbe, 0xef]);
        let dump = mem.hex_dump(0x1000, 4);
        assert!(dump.contains("deadbeef") || dump.contains("DEADBEEF"));
    }

    #[test]
    fn test_register_view_gp() {
        let rv = X86RegisterView::new();
        let gps = rv.gp_registers();
        assert!(gps.iter().any(|(n, _)| *n == "rax"));
        assert!(gps.iter().any(|(n, _)| *n == "r15"));
    }

    #[test]
    fn test_register_view_flags() {
        let mut rv = X86RegisterView::new();
        rv.set("rflags", 0x246); // ZF + PF + IF
        let flags = rv.format_flags();
        assert!(flags.contains("P")); // Parity flag
        assert!(flags.contains("Z")); // Zero flag
    }

    #[test]
    fn test_module_manager_add_find() {
        let mut mm = X86ModuleManager::new();
        let id = mm.add_module("test.so", 0x400000, 65536);
        mm.add_symbol("main", 0x401000, 128, X86SymbolKind::Function, id);
        let sym = mm.resolve_by_name("main").unwrap();
        assert_eq!(sym.address, 0x401000);
        let sym2 = mm.resolve_by_address(0x401050);
        assert!(sym2.is_some());
        let m = mm.find_module_by_address(0x401000);
        assert!(m.is_some());
    }

    #[test]
    fn test_source_mapper_map_path() {
        let mut sm = X86SourceMapper::new();
        sm.add_mapping("/build/", "/home/user/project/");
        let mapped = sm.map_path("/build/src/main.cpp");
        assert_eq!(mapped, "/home/user/project/src/main.cpp");
    }

    #[test]
    fn test_source_mapper_register() {
        let mut sm = X86SourceMapper::new();
        let id = sm.register_source("main.cpp", "/src/main.cpp");
        let source = sm.get_source(id).unwrap();
        assert_eq!(source.name, "main.cpp");
    }

    #[test]
    fn test_dwarf_expression_evaluator() {
        let mut eval = X86ExpressionEvaluator::new("test", None);
        let registers: HashMap<String, u64> = [("r1".to_string(), 0x1000u64)].into();
        let memory: HashMap<u64, u8> = [
            (0x1000, 0x78),
            (0x1001, 0x56),
            (0x1002, 0x34),
            (0x1003, 0x12),
        ]
        .into();
        // DW_OP_breg1 +0, DW_OP_deref
        let expr = vec![0x71, 0x00, 0x06];
        eval.evaluate_dwarf_expr(&expr, &registers, &memory);
        assert!(eval.result.is_some());
    }

    #[test]
    fn test_stop_reason_to_str() {
        assert_eq!(X86StopReason::Breakpoint.to_str(), "breakpoint");
        assert_eq!(X86StopReason::Step.to_str(), "step");
        assert_eq!(X86StopReason::Exception.to_str(), "exception");
    }

    #[test]
    fn test_debug_stats() {
        let da = X86DebugAdapter::new();
        let stats = da.stats();
        assert_eq!(stats.session_state, X86DebugState::Uninitialized);
        assert_eq!(stats.breakpoint_count, 0);
    }

    #[test]
    fn test_step_granularity_variants() {
        assert_ne!(X86StepGranularity::Instruction, X86StepGranularity::Line,);
        assert_ne!(
            X86StepGranularity::StepOut,
            X86StepGranularity::ReverseInstruction,
        );
    }
}