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
//! An implementation of the server side of the GDB Remote Serial
//! Protocol -- the protocol used by GDB and LLDB to talk to remote
//! targets.
//!
//! This library attempts to hide many of the protocol warts from
//! server implementations.  It is also mildly opinionated, in that it
//! implements certain features itself and requires users of the
//! library to conform.  For example, it unconditionally implements
//! the multiprocess and non-stop modes.
//!
//! ## Protocol Documentation
//!
//! * [Documentation of the protocol](https://sourceware.org/gdb/onlinedocs/gdb/Remote-Protocol.html)
//! * [LLDB extensions](https://github.com/llvm-mirror/lldb/blob/master/docs/lldb-gdb-remote.txt)
// from https://github.com/luser/rust-gdb-remote-protocol/blob/master/src/lib.rs

//#![deny(missing_docs)]
//#![allow(dead_code)]

use gdb_protocol::io::BUF_SIZE;
use log::{debug, info, trace};
use nom::IResult::*;
use nom::{
	alt, alt_complete, call, complete, do_parse, error_position, flat_map, is_not, is_not_s, many0,
	many1, map, map_res, named, one_of, opt, preceded, separated_list, separated_list_complete,
	separated_nonempty_list, separated_nonempty_list_complete, separated_pair, tag, take,
	take_till, take_while1, try_parse, tuple, tuple_parser,
};
use nom::{IResult, Needed};
use rustc_serialize::hex::ToHex;
use std::borrow::Cow;
use std::convert::From;
use std::ops::Range;
use std::str::{self, FromStr};
use strum_macros::EnumString;

#[allow(non_camel_case_types)]
#[derive(Copy, Clone, Debug, EnumString, PartialEq)]
enum GDBFeature {
	multiprocess,
	xmlRegisters,
	qRelocInsn,
	swbreak,
	hwbreak,
	#[strum(serialize = "fork-events")]
	fork_events,
	#[strum(serialize = "vfork-events")]
	vfork_events,
	#[strum(serialize = "exec-events")]
	exec_events,
	vContSupported,
	// these are not listed in the docs but GDB sends them
	#[strum(serialize = "no-resumed")]
	no_resumed,
	QThreadEvents,
}

#[derive(Clone, Debug, PartialEq)]
enum Known<'a> {
	Yes(GDBFeature),
	No(&'a str),
}

#[derive(Clone, Debug, PartialEq)]
struct GDBFeatureSupported<'a>(Known<'a>, FeatureSupported<'a>);

#[derive(Clone, Debug, PartialEq)]
enum FeatureSupported<'a> {
	Yes,
	No,
	#[allow(unused)]
	Maybe,
	Value(&'a str),
}

#[derive(Clone, Debug, PartialEq)]
enum Query<'a> {
	/// Return the attached state of the indicated process.
	// FIXME the PID only needs to be optional in the
	// non-multi-process case, which we aren't supporting; but we
	// don't send multiprocess+ in the feature response yet.
	Attached(Option<u64>),
	/// Return the current thread ID.
	CurrentThread,
	/// Search memory for some bytes.
	SearchMemory {
		address: u64,
		length: u64,
		bytes: Vec<u8>,
	},
	/// Compute the CRC checksum of a block of memory.
	// Uncomment this when qC is implemented.
	// #[allow(unused)]
	// CRC { addr: u64, length: u64 },
	/// Tell the remote stub about features supported by gdb, and query the stub for features
	/// it supports.
	SupportedFeatures(Vec<GDBFeatureSupported<'a>>),
	/// Disable acknowledgments.
	StartNoAckMode,
	/// Invoke a command on the server.  The server defines commands
	/// and how to parse them.
	Invoke(Vec<u8>),
	/// Enable or disable address space randomization.
	AddressRandomization(bool),
	/// Enable or disable catching of syscalls.
	CatchSyscalls(Option<Vec<u64>>),
	/// Set the list of pass signals.
	PassSignals(Vec<u64>),
	/// Set the list of program signals.
	ProgramSignals(Vec<u64>),
	/// Get a string description of a thread.
	ThreadInfo(ThreadId),
	/// Get a list of all active threads
	ThreadList(bool),
	/// Get a list of all active processes (LLDB ex)
	ProcessList(bool),
	/// Get Target triple etc.
	HostInfo,
	/// Read features (target.xml)
	FeatureRead {
		name: String,
		offset: u64,
		length: u64,
	},
}

/// Part of a process id.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Id {
	/// A process or thread id.  This value may not be 0 or -1.
	Id(u32),
	/// A special form meaning all processes or all threads of a given
	/// process.
	All,
	/// A special form meaning any process or any thread of a given
	/// process.
	Any,
}

/// A thread identifier.  In the RSP this is just a numeric handle
/// that is passed across the wire.  It needn't correspond to any real
/// thread or process id (though obviously it may be more convenient
/// when it does).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ThreadId {
	/// The process id.
	pub pid: Id,
	/// The thread id.
	pub tid: Id,
}

/// A process identifier for LLDBs qfProcessInfo.
#[derive(Clone, Debug, PartialEq)]
pub struct ProcessInfo {
	pub name: String,
	pub pid: Id,
	pub triple: String,
}

/// A descriptor for a watchpoint.  The particular semantics of the watchpoint
/// (watching memory for read or write access) are addressed elsewhere.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Watchpoint {
	/// The address.
	pub addr: u64,

	/// The number of bytes covered.
	pub n_bytes: u64,
}

impl Watchpoint {
	fn new(addr: u64, n_bytes: u64) -> Watchpoint {
		Watchpoint { addr, n_bytes }
	}
}

/// Target-specific bytecode.
#[derive(Clone, Debug, PartialEq)]
pub struct Bytecode {
	/// The bytecodes.
	pub bytecode: Vec<u8>,
}

/// A descriptor for a breakpoint.  The particular implementation technique
/// of the breakpoint, hardware or software, is handled elsewhere.
#[derive(Clone, Debug, PartialEq)]
pub struct Breakpoint {
	/// The address.
	pub addr: u64,

	/// The kind of breakpoint.  This field is generally 0 and its
	/// interpretation is target-specific.  A typical use of it is for
	/// targets that support multiple execution modes (e.g. ARM/Thumb);
	/// different values for this field would identify the kind of code
	/// region in which the breakpoint is being inserted.
	pub kind: u64,

	/// An optional list of target-specific bytecodes representing
	/// conditions.  Each condition should be evaluated by the target when
	/// the breakpoint is hit to determine whether the hit should be reported
	/// back to the debugger.
	pub conditions: Option<Vec<Bytecode>>,

	/// An optional list of target-specific bytecodes representing commands.
	/// These commands should be evaluated when a breakpoint is hit; any
	/// results are not reported back to the debugger.
	pub commands: Option<Vec<Bytecode>>,
}

impl Breakpoint {
	fn new(
		addr: u64,
		kind: u64,
		conditions: Option<Vec<Bytecode>>,
		commands: Option<Vec<Bytecode>>,
	) -> Breakpoint {
		Breakpoint {
			addr,
			kind,
			conditions,
			commands,
		}
	}
}

/// A descriptor for a region of memory.
#[derive(Clone, Debug, PartialEq)]
pub struct MemoryRegion {
	/// The base address.
	pub address: u64,
	/// The length.
	pub length: u64,
}

impl MemoryRegion {
	fn new(address: u64, length: u64) -> MemoryRegion {
		MemoryRegion { address, length }
	}
}

/// The name of certain vCont features to be addressed when queried
/// for which are supported.
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum VContFeature {
	/// Indicate that you support continuing until breakpoint
	Continue = b'c',
	/// Indicate that you support continuing with a signal
	ContinueWithSignal = b'C',
	/// Indicate that you support singlestepping one instruction
	Step = b's',
	/// Indicate that you support singlestepping with a signal
	StepWithSignal = b'S',
	/// Indicate that you support stopping a thread
	Stop = b't',
	/// Indicate that you support singlestepping while inside of a range
	RangeStep = b'r',
}

/// vCont commands
#[derive(Clone, Debug, PartialEq)]
pub enum VCont {
	/// Continue until breakpoint, signal or exit
	Continue,
	/// Like `Continue`, but replace any current signal with a
	/// specified one
	ContinueWithSignal(u8),
	/// Step one machine instruction
	Step,
	/// Like `Step`, but replace any current signal with a specified
	/// one
	StepWithSignal(u8),
	/// Only relevant in non-stop mode. Stop a thread and when
	/// queried, indicate a stop with signal 0
	Stop,
	/// Keep stepping until instruction pointer is outside of
	/// specified range. May also spuriously stop, such as when a
	/// breakpoint is reached.
	RangeStep(Range<u64>),
}

