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
use std::borrow::Cow;
use std::default::Default;
use std::fs;
use std::ops::Deref;

mod dwarf;

use fnv::FnvHashMap as HashMap;
use gimli;
use memmap;
use object::{self, Object, ObjectSection, ObjectSegment, ObjectSymbol, ObjectSymbolTable};
use typed_arena::Arena;

use crate::cfi::Cfi;
use crate::function::{Function, FunctionDetails, FunctionOffset};
use crate::location::Register;
use crate::range::{Range, RangeList};
use crate::types::{Enumerator, Type, TypeOffset};
use crate::unit::Unit;
use crate::variable::Variable;
use crate::{Address, Result, Size};

pub(crate) enum DebugInfo<'input, Endian>
where
    Endian: gimli::Endianity + 'input,
{
    Dwarf(&'input dwarf::DwarfDebugInfo<'input, Endian>),
}

impl<'input, Endian> DebugInfo<'input, Endian>
where
    Endian: gimli::Endianity + 'input,
{
    fn get_type(&self, offset: TypeOffset) -> Option<Type<'input>> {
        match self {
            DebugInfo::Dwarf(dwarf) => dwarf.get_type(offset),
        }
    }

    fn get_enumerators(&self, offset: TypeOffset) -> Vec<Enumerator<'input>> {
        match self {
            DebugInfo::Dwarf(dwarf) => dwarf.get_enumerators(offset),
        }
    }

    fn get_function_details(
        &self,
        offset: FunctionOffset,
        hash: &FileHash<'input>,
    ) -> Option<FunctionDetails<'input>> {
        match self {
            DebugInfo::Dwarf(dwarf) => dwarf.get_function_details(offset, hash),
        }
    }

    fn get_cfi(&self, address: Address, size: Size) -> Vec<Cfi> {
        match self {
            DebugInfo::Dwarf(dwarf) => dwarf.get_cfi(address, size),
        }
    }

    fn get_register_name(&self, machine: Architecture, register: Register) -> Option<&'static str> {
        match self {
            DebugInfo::Dwarf(dwarf) => dwarf.get_register_name(machine, register),
        }
    }
}

pub(crate) struct StringCache {
    strings: Arena<String>,
}

impl StringCache {
    fn new() -> Self {
        StringCache {
            strings: Arena::new(),
        }
    }

    fn get<'input>(&'input self, bytes: &'input [u8]) -> &'input str {
        // FIXME: this is effectively leaking strings that require lossy conversion,
        // fix by avoiding duplicates
        match String::from_utf8_lossy(bytes) {
            Cow::Borrowed(s) => s,
            Cow::Owned(s) => &*self.strings.alloc(s),
        }
    }
}

pub use object::Architecture;

/// The parsed debuginfo for a single file.
pub struct File<'input> {
    pub(crate) path: &'input str,
    pub(crate) machine: Architecture,
    pub(crate) segments: Vec<Segment<'input>>,
    pub(crate) sections: Vec<Section<'input>>,
    pub(crate) symbols: Vec<Symbol<'input>>,
    pub(crate) relocations: Vec<Relocation<'input>>,
    pub(crate) units: Vec<Unit<'input>>,
    debug_info: DebugInfo<'input, gimli::RunTimeEndian>,
}

