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
use regex::Regex;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
pub mod error;
pub mod mappings;
pub mod memory;
pub mod registers;
pub mod siginfo;
pub mod stacktrace;
#[derive(Debug, Clone)]
pub enum ExecType<'a> {
Local(&'a [&'a str]),
Remote(&'a str),
Core { target: &'a str, core: &'a str },
}
#[derive(Debug)]
pub struct GdbCommand<'a> {
exec_type: ExecType<'a>,
args: Vec<String>,
stdin: Option<&'a PathBuf>,
commands_cnt: usize,
}
impl<'a> GdbCommand<'a> {
pub fn new(exec_type: &'a ExecType) -> GdbCommand<'a> {
GdbCommand {
exec_type: exec_type.clone(),
args: Vec::new(),
stdin: None,
commands_cnt: 0,
}
}
pub fn stdin<T: Into<Option<&'a PathBuf>>>(&mut self, file: T) -> &'a mut GdbCommand {
self.stdin = file.into();
self
}
pub fn ex<T: Into<String>>(&mut self, cmd: T) -> &'a mut GdbCommand {
self.args.push("-ex".to_string());
self.args
.push(format!("p \"gdb-command-start-{}\"", self.commands_cnt));
self.args.push("-ex".to_string());
self.args.push(cmd.into());
self.args.push("-ex".to_string());
self.args
.push(format!("p \"gdb-command-end-{}\"", self.commands_cnt));
self.commands_cnt += 1;
self
}
pub fn raw(&self) -> error::Result<Vec<u8>> {
let mut gdb = Command::new("gdb");
let mut gdb_args: Vec<String> = vec![
"--batch".to_string(),
"-ex".to_string(),
"set backtrace limit 2000".to_string(),
"-ex".to_string(),
"set disassembly-flavor intel".to_string(),
"-ex".to_string(),
"set filename-display absolute".to_string(),
];
match &self.exec_type {
ExecType::Local(args) => {
if !Path::new(args[0]).exists() {
return Err(error::Error::NoFile(args[0].to_string()));
}
gdb_args.append(&mut self.args.clone());
gdb_args.push("--args".to_string());
args.iter().for_each(|a| gdb_args.push(a.to_string()));
}
ExecType::Remote(pid) => {
gdb_args.push("-p".to_string());
gdb_args.push(pid.to_string());
gdb_args.append(&mut self.args.clone());
}
ExecType::Core { target, core } => {
if !Path::new(target).exists() {
return Err(error::Error::NoFile(target.to_string()));
}
if !Path::new(core).exists() {
return Err(error::Error::NoFile(core.to_string()));
}
gdb_args.append(&mut self.args.clone());
gdb_args.push(target.to_string());
gdb_args.push(core.to_string());
}
}
let output = gdb.args(&gdb_args).output();
if let Err(e) = output {
return Err(error::Error::Gdb(e.to_string()));
}
let mut output = output.unwrap();
output.stdout.append(&mut output.stderr.clone());
Ok(output.stdout)
}
pub fn r(&mut self) -> &'a mut GdbCommand {
self.args.push("-ex".to_string());
let run_command = if let Some(stdin) = self.stdin {
format!("r < {}", stdin.display())
} else {
"r".to_string()
};
self.args.push(run_command);
self
}
pub fn c(&mut self) -> &'a mut GdbCommand {
self.args.push("-ex".to_string());
self.args.push("c".to_string());
self
}
pub fn bt(&mut self) -> &'a mut GdbCommand {
self.ex("bt")
}
pub fn disassembly(&mut self) -> &'a mut GdbCommand {
self.ex("x/16i $pc")
}
pub fn regs(&mut self) -> &'a mut GdbCommand {
self.ex("i r")
}
pub fn mappings(&mut self) -> &'a mut GdbCommand {
self.ex("info proc mappings")
}
pub fn cmdline(&mut self) -> &'a mut GdbCommand {
self.ex("info proc cmdline")
}
pub fn env(&mut self) -> &'a mut GdbCommand {
self.ex("show environment")
}
pub fn status(&mut self) -> &'a mut GdbCommand {
self.ex("info proc status")
}
pub fn sources(&mut self) -> &'a mut GdbCommand {
self.ex("info sources")
}
pub fn bmain(&mut self) -> &'a mut GdbCommand {
self.args.push("-ex".to_string());
self.args.push("b main".to_string());
self
}
pub fn list<T: Into<Option<&'a str>>>(&mut self, location: T) -> &'a mut GdbCommand {
if let Some(loc) = location.into() {
self.ex(format!("list {}", loc))
} else {
self.ex("list")
}
}
pub fn mem<T: AsRef<str>>(&mut self, expr: T, size: usize) -> &'a mut GdbCommand {
self.ex(format!("x/{}bx {}", size, expr.as_ref()))
}
pub fn siginfo(&mut self) -> &'a mut GdbCommand {
self.ex("p/x $_siginfo")
}
pub fn launch(&self) -> error::Result<Vec<String>> {
let stdout = self.raw()?;
let output = String::from_utf8_lossy(&stdout);
self.parse(output)
}
pub fn parse<T: AsRef<str>>(&self, output: T) -> error::Result<Vec<String>> {
let lines: Vec<String> = output.as_ref().lines().map(|l| l.to_string()).collect();
let mut results = Vec::new();
(0..self.commands_cnt).for_each(|_| results.push(String::new()));
let re_start = Regex::new(r#"^\$\d+\s*=\s*"gdb-command-start-(\d+)"$"#).unwrap();
let re_end = Regex::new(r#"^\$\d+\s*=\s*"gdb-command-end-(\d+)"$"#).unwrap();
let mut start = 0;
let mut cmd_idx = 0;
for (i, line) in lines.iter().enumerate() {
if let Some(caps) = re_start.captures(line) {
cmd_idx = caps.get(1).unwrap().as_str().parse::<usize>()?;
start = i;
}
if let Some(caps) = re_end.captures(line) {
let end_idx = caps.get(1).unwrap().as_str().parse::<usize>()?;
if end_idx == cmd_idx && cmd_idx < self.commands_cnt {
results[cmd_idx] = lines[start + 1..i].join("\n");
}
}
}
Ok(results)
}
}