/// GDB remote protocol commands, as defined in (the GDB documentation)[1]
/// [1]: https://sourceware.org/gdb/onlinedocs/gdb/Packets.html#Packets
#[derive(Clone, Debug, PartialEq)]
enum Command<'a> {
	/// Detach from a process or from all processes.
	Detach(Option<u64>),
	/// Enable extended mode.
	EnableExtendedMode,
	/// Indicate the reason the target halted.
	TargetHaltReason,
	// Read general registers.
	ReadGeneralRegisters,
	// Write general registers.
	WriteGeneralRegisters(Vec<u8>),
	// Read a single register.
	ReadRegister(u64),
	// Write a single register.
	WriteRegister(u64, Vec<u8>),
	// Kill request.  The argument is the optional PID, provided when the vKill
	// packet was used, and None when the k packet was used.
	Kill(Option<u64>),
	// Read specified region of memory.
	ReadMemory(MemoryRegion),
	// Write specified region of memory.
	WriteMemory(MemoryRegion, Vec<u8>),
	Query(Query<'a>),
	Reset,
	PingThread(ThreadId),
	CtrlC,
	UnknownV,
	/// Set the current thread for future commands, such as `ReadRegister`.
	SetCurrentThread(ThreadId),
	/// Insert a software breakpoint.
	InsertSoftwareBreakpoint(Breakpoint),
	/// Insert a hardware breakpoint
	InsertHardwareBreakpoint(Breakpoint),
	/// Insert a write watchpoint.
	InsertWriteWatchpoint(Watchpoint),
	/// Insert a read watchpoint.
	InsertReadWatchpoint(Watchpoint),
	/// Insert an access watchpoint.
	InsertAccessWatchpoint(Watchpoint),
	/// Remove a software breakpoint.
	RemoveSoftwareBreakpoint(Breakpoint),
	/// Remove a hardware breakpoint.
	RemoveHardwareBreakpoint(Breakpoint),
	/// Remove a write watchpoint.
	RemoveWriteWatchpoint(Watchpoint),
	/// Remove a read watchpoint.
	RemoveReadWatchpoint(Watchpoint),
	/// Remove an access watchpoint.
	RemoveAccessWatchpoint(Watchpoint),
	/// Query for a list of supported vCont features.
	VContSupported,
	/// Resume with different actions for each thread. Choose the
	/// first matching thread in the list.
	VCont(Vec<(VCont, Option<ThreadId>)>),
}

named!(
	gdbfeature<Known>,
	map!(map_res!(is_not_s!(";="), str::from_utf8), |s| {
		match GDBFeature::from_str(s) {
			Ok(f) => Known::Yes(f),
			Err(_) => Known::No(s),
		}
	})
);

fn gdbfeaturesupported<'a>(i: &'a [u8]) -> IResult<&'a [u8], GDBFeatureSupported<'a>> {
	flat_map!(i, is_not!(";"), |f: &'a [u8]| {
		match f.split_last() {
			None => IResult::Incomplete(Needed::Size(2)),
			Some((&b'+', first)) => map!(first, gdbfeature, |feat| GDBFeatureSupported(
				feat,
				FeatureSupported::Yes
			)),
			Some((&b'-', first)) => map!(first, gdbfeature, |feat| GDBFeatureSupported(
				feat,
				FeatureSupported::No
			)),
			Some((_, _)) => map!(
				f,
				separated_pair!(
					gdbfeature,
					tag!("="),
					map_res!(is_not!(";"), str::from_utf8)
				),
				|(feat, value)| GDBFeatureSupported(feat, FeatureSupported::Value(value))
			),
		}
	})
}

named!(q_search_memory<&[u8], (u64, u64, Vec<u8>)>,
	   complete!(do_parse!(
		   tag!("qSearch:memory:") >>
		   address: hex_value >>
		   tag!(";") >>
		   length: hex_value >>
		   tag!(";") >>
		   data: hex_byte_sequence >>
		   (address, length, data))));

named!(q_read_feature<&[u8], (&str, u64, u64)>,
	   complete!(do_parse!(
		   tag!("qXfer:features:read:") >>
		   filename: map!(is_not_s!(":"), |s| std::str::from_utf8(s).unwrap()) >>
		   tag!(":") >>
		   offset: hex_value >>
		   tag!(",") >>
		   length: hex_value >>
		   (filename, offset, length))));

fn query<'a>(i: &'a [u8]) -> IResult<&'a [u8], Query<'a>> {
	alt_complete!(i,
	tag!("qC") => { |_| Query::CurrentThread }
	| preceded!(tag!("qSupported"),
				preceded!(tag!(":"),
						  separated_list_complete!(tag!(";"),
												   gdbfeaturesupported))) => {
		|features: Vec<GDBFeatureSupported<'a>>| Query::SupportedFeatures(features)
	}
	| q_read_feature => {
		|(filename, offset, length): (&str, u64, u64)| Query::FeatureRead {
			name: filename.to_string(),
			offset, length,
		}
	}
	| preceded!(tag!("qRcmd,"), hex_byte_sequence) => {
		|bytes| Query::Invoke(bytes)
	}
	| q_search_memory => {
		|(address, length, bytes)| Query::SearchMemory { address, length, bytes }
	}
	| tag!("QStartNoAckMode") => { |_| Query::StartNoAckMode }
	| preceded!(tag!("qAttached:"), hex_value) => {
		|value| Query::Attached(Some(value))
	}
	| tag!("qAttached") => { |_| Query::Attached(None) }
	| tag!("qfThreadInfo") => { |_| Query::ThreadList(true) }
	| tag!("qsThreadInfo") => { |_| Query::ThreadList(false) }
	| tag!("QDisableRandomization:0") => { |_| Query::AddressRandomization(true) }
	| tag!("QDisableRandomization:1") => { |_| Query::AddressRandomization(false) }
	| tag!("QCatchSyscalls:0") => { |_| Query::CatchSyscalls(None) }
	| preceded!(tag!("QCatchSyscalls:1"),
				many0!(preceded!(tag!(";"), hex_value))) => {
		|syscalls| Query::CatchSyscalls(Some(syscalls))
	}
	| preceded!(tag!("QPassSignals:"),
				separated_list_complete!(tag!(";"), hex_value)) => {
		|signals| Query::PassSignals(signals)
	}
	| preceded!(tag!("QProgramSignals:"),
				separated_nonempty_list_complete!(tag!(";"), hex_value)) => {
		|signals| Query::ProgramSignals(signals)
	}
	| preceded!(tag!("qThreadExtraInfo,"), parse_thread_id) => {
		|thread_id| Query::ThreadInfo(thread_id)
	}
	| tag!("qfProcessInfo") => { |_| Query::ProcessList(true) }
	| tag!("qsProcessInfo") => { |_| Query::ProcessList(false) }
	| tag!("qHostInfo") => { |_| Query::HostInfo }
	)
}

// TODO: should the caller be responsible for determining whether they actually
// wanted a u32, or should we provide different versions of this function with
// extra checking?
named!(hex_value<&[u8], u64>,
map!(take_while1!(&nom::is_hex_digit),
	 |hex| {
		 let s = str::from_utf8(hex).unwrap();
		 let r = u64::from_str_radix(s, 16);
		 r.unwrap()
	 }));

named!(hex_digit<&[u8], char>,
	   one_of!("0123456789abcdefABCDEF"));

named!(hex_byte<&[u8], u8>,
	   do_parse!(
		   digit0: hex_digit >>
		   digit1: hex_digit >>
		   ((16 * digit0.to_digit(16).unwrap() + digit1.to_digit(16).unwrap()) as u8)
	   )
);

named!(hex_byte_sequence<&[u8], Vec<u8>>,
	   many1!(hex_byte));

named!(write_memory<&[u8], (u64, u64, Vec<u8>)>,
	   complete!(do_parse!(
		   tag!("M") >>
		   address: hex_value >>
		   tag!(",") >>
		   length: hex_value >>
		   tag!(":") >>
		   data: hex_byte_sequence >>
		   (address, length, data))));

named!(binary_byte<&[u8], u8>,
	   alt_complete!(
		   preceded!(tag!("}"), take!(1)) => { |b: &[u8]| b[0] ^ 0x20 } |
		   take!(1) => { |b: &[u8]| b[0] }));

named!(binary_byte_sequence<&[u8], Vec<u8>>,
	   many1!(binary_byte));

named!(write_memory_binary<&[u8], (u64, u64, Vec<u8>)>,
	   complete!(do_parse!(
		   tag!("X") >>
		   address: hex_value >>
		   tag!(",") >>
		   length: hex_value >>
		   tag!(":") >>
		   data: binary_byte_sequence >>
		   (address, length, data))));

named!(read_memory<&[u8], (u64, u64)>,
	   preceded!(tag!("m"),
				 separated_pair!(hex_value,
								 tag!(","),
								 hex_value)));

named!(read_register<&[u8], u64>,
	   preceded!(tag!("p"), hex_value));

named!(write_register<&[u8], (u64, Vec<u8>)>,
	   preceded!(tag!("P"),
				 separated_pair!(hex_value,
								 tag!("="),
								 hex_byte_sequence)));

named!(write_general_registers<&[u8], Vec<u8>>,
	   preceded!(tag!("G"), hex_byte_sequence));