impl<'input> File<'input> {
    pub(crate) fn get_type(&self, offset: TypeOffset) -> Option<Type<'input>> {
        self.debug_info.get_type(offset)
    }

    pub(crate) fn get_enumerators(&self, offset: TypeOffset) -> Vec<Enumerator<'input>> {
        self.debug_info.get_enumerators(offset)
    }

    pub(crate) fn get_function_details(
        &self,
        offset: FunctionOffset,
        hash: &FileHash<'input>,
    ) -> FunctionDetails<'input> {
        self.debug_info
            .get_function_details(offset, hash)
            .unwrap_or_default()
    }

    pub(crate) fn get_cfi(&self, address: Address, size: Size) -> Vec<Cfi> {
        self.debug_info.get_cfi(address, size)
    }

    pub(crate) fn get_register_name(&self, register: Register) -> Option<&'static str> {
        self.debug_info.get_register_name(self.machine, register)
    }

    /// Parse the file with the given path.
    ///
    /// `cb` is a callback function that is called with the parsed File.
    /// It requires a callback so that memory management is simplified.
    pub fn parse<Cb>(path: &str, cb: Cb) -> Result<()>
    where
        Cb: FnOnce(&File) -> Result<()>,
    {
        let handle = match fs::File::open(path) {
            Ok(handle) => handle,
            Err(e) => {
                return Err(format!("open failed: {}", e).into());
            }
        };

        let map = match unsafe { memmap::Mmap::map(&handle) } {
            Ok(map) => map,
            Err(e) => {
                return Err(format!("memmap failed: {}", e).into());
            }
        };

        let object = object::File::parse(&*map)?;

        // TODO: split DWARF
        // TODO: PDB
        File::parse_object(&object, &object, path, cb)
    }

    fn parse_object<Cb>(
        object: &object::File,
        debug_object: &object::File,
        path: &str,
        cb: Cb,
    ) -> Result<()>
    where
        Cb: FnOnce(&File) -> Result<()>,
    {
        let machine = object.architecture();
        let mut segments = Vec::new();
        for segment in object.segments() {
            if let Ok(bytes) = segment.data() {
                segments.push(Segment {
                    address: segment.address(),
                    bytes,
                });
            }
        }

        let mut sections = Vec::new();
        for section in object.sections() {
            let name = Some(section.name()?).map(|x| Cow::Owned(x.to_string()));
            let segment = section.segment_name()?.map(|x| Cow::Owned(x.to_string()));
            let address = if section.address() != 0 {
                Some(section.address())
            } else {
                None
            };
            let size = section.size();
            if size != 0 {
                sections.push(Section {
                    name,
                    segment,
                    address,
                    size,
                });
            }
        }

        // TODO: symbols from debug_object too?
        let mut symbols = Vec::new();
        for symbol in object.symbols() {
            // TODO: handle relocatable objects
            let address = symbol.address();
            if address == 0 {
                continue;
            }

            let size = symbol.size();
            if size == 0 {
                continue;
            }

            // TODO: handle SymbolKind::File
            let kind = match symbol.kind() {
                object::SymbolKind::Text => SymbolKind::Function,
                object::SymbolKind::Data | object::SymbolKind::Unknown => SymbolKind::Variable,
                _ => continue,
            };

            let name = Some(symbol.name()?);

            symbols.push(Symbol {
                name,
                kind,
                address,
                size,
            });
        }

        let mut relocations = Vec::new();
        if let (Some(dynamic_symbols), Some(dynamic_relocations)) =
            (object.dynamic_symbol_table(), object.dynamic_relocations())
        {
            for (address, relocation) in dynamic_relocations {
                let size = relocation.size();
                match relocation.target() {
                    object::RelocationTarget::Symbol(index) => {
                        if let Ok(symbol) = dynamic_symbols.symbol_by_index(index) {
                            relocations.push(Relocation {
                                address,
                                size,
                                symbol: symbol.name()?,
                            });
                        }
                    }
                    _ => {}
                }
            }
        }

        let endian = if debug_object.is_little_endian() {
            gimli::RunTimeEndian::Little
        } else {
            gimli::RunTimeEndian::Big
        };

        let strings = &StringCache::new();
        dwarf::parse(endian, debug_object, strings, |units, debug_info| {
            let mut file = File {
                path,
                machine,
                segments,
                sections,
                symbols,
                relocations,
                units,
                debug_info,
            };
            file.normalize();
            cb(&file)
        })
    }

    fn normalize(&mut self) {
        self.symbols.sort_by(|a, b| a.address.cmp(&b.address));
        let mut used_symbols = vec![false; self.symbols.len()];

        // Set symbol names on functions/variables.
        for unit in &mut self.units {
            for function in &mut unit.functions {
                if let Some(address) = function.address() {
                    if let Some(symbol) = Self::get_symbol(
                        &*self.symbols,
                        &mut used_symbols,
                        address,
                        function.linkage_name().or_else(|| function.name()),
                    ) {
                        function.symbol_name = symbol.name;
                    }
                }
            }

            for variable in &mut unit.variables {
                if let Some(address) = variable.address() {
                    if let Some(symbol) = Self::get_symbol(
                        &*self.symbols,
                        &mut used_symbols,
                        address,
                        variable.linkage_name().or_else(|| variable.name()),
                    ) {
                        variable.symbol_name = symbol.name;
                    }
                }
            }
        }

        // Create a unit for symbols that don't have debuginfo.
        let mut unit = Unit::default();
        unit.name = Some(Cow::Borrowed("<symtab>"));
        for (symbol, used) in self.symbols.iter().zip(used_symbols.iter()) {
            if *used {
                continue;
            }
            unit.ranges.push(Range {
                begin: symbol.address,
                end: symbol.address + symbol.size,
            });
            match symbol.kind() {
                SymbolKind::Variable => {
                    unit.variables.push(Variable {
                        name: symbol.name,
                        linkage_name: symbol.name,
                        address: Address::new(symbol.address),
                        size: Size::new(symbol.size),
                        ..Default::default()
                    });
                }
                SymbolKind::Function => {
                    unit.functions.push(Function {
                        name: symbol.name,
                        linkage_name: symbol.name,
                        address: Address::new(symbol.address),
                        size: Size::new(symbol.size),
                        ..Default::default()
                    });
                }
            }
        }
        unit.ranges.sort();
        self.units.push(unit);

        // Create a unit for all remaining address ranges.
        let mut unit = Unit::default();
        unit.name = Some(Cow::Borrowed("<unknown>"));
        unit.ranges = self.unknown_ranges();
        self.units.push(unit);
    }

    // Determine if the symbol at the given address has the given name.
    // There may be multiple symbols for the same address.
    // If none match the given name, then return the first one.
    fn get_symbol<'sym>(
        symbols: &'sym [Symbol<'input>],
        used_symbols: &mut [bool],
        address: u64,
        name: Option<&str>,
    ) -> Option<&'sym Symbol<'input>> {
        if let Ok(mut index) = symbols.binary_search_by(|x| x.address.cmp(&address)) {
            while index > 0 && symbols[index - 1].address == address {
                index -= 1;
            }
            let mut found = false;
            for (symbol, used_symbol) in (&symbols[index..])
                .iter()
                .zip((&mut used_symbols[index..]).iter_mut())
            {
                if symbol.address != address {
                    break;
                }
                *used_symbol = true;
                if symbol.name() == name {
                    found = true;
                }
            }
            if found {
                None
            } else {
                Some(&symbols[index])
            }
        } else {
            None
        }
    }

    /// The file path.
    #[inline]
    pub fn path(&self) -> &'input str {
        self.path
    }

    /// The machine type that the file contains debuginfo for.
    #[inline]
    pub fn machine(&self) -> Architecture {
        self.machine
    }

    /// Find the segment data for the given address range.
    pub fn segment_bytes(&self, range: Range) -> Option<&'input [u8]> {
        for segment in &self.segments {
            if range.begin >= segment.address
                && range.end <= segment.address + segment.bytes.len() as u64
            {
                let begin = (range.begin - segment.address) as usize;
                let len = (range.end - range.begin) as usize;
                return Some(&segment.bytes[begin..][..len]);
            }
        }
        None
    }

    /// A list of segments in the file.
    #[inline]
    pub fn segments(&self) -> &[Segment<'input>] {
        &self.segments
    }

    /// A list of sections in the file.
    #[inline]
    pub fn sections(&self) -> &[Section<'input>] {
        &self.sections
    }

    /// A list of relocations in the file.
    #[inline]
    pub fn relocations(&self) -> &[Relocation<'input>] {
        &self.relocations
    }

    /// A list of compilation units in the file.
    #[inline]
    pub fn units(&self) -> &[Unit<'input>] {
        &self.units
    }

    /// A list of address ranges covered by the compilation units.
    ///
    /// This includes both `Unit::ranges` and `Unit::unknown_ranges`.
    pub fn ranges(&self, hash: &FileHash) -> RangeList {
        let mut ranges = RangeList::default();
        for unit in &self.units {
            for range in unit.ranges(hash).list() {
                ranges.push(*range);
            }
            for range in unit.unknown_ranges(hash).list() {
                ranges.push(*range);
            }
        }
        ranges.sort();
        ranges
    }

    // Used to create <unknown> unit. After creation of that unit
    // this will return an empty range list.
    fn unknown_ranges(&self) -> RangeList {
        // FIXME: don't create this hash twice
        let hash = FileHash::new(self);
        let unit_ranges = self.ranges(&hash);

        let mut ranges = RangeList::default();
        for section in &self.sections {
            if let Some(range) = section.address() {
                ranges.push(range);
            }
        }
        ranges.sort();
        ranges.subtract(&unit_ranges)
    }

    /// The total size of functions in all compilation units.
    pub fn function_size(&self) -> u64 {
        let mut size = 0;
        for unit in &self.units {
            size += unit.function_size();
        }
        size
    }

    /// The total size of variables in all compilation units.
    pub fn variable_size(&self, hash: &FileHash) -> u64 {
        let mut size = 0;
        for unit in &self.units {
            size += unit.variable_size(hash);
        }
        size
    }
}

