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
extern crate minidump_common;
#[macro_use]
extern crate nom;
extern crate range_map;
#[cfg(test)]
extern crate tempdir;
mod sym_file;
pub use minidump_common::traits::Module;
use std::borrow::Cow;
use std::boxed::Box;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
pub use sym_file::SymbolFile;
#[derive(Default)]
pub struct SimpleModule {
pub base_address : Option<u64>,
pub size : Option<u64>,
pub code_file : Option<String>,
pub code_identifier : Option<String>,
pub debug_file : Option<String>,
pub debug_id : Option<String>,
pub version : Option<String>,
}
impl SimpleModule {
pub fn new(debug_file : &str, debug_id : &str) -> SimpleModule {
SimpleModule {
debug_file: Some(String::from(debug_file)),
debug_id: Some(String::from(debug_id)),
..SimpleModule::default()
}
}
}
impl Module for SimpleModule {
fn base_address(&self) -> u64 { self.base_address.unwrap_or(0) }
fn size(&self) -> u64 { self.size.unwrap_or(0) }
fn code_file(&self) -> Cow<str> {
self.code_file.as_ref().map_or(Cow::from(""), |s| Cow::Borrowed(&s[..]))
}
fn code_identifier(&self) -> Cow<str> {
self.code_identifier.as_ref().map_or(Cow::from(""),
|s| Cow::Borrowed(&s[..]))
}
fn debug_file(&self) -> Option<Cow<str>> {
self.debug_file.as_ref().map(|s| Cow::Borrowed(&s[..]))
}
fn debug_identifier(&self) -> Option<Cow<str>> {
self.debug_id.as_ref().map(|s| Cow::Borrowed(&s[..]))
}
fn version(&self) -> Option<Cow<str>> {
self.version.as_ref().map(|s| Cow::Borrowed(&s[..]))
}
}
fn leafname(path : &str) -> &str {
path.rsplit(|c| c == '/' || c == '\\').next().unwrap_or(path)
}
fn replace_or_add_extension(filename : &str,
match_extension : &str,
new_extension : &str) -> String {
let mut bits = filename.split('.').collect::<Vec<_>>();
if bits.len() > 1 && bits.last().map_or(false, |e| e.to_lowercase() == match_extension) {
bits.pop();
}
bits.push(new_extension);
bits.join(".")
}
pub fn relative_symbol_path(module : &Module, extension : &str)
-> Option<String> {
module.debug_file().and_then(|debug_file| {
module.debug_identifier().map(|debug_id| {
let leaf = leafname(&debug_file);
let filename = replace_or_add_extension(leaf, "pdb", extension);
[leaf, &debug_id[..], &filename[..]].join("/")
})
})
}
#[derive(Debug, PartialEq)]
pub enum SymbolResult {
Ok(SymbolFile),
NotFound,
LoadError(&'static str),
}
pub trait SymbolSupplier {
fn locate_symbols(&self, module : &Module) -> SymbolResult;
}
pub struct SimpleSymbolSupplier {
paths : Vec<PathBuf>,
}
impl SimpleSymbolSupplier {
pub fn new(paths : Vec<PathBuf>) -> SimpleSymbolSupplier {
SimpleSymbolSupplier { paths : paths }
}
}
impl SymbolSupplier for SimpleSymbolSupplier {
fn locate_symbols(&self, module : &Module) -> SymbolResult {
if let Some(rel_path) = relative_symbol_path(module, "sym") {
for ref path in self.paths.iter() {
let test_path = path.join(&rel_path);
if fs::metadata(&test_path).ok()
.map_or(false, |m| m.is_file()) {
return SymbolFile::from_file(&test_path)
.and_then(|s| Ok(SymbolResult::Ok(s)))
.unwrap_or_else(|e| SymbolResult::LoadError(e))
}
}
}
SymbolResult::NotFound
}
}
pub trait FrameSymbolizer {
fn get_instruction(&self) -> u64;
fn set_function(&mut self, name : &str, base : u64);
fn set_source_file(&mut self, file : &str, line : u32, base : u64);
}
#[derive(Default)]
pub struct SimpleFrame {
pub instruction : u64,
pub function : Option<String>,
pub function_base : Option<u64>,
pub source_file : Option<String>,
pub source_line : Option<u32>,
pub source_line_base : Option<u64>,
}
impl SimpleFrame {
pub fn with_instruction(instruction : u64) -> SimpleFrame {
SimpleFrame {
instruction: instruction,
..SimpleFrame::default()
}
}
}
impl FrameSymbolizer for SimpleFrame {
fn get_instruction(&self) -> u64 { self.instruction }
fn set_function(&mut self, name : &str, base : u64) {
self.function = Some(String::from(name));
self.function_base = Some(base);
}
fn set_source_file(&mut self, file : &str, line : u32, base : u64) {
self.source_file = Some(String::from(file));
self.source_line = Some(line);
self.source_line_base = Some(base);
}
}
type ModuleKey = (String, String, Option<String>, Option<String>);
fn key(module : &Module) -> ModuleKey {
(module.code_file().to_string(),
module.code_identifier().to_string(),
module.debug_file().map(|s| s.to_string()),
module.debug_identifier().map(|s| s.to_string()))
}
pub struct Symbolizer {
supplier : Box<SymbolSupplier + 'static>,
symbols : RefCell<HashMap<ModuleKey, SymbolResult>>,
}
impl Symbolizer {
pub fn new<T: SymbolSupplier + 'static>(supplier : T) -> Symbolizer {
Symbolizer {
supplier: Box::new(supplier),
symbols: RefCell::new(HashMap::new()),
}
}
pub fn get_symbol_at_address(&self,
debug_file : &str,
debug_id : &str,
address : u64) -> Option<String> {
let k = (debug_file, debug_id);
let mut frame = SimpleFrame::with_instruction(address);
self.fill_symbol(&k, &mut frame);
frame.function
}
pub fn fill_symbol(&self,
module : &Module,
frame : &mut FrameSymbolizer) {
let k = key(module);
if !self.symbols.borrow().contains_key(&k) {
self.symbols
.borrow_mut()
.insert(k.clone(),
self.supplier.locate_symbols(module));
}
if let Some(res) = self.symbols.borrow().get(&k) {
match res {
&SymbolResult::Ok(ref sym) => sym.fill_symbol(module, frame),
_ => {},
}
}
}
}
#[test]
fn test_leafname() {
assert_eq!(leafname("c:\\foo\\bar\\test.pdb"), "test.pdb");
assert_eq!(leafname("c:/foo/bar/test.pdb"), "test.pdb");
assert_eq!(leafname("test.pdb"), "test.pdb");
assert_eq!(leafname("test"), "test");
assert_eq!(leafname("/path/to/test"), "test");
}
#[test]
fn test_replace_or_add_extension() {
assert_eq!(replace_or_add_extension("test.pdb", "pdb", "sym"), "test.sym");
assert_eq!(replace_or_add_extension("TEST.PDB", "pdb", "sym"), "TEST.sym");
assert_eq!(replace_or_add_extension("test", "pdb", "sym"), "test.sym");
assert_eq!(replace_or_add_extension("test.x", "pdb", "sym"), "test.x.sym");
assert_eq!(replace_or_add_extension("", "pdb", "sym"), ".sym");
assert_eq!(replace_or_add_extension("test.x", "x", "y"), "test.y");
}
#[cfg(test)]
mod test {
use super::*;
use std::fs;
use std::fs::File;
use std::io::Write;
use std::path::{Path,PathBuf};
use tempdir::TempDir;
#[test]
fn test_relative_symbol_path() {
let m = SimpleModule::new("foo.pdb", "abcd1234");
assert_eq!(&relative_symbol_path(&m, "sym").unwrap(),
"foo.pdb/abcd1234/foo.sym");
let m2 = SimpleModule::new("foo.pdb", "abcd1234");
assert_eq!(&relative_symbol_path(&m2, "bar").unwrap(),
"foo.pdb/abcd1234/foo.bar");
let m3 = SimpleModule::new("foo.xyz", "abcd1234");
assert_eq!(&relative_symbol_path(&m3, "sym").unwrap(),
"foo.xyz/abcd1234/foo.xyz.sym");
let m4 = SimpleModule::new("foo.xyz", "abcd1234");
assert_eq!(&relative_symbol_path(&m4, "bar").unwrap(),
"foo.xyz/abcd1234/foo.xyz.bar");
let bad = SimpleModule::default();
assert!(relative_symbol_path(&bad, "sym").is_none());
let bad2 = SimpleModule { debug_file: Some("foo".to_string()),
..SimpleModule::default() };
assert!(relative_symbol_path(&bad2, "sym").is_none());
let bad3 = SimpleModule { debug_id: Some("foo".to_string()),
..SimpleModule::default() };
assert!(relative_symbol_path(&bad3, "sym").is_none());
}
#[test]
fn test_relative_symbol_path_abs_paths() {
{
let m = SimpleModule::new("/path/to/foo.bin", "abcd1234");
assert_eq!(&relative_symbol_path(&m, "sym").unwrap(),
"foo.bin/abcd1234/foo.bin.sym");
}
{
let m = SimpleModule::new("c:/path/to/foo.pdb", "abcd1234");
assert_eq!(&relative_symbol_path(&m, "sym").unwrap(),
"foo.pdb/abcd1234/foo.sym");
}
{
let m = SimpleModule::new("c:\\path\\to\\foo.pdb", "abcd1234");
assert_eq!(&relative_symbol_path(&m, "sym").unwrap(),
"foo.pdb/abcd1234/foo.sym");
}
}
fn mksubdirs(path : &Path, dirs : &[&str]) -> Vec<PathBuf> {
dirs.iter().map(|dir| {
let new_path = path.join(dir);
fs::create_dir(&new_path).unwrap();
new_path
}).collect()
}
fn write_symbol_file(path : &Path, contents : &[u8]) {
let dir = path.parent().unwrap();
if !fs::metadata(&dir).ok().map_or(false, |m| m.is_dir()) {
fs::create_dir_all(&dir).unwrap();
}
let mut f = File::create(path).unwrap();
f.write_all(contents).unwrap();
}
fn write_good_symbol_file(path : &Path) {
write_symbol_file(path, b"MODULE Linux x86 abcd1234 foo\n");
}
fn write_bad_symbol_file(path : &Path) {
write_symbol_file(path, b"this is not a symbol file\n");
}
#[test]
fn test_simple_symbol_supplier() {
let t = TempDir::new("symtest").unwrap();
let paths = mksubdirs(t.path(), &["one", "two"]);
let supplier = SimpleSymbolSupplier::new(paths.clone());
let bad = SimpleModule::default();
assert_eq!(supplier.locate_symbols(&bad), SymbolResult::NotFound);
for &(path, file, id, sym) in [(&paths[0], "foo.pdb", "abcd1234",
"foo.pdb/abcd1234/foo.sym"),
(&paths[1], "bar.xyz", "ff9900",
"bar.xyz/ff9900/bar.xyz.sym")].iter() {
let m = SimpleModule::new(file, id);
assert_eq!(supplier.locate_symbols(&m), SymbolResult::NotFound);
write_good_symbol_file(&path.join(sym));
assert!(if let SymbolResult::Ok(_) = supplier.locate_symbols(&m) {
true
} else {
false
}, format!("Located symbols for {}", sym));
}
let mal = SimpleModule::new("baz.pdb", "ffff0000");
let sym = "baz.pdb/ffff0000/baz.sym";
assert_eq!(supplier.locate_symbols(&mal), SymbolResult::NotFound);
write_bad_symbol_file(&paths[0].join(sym));
let res = supplier.locate_symbols(&mal);
assert!(if let SymbolResult::LoadError(_) = res {
true
} else {
false
}, format!("Correctly failed to parse {}, result: {:?}", sym, res));
}
#[test]
fn test_symbolizer() {
let t = TempDir::new("symtest").unwrap();
let path = t.path();
let supplier = SimpleSymbolSupplier::new(vec!(PathBuf::from(path)));
let symbolizer = Symbolizer::new(supplier);
let m1 = SimpleModule::new("foo.pdb", "abcd1234");
write_symbol_file(&path.join("foo.pdb/abcd1234/foo.sym"),
b"MODULE Linux x86 abcd1234 foo
FILE 1 foo.c
FUNC 1000 30 10 some func
1000 30 100 1
");
let mut f1 = SimpleFrame::with_instruction(0x1010);
symbolizer.fill_symbol(&m1, &mut f1);
assert_eq!(f1.function.unwrap(), "some func");
assert_eq!(f1.function_base.unwrap(), 0x1000);
assert_eq!(f1.source_file.unwrap(), "foo.c");
assert_eq!(f1.source_line.unwrap(), 100);
assert_eq!(f1.source_line_base.unwrap(), 0x1000);
assert_eq!(symbolizer.get_symbol_at_address("foo.pdb", "abcd1234", 0x1010)
.unwrap(),
"some func");
let m2 = SimpleModule::new("bar.pdb", "ffff0000");
let mut f2 = SimpleFrame::with_instruction(0x1010);
symbolizer.fill_symbol(&m2, &mut f2);
assert!(f2.function.is_none());
assert!(f2.function_base.is_none());
assert!(f2.source_file.is_none());
assert!(f2.source_line.is_none());
write_symbol_file(&path.join("bar.pdb/ffff0000/bar.sym"),
b"MODULE Linux x86 ffff0000 bar
FILE 53 bar.c
FUNC 1000 30 10 another func
1000 30 7 53
");
symbolizer.fill_symbol(&m2, &mut f2);
assert!(f2.function.is_none());
assert!(f2.function_base.is_none());
assert!(f2.source_file.is_none());
assert!(f2.source_line.is_none());
assert!(symbolizer.get_symbol_at_address("bar.pdb", "ffff0000", 0x1010)
.is_none());
}
}