// Helper for parse_thread_id that parses a single thread-id element.
named!(parse_thread_id_element<&[u8], Id>,
	   alt_complete!(tag!("0") => { |_| Id::Any }
					 | tag!("-1") => { |_| Id::All }
					 | hex_value => { |val: u64| Id::Id(val as u32) }));

// Parse a thread-id.
named!(parse_thread_id<&[u8], ThreadId>,
alt_complete!(parse_thread_id_element => { |pid| ThreadId { pid, tid: Id::Any } }
			  | preceded!(tag!("p"),
						  separated_pair!(parse_thread_id_element,
										  tag!("."),
										  parse_thread_id_element)) => {
				  |pair: (Id, Id)| ThreadId { pid: pair.0, tid: pair.1 }
			  }
			  | preceded!(tag!("p"), parse_thread_id_element) => {
				  |id: Id| ThreadId { pid: id, tid: Id::All }
			  }));

// Parse the T packet.
named!(parse_ping_thread<&[u8], ThreadId>,
	   preceded!(tag!("T"), parse_thread_id));

fn v_command(i: &[u8]) -> IResult<&[u8], Command> {
	alt_complete!(i,
	tag!("vCtrlC") => { |_| Command::CtrlC }
	| preceded!(tag!("vCont"),
				alt_complete!(tag!("?") => { |_| Command::VContSupported }
							  | many0!(do_parse!(
								  tag!(";") >>
								  action: alt_complete!(tag!("c") => { |_| VCont::Continue }
														| preceded!(tag!("C"), hex_byte) => { |sig| VCont::ContinueWithSignal(sig) }
														| tag!("s") => { |_| VCont::Step }
														| preceded!(tag!("S"), hex_byte) => { |sig| VCont::StepWithSignal(sig) }
														| tag!("t") => { |_| VCont::Stop }
														| do_parse!(tag!("r") >>
																	start: hex_value >>
																	tag!(",") >>
																	end: hex_value >>
																	(start, end)) => { |(start, end)| VCont::RangeStep(start..end) }
								  ) >>
								  thread: opt!(complete!(preceded!(tag!(":"), parse_thread_id))) >>
								  (action, thread)
							  )) => { |actions| Command::VCont(actions) }
				)) => {
		|c| c
	}
	| preceded!(tag!("vKill;"), hex_value) => {
		|pid| Command::Kill(Some(pid))
	}
	// TODO: log the unknown command for debugging purposes.
	| preceded!(tag!("v"), take_till!(|_| { false })) => {
		|_| Command::UnknownV
	})
}

// Parse the H packet.
named!(parse_h_packet<&[u8], ThreadId>,
	   preceded!(tag!("Hg"), parse_thread_id));

// Parse the D packet.
named!(parse_d_packet<&[u8], Option<u64>>,
	   alt_complete!(preceded!(tag!("D;"), hex_value) => {
		   |pid| Some(pid)
	   }
	   | tag!("D") => { |_| None }));

#[derive(Copy, Clone)]
enum ZAction {
	Insert,
	Remove,
}

named!(parse_z_action<&[u8], ZAction>,
	   alt_complete!(tag!("z") => { |_| ZAction::Remove } |
					 tag!("Z") => { |_| ZAction::Insert }));

#[derive(Copy, Clone)]
enum ZType {
	SoftwareBreakpoint,
	HardwareBreakpoint,
	WriteWatchpoint,
	ReadWatchpoint,
	AccessWatchpoint,
}

named!(parse_z_type<&[u8], ZType>,
	   alt_complete!(tag!("0") => { |_| ZType::SoftwareBreakpoint } |
					 tag!("1") => { |_| ZType::HardwareBreakpoint } |
					 tag!("2") => { |_| ZType::WriteWatchpoint } |
					 tag!("3") => { |_| ZType::ReadWatchpoint } |
					 tag!("4") => { |_| ZType::AccessWatchpoint }));

named!(parse_cond_or_command_expression<&[u8], Bytecode>,
	   do_parse!(tag!("X") >>
				 len: hex_value >>
				 tag!(",") >>
				 expr: take!(len) >>
				 (Bytecode { bytecode: expr.to_vec() })));

named!(parse_condition_list<&[u8], Vec<Bytecode>>,
	   do_parse!(tag!(";") >>
				 list: many1!(parse_cond_or_command_expression) >>
				 (list)));

fn maybe_condition_list<'a>(i: &'a [u8]) -> IResult<&'a [u8], Option<Vec<Bytecode>>> {
	// An Incomplete here really means "not enough input to match a
	// condition list", and that's OK.  An Error is *probably* that the
	// input contains a command list rather than a condition list; the
	// two are identical in their first character.  So just ignore that
	// FIXME.
	match parse_condition_list(i) {
		Done(rest, v) => Done(rest, Some(v)),
		Incomplete(_i) => Done(i, None),
		Error(_) => Done(i, None),
	}
}

named!(parse_command_list<&[u8], Vec<Bytecode>>,
	   // FIXME we drop the persistence flag here.
	   do_parse!(tag!(";cmds") >>
				 list: alt_complete!(do_parse!(persist_flag: hex_value >>
											   tag!(",") >>
											   cmd_list: many1!(parse_cond_or_command_expression) >>
											   (cmd_list)) |
									 many1!(parse_cond_or_command_expression)) >>
				 (list)));

fn maybe_command_list<'a>(i: &'a [u8]) -> IResult<&'a [u8], Option<Vec<Bytecode>>> {
	// An Incomplete here really means "not enough input to match a
	// command list", and that's OK.
	match parse_command_list(i) {
		Done(rest, v) => Done(rest, Some(v)),
		Incomplete(_i) => Done(i, None),
		Error(e) => Error(e),
	}
}

named!(parse_cond_and_command_list<&[u8], (Option<Vec<Bytecode>>,
										   Option<Vec<Bytecode>>)>,
	   do_parse!(cond_list: maybe_condition_list >>
				 cmd_list: maybe_command_list >>
				 (cond_list, cmd_list)));

fn parse_z_packet(i: &[u8]) -> IResult<&[u8], Command> {
	let (rest, (action, type_, addr, kind)) = try_parse!(
		i,
		do_parse!(
			action: parse_z_action
				>> type_: parse_z_type
				>> tag!(",") >> addr: hex_value
				>> tag!(",") >> kind: hex_value
				>> (action, type_, addr, kind)
		)
	);

	return match action {
		ZAction::Insert => insert_command(rest, type_, addr, kind),
		ZAction::Remove => Done(rest, remove_command(type_, addr, kind)),
	};

	fn insert_command(rest: &[u8], type_: ZType, addr: u64, kind: u64) -> IResult<&[u8], Command> {
		match type_ {
			// Software and hardware breakpoints both permit optional condition
			// lists and commands that are evaluated on the target when
			// breakpoints are hit.
			ZType::SoftwareBreakpoint | ZType::HardwareBreakpoint => {
				let (rest, (cond_list, cmd_list)) = parse_cond_and_command_list(rest).unwrap();
				let c = (match type_ {
					ZType::SoftwareBreakpoint => Command::InsertSoftwareBreakpoint,
					ZType::HardwareBreakpoint => Command::InsertHardwareBreakpoint,
					// Satisfy rustc's checking
					_ => panic!("cannot get here"),
				})(Breakpoint::new(addr, kind, cond_list, cmd_list));
				Done(rest, c)
			}
			ZType::WriteWatchpoint => Done(
				rest,
				Command::InsertWriteWatchpoint(Watchpoint::new(addr, kind)),
			),
			ZType::ReadWatchpoint => Done(
				rest,
				Command::InsertReadWatchpoint(Watchpoint::new(addr, kind)),
			),
			ZType::AccessWatchpoint => Done(
				rest,
				Command::InsertAccessWatchpoint(Watchpoint::new(addr, kind)),
			),
		}
	}

	fn remove_command<'a>(type_: ZType, addr: u64, kind: u64) -> Command<'a> {
		match type_ {
			ZType::SoftwareBreakpoint => {
				Command::RemoveSoftwareBreakpoint(Breakpoint::new(addr, kind, None, None))
			}
			ZType::HardwareBreakpoint => {
				Command::RemoveHardwareBreakpoint(Breakpoint::new(addr, kind, None, None))
			}
			ZType::WriteWatchpoint => Command::RemoveWriteWatchpoint(Watchpoint::new(addr, kind)),
			ZType::ReadWatchpoint => Command::RemoveReadWatchpoint(Watchpoint::new(addr, kind)),
			ZType::AccessWatchpoint => Command::RemoveAccessWatchpoint(Watchpoint::new(addr, kind)),
		}
	}
}

