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
use super::{
packet::{Kind, UncheckedPacket},
Error,
};
use std::{cmp, iter, mem};
enum State {
Type, // % or $
Data, // packet-data#
Escape, // "}x" = 'x' | 0x20
Repeat, // "x*y" = "x" * ('y' - 29)
Checksum(u8), // checksum
}
pub const CHECKSUM_LEN: u8 = 2;
pub struct Parser {
state: State,
kind: Kind,
data: Vec<u8>,
checksum: [u8; CHECKSUM_LEN as usize],
}
impl Default for Parser {
fn default() -> Self {
Self {
state: State::Type,
// placeholders:
kind: Kind::Notification,
data: Vec::new(),
checksum: [0; CHECKSUM_LEN as usize],
}
}
}
impl Parser {
/// Parse as much of `input` as possible into a packet. Returns
/// the number of bytes read (the rest will need to be re-fed),
/// and maybe a packet which will need handling.
///
/// ```rust
/// # use gdb_protocol::{Error, packet::{Kind, UncheckedPacket}, parser::Parser};
/// # let mut parser = Parser::default();
/// assert_eq!(
/// parser.feed(b"$hello#14").unwrap(),
/// (9, Some(UncheckedPacket {
/// kind: Kind::Packet,
/// data: b"hello".to_vec(),
/// checksum: *b"14",
/// }))
/// );
/// ```
///
/// Apart from splitting the input up and expanding the data,
/// nothing else is done. No checksums are compared, no data is
/// handled. This is just the most basic building block used to
/// supply data that can be further validated and interpreted.
///
/// ```rust
/// # use gdb_protocol::{Error, packet::{Kind, UncheckedPacket}, parser::Parser};
/// # let mut parser = Parser::default();
/// assert_eq!(
/// parser.feed(b"$in:valid}]}}Hello* }]*!CHECKS#UM").unwrap(),
/// (33, Some(UncheckedPacket {
/// kind: Kind::Packet,
/// data: b"in:valid}]Helloooo}}}}}CHECKS".to_vec(),
/// checksum: *b"UM",
/// }))
/// );
/// ```
///
/// Note that although the GDB protocol mostly only uses 7 bits,
/// this will *not* work without the 8th bit clear. This is to
/// make the overhead of updating each element in the list
/// optional. Although that's simple: *Every* element's 8th bit
/// can be cleared so just do that before passing it to the
/// parser.
///
/// ```rust
/// # use gdb_protocol::{Error, packet::{Kind, UncheckedPacket}, parser::Parser};
/// # let mut parser = Parser::default();
/// assert_eq!(
/// parser.feed(&[b'%', 1, 2, 99, 255, 128, 0, 200, b'#', 0, 0]).unwrap(),
/// (11, Some(UncheckedPacket {
/// kind: Kind::Notification,
/// data: vec![1, 2, 99, 255, 128, 0, 200],
/// checksum: [0, 0],
/// }))
/// );
/// ```
///
/// This is a state machine: You may input half a packet now and
/// half in a later invocation.
///
/// ```rust
/// # use gdb_protocol::{Error, parser::Parser};
/// #
/// # let full_input = b"$hello#14";
/// # #[allow(non_snake_case)]
/// # fn getRandomNumber() -> usize {
/// # return 4; // chosen by a fair dice roll.
/// # // guaranteed to be random.
/// # }
/// # let random_index = getRandomNumber();
/// let mut parser1 = Parser::default();
/// let (full_len, full_packet) = parser1.feed(full_input)?;
///
/// let mut parser2 = Parser::default();
/// let (start_input, end_input) = full_input.split_at(random_index);
/// let (start_len, start_packet) = parser2.feed(start_input)?;
/// let (end_len, end_packet) = parser2.feed(end_input)?;
///
/// assert_eq!(start_len + end_len, full_len, "The total consumed lengths must be equal");
/// assert_eq!(start_packet.or(end_packet), full_packet, "The end packets must be equal");
/// # Ok::<(), Error>(())
/// ```
pub fn feed(&mut self, input: &[u8]) -> Result<(usize, Option<UncheckedPacket>), Error> {
let mut read = 0;
loop {
let (partial, packet) = self.feed_one(&input[read..])?;
read += partial;
debug_assert!(read <= input.len());
if read == input.len() || packet.is_some() {
return Ok((read, packet));
}
}
}
fn feed_one(&mut self, input: &[u8]) -> Result<(usize, Option<UncheckedPacket>), Error> {
let first = match input.first() {
Some(b) => *b,
None => return Ok((0, None)),
};
match self.state {
State::Type => {
let start = memchr::memchr2(b'%', b'$', input);
match start.map(|pos| input[pos]) {
Some(b'%') => self.kind = Kind::Notification,
Some(b'$') => self.kind = Kind::Packet,
Some(_) => unreachable!("did memchr just lie to me?!"),
None => (),
}
if start.is_some() {
self.state = State::Data;
}
Ok((start.map(|n| n + 1).unwrap_or_else(|| input.len()), None))
}
State::Data => {
let end = memchr::memchr3(b'#', b'}', b'*', input);
match end.map(|pos| input[pos]) {
Some(b'#') => self.state = State::Checksum(0),
Some(b'}') => self.state = State::Escape,
Some(b'*') => self.state = State::Repeat,
Some(_) => unreachable!("did memchr just lie to me?!"),
None => (),
}
self.data
.extend_from_slice(&input[..end.unwrap_or_else(|| input.len())]);
Ok((end.map(|n| n + 1).unwrap_or_else(|| input.len()), None))
}
State::Escape => {
self.data.push(first ^ 0x20);
self.state = State::Data;
Ok((1, None))
}
State::Repeat => {
let c = *self
.data
.last()
.expect("State::Repeat must only be used once data has been inserted");
let count = first.saturating_sub(29);
self.data.extend(iter::repeat(c).take(count.into()));
self.state = State::Data;
Ok((1, None))
}
State::Checksum(mut i) => {
let read = cmp::min((CHECKSUM_LEN - i) as usize, input.len());
self.checksum[i as usize..].copy_from_slice(&input[..read]);
i += read as u8; // read <= CHECKSUM_LEN
if i < CHECKSUM_LEN {
self.state = State::Checksum(i);
Ok((read, None))
} else {
self.state = State::Type;
Ok((
read,
Some(UncheckedPacket {
kind: self.kind,
data: mem::replace(&mut self.data, Vec::new()),
checksum: self.checksum,
}),
))
}
}
}
}
}