/// An index of functions and types within a file.
pub struct FileHash<'input> {
    /// The file being indexed.
    pub file: &'input File<'input>,
    /// All functions by address.
    pub functions_by_address: HashMap<u64, &'input Function<'input>>,
    /// All functions by offset.
    pub functions_by_offset: HashMap<FunctionOffset, &'input Function<'input>>,
    /// All types by offset.
    pub types: HashMap<TypeOffset, &'input Type<'input>>,
    // The type corresponding to `TypeOffset::none()`.
    pub(crate) void: Type<'input>,
}

impl<'input> FileHash<'input> {
    /// Create a new `FileHash` for the given `File`.
    pub fn new(file: &'input File<'input>) -> Self {
        FileHash {
            file,
            functions_by_address: FileHash::functions_by_address(file),
            functions_by_offset: FileHash::functions_by_offset(file),
            types: FileHash::types(file),
            void: Type::void(),
        }
    }

    /// Returns a map from address to function for all functions in the file.
    fn functions_by_address<'a>(file: &'a File<'input>) -> HashMap<u64, &'a Function<'input>> {
        let mut functions = HashMap::default();
        for unit in &file.units {
            for function in &unit.functions {
                if let Some(address) = function.address() {
                    // TODO: handle duplicate addresses
                    functions.insert(address, function);
                }
            }
        }
        functions
    }

    /// Returns a map from offset to function for all functions in the file.
    fn functions_by_offset<'a>(
        file: &'a File<'input>,
    ) -> HashMap<FunctionOffset, &'a Function<'input>> {
        let mut functions = HashMap::default();
        for unit in &file.units {
            for function in &unit.functions {
                functions.insert(function.offset, function);
            }
        }
        functions
    }

    /// Returns a map from offset to type for all types in the file.
    fn types<'a>(file: &'a File<'input>) -> HashMap<TypeOffset, &'a Type<'input>> {
        let mut types = HashMap::default();
        for unit in &file.units {
            for ty in &unit.types {
                types.insert(ty.offset, ty);
            }
        }
        types
    }
}