fn command(i: &[u8]) -> IResult<&[u8], Command> {
	alt!(i,
		 tag!("!") => { |_|   Command::EnableExtendedMode }
		 | tag!("?") => { |_| Command::TargetHaltReason }
		 | tag!("c") => { |_| Command::VCont(vec![(VCont::Continue, None)]) } // simluate c as VCont;c
		 | parse_d_packet => { |pid| Command::Detach(pid) }
		 | tag!("g") => { |_| Command::ReadGeneralRegisters }
		 | write_general_registers => { |bytes| Command::WriteGeneralRegisters(bytes) }
		 | parse_h_packet => { |thread_id| Command::SetCurrentThread(thread_id) }
		 | tag!("k") => { |_| Command::Kill(None) }
		 | read_memory => { |(addr, length)| Command::ReadMemory(MemoryRegion::new(addr, length)) }
		 | write_memory => { |(addr, length, bytes)| Command::WriteMemory(MemoryRegion::new(addr, length), bytes) }
		 | read_register => { |regno| Command::ReadRegister(regno) }
		 | write_register => { |(regno, bytes)| Command::WriteRegister(regno, bytes) }
		 | query => { |q| Command::Query(q) }
		 | tag!("r") => { |_| Command::Reset }
		 | preceded!(tag!("R"), take!(2)) => { |_| Command::Reset }
		 | parse_ping_thread => { |thread_id| Command::PingThread(thread_id) }
		 | v_command => { |command| command }
		 | write_memory_binary => { |(addr, length, bytes)| Command::WriteMemory(MemoryRegion::new(addr, length), bytes) }
		 | parse_z_packet => { |command| command }
	)
}

/// An error as returned by a `Handler` method.
#[allow(dead_code)]
#[derive(Debug)]
pub enum Error {
	/// A plain error.  The meaning of the value is not defined by the
	/// protocol.  Different values can therefore be used by a handler
	/// for debugging purposes.
	Error(u8),
	/// The request is not implemented.  Note that, in some cases, the
	/// protocol implementation tells the client that a feature is implemented;
	/// if the handler method then returns `Unimplemented`, the client will
	/// be confused.  So, normally it is best either to not implement
	/// a `Handler` method, or to return `Error` from implementations.
	Unimplemented,
}

/// simple wrapper around File contents. TODO: extend, so we can return errors as well.
#[derive(Clone, Debug)]
pub struct FileData(pub String);

/// The `qAttached` packet lets the client distinguish between
/// attached and created processes, so that it knows whether to send a
/// detach request when disconnecting.
#[derive(Clone, Copy, Debug)]
#[allow(dead_code)]
pub enum ProcessType {
	/// The process already existed and was attached to.
	Attached,
	/// The process was created by the server.
	Created,
}

/// The possible reasons for a thread to stop.
#[derive(Clone, Copy, Debug)]
#[allow(dead_code)]
pub enum StopReason {
	/// Process stopped due to a signal.
	Signal(u8),
	/// The process with the given PID exited with the given status.
	Exited(u64, u8),
	/// The process with the given PID terminated due to the given
	/// signal.
	ExitedWithSignal(u64, u8),
	/// The indicated thread exited with the given status.
	ThreadExited(ThreadId, u64),
	/// There are no remaining resumed threads.
	// FIXME we should report the 'no-resumed' feature in response to
	// qSupports before emitting this; and we should also check that
	// the client knows about it.
	NoMoreThreads,
	// FIXME implement these as well.  These are used by the T packet,
	// which can also send along registers.
	// Watchpoint(u64),
	// ReadWatchpoint(u64),
	// AccessWatchpoint(u64),
	// SyscallEntry(u8),
	// SyscallExit(u8),
	// LibraryChange,
	// ReplayLogStart,
	// ReplayLogEnd,
	// SoftwareBreakpoint,
	// HardwareBreakpoint,
	// Fork(ThreadId),
	// VFork(ThreadId),
	// VForkDone,
	// Exec(String),
	// NewThread(ThreadId),
}

/// This trait should be implemented by servers.  Methods in the trait
/// generally default to returning `Error::Unimplemented`; but some
/// exceptions are noted below.  Methods that must be implemented in
/// order for the server to work at all do not have a default
/// implementation.
pub trait Handler {
	/// Return a vector of additional features supported by this handler.
	/// Note that there currently is no way to override the built-in
	/// features that are always handled by the protocol
	/// implementation.
	fn query_supported_features(&self) -> Vec<String> {
		vec![]
	}

	/// Indicate whether the process in question already existed, and
	/// was attached to; or whether it was created by this server.
	fn attached(&self, _pid: Option<u64>) -> Result<ProcessType, Error>;

	/// Detach from the process.
	fn detach(&self, _pid: Option<u64>) -> Result<(), Error> {
		Err(Error::Unimplemented)
	}

	/// Kill the indicated process.  If no process is given, then the
	/// precise effect is unspecified; but killing any or all
	/// processes, or even rebooting an entire bare-metal target,
	/// would be appropriate.
	fn kill(&self, _pid: Option<u64>) -> Result<(), Error> {
		Err(Error::Unimplemented)
	}

	/// Check whether the indicated thread is alive.  If alive, return
	/// `()`.  Otherwise, return an error.
	fn ping_thread(&self, _id: ThreadId) -> Result<(), Error> {
		Err(Error::Unimplemented)
	}

	/// Read a memory region.
	fn read_memory(&self, _region: MemoryRegion) -> Result<Vec<u8>, Error> {
		Err(Error::Unimplemented)
	}

	/// Write the provided bytes to memory at the given address.
	fn write_memory(&self, _address: u64, _bytes: &[u8]) -> Result<(), Error> {
		Err(Error::Unimplemented)
	}

	/// Read the contents of the indicated register.  The results
	/// should be in target byte order.  Note that a value-based API
	/// is not provided here because on some architectures, there are
	/// registers wider than ordinary integer types.
	fn read_register(&self, _register: u64) -> Result<Vec<u8>, Error> {
		Err(Error::Unimplemented)
	}

	/// Set the contents of the indicated register to the given
	/// contents.  The contents are in target byte order.  Note that a
	/// value-based API is not provided here because on some
	/// architectures, there are registers wider than ordinary integer
	/// types.
	fn write_register(&self, _register: u64, _contents: &[u8]) -> Result<(), Error> {
		Err(Error::Unimplemented)
	}

	/// Return the general registers.  The registers are returned as a
	/// vector of bytes, with the registers appearing contiguously in
	/// a target-specific order, with the bytes laid out in the target
	/// byte order.
	fn read_general_registers(&self) -> Result<Vec<u8>, Error> {
		Err(Error::Unimplemented)
	}

	/// Write the general registers.  The registers are specified as a
	/// vector of bytes, with the registers appearing contiguously in
	/// a target-specific order, with the bytes laid out in the target
	/// byte order.
	fn write_general_registers(&self, _contents: &[u8]) -> Result<(), Error> {
		Err(Error::Unimplemented)
	}

	/// Return the identifier of the current thread.
	fn current_thread(&self) -> Result<Option<ThreadId>, Error> {
		Ok(None)
	}

	/// Set the current thread for future operations.
	fn set_current_thread(&self, _id: ThreadId) -> Result<(), Error> {
		Err(Error::Unimplemented)
	}

	/// Search memory.  The search begins at the given address, and
	/// ends after length bytes have been searched.  If the provided
	/// bytes are not seen, `None` should be returned; otherwise, the
	/// address at which the bytes were found should be returned.
	fn search_memory(
		&self,
		_address: u64,
		_length: u64,
		_bytes: &[u8],
	) -> Result<Option<u64>, Error> {
		Err(Error::Unimplemented)
	}

	/// Return the reason that the inferior has halted.
	fn halt_reason(&self) -> Result<StopReason, Error>;

	/// Invoke a command.  The command is just a sequence of bytes
	/// (typically ASCII characters), to be interpreted by the server
	/// in any way it likes.  The result is output to send back to the
	/// client.  This is used to implement gdb's `monitor` command.
	fn invoke(&self, _: &[u8]) -> Result<String, Error> {
		Err(Error::Unimplemented)
	}

	/// Enable or disable address space randomization.  This setting
	/// should be used when launching a new process.
	fn set_address_randomization(&self, _enable: bool) -> Result<(), Error> {
		Err(Error::Unimplemented)
	}

	/// Start or stop catching syscalls.  If the argument is `None`, then
	/// stop catching syscalls.  Otherwise, start catching syscalls.
	/// If any syscalls are specified, then only those need be caught;
	/// however, it is ok to report syscall stops that aren't in the
	/// list if that is convenient.
	fn catch_syscalls(&self, _syscalls: Option<Vec<u64>>) -> Result<(), Error> {
		Err(Error::Unimplemented)
	}

	/// Set the list of "pass signals".  A signal marked as a pass
	/// signal can be delivered to the inferior.  No stopping or
	/// notification of the client is required.
	fn set_pass_signals(&self, _signals: Vec<u64>) -> Result<(), Error> {
		Ok(())
	}

	/// Set the list of "program signals".  A signal marked as a
	/// program signal can be delivered to the inferior; other signals
	/// should be silently discarded.
	fn set_program_signals(&self, _signals: Vec<u64>) -> Result<(), Error> {
		Ok(())
	}

