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
pub use maybe_owned;
pub use pdb;
mod type_formatter;
use pdb::PublicSymbol;
use pdb::SymbolTable;
pub use type_formatter::*;
use maybe_owned::MaybeOwned;
use pdb::DebugInformation;
use pdb::IdInformation;
use pdb::TypeInformation;
use pdb::{
AddressMap, FallibleIterator, FileIndex, IdIndex, InlineSiteSymbol, Inlinee, LineProgram,
ModuleInfo, PdbInternalSectionOffset, RawString, Result, Source, StringTable, SymbolData,
SymbolIndex, SymbolIter, TypeIndex, PDB,
};
use range_collections::RangeSet;
use std::cmp::Ordering;
use std::collections::btree_map::Entry;
use std::ops::Bound;
use std::rc::Rc;
use std::{borrow::Cow, cell::RefCell, collections::BTreeMap};
pub struct ContextPdbData<'s> {
modules: Vec<ModuleInfo<'s>>,
address_map: AddressMap<'s>,
string_table: Option<StringTable<'s>>,
global_symbols: SymbolTable<'s>,
debug_info: DebugInformation<'s>,
type_info: TypeInformation<'s>,
id_info: IdInformation<'s>,
}
impl<'s> ContextPdbData<'s> {
pub fn try_from_pdb<S: Source<'s> + 's>(pdb: &mut PDB<'s, S>) -> Result<Self> {
let global_symbols = pdb.global_symbols()?;
let debug_info = pdb.debug_information()?;
let type_info = pdb.type_information()?;
let id_info = pdb.id_information()?;
let address_map = pdb.address_map()?;
let string_table = pdb.string_table().ok();
let mut module_iter = debug_info.modules()?;
let mut modules = Vec::new();
while let Some(module) = module_iter.next()? {
if let Some(module_info) = pdb.module_info(&module)? {
modules.push(module_info);
};
}
Ok(Self {
modules,
global_symbols,
debug_info,
type_info,
id_info,
address_map,
string_table,
})
}
pub fn make_context(&self) -> Result<Context<'_, 's, '_>> {
self.make_context_with_formatter_flags(Default::default())
}
pub fn make_context_with_formatter_flags(
&self,
flags: TypeFormatterFlags,
) -> Result<Context<'_, 's, '_>> {
let type_formatter =
TypeFormatter::new(&self.debug_info, &self.type_info, &self.id_info, flags)?;
Context::new_from_parts(
&self.address_map,
&self.global_symbols,
self.string_table.as_ref(),
&self.modules,
MaybeOwned::Owned(type_formatter),
)
}
}
#[derive(Clone)]
pub struct Function {
pub start_rva: u32,
pub end_rva: Option<u32>,
pub function: Option<String>,
}
#[derive(Clone)]
pub struct FunctionFrames<'a> {
pub start_rva: u32,
pub end_rva: Option<u32>,
pub frames: Vec<Frame<'a>>,
}
#[derive(Clone)]
pub struct Frame<'a> {
pub function: Option<String>,
pub file: Option<Cow<'a, str>>,
pub line: Option<u32>,
}
pub struct Context<'a: 't, 's, 't> {
address_map: &'a AddressMap<'s>,
string_table: Option<&'a StringTable<'s>>,
type_formatter: MaybeOwned<'a, TypeFormatter<'t>>,
modules: &'a [ModuleInfo<'s>],
functions: Vec<BasicFunctionInfo<'a>>,
procedure_cache: RefCell<ProcedureCache>,
module_cache: RefCell<BTreeMap<u16, Rc<ExtendedModuleInfo<'a>>>>,
}
impl<'a, 's, 't> Context<'a, 's, 't> {
pub fn new_from_parts(
address_map: &'a AddressMap<'s>,
global_symbols: &'a SymbolTable<'s>,
string_table: Option<&'a StringTable<'s>>,
modules: &'a [ModuleInfo<'s>],
type_formatter: MaybeOwned<'a, TypeFormatter<'t>>,
) -> Result<Self> {
let mut functions = Vec::new();
let mut symbol_iter = global_symbols.iter();
while let Some(symbol) = symbol_iter.next()? {
if let Ok(SymbolData::Public(PublicSymbol {
function: true,
name,
offset,
..
})) = symbol.parse()
{
let start_rva = match offset.to_rva(&address_map) {
Some(rva) => rva.0,
None => continue,
};
functions.push(BasicFunctionInfo {
start_rva,
end_rva: None,
name,
procedure_symbol_info: None,
});
}
}
for (module_index, module_info) in modules.iter().enumerate() {
let mut symbols_iter = module_info.symbols()?;
while let Some(symbol) = symbols_iter.next()? {
if let Ok(SymbolData::Procedure(proc)) = symbol.parse() {
if proc.len == 0 {
continue;
}
let start_rva = match proc.offset.to_rva(&address_map) {
Some(rva) => rva.0,
None => continue,
};
functions.push(BasicFunctionInfo {
start_rva,
end_rva: Some(start_rva + proc.len),
name: proc.name,
procedure_symbol_info: Some(ProcedureSymbolInfo {
module_index: module_index as u16,
symbol_index: symbol.index(),
end_symbol_index: proc.end,
offset: proc.offset,
type_index: proc.type_index,
}),
});
}
}
}
functions.reverse();
functions.sort_by_key(|p| p.start_rva);
functions.dedup_by_key(|p| p.start_rva);
Ok(Self {
address_map,
string_table,
type_formatter,
modules,
functions,
procedure_cache: RefCell::new(Default::default()),
module_cache: RefCell::new(BTreeMap::new()),
})
}
pub fn function_count(&self) -> usize {
self.functions.len()
}
pub fn functions(&self) -> FunctionIter<'_, 'a, 's, 't> {
FunctionIter {
context: self,
cur_index: 0,
}
}
pub fn find_procedure(&self, probe: u32) -> Result<Option<Function>> {
let proc = match self.lookup_function(probe) {
Some(proc) => proc,
None => return Ok(None),
};
let function = (*self.get_function_name(proc)).clone();
Ok(Some(Function {
start_rva: proc.start_rva,
end_rva: proc.end_rva,
function,
}))
}
pub fn find_frames(&self, probe: u32) -> Result<Option<FunctionFrames>> {
let func = match self.lookup_function(probe) {
Some(func) => func,
None => return Ok(None),
};
let start_rva = func.start_rva;
let function = (*self.get_function_name(func)).clone();
let proc = match &func.procedure_symbol_info {
Some(proc) => proc,
None => {
return Ok(Some(FunctionFrames {
start_rva,
end_rva: None,
frames: vec![Frame {
function,
file: None,
line: None,
}],
}));
}
};
let module_info = &self.modules[proc.module_index as usize];
let module = self.get_extended_module_info(proc.module_index)?;
let line_program = &module.line_program;
let inlinees = &module.inlinees;
let lines = &self.get_procedure_lines(start_rva, proc, line_program)?[..];
let search = match lines.binary_search_by_key(&probe, |li| li.start_rva) {
Err(0) => None,
Ok(i) => Some(i),
Err(i) => Some(i - 1),
};
let (file, line) = match search {
Some(index) => {
let line_info = &lines[index];
(
self.resolve_filename(&line_program, line_info.file_index),
Some(line_info.line_start),
)
}
None => (None, None),
};
let frame = Frame {
function,
file,
line,
};
let mut frames = vec![frame];
let inline_ranges =
self.get_procedure_inline_ranges(start_rva, module_info, proc, inlinees)?;
let mut inline_ranges = &inline_ranges[..];
loop {
let current_depth = (frames.len() - 1) as u16;
let search = inline_ranges.binary_search_by(|range| {
if range.call_depth > current_depth {
Ordering::Greater
} else if range.call_depth < current_depth {
Ordering::Less
} else if range.start_rva > probe {
Ordering::Greater
} else if range.end_rva <= probe {
Ordering::Less
} else {
Ordering::Equal
}
});
let (inline_range, remainder) = match search {
Ok(index) => (&inline_ranges[index], &inline_ranges[index + 1..]),
Err(_) => break,
};
let mut name = String::new();
let res = self
.type_formatter
.write_id(&mut name, inline_range.inlinee);
let function = res.ok().map(|_| name);
let file = inline_range
.file_index
.and_then(|file_index| self.resolve_filename(line_program, file_index));
let line = inline_range.line_start;
frames.push(Frame {
function,
file,
line,
});
inline_ranges = remainder;
}
frames.reverse();
Ok(Some(FunctionFrames {
start_rva: func.start_rva,
end_rva: func.end_rva,
frames,
}))
}
fn lookup_function(&self, probe: u32) -> Option<&BasicFunctionInfo<'a>> {
let last_function_starting_lte_address =
match self.functions.binary_search_by_key(&probe, |p| p.start_rva) {
Err(0) => return None,
Ok(i) => i,
Err(i) => i - 1,
};
assert!(self.functions[last_function_starting_lte_address].start_rva <= probe);
if let Some(end_rva) = self.functions[last_function_starting_lte_address].end_rva {
if probe >= end_rva {
return None;
}
}
Some(&self.functions[last_function_starting_lte_address])
}
fn get_extended_module_info(&self, module_index: u16) -> Result<Rc<ExtendedModuleInfo<'a>>> {
let mut cache = self.module_cache.borrow_mut();
match cache.entry(module_index) {
Entry::Occupied(e) => Ok(e.get().clone()),
Entry::Vacant(e) => {
let m = self.compute_extended_module_info(module_index)?;
Ok(e.insert(Rc::new(m)).clone())
}
}
}
fn compute_extended_module_info(&self, module_index: u16) -> Result<ExtendedModuleInfo<'a>> {
let module_info = &self.modules[module_index as usize];
let line_program = module_info.line_program()?;
let inlinees: BTreeMap<IdIndex, Inlinee> = module_info
.inlinees()?
.map(|i| Ok((i.index(), i)))
.collect()?;
Ok(ExtendedModuleInfo {
inlinees,
line_program,
})
}
fn get_function_name(&self, func: &BasicFunctionInfo<'a>) -> Rc<Option<String>> {
match &func.procedure_symbol_info {
Some(proc) => self.get_procedure_name(func.start_rva, &func.name, proc),
None => Rc::new(Some(func.name.to_string().to_string())),
}
}
fn get_procedure_name(
&self,
start_rva: u32,
name: &RawString<'a>,
proc: &ProcedureSymbolInfo,
) -> Rc<Option<String>> {
let mut cache = self.procedure_cache.borrow_mut();
let entry = cache.get_entry_mut(start_rva);
match &entry.name {
Some(name) => name.clone(),
None => {
let name = Rc::new(self.compute_procedure_name(name, proc));
entry.name = Some(name.clone());
name
}
}
}
fn compute_procedure_name(
&self,
name: &RawString<'a>,
proc: &ProcedureSymbolInfo,
) -> Option<String> {
let mut formatted_function_name = String::new();
self.type_formatter
.write_function(
&mut formatted_function_name,
&name.to_string(),
proc.type_index,
)
.ok()?;
Some(formatted_function_name)
}
fn get_procedure_lines(
&self,
start_rva: u32,
proc: &ProcedureSymbolInfo,
line_program: &LineProgram,
) -> Result<Rc<Vec<CachedLineInfo>>> {
let mut cache = self.procedure_cache.borrow_mut();
let entry = cache.get_entry_mut(start_rva);
match &entry.lines {
Some(lines) => Ok(lines.clone()),
None => {
let lines = Rc::new(self.compute_procedure_lines(proc, line_program)?);
entry.lines = Some(lines.clone());
Ok(lines)
}
}
}
fn compute_procedure_lines(
&self,
proc: &ProcedureSymbolInfo,
line_program: &LineProgram,
) -> Result<Vec<CachedLineInfo>> {
let lines_for_proc = line_program.lines_at_offset(proc.offset);
let mut iterator = lines_for_proc.map(|line_info| {
let rva = line_info.offset.to_rva(&self.address_map).unwrap().0;
Ok((rva, line_info))
});
let mut lines = Vec::new();
let mut next_item = iterator.next()?;
while let Some((start_rva, line_info)) = next_item {
next_item = iterator.next()?;
lines.push(CachedLineInfo {
start_rva,
file_index: line_info.file_index,
line_start: line_info.line_start,
});
}
Ok(lines)
}
fn get_procedure_inline_ranges(
&self,
start_rva: u32,
module_info: &ModuleInfo,
proc: &ProcedureSymbolInfo,
inlinees: &BTreeMap<IdIndex, Inlinee>,
) -> Result<Rc<Vec<InlineRange>>> {
let mut cache = self.procedure_cache.borrow_mut();
let entry = cache.get_entry_mut(start_rva);
match &entry.inline_ranges {
Some(inline_ranges) => Ok(inline_ranges.clone()),
None => {
let inline_ranges =
Rc::new(self.compute_procedure_inline_ranges(module_info, proc, inlinees)?);
entry.inline_ranges = Some(inline_ranges.clone());
Ok(inline_ranges)
}
}
}
fn compute_procedure_inline_ranges(
&self,
module_info: &ModuleInfo,
proc: &ProcedureSymbolInfo,
inlinees: &BTreeMap<IdIndex, Inlinee>,
) -> Result<Vec<InlineRange>> {
let mut lines = Vec::new();
let mut symbols_iter = module_info.symbols_at(proc.symbol_index)?;
let _proc_sym = symbols_iter.next()?;
while let Some(symbol) = symbols_iter.next()? {
if symbol.index() >= proc.end_symbol_index {
break;
}
match symbol.parse() {
Ok(SymbolData::Procedure(p)) => {
symbols_iter.skip_to(p.end)?;
}
Ok(SymbolData::InlineSite(site)) => {
self.process_inlinee_symbols(
&mut symbols_iter,
inlinees,
proc.offset,
site,
0,
&mut lines,
)?;
}
_ => {}
}
}
lines.sort_by(|r1, r2| {
if r1.call_depth < r2.call_depth {
Ordering::Less
} else if r1.call_depth > r2.call_depth {
Ordering::Greater
} else if r1.start_rva < r2.start_rva {
Ordering::Less
} else if r1.start_rva > r2.start_rva {
Ordering::Greater
} else {
Ordering::Equal
}
});
Ok(lines)
}
fn process_inlinee_symbols(
&self,
symbols_iter: &mut SymbolIter,
inlinees: &BTreeMap<IdIndex, Inlinee>,
proc_offset: PdbInternalSectionOffset,
site: InlineSiteSymbol,
call_depth: u16,
lines: &mut Vec<InlineRange>,
) -> Result<RangeSet<u32>> {
let mut name = String::new();
let _ = self.type_formatter.write_id(&mut name, site.inlinee);
let mut ranges = RangeSet::empty();
let mut file_index = None;
if let Some(inlinee) = inlinees.get(&site.inlinee) {
let mut iter = inlinee.lines(proc_offset, &site);
while let Ok(Some(line_info)) = iter.next() {
let length = match line_info.length {
Some(0) | None => {
continue;
}
Some(l) => l,
};
let start_rva = line_info.offset.to_rva(&self.address_map).unwrap().0;
let end_rva = start_rva + length;
lines.push(InlineRange {
start_rva,
end_rva,
call_depth,
inlinee: site.inlinee,
file_index: Some(line_info.file_index),
line_start: Some(line_info.line_start),
});
ranges |= RangeSet::from(start_rva..end_rva);
if file_index.is_none() {
file_index = Some(line_info.file_index);
}
}
}
let mut callee_ranges = RangeSet::empty();
while let Some(symbol) = symbols_iter.next()? {
if symbol.index() >= site.end {
break;
}
match symbol.parse() {
Ok(SymbolData::Procedure(p)) => {
symbols_iter.skip_to(p.end)?;
}
Ok(SymbolData::InlineSite(site)) => {
callee_ranges |= self.process_inlinee_symbols(
symbols_iter,
inlinees,
proc_offset,
site,
call_depth + 1,
lines,
)?;
}
_ => {}
}
}
if !ranges.is_superset(&callee_ranges) {
let missing_ranges: RangeSet<u32> = &callee_ranges - &ranges;
for range in missing_ranges.iter() {
let (start_rva, end_rva) = match range {
(Bound::Included(s), Bound::Excluded(e)) => (*s, *e),
other => {
panic!("Unexpected range bounds {:?}", other);
}
};
lines.push(InlineRange {
start_rva,
end_rva,
call_depth,
inlinee: site.inlinee,
file_index,
line_start: None,
});
}
ranges |= missing_ranges;
}
Ok(ranges)
}
fn resolve_filename(
&self,
line_program: &LineProgram,
file_index: FileIndex,
) -> Option<Cow<'a, str>> {
if let Some(string_table) = self.string_table {
if let Ok(file_info) = line_program.get_file_info(file_index) {
return file_info.name.to_string_lossy(string_table).ok();
}
}
None
}
}
#[derive(Clone)]
pub struct FunctionIter<'c, 'a, 's, 't> {
context: &'c Context<'a, 's, 't>,
cur_index: usize,
}
impl<'c, 'a, 's, 't> Iterator for FunctionIter<'c, 'a, 's, 't> {
type Item = Function;
fn next(&mut self) -> Option<Function> {
if self.cur_index >= self.context.functions.len() {
return None;
}
let proc = &self.context.functions[self.cur_index];
self.cur_index += 1;
let function = (*self.context.get_function_name(proc)).clone();
Some(Function {
start_rva: proc.start_rva,
end_rva: proc.end_rva,
function,
})
}
}
#[derive(Default)]
struct ProcedureCache(BTreeMap<u32, ExtendedProcedureInfo>);
impl ProcedureCache {
fn get_entry_mut(&mut self, start_rva: u32) -> &mut ExtendedProcedureInfo {
self.0
.entry(start_rva)
.or_insert_with(|| ExtendedProcedureInfo {
name: None,
lines: None,
inline_ranges: None,
})
}
}
#[derive(Clone)]
struct BasicFunctionInfo<'a> {
start_rva: u32,
end_rva: Option<u32>,
name: RawString<'a>,
procedure_symbol_info: Option<ProcedureSymbolInfo>,
}
#[derive(Clone)]
struct ProcedureSymbolInfo {
module_index: u16,
symbol_index: SymbolIndex,
end_symbol_index: SymbolIndex,
offset: PdbInternalSectionOffset,
type_index: TypeIndex,
}
struct ExtendedProcedureInfo {
name: Option<Rc<Option<String>>>,
lines: Option<Rc<Vec<CachedLineInfo>>>,
inline_ranges: Option<Rc<Vec<InlineRange>>>,
}
struct ExtendedModuleInfo<'a> {
inlinees: BTreeMap<IdIndex, Inlinee<'a>>,
line_program: LineProgram<'a>,
}
#[derive(Clone)]
struct CachedLineInfo {
pub start_rva: u32,
pub file_index: FileIndex,
pub line_start: u32,
}
#[derive(Clone, Debug)]
struct InlineRange {
pub start_rva: u32,
pub end_rva: u32,
pub call_depth: u16,
pub inlinee: IdIndex,
pub file_index: Option<FileIndex>,
pub line_start: Option<u32>,
}