/// A loadable range of bytes.
#[derive(Debug)]
pub struct Segment<'input> {
    /// The address that the bytes should be loaded at.
    pub address: u64,
    /// The bytes, which may be code or data.
    pub bytes: &'input [u8],
}

/// A named section.
#[derive(Debug)]
pub struct Section<'input> {
    pub(crate) name: Option<Cow<'input, str>>,
    pub(crate) segment: Option<Cow<'input, str>>,
    pub(crate) address: Option<u64>,
    pub(crate) size: u64,
}

impl<'input> Section<'input> {
    /// The name of this section.
    pub fn name(&self) -> Option<&str> {
        self.name.as_ref().map(Cow::deref)
    }

    /// The name of the segment containing this section, if applicable.
    pub fn segment(&self) -> Option<&str> {
        self.segment.as_ref().map(Cow::deref)
    }

    /// The address range covered by this section if it is loadable.
    pub fn address(&self) -> Option<Range> {
        self.address.map(|address| Range {
            begin: address,
            end: address + self.size,
        })
    }

    /// The size of the section.
    #[inline]
    pub fn size(&self) -> u64 {
        self.size
    }
}

/// A symbol kind.
#[derive(Debug, Clone, Copy)]
pub enum SymbolKind {
    /// The symbol is a variable.
    Variable,
    /// The symbol is a function.
    Function,
}

/// A symbol.
#[derive(Debug, Clone)]
pub struct Symbol<'input> {
    pub(crate) name: Option<&'input str>,
    pub(crate) kind: SymbolKind,
    pub(crate) address: u64,
    pub(crate) size: u64,
}

impl<'input> Symbol<'input> {
    /// The symbol name.
    #[inline]
    pub fn name(&self) -> Option<&str> {
        self.name
    }

    /// The symbol kind.
    #[inline]
    pub fn kind(&self) -> SymbolKind {
        self.kind
    }

    /// The symbol address range.
    #[inline]
    pub fn address(&self) -> Range {
        Range {
            begin: self.address,
            end: self.address + self.size,
        }
    }

    /// The symbol size range.
    #[inline]
    pub fn size(&self) -> u64 {
        self.size
    }
}

/// A relocation.
#[derive(Debug, Clone)]
pub struct Relocation<'input> {
    pub(crate) address: u64,
    pub(crate) size: u8,
    pub(crate) symbol: &'input str,
}

impl<'input> Relocation<'input> {
    /// The relocation address.
    #[inline]
    pub fn address(&self) -> u64 {
        self.address
    }

    /// The relocation size.
    #[inline]
    pub fn size(&self) -> u8 {
        self.size
    }

    /// The name of the symbol referenced by the relocation.
    #[inline]
    pub fn symbol(&self) -> &'input str {
        self.symbol
    }
}