	/// Return information about a given thread.  The returned
	/// information is just a string description that can be presented
	/// to the user.
	fn thread_info(&self, _thread: ThreadId) -> Result<String, Error> {
		Err(Error::Unimplemented)
	}

	/// Return a list of all active thread IDs. GDB will call this in
	/// a paging fashion: First query has `reset` set to true and
	/// should reply with the first chunk of threads. Further queries
	/// have `reset` set to false and should respond with a chunk of
	/// remaining threads, until completion which should return an
	/// empty list to signify it's the end.
	///
	/// Each initial GDB connection will query this and the very first
	/// thread ID will be stopped - so ensure the first ID is ready to
	/// be stopped and inspected by GDB.
	fn thread_list(&self, _reset: bool) -> Result<Vec<ThreadId>, Error> {
		Err(Error::Unimplemented)
	}

	/// Return a list of all active processes for LLDB. Called in
	/// a paging fashion: First query has `reset` set to true and
	/// should reply with the first chunk of threads. Further queries
	/// have `reset` set to false and should respond with a chunk of
	/// remaining threads, until completion which should return an
	/// empty list to signify it's the end.
	fn process_list(&self, _reset: bool) -> Result<Vec<ProcessInfo>, Error> {
		Err(Error::Unimplemented)
	}

	fn read_feature(&self, _name: String, _offset: u64, _length: u64) -> Result<FileData, Error> {
		Err(Error::Unimplemented)
	}

	/// Insert a software breakpoint.
	fn insert_software_breakpoint(&self, _breakpoint: Breakpoint) -> Result<(), Error> {
		Err(Error::Unimplemented)
	}

	/// Insert a hardware breakpoint.
	fn insert_hardware_breakpoint(&self, _breakpoint: Breakpoint) -> Result<(), Error> {
		Err(Error::Unimplemented)
	}

	/// Insert a write watchpoint.
	fn insert_write_watchpoint(&self, _watchpoint: Watchpoint) -> Result<(), Error> {
		Err(Error::Unimplemented)
	}

	/// Insert a read watchpoint.
	fn insert_read_watchpoint(&self, _watchpoint: Watchpoint) -> Result<(), Error> {
		Err(Error::Unimplemented)
	}

	/// Insert an access watchpoint.
	fn insert_access_watchpoint(&self, _watchpoint: Watchpoint) -> Result<(), Error> {
		Err(Error::Unimplemented)
	}

	/// Remove a software breakpoint.
	fn remove_software_breakpoint(&self, _breakpoint: Breakpoint) -> Result<(), Error> {
		Err(Error::Unimplemented)
	}

	/// Remove a hardware breakpoint.
	fn remove_hardware_breakpoint(&self, _breakpoint: Breakpoint) -> Result<(), Error> {
		Err(Error::Unimplemented)
	}

	/// Remove a write watchpoint.
	fn remove_write_watchpoint(&self, _watchpoint: Watchpoint) -> Result<(), Error> {
		Err(Error::Unimplemented)
	}

	/// Remove a read watchpoint.
	fn remove_read_watchpoint(&self, _watchpoint: Watchpoint) -> Result<(), Error> {
		Err(Error::Unimplemented)
	}

	/// Remove an access watchpoint.
	fn remove_access_watchpoint(&self, _watchpoint: Watchpoint) -> Result<(), Error> {
		Err(Error::Unimplemented)
	}

	/// Query for a list of supported vCont features.
	fn query_supported_vcont(&self) -> Result<Cow<'static, [VContFeature]>, Error> {
		Err(Error::Unimplemented)
	}

	/// Resume with different actions for each thread. Choose the
	/// first matching thread in the list.
	fn vcont(&self, _request: Vec<(VCont, Option<ThreadId>)>) -> Result<StopReason, Error> {
		Err(Error::Unimplemented)
	}

	/// Get target triple etc.
	fn host_info(&self) -> Result<String, Error> {
		Err(Error::Unimplemented)
	}

	/// Return true when the gdb-event-loop should be exited.
	fn should_cont(&self) -> Option<VCont>;
}

#[derive(Debug)]
pub enum Response<'a> {
	Empty,
	Ok,
	Error(u8),
	String(Cow<'a, str>),
	Output(String),
	Bytes(Vec<u8>),
	CurrentThread(Option<ThreadId>),
	ProcessType(ProcessType),
	Stopped(StopReason),
	SearchResult(Option<u64>),
	VContFeatures(Cow<'static, [VContFeature]>),
	ThreadList(Vec<ThreadId>),
	ProcessList(Vec<ProcessInfo>),
	File(FileData),
}

impl<'a, T> From<Result<T, Error>> for Response<'a>
where
	Response<'a>: From<T>,
{
	fn from(result: Result<T, Error>) -> Self {
		match result {
			Result::Ok(val) => val.into(),
			Result::Err(Error::Error(val)) => Response::Error(val),
			Result::Err(Error::Unimplemented) => {
				println!("Unimplemented!");
				Response::Empty
			}
		}
	}
}

impl<'a> From<()> for Response<'a> {
	fn from(_: ()) -> Self {
		Response::Ok
	}
}

impl<'a> From<Vec<u8>> for Response<'a> {
	fn from(response: Vec<u8>) -> Self {
		Response::Bytes(response)
	}
}

impl<'a> From<FileData> for Response<'a> {
	fn from(response: FileData) -> Self {
		Response::File(response)
	}
}

impl<'a> From<Option<ThreadId>> for Response<'a> {
	fn from(response: Option<ThreadId>) -> Self {
		Response::CurrentThread(response)
	}
}

// This seems a bit specific -- what if some other handler method
// wants to return an Option<u64>?
impl<'a> From<Option<u64>> for Response<'a> {
	fn from(response: Option<u64>) -> Self {
		Response::SearchResult(response)
	}
}

impl<'a> From<ProcessType> for Response<'a> {
	fn from(process_type: ProcessType) -> Self {
		Response::ProcessType(process_type)
	}
}

impl<'a> From<StopReason> for Response<'a> {
	fn from(reason: StopReason) -> Self {
		Response::Stopped(reason)
	}
}

impl<'a> From<String> for Response<'a> {
	fn from(reason: String) -> Self {
		Response::String(Cow::Owned(reason) as Cow<str>)
	}
}

impl<'a> From<Cow<'static, [VContFeature]>> for Response<'a> {
	fn from(features: Cow<'static, [VContFeature]>) -> Self {
		Response::VContFeatures(features)
	}
}

impl<'a> From<Vec<ThreadId>> for Response<'a> {
	fn from(threads: Vec<ThreadId>) -> Self {
		Response::ThreadList(threads)
	}
}

impl<'a> From<Vec<ProcessInfo>> for Response<'a> {
	fn from(procs: Vec<ProcessInfo>) -> Self {
		Response::ProcessList(procs)
	}
}

fn get_thread_id(thread_id: ThreadId) -> String {
	let mut tid = String::new();
	// LLDB does not support multiprocess syntax!
	// Always just send thread
	/*tid.push_str("p");
	match thread_id.pid {
		Id::All => tid.push_str("-1"),
		Id::Any => tid.push_str( "0"),
		Id::Id(num) => tid.push_str(&format!("{:x}", num)),
	};
	tid.push_str(".");*/
	match thread_id.tid {
		Id::All => tid.push_str("-1"),
		Id::Any => tid.push_str("0"),
		Id::Id(num) => tid.push_str(&format!("{:x}", num)),
	};
	tid
}

fn get_process_info(p: &ProcessInfo) -> String {
	let mut out = String::new();
	out.push_str("pid:");
	match p.pid {
		Id::All => out.push_str("-1"),
		Id::Any => out.push_str("0"),
		Id::Id(num) => out.push_str(&format!("{:x}", num)),
	};
	out.push_str(&format!("name:{}", p.name));
	out.push_str(&format!("triple:{}", p.triple));
	out
}

