samply-symbols

This crate allows obtaining symbol information from binaries and compilation artifacts. It maps raw code addresses to symbol strings, and, if available, file name + line number information. The API was designed for the Firefox profiler.

The main entry point of this crate is the SymbolManager struct and its async get_symbol_map method.

Design constraints

This crate operates under the following design constraints:

The WebAssembly requirement means that this crate cannot contain any direct file access. Instead, all file access is mediated through a FileAndPathHelper trait which has to be implemented by the caller. Furthermore, the API request does not carry any absolute file paths, so the resolution to absolute file paths needs to be done by the caller as well.

Supported formats and data

This crate supports obtaining symbol data from PE binaries (Windows), PDB files (Windows), mach-o binaries (including fat binaries) (macOS & iOS), and ELF binaries (Linux, Android, etc.). For mach-o files it also supports finding debug information in external objects, by following OSO stabs entries. It supports gathering both basic symbol information (function name strings) as well as information based on debug data, i.e. inline callstacks where each frame has a function name, a file name, and a line number. For debug data we support both DWARF debug data (inside mach-o and ELF binaries) and PDB debug data.

Example

```rust use samplysymbols::debugid::{CodeId, DebugId}; use samplysymbols::{ CandidatePathInfo, FileAndPathHelper, FileAndPathHelperResult, FileLocation, FramesLookupResult, OptionallySendFuture, SymbolManager, };

async fn runquery() { let thisdir = std::path::PathBuf::from(env!("CARGOMANIFESTDIR")); let helper = ExampleHelper { artifactdirectory: thisdir.join("..").join("fixtures").join("win64-ci"), };

let symbol_manager = SymbolManager::with_helper(&helper);

let symbol_map = match symbol_manager
    .load_symbol_map(
        "firefox.pdb",
        DebugId::from_breakpad("AA152DEB2D9B76084C4C44205044422E1").unwrap(),
    )
    .await
{
    Ok(symbol_map) => symbol_map,
    Err(e) => {
        println!("Error while loading the symbol map: {:?}", e);
        return;
    }
};

// Look up the symbol for an address.
let lookup_result = symbol_map.lookup(0x1f98f);

match lookup_result {
    Some(address_info) => {
        // Print the symbol name for this address:
        println!("0x1f98f: {}", address_info.symbol.name);

        // See if we have debug info (file name + line, and inlined frames):
        match address_info.frames {
            FramesLookupResult::Available(frames) => {
                println!("Debug info:");
                for frame in frames {
                    println!(
                        " - {:?} ({:?}:{:?})",
                        frame.function, frame.file_path, frame.line_number
                    );
                }
            }
            FramesLookupResult::External(ext_address) => {
                // Debug info is located in a different file.
                if let Some(frames) =
                    symbol_manager.lookup_external(&ext_address).await
                {
                    println!("Debug info:");
                    for frame in frames {
                        println!(
                            " - {:?} ({:?}:{:?})",
                            frame.function, frame.file_path, frame.line_number
                        );
                    }
                }
            }
            FramesLookupResult::Unavailable => {}
        }
    }
    None => {
        println!("No symbol was found for address 0x1f98f.")
    }
}

}

struct ExampleHelper { artifact_directory: std::path::PathBuf, }

impl<'h> FileAndPathHelper<'h> for ExampleHelper { type F = Vec; type OpenFileFuture = std::pin::Pin< Box> + 'h>,

;

fn get_candidate_paths_for_debug_file(
    &self,
    debug_name: &str,
    _debug_id: DebugId,
) -> FileAndPathHelperResult<Vec<CandidatePathInfo>> {
    Ok(vec![CandidatePathInfo::SingleFile(FileLocation::Path(
        self.artifact_directory.join(debug_name),
    ))])
}

fn get_candidate_paths_for_binary(
    &self,
    _debug_name: Option<&str>,
    _debug_id: Option<DebugId>,
    name: Option<&str>,
    _code_id: Option<&CodeId>,
) -> FileAndPathHelperResult<Vec<CandidatePathInfo>> {
    if let Some(name) = name {
        Ok(vec![CandidatePathInfo::SingleFile(FileLocation::Path(
            self.artifact_directory.join(name),
        ))])
    } else {
        Ok(vec![])
    }
}

fn open_file(
    &'h self,
    location: &FileLocation,
) -> std::pin::Pin<
    Box<dyn OptionallySendFuture<Output = FileAndPathHelperResult<Self::F>> + 'h>,
> {
    async fn read_file_impl(path: std::path::PathBuf) -> FileAndPathHelperResult<Vec<u8>> {
        Ok(std::fs::read(&path)?)
    }

    let path = match location {
        FileLocation::Path(path) => path.clone(),
        FileLocation::Custom(_) => panic!("Unexpected FileLocation::Custom"),
    };
    Box::pin(read_file_impl(path))
}

} ```