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 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
use std::borrow::Cow;
use std::fmt;
use std::iter::FromIterator;
use std::ops::{Bound, Deref, RangeBounds};
use std::str::FromStr;
use symbolic_common::{clean_path, join_path, Arch, CodeId, DebugId, Name};
use crate::sourcebundle::SourceFileDescriptor;
pub(crate) trait Parse<'data>: Sized {
type Error;
fn parse(data: &'data [u8]) -> Result<Self, Self::Error>;
fn test(data: &'data [u8]) -> bool {
Self::parse(data).is_ok()
}
}
/// An error returned for unknown or invalid `ObjectKinds`.
#[derive(Debug)]
pub struct UnknownObjectKindError;
impl fmt::Display for UnknownObjectKindError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "unknown object class")
}
}
impl std::error::Error for UnknownObjectKindError {}
/// Represents the designated use of the object file and hints at its contents.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone)]
pub enum ObjectKind {
/// There is no object class specified for this object file.
None,
/// The Relocatable file type is the format used for intermediate object
/// files. It is a very compact format containing all its sections in one
/// segment. The compiler and assembler usually create one Relocatable file
/// for each source code file. By convention, the file name extension for
/// this format is .o.
Relocatable,
/// The Executable file type is the format used by standard executable
/// programs.
Executable,
/// The Library file type is for dynamic shared libraries. It contains
/// some additional tables to support multiple modules. By convention, the
/// file name extension for this format is .dylib, except for the main
/// shared library of a framework, which does not usually have a file name
/// extension.
Library,
/// The Dump file type is used to store core files, which are
/// traditionally created when a program crashes. Core files store the
/// entire address space of a process at the time it crashed. You can
/// later run gdb on the core file to figure out why the crash occurred.
Dump,
/// The Debug file type designates files that store symbol information
/// for a corresponding binary file.
Debug,
/// A container that just stores source code files, but no other debug
/// information corresponding to the original object file.
Sources,
/// The Other type represents any valid object class that does not fit any
/// of the other classes. These are mostly CPU or OS dependent, or unique
/// to a single kind of object.
Other,
}
impl ObjectKind {
/// Returns the name of the object kind.
pub fn name(self) -> &'static str {
match self {
ObjectKind::None => "none",
ObjectKind::Relocatable => "rel",
ObjectKind::Executable => "exe",
ObjectKind::Library => "lib",
ObjectKind::Dump => "dump",
ObjectKind::Debug => "dbg",
ObjectKind::Sources => "src",
ObjectKind::Other => "other",
}
}
/// Returns a human readable name of the object kind.
///
/// This is also used in alternate formatting:
///
/// ```rust
/// # use symbolic_debuginfo::ObjectKind;
/// assert_eq!(format!("{:#}", ObjectKind::Executable), ObjectKind::Executable.human_name());
/// ```
pub fn human_name(self) -> &'static str {
match self {
ObjectKind::None => "file",
ObjectKind::Relocatable => "object",
ObjectKind::Executable => "executable",
ObjectKind::Library => "library",
ObjectKind::Dump => "memory dump",
ObjectKind::Debug => "debug companion",
ObjectKind::Sources => "sources",
ObjectKind::Other => "file",
}
}
}
impl fmt::Display for ObjectKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
f.write_str(self.human_name())
} else {
f.write_str(self.name())
}
}
}
impl FromStr for ObjectKind {
type Err = UnknownObjectKindError;
fn from_str(string: &str) -> Result<ObjectKind, UnknownObjectKindError> {
Ok(match string {
"none" => ObjectKind::None,
"rel" => ObjectKind::Relocatable,
"exe" => ObjectKind::Executable,
"lib" => ObjectKind::Library,
"dump" => ObjectKind::Dump,
"dbg" => ObjectKind::Debug,
"src" => ObjectKind::Sources,
"other" => ObjectKind::Other,
_ => return Err(UnknownObjectKindError),
})
}
}
/// An error returned for unknown or invalid [`FileFormats`](enum.FileFormat.html).
#[derive(Debug)]
pub struct UnknownFileFormatError;
impl fmt::Display for UnknownFileFormatError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "unknown file format")
}
}
impl std::error::Error for UnknownFileFormatError {}
/// Represents the physical object file format.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone)]
pub enum FileFormat {
/// An unknown file format.
Unknown,
/// Breakpad ASCII symbol.
Breakpad,
/// Executable and Linkable Format, used on Linux.
Elf,
/// Mach Objects, used on macOS and iOS derivatives.
MachO,
/// Program Database, the debug companion format on Windows.
Pdb,
/// Portable Executable, an extension of COFF used on Windows.
Pe,
/// Source code bundle ZIP.
SourceBundle,
/// WASM container.
Wasm,
/// Portable PDB
PortablePdb,
}
impl FileFormat {
/// Returns the name of the file format.
pub fn name(self) -> &'static str {
match self {
FileFormat::Unknown => "unknown",
FileFormat::Breakpad => "breakpad",
FileFormat::Elf => "elf",
FileFormat::MachO => "macho",
FileFormat::Pdb => "pdb",
FileFormat::Pe => "pe",
FileFormat::SourceBundle => "sourcebundle",
FileFormat::Wasm => "wasm",
FileFormat::PortablePdb => "portablepdb",
}
}
}
impl fmt::Display for FileFormat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
impl FromStr for FileFormat {
type Err = UnknownFileFormatError;
fn from_str(string: &str) -> Result<FileFormat, UnknownFileFormatError> {
Ok(match string {
"breakpad" => FileFormat::Breakpad,
"elf" => FileFormat::Elf,
"macho" => FileFormat::MachO,
"pdb" => FileFormat::Pdb,
"pe" => FileFormat::Pe,
"sourcebundle" => FileFormat::SourceBundle,
"wasm" => FileFormat::Wasm,
"portablepdb" => FileFormat::PortablePdb,
_ => return Err(UnknownFileFormatError),
})
}
}
/// A symbol from a symbol table.
#[derive(Clone, Default, Eq, PartialEq)]
pub struct Symbol<'data> {
/// The name of the symbol.
///
/// This name is generally mangled. It can be demangled by constructing a `Name` instance and
/// calling demangle on it. Certain object files might only store demangled symbol names.
pub name: Option<Cow<'data, str>>,
/// The relative address of this symbol.
pub address: u64,
/// The size of this symbol, if known.
///
/// When loading symbols from an object file, the size will generally not be known. Instead,
/// construct a [`SymbolMap`] from the object, which also fills in sizes.
///
/// [`SymbolMap`]: struct.SymbolMap.html
pub size: u64,
}
impl<'data> Symbol<'data> {
/// Returns the name of this symbol as string.
pub fn name(&self) -> Option<&str> {
self.name.as_ref().map(Cow::as_ref)
}
/// Determines whether the given address is covered by this symbol.
///
/// If the symbol size has not been computed, the address is assumed to be covered if it is
/// greated than the symbol address. Otherwise, the address must be in the half-open interval
/// `[address, address + size)`.
pub fn contains(&self, address: u64) -> bool {
address >= self.address && (self.size == 0 || address < self.address + self.size)
}
}
impl<'d> fmt::Debug for Symbol<'d> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Symbol")
.field("name", &self.name().unwrap_or("<unknown>"))
.field("address", &format_args!("{:#x}", self.address))
.field("size", &format_args!("{:#x}", self.size))
.finish()
}
}
/// IntoIterator type for [`SymbolMap`](struct.SymbolMap.html).
pub type SymbolMapIter<'data> = std::vec::IntoIter<Symbol<'data>>;
/// A sorted list of symbols, suitable for quick lookups.
///
/// This type can either be computed from a list or iterator of symbols, or preferrably directly
/// by calling [`ObjectLike::symbol_map`] on any object. Symbols in the symbol map are guaranteed to
/// have a `size` set, except for the last symbol, which is computed by taking the offset to the
/// subsequent symbol.
///
/// `SymbolMap` also exposes a read-only view on the sorted slice of symbols. It can be converted to
/// and from lists of symbols.
///
/// ## Example
///
/// ```rust
/// # use symbolic_debuginfo::{Symbol, SymbolMap};
/// let map = SymbolMap::from(vec![
/// Symbol { name: Some("A".into()), address: 0x4400, size: 0 },
/// Symbol { name: Some("B".into()), address: 0x4200, size: 0 },
/// Symbol { name: Some("C".into()), address: 0x4000, size: 0 },
/// ]);
///
/// assert_eq!(map[0], Symbol {
/// name: Some("C".into()),
/// address: 0x4000,
/// size: 0x200,
/// });
/// ```
///
/// [`ObjectLike::symbol_map`]: trait.ObjectLike.html#tymethod.symbol_map
#[derive(Clone, Debug, Default)]
pub struct SymbolMap<'data> {
symbols: Vec<Symbol<'data>>,
}
impl<'data> SymbolMap<'data> {
/// Creates a new, empty symbol map.
pub fn new() -> Self {
SymbolMap {
symbols: Vec::new(),
}
}
/// Looks up the symbol covering the given address.
pub fn lookup(&self, address: u64) -> Option<&Symbol<'data>> {
match self.symbols.binary_search_by_key(&address, Self::key) {
Ok(index) => Some(&self.symbols[index]),
Err(0) => None,
Err(next_index) => {
let symbol = &self.symbols[next_index - 1];
if symbol.contains(address) {
Some(symbol)
} else {
None
}
}
}
}
/// Looks up a symbol by its start address.
pub fn lookup_exact(&self, address: u64) -> Option<&Symbol<'data>> {
let idx = self
.symbols
.binary_search_by_key(&address, Self::key)
.ok()?;
self.symbols.get(idx)
}
/// Looks up a symbol covering an entire range.
///
/// This is similar to [`lookup`], but it only returns the symbol result if it _also_ covers the
/// inclusive end address of the range.
///
/// [`lookup`]: struct.SymbolMap.html#method.lookup
pub fn lookup_range<R>(&self, range: R) -> Option<&Symbol<'data>>
where
R: RangeBounds<u64>,
{
let start = match range.start_bound() {
Bound::Included(start) => *start,
Bound::Excluded(start) => *start + 1,
Bound::Unbounded => 0,
};
let symbol = self.lookup(start)?;
let end = match range.end_bound() {
Bound::Included(end) => *end,
Bound::Excluded(end) => *end - 1,
Bound::Unbounded => u64::max_value(),
};
if end <= start || symbol.contains(end) {
Some(symbol)
} else {
None
}
}
/// Returns the lookup key for a symbol, which is the symbol's address.
#[inline(always)]
fn key(symbol: &Symbol<'data>) -> u64 {
symbol.address
}
}
impl<'d> Deref for SymbolMap<'d> {
type Target = [Symbol<'d>];
fn deref(&self) -> &Self::Target {
&self.symbols
}
}
impl<'data> IntoIterator for SymbolMap<'data> {
type Item = Symbol<'data>;
type IntoIter = SymbolMapIter<'data>;
fn into_iter(self) -> Self::IntoIter {
self.symbols.into_iter()
}
}
impl<'data, 'a> IntoIterator for &'a SymbolMap<'data> {
type Item = &'a Symbol<'data>;
type IntoIter = std::slice::Iter<'a, Symbol<'data>>;
fn into_iter(self) -> Self::IntoIter {
self.symbols.iter()
}
}
impl<'d> AsRef<[Symbol<'d>]> for SymbolMap<'d> {
fn as_ref(&self) -> &[Symbol<'d>] {
&self.symbols
}
}
impl<'d> From<Vec<Symbol<'d>>> for SymbolMap<'d> {
fn from(mut symbols: Vec<Symbol<'d>>) -> Self {
if !symbols.is_empty() {
// NB: This might require stable sorting to ensure determinism if multiple symbols point
// at the same location. However, this only seems to happen for equivalent variants of
// the same function.
//
// An example would be destructors where D2 (base object destructor) and D1 (complete
// object destructor) might share the same code. Since those always demangle to the same
// name, we do not care which function to keep in this case.
//
// Inlined functions will generally not appear in this list, unless they _also_ have an
// explicit function body, in which case they will have a unique address, again.
dmsort::sort_by_key(&mut symbols, Self::key);
// Compute sizes of consecutive symbols if the size has not been provided by the symbol
// iterator. In the same go, drop all but the first symbols at any given address. We do
// not rely on the size of symbols in this case, since the ranges might still be
// overlapping.
symbols.dedup_by(|next, symbol| {
if symbol.size == 0 {
symbol.size = next.address - symbol.address;
}
symbol.address == next.address
})
}
SymbolMap { symbols }
}
}
impl<'d> FromIterator<Symbol<'d>> for SymbolMap<'d> {
fn from_iter<I>(iter: I) -> Self
where
I: IntoIterator<Item = Symbol<'d>>,
{
Vec::from_iter(iter).into()
}
}
/// File information referred by [`LineInfo`](struct.LineInfo.html) comprising a directory and name.
///
/// The file path is usually relative to a compilation directory. It might contain parent directory
/// segments (`../`).
#[derive(Clone, Default, Eq, PartialEq)]
pub struct FileInfo<'data> {
/// The file's basename.
name: Cow<'data, [u8]>,
/// Path to the file.
dir: Cow<'data, [u8]>,
}
impl<'data> FileInfo<'data> {
/// Creates a `FileInfo` with a given directory and the file name.
#[cfg(feature = "dwarf")]
pub fn new(dir: Cow<'data, [u8]>, name: Cow<'data, [u8]>) -> Self {
FileInfo { name, dir }
}
/// Creates a `FileInfo` from a joined path by trying to split it.
#[cfg(any(feature = "breakpad", feature = "ms", feature = "sourcebundle"))]
pub fn from_path(path: &'data [u8]) -> Self {
let (dir, name) = symbolic_common::split_path_bytes(path);
FileInfo {
name: Cow::Borrowed(name),
dir: match dir {
Some(dir) => Cow::Borrowed(dir),
None => Cow::default(),
},
}
}
/// Creates a `FileInfo` from a joined path by trying to split it.
/// Unlike from_path(), copies the given data instead of referencing it.
#[cfg(feature = "ppdb")]
pub(crate) fn from_path_owned(path: &[u8]) -> Self {
let (dir, name) = symbolic_common::split_path_bytes(path);
FileInfo {
name: Cow::Owned(name.to_vec()),
dir: match dir {
Some(dir) => Cow::Owned(dir.to_vec()),
None => Cow::default(),
},
}
}
/// Creates a `FileInfo` with the file name.
pub fn from_filename(name: &'data [u8]) -> Self {
FileInfo {
name: Cow::Borrowed(name),
dir: Cow::default(),
}
}
/// The file name as UTF-8 string.
pub fn name_str(&self) -> Cow<'data, str> {
from_utf8_cow_lossy(&self.name)
}
/// Path to the file relative to the compilation directory.
pub fn dir_str(&self) -> Cow<'data, str> {
from_utf8_cow_lossy(&self.dir)
}
/// The full path to the file, relative to the compilation directory.
pub fn path_str(&self) -> String {
let joined = join_path(&self.dir_str(), &self.name_str());
clean_path(&joined).into_owned()
}
}
#[allow(clippy::ptr_arg)] // false positive https://github.com/rust-lang/rust-clippy/issues/9218
pub(crate) fn from_utf8_cow_lossy<'data>(input: &Cow<'data, [u8]>) -> Cow<'data, str> {
// See https://github.com/rust-lang/rust/issues/32669
match input {
Cow::Borrowed(bytes) => String::from_utf8_lossy(bytes),
Cow::Owned(bytes) => match String::from_utf8_lossy(bytes) {
Cow::Borrowed(_) => unsafe { String::from_utf8_unchecked(bytes.to_vec()) }.into(),
Cow::Owned(s) => s.into(),
},
}
}
impl fmt::Debug for FileInfo<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FileInfo")
.field("name", &self.name_str())
.field("dir", &self.dir_str())
.finish()
}
}
/// File information comprising a compilation directory, relative path and name.
pub struct FileEntry<'data> {
/// Path to the compilation directory. File paths are relative to this.
compilation_dir: Cow<'data, [u8]>,
/// File name and path.
pub info: FileInfo<'data>,
}
impl<'data> FileEntry<'data> {
/// Path to the compilation directory.
pub fn new(compilation_dir: Cow<'data, [u8]>, info: FileInfo<'data>) -> Self {
FileEntry {
compilation_dir,
info,
}
}
/// Path to the compilation directory.
pub fn compilation_dir_str(&self) -> Cow<'data, str> {
from_utf8_cow_lossy(&self.compilation_dir)
}
/// Absolute path to the file, including the compilation directory.
pub fn abs_path_str(&self) -> String {
let joined_path = join_path(&self.dir_str(), &self.name_str());
let joined = join_path(&self.compilation_dir_str(), &joined_path);
clean_path(&joined).into_owned()
}
}
impl fmt::Debug for FileEntry<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FileInfo")
.field("compilation_dir", &self.compilation_dir_str())
.field("name", &self.name_str())
.field("dir", &self.dir_str())
.finish()
}
}
impl<'data> Deref for FileEntry<'data> {
type Target = FileInfo<'data>;
fn deref(&self) -> &Self::Target {
&self.info
}
}
/// File and line number mapping for an instruction address.
#[derive(Clone, Eq, PartialEq)]
pub struct LineInfo<'data> {
/// The instruction address relative to the image base (load address).
pub address: u64,
/// Total code size covered by this line record.
pub size: Option<u64>,
/// File name and path.
pub file: FileInfo<'data>,
/// Absolute line number starting at 1. Zero means no line number.
pub line: u64,
}
#[cfg(test)]
impl LineInfo<'static> {
pub(crate) fn new(address: u64, size: u64, file: &[u8], line: u64) -> LineInfo {
LineInfo {
address,
size: Some(size),
file: FileInfo::from_filename(file),
line,
}
}
}
impl fmt::Debug for LineInfo<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut s = f.debug_struct("LineInfo");
s.field("address", &format_args!("{:#x}", self.address));
match self.size {
Some(size) => s.field("size", &format_args!("{size:#x}")),
None => s.field("size", &self.size),
};
s.field("file", &self.file)
.field("line", &self.line)
.finish()
}
}
/// Debug information for a function.
#[derive(Clone)]
pub struct Function<'data> {
/// Relative instruction address of the start of the function.
pub address: u64,
/// Total code size covered by the function body, including inlined functions.
pub size: u64,
/// The name and language of the function symbol.
pub name: Name<'data>,
/// Path to the compilation directory. File paths are relative to this.
pub compilation_dir: &'data [u8],
/// Lines covered by this function, including inlined children.
pub lines: Vec<LineInfo<'data>>,
/// Functions that have been inlined into this function's body.
pub inlinees: Vec<Function<'data>>,
/// Specifies whether this function is inlined.
pub inline: bool,
}
impl Function<'_> {
/// End address of the entire function body, including inlined functions.
///
/// This address points at the first instruction after the function body.
pub fn end_address(&self) -> u64 {
self.address.saturating_add(self.size)
}
}
impl fmt::Debug for Function<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Function")
.field("address", &format_args!("{:#x}", self.address))
.field("size", &format_args!("{:#x}", self.size))
.field("name", &self.name)
.field(
"compilation_dir",
&String::from_utf8_lossy(self.compilation_dir),
)
.field("lines", &self.lines)
.field("inlinees", &self.inlinees)
.field("inline", &self.inline)
.finish()
}
}
/// A dynamically dispatched iterator over items with the given lifetime.
pub type DynIterator<'a, T> = Box<dyn Iterator<Item = T> + 'a>;
/// A stateful session for interfacing with debug information.
///
/// Debug sessions can be obtained via [`ObjectLike::debug_session`]. Since computing a session may
/// be a costly operation, try to reuse the session as much as possible.
///
/// ## Implementing DebugSession
///
/// Reading debug information from object files usually requires loading multiple sections into
/// memory and computing maps for quick random access to certain information. Since this can be a
/// quite costly process, this is encapsulated into a `DebugSession`. The session may hold whatever
/// data and caches may be necessary for efficiently interfacing with the debug info.
///
/// All trait methods on a `DebugSession` receive `&mut self`, to allow mutation of internal cache
/// structures. Lifetimes of returned types are tied to this session's lifetime, which allows to
/// borrow data from the session.
///
/// Examples for things to compute when building a debug session are:
///
/// - Decompress debug information if it is stored with compression.
/// - Build a symbol map for random access to public symbols.
/// - Map string tables and other lookup tables.
/// - Read headers of compilation units (compilands) to resolve cross-unit references.
///
/// [`ObjectLike::debug_session`]: trait.ObjectLike.html#tymethod.debug_session
pub trait DebugSession<'session> {
/// The error returned when reading debug information fails.
type Error;
/// An iterator over all functions in this debug file.
type FunctionIterator: Iterator<Item = Result<Function<'session>, Self::Error>>;
/// An iterator over all source files referenced by this debug file.
type FileIterator: Iterator<Item = Result<FileEntry<'session>, Self::Error>>;
/// Returns an iterator over all functions in this debug file.
///
/// Functions are iterated in the order they are declared in their compilation units. The
/// functions yielded by this iterator include all inlinees and line records resolved.
///
/// Note that the iterator holds a mutable borrow on the debug session, which allows it to use
/// caches and optimize resources while resolving function and line information.
fn functions(&'session self) -> Self::FunctionIterator;
/// Returns an iterator over all source files referenced by this debug file.
fn files(&'session self) -> Self::FileIterator;
/// Looks up a file's source by its full canonicalized path.
///
/// Returns a descriptor that has all the information available of the source. It can
/// either contain the source contents directly, if it was embedded, or a source link.
fn source_by_path(&self, path: &str) -> Result<Option<SourceFileDescriptor<'_>>, Self::Error>;
}
/// An object containing debug information.
pub trait ObjectLike<'data, 'object> {
/// Errors thrown when reading information from this object.
type Error;
/// A session that allows optimized access to debugging information.
type Session: for<'session> DebugSession<'session, Error = Self::Error>;
/// The iterator over the symbols in the public symbol table.
type SymbolIterator: Iterator<Item = Symbol<'data>>;
/// The container format of this file.
fn file_format(&self) -> FileFormat;
/// The code identifier of this object.
///
/// The identifier can be `None` if it cannot be determined from the object file, for instance,
/// because the identifier was stripped in the build process.
fn code_id(&self) -> Option<CodeId>;
/// The debug information identifier of this object.
fn debug_id(&self) -> DebugId;
/// The CPU architecture of this object.
fn arch(&self) -> Arch;
/// The kind of this object.
fn kind(&self) -> ObjectKind;
/// The address at which the image prefers to be loaded into memory.
fn load_address(&self) -> u64;
/// Determines whether this object exposes a public symbol table.
fn has_symbols(&self) -> bool;
/// Returns an iterator over symbols in the public symbol table.
fn symbols(&'object self) -> Self::SymbolIterator;
/// Returns an ordered map of symbols in the symbol table.
fn symbol_map(&self) -> SymbolMap<'data>;
/// Determines whether this object contains debug information.
fn has_debug_info(&self) -> bool;
/// Constructs a debugging session.
///
/// A debugging session loads certain information from the object file and creates caches for
/// efficient access to various records in the debug information. Since this can be quite a
/// costly process, try to reuse the debugging session as long as possible.
///
/// Constructing this session will also work if the object does not contain debugging
/// information, in which case the session will be a no-op. This can be checked via
/// [`has_debug_info`](trait.ObjectLike.html#tymethod.has_debug_info).
fn debug_session(&'object self) -> Result<Self::Session, Self::Error>;
/// Determines whether this object contains stack unwinding information.
fn has_unwind_info(&self) -> bool;
/// Determines whether this object contains embedded sources.
fn has_sources(&self) -> bool;
/// Determines whether this object is malformed and was only partially parsed
fn is_malformed(&self) -> bool;
}
mod derive_serde {
/// Helper macro to implement string based serialization and deserialization.
///
/// If a type implements `FromStr` and `Display` then this automatically
/// implements a serializer/deserializer for that type that dispatches
/// appropriately.
macro_rules! impl_str_serde {
($type:ty) => {
impl ::serde::ser::Serialize for $type {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: ::serde::ser::Serializer,
{
serializer.serialize_str(self.name())
}
}
impl<'de> ::serde::de::Deserialize<'de> for $type {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: ::serde::de::Deserializer<'de>,
{
<::std::borrow::Cow<'_, str>>::deserialize(deserializer)?
.parse()
.map_err(::serde::de::Error::custom)
}
}
};
}
impl_str_serde!(super::ObjectKind);
impl_str_serde!(super::FileFormat);
}
#[cfg(test)]
mod tests {
use super::*;
use similar_asserts::assert_eq;
fn file_info<'a>(dir: &'a str, name: &'a str) -> FileInfo<'a> {
FileInfo::new(
Cow::Borrowed(dir.as_bytes()),
Cow::Borrowed(name.as_bytes()),
)
}
fn file_entry<'a>(compilation_dir: &'a str, dir: &'a str, name: &'a str) -> FileEntry<'a> {
FileEntry::new(
Cow::Borrowed(compilation_dir.as_bytes()),
file_info(dir, name),
)
}
#[test]
fn test_file_info() {
assert_eq!(file_info("", "foo.h").path_str(), "foo.h");
assert_eq!(
file_info("C:\\Windows", "foo.h").path_str(),
"C:\\Windows\\foo.h"
);
assert_eq!(
file_info("/usr/local", "foo.h").path_str(),
"/usr/local/foo.h"
);
assert_eq!(file_info("/usr/local", "../foo.h").path_str(), "/usr/foo.h");
assert_eq!(file_info("/usr/local", "/foo.h").path_str(), "/foo.h");
}
#[test]
fn test_file_entry() {
assert_eq!(file_entry("", "", "foo.h").abs_path_str(), "foo.h");
assert_eq!(
file_entry("C:\\Windows", "src", "foo.h").abs_path_str(),
"C:\\Windows\\src\\foo.h"
);
assert_eq!(
file_entry("/usr", "local", "foo.h").abs_path_str(),
"/usr/local/foo.h"
);
assert_eq!(
file_entry("/usr/local", "..", "foo.h").abs_path_str(),
"/usr/foo.h"
);
assert_eq!(
file_entry("/usr", "/src", "foo.h").abs_path_str(),
"/src/foo.h"
);
}
}