/// get a byte vector we can send to remote from a response
impl<'a> From<Response<'a>> for Vec<u8> {
	fn from(response: Response) -> Vec<u8> {
		trace!("Response: {:?}", response);

		let mut rsp = String::new();
		match response {
			Response::Ok => "OK".into(),
			Response::Empty => "".into(),
			Response::Error(val) => format!("E{:02x}", val),
			Response::String(s) => format!("{}", s),
			Response::Output(s) => format!("O{}", s.as_bytes().to_hex()),
			Response::Bytes(bytes) => bytes.to_hex(),
			Response::File(data) => {
				if data.0.is_empty() {
					"l".into()
				} else {
					// LLDB is weird and does not decode our hex.
					format!("m{}", data.0 /*.as_bytes().to_hex()*/)
				}
			}
			Response::CurrentThread(tid) => {
				// This is incorrect if multiprocess hasn't yet been enabled.
				match tid {
					None => "OK".into(),
					Some(thread_id) => format!("QC{}", get_thread_id(thread_id)),
				}
			}
			Response::ProcessType(process_type) => match process_type {
				ProcessType::Attached => "1".into(),
				ProcessType::Created => "0".into(),
			},
			Response::SearchResult(maybe_addr) => match maybe_addr {
				Some(addr) => format!("1,{:x}", addr),
				None => "0".into(),
			},
			Response::Stopped(stop_reason) => {
				match stop_reason {
					StopReason::Signal(signo) => format!("S{:02x}", signo),
					StopReason::Exited(pid, status) => {
						// Non-multi-process gdb only accepts 2 hex digits
						// for the status.
						format!("W{:02x};process:{:x}", status, pid)
					}
					StopReason::ExitedWithSignal(pid, status) => {
						// Non-multi-process gdb only accepts 2 hex digits
						// for the status.
						format!("X{:x};process:{:x}", status, pid)
					}
					StopReason::ThreadExited(thread_id, status) => {
						format!("w{:x}{};", status, get_thread_id(thread_id))
					}
					StopReason::NoMoreThreads => "N".to_string(),
				}
			}
			Response::VContFeatures(features) => {
				rsp.push_str("vCont");
				for &feature in &*features {
					rsp.push_str(&format!(";{}", feature as u8 as char));
				}
				rsp
			}
			Response::ThreadList(threads) => {
				if threads.is_empty() {
					"l".into()
				} else {
					rsp.push_str("m");
					for (i, &id) in threads.iter().enumerate() {
						// Write separator
						if i != 0 {
							rsp.push_str(",");
						}
						rsp.push_str(&get_thread_id(id));
					}
					rsp
				}
			}
			Response::ProcessList(procs) => {
				if procs.is_empty() {
					"E00".into() // lldb spec just says error Exx where xx is hex
				} else {
					rsp.push_str("m");
					for (i, p) in procs.iter().enumerate() {
						// Write separator
						if i != 0 {
							rsp.push_str(",");
						}
						rsp.push_str(&get_process_info(p));
					}
					rsp
				}
			}
		}
		.as_bytes()
		.to_vec()
	}
}

fn handle_supported_features<'a, H>(
	handler: &H,
	_features: &[GDBFeatureSupported<'a>],
) -> Response<'static>
where
	H: Handler,
{
	let mut features = vec![
		format!("PacketSize={}", BUF_SIZE),
		//"QStartNoAckMode+".to_string(), gdb-protocol crate does not support no ack mode
		//"multiprocess+".to_string(), llvm does not support multiprocess syntax
		//"QDisableRandomization+".to_string(),
		//"QCatchSyscalls+".to_string(),
		//"QPassSignals+".to_string(),
		//"QProgramSignals+".to_string(),
	];
	let mut new_features = handler.query_supported_features();
	features.append(&mut new_features);
	Response::String(Cow::Owned(features.join(";")) as Cow<str>)
}

/// Handle a single packet `data` with `handler` and return response
pub fn handle_packet<'a, H>(data: &[u8], handler: &'a H) -> Result<Response<'a>, Error>
where
	H: Handler,
{
	let mut _no_ack_mode = false;
	let response = if let Done(_, command) = command(data) {
		debug!(
			"Successfully parsed command: {} into {:?}",
			String::from_utf8_lossy(data),
			command
		);
		match command {
			// We unconditionally support extended mode.
			Command::EnableExtendedMode => Response::Ok,
			Command::TargetHaltReason => handler.halt_reason()?.into(),
			Command::ReadGeneralRegisters => handler.read_general_registers()?.into(),
			Command::WriteGeneralRegisters(bytes) => {
				handler.write_general_registers(&bytes[..])?.into()
			}
			Command::Kill(None) => {
				// The k packet requires no response, so purposely
				// ignore the result.
				drop(handler.kill(None));
				Response::Empty
			}
			Command::Kill(pid) => handler.kill(pid)?.into(),
			Command::Reset => Response::Empty,
			Command::ReadRegister(regno) => handler.read_register(regno)?.into(),
			Command::WriteRegister(regno, bytes) => {
				handler.write_register(regno, &bytes[..])?.into()
			}
			Command::ReadMemory(region) => handler.read_memory(region)?.into(),
			Command::WriteMemory(region, bytes) => {
				// The docs don't really say what to do if the given
				// length disagrees with the number of bytes sent, so
				// just error if they disagree.
				if region.length as usize != bytes.len() {
					Response::Error(1)
				} else {
					handler.write_memory(region.address, &bytes[..])?.into()
				}
			}
			Command::SetCurrentThread(thread_id) => handler.set_current_thread(thread_id)?.into(),
			Command::Detach(pid) => handler.detach(pid)?.into(),

			Command::Query(Query::Attached(pid)) => handler.attached(pid)?.into(),
			Command::Query(Query::CurrentThread) => handler.current_thread()?.into(),
			Command::Query(Query::Invoke(cmd)) => match handler.invoke(&cmd[..]) {
				Result::Ok(val) => {
					if val.is_empty() {
						Response::Ok
					} else {
						Response::Output(val)
					}
				}
				Result::Err(Error::Error(val)) => Response::Error(val),
				Result::Err(Error::Unimplemented) => Response::Empty,
			},
			Command::Query(Query::SearchMemory {
				address,
				length,
				bytes,
			}) => handler.search_memory(address, length, &bytes[..])?.into(),
			Command::Query(Query::SupportedFeatures(features)) => {
				handle_supported_features(handler, &features)
			}
			Command::Query(Query::StartNoAckMode) => {
				_no_ack_mode = true;
				Response::Empty // gdb-protocol crate does not support no ack mode!
			}
			Command::Query(Query::AddressRandomization(randomize)) => {
				handler.set_address_randomization(randomize)?.into()
			}
			Command::Query(Query::CatchSyscalls(calls)) => handler.catch_syscalls(calls)?.into(),
			Command::Query(Query::PassSignals(signals)) => {
				handler.set_pass_signals(signals)?.into()
			}
			Command::Query(Query::ProgramSignals(signals)) => {
				handler.set_program_signals(signals)?.into()
			}
			Command::Query(Query::ThreadInfo(thread_info)) => {
				handler.thread_info(thread_info)?.into()
			}
			Command::Query(Query::ThreadList(reset)) => handler.thread_list(reset)?.into(),
			Command::Query(Query::ProcessList(reset)) => handler.process_list(reset)?.into(),
			Command::Query(Query::HostInfo) => handler.host_info()?.into(),
			Command::Query(Query::FeatureRead {
				name,
				offset,
				length,
			}) => handler.read_feature(name, offset, length)?.into(),
			Command::PingThread(thread_id) => handler.ping_thread(thread_id)?.into(),
			// Empty means "not implemented".
			Command::CtrlC => Response::Empty,

			// Unknown v commands are required to give an empty
			// response.
			Command::UnknownV => Response::Empty,

			Command::InsertSoftwareBreakpoint(bp) => handler.insert_software_breakpoint(bp)?.into(),
			Command::InsertHardwareBreakpoint(bp) => handler.insert_hardware_breakpoint(bp)?.into(),
			Command::InsertWriteWatchpoint(wp) => handler.insert_write_watchpoint(wp)?.into(),
			Command::InsertReadWatchpoint(wp) => handler.insert_read_watchpoint(wp)?.into(),
			Command::InsertAccessWatchpoint(wp) => handler.insert_access_watchpoint(wp)?.into(),
			Command::RemoveSoftwareBreakpoint(bp) => handler.remove_software_breakpoint(bp)?.into(),
			Command::RemoveHardwareBreakpoint(bp) => handler.remove_hardware_breakpoint(bp)?.into(),
			Command::RemoveWriteWatchpoint(wp) => handler.remove_write_watchpoint(wp)?.into(),
			Command::RemoveReadWatchpoint(wp) => handler.remove_read_watchpoint(wp)?.into(),
			Command::RemoveAccessWatchpoint(wp) => handler.remove_access_watchpoint(wp)?.into(),
			Command::VContSupported => handler.query_supported_vcont()?.into(),
			Command::VCont(list) => handler.vcont(list)?.into(),
		}
	} else {
		info!(
			"Command could not be parsed: {}",
			String::from_utf8_lossy(data)
		);
		Response::Empty
	};
	//Ok(no_ack_mode)
	Ok(response)
}

#[test]
fn test_gdbfeaturesupported() {
	assert_eq!(
		gdbfeaturesupported(&b"multiprocess+"[..]),
		Done(
			&b""[..],
			GDBFeatureSupported(Known::Yes(GDBFeature::multiprocess), FeatureSupported::Yes)
		)
	);
	assert_eq!(
		gdbfeaturesupported(&b"xmlRegisters=i386"[..]),
		Done(
			&b""[..],
			GDBFeatureSupported(
				Known::Yes(GDBFeature::xmlRegisters),
				FeatureSupported::Value("i386")
			)
		)
	);
	assert_eq!(
		gdbfeaturesupported(&b"qRelocInsn-"[..]),
		Done(
			&b""[..],
			GDBFeatureSupported(Known::Yes(GDBFeature::qRelocInsn), FeatureSupported::No)
		)
	);
	assert_eq!(
		gdbfeaturesupported(&b"vfork-events+"[..]),
		Done(
			&b""[..],
			GDBFeatureSupported(Known::Yes(GDBFeature::vfork_events), FeatureSupported::Yes)
		)
	);
	assert_eq!(
		gdbfeaturesupported(&b"vfork-events-"[..]),
		Done(
			&b""[..],
			GDBFeatureSupported(Known::Yes(GDBFeature::vfork_events), FeatureSupported::No)
		)
	);
	assert_eq!(
		gdbfeaturesupported(&b"unknown-feature+"[..]),
		Done(
			&b""[..],
			GDBFeatureSupported(Known::No("unknown-feature"), FeatureSupported::Yes)
		)
	);
	assert_eq!(
		gdbfeaturesupported(&b"unknown-feature-"[..]),
		Done(
			&b""[..],
			GDBFeatureSupported(Known::No("unknown-feature"), FeatureSupported::No)
		)
	);
}

#[test]
fn test_gdbfeature() {
	assert_eq!(
		gdbfeature(&b"multiprocess"[..]),
		Done(&b""[..], Known::Yes(GDBFeature::multiprocess))
	);
	assert_eq!(
		gdbfeature(&b"fork-events"[..]),
		Done(&b""[..], Known::Yes(GDBFeature::fork_events))
	);
	assert_eq!(
		gdbfeature(&b"some-unknown-feature"[..]),
		Done(&b""[..], Known::No("some-unknown-feature"))
	);
}

#[test]
fn test_query() {
	// From a gdbserve packet capture.
	let b = concat!(
		"qSupported:multiprocess+;swbreak+;hwbreak+;qRelocInsn+;fork-events+;",
		"vfork-events+;exec-events+;vContSupported+;QThreadEvents+;no-resumed+;",
		"xmlRegisters=i386"
	);
	assert_eq!(
		query(b.as_bytes()),
		Done(
			&b""[..],
			Query::SupportedFeatures(vec![
				GDBFeatureSupported(Known::Yes(GDBFeature::multiprocess), FeatureSupported::Yes),
				GDBFeatureSupported(Known::Yes(GDBFeature::swbreak), FeatureSupported::Yes),
				GDBFeatureSupported(Known::Yes(GDBFeature::hwbreak), FeatureSupported::Yes),
				GDBFeatureSupported(Known::Yes(GDBFeature::qRelocInsn), FeatureSupported::Yes),
				GDBFeatureSupported(Known::Yes(GDBFeature::fork_events), FeatureSupported::Yes),
				GDBFeatureSupported(Known::Yes(GDBFeature::vfork_events), FeatureSupported::Yes),
				GDBFeatureSupported(Known::Yes(GDBFeature::exec_events), FeatureSupported::Yes),
				GDBFeatureSupported(
					Known::Yes(GDBFeature::vContSupported),
					FeatureSupported::Yes
				),
				GDBFeatureSupported(Known::Yes(GDBFeature::QThreadEvents), FeatureSupported::Yes),
				GDBFeatureSupported(Known::Yes(GDBFeature::no_resumed), FeatureSupported::Yes),
				GDBFeatureSupported(
					Known::Yes(GDBFeature::xmlRegisters),
					FeatureSupported::Value("i386")
				),
			])
		)
	);
}

#[test]
fn test_hex_value() {
	assert_eq!(hex_value(&b""[..]), Incomplete(Needed::Size(1)));
	assert_eq!(hex_value(&b","[..]), Error(nom::ErrorKind::TakeWhile1));
	assert_eq!(hex_value(&b"a"[..]), Done(&b""[..], 0xa));
	assert_eq!(hex_value(&b"10,"[..]), Done(&b","[..], 0x10));
	assert_eq!(hex_value(&b"ff"[..]), Done(&b""[..], 0xff));
}

#[test]
fn test_parse_thread_id_element() {
	assert_eq!(parse_thread_id_element(&b"0"[..]), Done(&b""[..], Id::Any));
	assert_eq!(parse_thread_id_element(&b"-1"[..]), Done(&b""[..], Id::All));
	assert_eq!(
		parse_thread_id_element(&b"23"[..]),
		Done(&b""[..], Id::Id(0x23))
	);
}

#[test]
fn test_parse_thread_id() {
	assert_eq!(
		parse_thread_id(&b"0"[..]),
		Done(
			&b""[..],
			ThreadId {
				pid: Id::Any,
				tid: Id::Any
			}
		)
	);
	assert_eq!(
		parse_thread_id(&b"-1"[..]),
		Done(
			&b""[..],
			ThreadId {
				pid: Id::All,
				tid: Id::Any
			}
		)
	);
	assert_eq!(
		parse_thread_id(&b"23"[..]),
		Done(
			&b""[..],
			ThreadId {
				pid: Id::Id(0x23),
				tid: Id::Any
			}
		)
	);

	assert_eq!(
		parse_thread_id(&b"p23"[..]),
		Done(
			&b""[..],
			ThreadId {
				pid: Id::Id(0x23),
				tid: Id::All
			}
		)
	);

	assert_eq!(
		parse_thread_id(&b"p0.0"[..]),
		Done(
			&b""[..],
			ThreadId {
				pid: Id::Any,
				tid: Id::Any
			}
		)
	);
	assert_eq!(
		parse_thread_id(&b"p-1.23"[..]),
		Done(
			&b""[..],
			ThreadId {
				pid: Id::All,
				tid: Id::Id(0x23)
			}
		)
	);
	assert_eq!(
		parse_thread_id(&b"pff.23"[..]),
		Done(
			&b""[..],
			ThreadId {
				pid: Id::Id(0xff),
				tid: Id::Id(0x23)
			}
		)
	);
}

#[test]
fn test_parse_v_commands() {
	assert_eq!(
		v_command(&b"vKill;33"[..]),
		Done(&b""[..], Command::Kill(Some(0x33)))
	);
	assert_eq!(v_command(&b"vCtrlC"[..]), Done(&b""[..], Command::CtrlC));
	assert_eq!(
		v_command(&b"vMustReplyEmpty"[..]),
		Done(&b""[..], Command::UnknownV)
	);
	assert_eq!(
		v_command(&b"vFile:close:0"[..]),
		Done(&b""[..], Command::UnknownV)
	);

	assert_eq!(
		v_command(&b"vCont?"[..]),
		Done(&b""[..], Command::VContSupported)
	);
	assert_eq!(
		v_command(&b"vCont"[..]),
		Done(&b""[..], Command::VCont(Vec::new()))
	);
	assert_eq!(
		v_command(&b"vCont;c"[..]),
		Done(&b""[..], Command::VCont(vec![(VCont::Continue, None)]))
	);
	assert_eq!(
		v_command(&b"vCont;r1,2:p34.56;SAD:-1;c"[..]),
		Done(
			&b""[..],
			Command::VCont(vec![
				(
					VCont::RangeStep(1..2),
					Some(ThreadId {
						pid: Id::Id(0x34),
						tid: Id::Id(0x56)
					})
				),
				(
					VCont::StepWithSignal(0xAD),
					Some(ThreadId {
						pid: Id::All,
						tid: Id::Any
					})
				),
				(VCont::Continue, None)
			])
		)
	);
}

#[test]
fn test_parse_d_packets() {
	assert_eq!(parse_d_packet(&b"D"[..]), Done(&b""[..], None));
	assert_eq!(parse_d_packet(&b"D;f0"[..]), Done(&b""[..], Some(240)));
}

#[test]
fn test_parse_write_memory() {
	assert_eq!(
		write_memory(&b"Mf0,3:ff0102"[..]),
		Done(&b""[..], (240, 3, vec!(255, 1, 2)))
	);
}

#[test]
fn test_parse_write_memory_binary() {
	assert_eq!(
		write_memory_binary(&b"Xf0,1: "[..]),
		Done(&b""[..], (240, 1, vec!(0x20)))
	);
	assert_eq!(
		write_memory_binary(&b"X90,10:}\x5d"[..]),
		Done(&b""[..], (144, 16, vec!(0x7d)))
	);
	assert_eq!(
		write_memory_binary(&b"X5,100:}\x5d}\x03"[..]),
		Done(&b""[..], (5, 256, vec!(0x7d, 0x23)))
	);
	assert_eq!(
		write_memory_binary(&b"Xff,2:}\x04\x9a"[..]),
		Done(&b""[..], (255, 2, vec!(0x24, 0x9a)))
	);
	assert_eq!(
		write_memory_binary(&b"Xff,2:\xce}\x0a\x9a"[..]),
		Done(&b""[..], (255, 2, vec!(0xce, 0x2a, 0x9a)))
	);
}

#[test]
fn test_parse_qrcmd() {
	assert_eq!(
		query(&b"qRcmd,736f6d657468696e67"[..]),
		Done(&b""[..], Query::Invoke(b"something".to_vec()))
	);
}

#[test]
fn test_parse_randomization() {
	assert_eq!(
		query(&b"QDisableRandomization:0"[..]),
		Done(&b""[..], Query::AddressRandomization(true))
	);
	assert_eq!(
		query(&b"QDisableRandomization:1"[..]),
		Done(&b""[..], Query::AddressRandomization(false))
	);
}

#[test]
fn test_parse_syscalls() {
	assert_eq!(
		query(&b"QCatchSyscalls:0"[..]),
		Done(&b""[..], Query::CatchSyscalls(None))
	);
	assert_eq!(
		query(&b"QCatchSyscalls:1"[..]),
		Done(&b""[..], Query::CatchSyscalls(Some(vec!())))
	);
	assert_eq!(
		query(&b"QCatchSyscalls:1;0;1;ff"[..]),
		Done(&b""[..], Query::CatchSyscalls(Some(vec!(0, 1, 255))))
	);
}

#[test]
fn test_parse_signals() {
	assert_eq!(
		query(&b"QPassSignals:"[..]),
		Done(&b""[..], Query::PassSignals(vec!()))
	);
	assert_eq!(
		query(&b"QPassSignals:0"[..]),
		Done(&b""[..], Query::PassSignals(vec!(0)))
	);
	assert_eq!(
		query(&b"QPassSignals:1;2;ff"[..]),
		Done(&b""[..], Query::PassSignals(vec!(1, 2, 255)))
	);
	assert_eq!(
		query(&b"QProgramSignals:0"[..]),
		Done(&b""[..], Query::ProgramSignals(vec!(0)))
	);
	assert_eq!(
		query(&b"QProgramSignals:1;2;ff"[..]),
		Done(&b""[..], Query::ProgramSignals(vec!(1, 2, 255)))
	);
}

#[test]
fn test_thread_info() {
	assert_eq!(
		query(&b"qThreadExtraInfo,ffff"[..]),
		Done(
			&b""[..],
			Query::ThreadInfo(ThreadId {
				pid: Id::Id(65535),
				tid: Id::Any
			})
		)
	);
}

#[test]
fn test_thread_list() {
	assert_eq!(
		query(&b"qfThreadInfo"[..]),
		Done(&b""[..], Query::ThreadList(true))
	);
	assert_eq!(
		query(&b"qsThreadInfo"[..]),
		Done(&b""[..], Query::ThreadList(false))
	);
}

#[test]
fn test_parse_write_register() {
	assert_eq!(
		write_register(&b"Pff=1020"[..]),
		Done(&b""[..], (255, vec!(16, 32)))
	);
}

#[test]
fn test_parse_write_general_registers() {
	assert_eq!(
		write_general_registers(&b"G0001020304"[..]),
		Done(&b""[..], vec!(0, 1, 2, 3, 4))
	);
}

#[cfg(test)]
macro_rules! bytecode {
	($elem:expr; $n:expr) => (Bytecode { bytecode: vec![$elem; $n] });
	($($x:expr),*) => (Bytecode { bytecode: vec!($($x),*) })
}

#[test]
fn test_breakpoints() {
	assert_eq!(
		parse_z_packet(&b"Z0,1ff,0"[..]),
		Done(
			&b""[..],
			Command::InsertSoftwareBreakpoint(Breakpoint::new(0x1ff, 0, None, None))
		)
	);
	assert_eq!(
		parse_z_packet(&b"z0,1fff,0"[..]),
		Done(
			&b""[..],
			Command::RemoveSoftwareBreakpoint(Breakpoint::new(0x1fff, 0, None, None))
		)
	);
	assert_eq!(
		parse_z_packet(&b"Z1,ae,0"[..]),
		Done(
			&b""[..],
			Command::InsertHardwareBreakpoint(Breakpoint::new(0xae, 0, None, None))
		)
	);
	assert_eq!(
		parse_z_packet(&b"z1,aec,0"[..]),
		Done(
			&b""[..],
			Command::RemoveHardwareBreakpoint(Breakpoint::new(0xaec, 0, None, None))
		)
	);
	assert_eq!(
		parse_z_packet(&b"Z2,4cc,2"[..]),
		Done(
			&b""[..],
			Command::InsertWriteWatchpoint(Watchpoint::new(0x4cc, 2))
		)
	);
	assert_eq!(
		parse_z_packet(&b"z2,4ccf,4"[..]),
		Done(
			&b""[..],
			Command::RemoveWriteWatchpoint(Watchpoint::new(0x4ccf, 4))
		)
	);
	assert_eq!(
		parse_z_packet(&b"Z3,7777,4"[..]),
		Done(
			&b""[..],
			Command::InsertReadWatchpoint(Watchpoint::new(0x7777, 4))
		)
	);
	assert_eq!(
		parse_z_packet(&b"z3,77778,8"[..]),
		Done(
			&b""[..],
			Command::RemoveReadWatchpoint(Watchpoint::new(0x77778, 8))
		)
	);
	assert_eq!(
		parse_z_packet(&b"Z4,7777,10"[..]),
		Done(
			&b""[..],
			Command::InsertAccessWatchpoint(Watchpoint::new(0x7777, 16))
		)
	);
	assert_eq!(
		parse_z_packet(&b"z4,77778,20"[..]),
		Done(
			&b""[..],
			Command::RemoveAccessWatchpoint(Watchpoint::new(0x77778, 32))
		)
	);

	assert_eq!(
		parse_z_packet(&b"Z0,1ff,2;X1,0"[..]),
		Done(
			&b""[..],
			Command::InsertSoftwareBreakpoint(Breakpoint::new(
				0x1ff,
				2,
				Some(vec!(bytecode!(b'0'))),
				None
			))
		)
	);
	assert_eq!(
		parse_z_packet(&b"Z1,1ff,2;X1,0"[..]),
		Done(
			&b""[..],
			Command::InsertHardwareBreakpoint(Breakpoint::new(
				0x1ff,
				2,
				Some(vec!(bytecode!(b'0'))),
				None
			))
		)
	);

	assert_eq!(
		parse_z_packet(&b"Z0,1ff,2;cmdsX1,z"[..]),
		Done(
			&b""[..],
			Command::InsertSoftwareBreakpoint(Breakpoint::new(
				0x1ff,
				2,
				None,
				Some(vec!(bytecode!(b'z')))
			))
		)
	);
	assert_eq!(
		parse_z_packet(&b"Z1,1ff,2;cmdsX1,z"[..]),
		Done(
			&b""[..],
			Command::InsertHardwareBreakpoint(Breakpoint::new(
				0x1ff,
				2,
				None,
				Some(vec!(bytecode!(b'z')))
			))
		)
	);

	assert_eq!(
		parse_z_packet(&b"Z0,1ff,2;X1,0;cmdsX1,a"[..]),
		Done(
			&b""[..],
			Command::InsertSoftwareBreakpoint(Breakpoint::new(
				0x1ff,
				2,
				Some(vec!(bytecode!(b'0'))),
				Some(vec!(bytecode!(b'a')))
			))
		)
	);
	assert_eq!(
		parse_z_packet(&b"Z1,1ff,2;X1,0;cmdsX1,a"[..]),
		Done(
			&b""[..],
			Command::InsertHardwareBreakpoint(Breakpoint::new(
				0x1ff,
				2,
				Some(vec!(bytecode!(b'0'))),
				Some(vec!(bytecode!(b'a')))
			))
		)
	);
}

#[test]
fn test_cond_or_command_list() {
	assert_eq!(
		parse_condition_list(&b";X1,a"[..]),
		Done(&b""[..], vec!(bytecode!(b'a')))
	);
	assert_eq!(
		parse_condition_list(&b";X2,ab"[..]),
		Done(&b""[..], vec!(bytecode!(b'a', b'b')))
	);
	assert_eq!(
		parse_condition_list(&b";X1,zX1,y"[..]),
		Done(&b""[..], vec!(bytecode!(b'z'), bytecode!(b'y')))
	);
	assert_eq!(
		parse_condition_list(&b";X1,zX10,yyyyyyyyyyyyyyyy"[..]),
		Done(&b""[..], vec!(bytecode!(b'z'), bytecode![b'y'; 16]))
	);

	assert_eq!(
		parse_command_list(&b";cmdsX1,a"[..]),
		Done(&b""[..], vec!(bytecode!(b'a')))
	);
	assert_eq!(
		parse_command_list(&b";cmdsX2,ab"[..]),
		Done(&b""[..], vec!(bytecode!(b'a', b'b')))
	);
	assert_eq!(
		parse_command_list(&b";cmdsX1,zX1,y"[..]),
		Done(&b""[..], vec!(bytecode!(b'z'), bytecode!(b'y')))
	);
	assert_eq!(
		parse_command_list(&b";cmdsX1,zX10,yyyyyyyyyyyyyyyy"[..]),
		Done(&b""[..], vec!(bytecode!(b'z'), bytecode![b'y'; 16]))
	);
}