Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve backtrace symbolization #217

Merged
merged 7 commits into from
Oct 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ members = [
"crates/sel4-backtrace/embedded-debug-info",
"crates/sel4-backtrace/embedded-debug-info/cli",
"crates/sel4-backtrace/simple",
"crates/sel4-backtrace/symbolize",
"crates/sel4-backtrace/types",
"crates/sel4-bounce-buffer-allocator",
"crates/sel4-capdl-initializer",
Expand Down
22 changes: 22 additions & 0 deletions crates/sel4-backtrace/symbolize/Cargo.nix
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#
# Copyright 2024, Colias Group, LLC
#
# SPDX-License-Identifier: BSD-2-Clause
#

{ mk, mkDefaultFrontmatterWithReuseArgs, defaultReuseFrontmatterArgs, versions }:

mk rec {
nix.frontmatter = mkDefaultFrontmatterWithReuseArgs (defaultReuseFrontmatterArgs // {
licenseID = package.license;
});
package.name = "sel4-backtrace-symbolize";
package.license = "MIT OR Apache-2.0";
dependencies = {
addr2line = {
version = versions.addr2line;
default-features = false;
features = [ "rustc-demangle" "cpp_demangle" "fallible-iterator" "smallvec" ];
};
};
}
22 changes: 22 additions & 0 deletions crates/sel4-backtrace/symbolize/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#
# Copyright 2023, Colias Group, LLC
#
# SPDX-License-Identifier: MIT OR Apache-2.0
#
#
# This file is generated from './Cargo.nix'. You can edit this file directly
# if you are not using this project's Cargo manifest management tools.
# See 'hacking/cargo-manifest-management/README.md' for more information.
#

[package]
name = "sel4-backtrace-symbolize"
version = "0.1.0"
authors = ["Nick Spinale <nick.spinale@coliasgroup.com>"]
edition = "2021"
license = "MIT OR Apache-2.0"

[dependencies.addr2line]
version = "0.24.2"
default-features = false
features = ["rustc-demangle", "cpp_demangle", "fallible-iterator", "smallvec"]
142 changes: 142 additions & 0 deletions crates/sel4-backtrace/symbolize/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
//
// Copyright 2024, Colias Group, LLC
// Copyright (c) 2016-2018 The gimli Developers
//
// SPDX-License-Identifier: MIT OR Apache-2.0
//

// Adapted from:
// https://github.com/gimli-rs/addr2line/blob/0.24.2/src/bin/addr2line.rs

#![no_std]

extern crate alloc;

use alloc::borrow::Cow;
use core::fmt;

use addr2line::fallible_iterator::FallibleIterator;
use addr2line::gimli;
use addr2line::{Context, Location};

fn print_loc(w: &mut impl fmt::Write, loc: Option<&Location<'_>>) -> Result<(), fmt::Error> {
if let Some(loc) = loc {
if let Some(ref file) = loc.file.as_ref() {
write!(w, "{}:", file)?;
} else {
write!(w, "??:")?;
}
if let Some(line) = loc.line {
write!(w, "{}", line)?;
} else {
write!(w, "?")?;
}
writeln!(w)?;
} else {
writeln!(w, "??:0")?;
}
Ok(())
}

fn print_function(
w: &mut impl fmt::Write,
name: Option<&str>,
language: Option<gimli::DwLang>,
demangle: bool,
) -> Result<(), fmt::Error> {
if let Some(name) = name {
if demangle {
write!(w, "{}", addr2line::demangle_auto(Cow::from(name), language))?;
} else {
write!(w, "{}", name)?;
}
} else {
write!(w, "??")?;
}
Ok(())
}

#[derive(Copy, Clone, Eq, PartialEq)]
pub struct Options {
pub do_functions: bool,
pub do_inlines: bool,
pub demangle: bool,
}

impl Default for Options {
fn default() -> Self {
Self {
do_functions: true,
do_inlines: true,
demangle: true,
}
}
}

pub fn symbolize(
w: &mut impl fmt::Write,
ctx: &Context<impl gimli::Reader>,
opts: &Options,
addrs: impl Iterator<Item = u64>,
) -> Result<(), fmt::Error> {
for probe in addrs {
write!(w, "{:#018x} ", probe)?;

if opts.do_functions || opts.do_inlines {
let mut printed_anything = false;
let mut frames = ctx.find_frames(probe).skip_all_loads().unwrap().peekable();
let mut first = true;
while let Some(frame) = frames.next().unwrap() {
if !first {
write!(w, "{: >18} ", "(inlined by)")?;
}
first = false;

if opts.do_functions {
// TODO
// See:
// https://github.com/gimli-rs/addr2line/blob/621a3abe985b32f43dd1e8c10e003abe902c68e2/src/bin/addr2line.rs#L223-L242
if let Some(func) = frame.function {
print_function(
w,
func.raw_name().ok().as_deref(),
func.language,
opts.demangle,
)?;
} else {
print_function(w, None, None, opts.demangle)?;
}

write!(w, " at ")?;
}

print_loc(w, frame.location.as_ref())?;

printed_anything = true;

if !opts.do_inlines {
break;
}
}

if !printed_anything {
if opts.do_functions {
// TODO
// let name = ctx.find_symbol(probe);
let name = None;

print_function(w, name, None, opts.demangle)?;

write!(w, " at ")?;
}

print_loc(w, None)?;
}
} else {
let loc = ctx.find_location(probe).unwrap();
print_loc(w, loc.as_ref())?;
}
}

Ok(())
}
4 changes: 3 additions & 1 deletion crates/sel4-backtrace/types/Cargo.nix
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
# SPDX-License-Identifier: MIT
#

{ mk, mkDefaultFrontmatterWithReuseArgs, defaultReuseFrontmatterArgs, versions, serdeWith, postcardWith }:
{ mk, mkDefaultFrontmatterWithReuseArgs, defaultReuseFrontmatterArgs, versions, serdeWith, postcardWith, localCrates }:

mk rec {
nix.frontmatter = mkDefaultFrontmatterWithReuseArgs (defaultReuseFrontmatterArgs // {
Expand All @@ -17,6 +17,7 @@ mk rec {
serde = serdeWith [ "derive" ] // { optional = true; };
postcard = postcardWith [] // { optional = true; };
addr2line = { version = versions.addr2line; default-features = false; features = [ "rustc-demangle" "cpp_demangle" "fallible-iterator" "smallvec" ]; optional = true; };
sel4-backtrace-symbolize = localCrates.sel4-backtrace-symbolize // { optional = true; };
};
features = {
alloc = [
Expand All @@ -32,6 +33,7 @@ mk rec {
symbolize = [
"addr2line"
"alloc"
"sel4-backtrace-symbolize"
];
full = [
"alloc"
Expand Down
3 changes: 2 additions & 1 deletion crates/sel4-backtrace/types/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,12 @@ alloc = ["serde?/alloc"]
full = ["alloc", "serde", "postcard", "symbolize"]
postcard = ["serde", "dep:postcard"]
serde = ["dep:serde"]
symbolize = ["addr2line", "alloc"]
symbolize = ["addr2line", "alloc", "sel4-backtrace-symbolize"]

[dependencies]
cfg-if = "1.0.0"
postcard = { version = "1.0.2", default-features = false, optional = true }
sel4-backtrace-symbolize = { path = "../symbolize", optional = true }
serde = { version = "1.0.147", default-features = false, features = ["derive"], optional = true }

[dependencies.addr2line]
Expand Down
77 changes: 11 additions & 66 deletions crates/sel4-backtrace/types/src/with_symbolize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,15 @@

#![allow(clippy::write_with_newline)]

use alloc::format;
use alloc::string::String;
use alloc::string::ToString;
use core::fmt;

use addr2line::fallible_iterator::FallibleIterator;
use addr2line::gimli::read::Reader;
use addr2line::gimli::Error;
use addr2line::Context;

use crate::Backtrace;
use sel4_backtrace_symbolize::symbolize;

// TODO handle inlining better (see TODOs scattered throughout this file)
use crate::Backtrace;

impl<T> Backtrace<T> {
pub fn symbolize<R: Reader>(
Expand All @@ -30,66 +26,15 @@ impl<T> Backtrace<T> {
if let Some(ref err) = self.postamble.error {
writeln!(w, " error: {:?}", err).unwrap();
}
for (i, entry) in self.entries.iter().enumerate() {
let mut first = true;
let frame = &entry.stack_frame;
// TODO
// let mut seen = false;
// let initial_location = ctx.find_location(frame.ip as u64)?;
ctx.find_frames(frame.ip as u64)
.skip_all_loads()?
.for_each(|inner_frame| {
if first {
write!(w, " {:4}: {:#18x} - ", i, frame.ip).unwrap();
} else {
write!(w, " {:4} {:18 } ", "", "").unwrap();
}
// TODO
// if inner_frame.location == frame {
// seen = true;
// }
match inner_frame.function {
Some(f) => {
// TODO
// let raw_name = f.raw_name()?;
// let demangled = demangle(&raw_name);
let demangled = f.demangle()?;
write!(w, "{}", demangled).unwrap()
}
None => write!(w, "<unknown>").unwrap(),
}
write!(w, "\n").unwrap();
// TODO
// if let Some(loc) = inner_frame.location {
// writeln!(w, " {:18} at {}", "", fmt_location(loc)).unwrap();
// }
first = false;
Ok(())
})?;
// TODO this isn't accurate
if let Some(loc) = ctx.find_location(frame.ip as u64)? {
writeln!(w, " {:18} at {}", "", fmt_location(loc)).unwrap();
}
// TODO
// if !seen {
// write!(w, " ").unwrap();
// write!(w, "warning: initial location missing: {}", initial_location).unwrap();
// write!(w, "\n").unwrap();
// }
}
symbolize(
w,
ctx,
&Default::default(),
self.entries
.iter()
.map(|entry| entry.stack_frame.ip.try_into().unwrap()),
)
.unwrap();
Ok(())
}
}

fn fmt_location(loc: addr2line::Location) -> String {
format!(
"{} {},{}",
loc.file.unwrap_or("<unknown>"),
loc.line
.map(|x| x.to_string())
.unwrap_or(String::from("<unknown>")),
loc.column
.map(|x| x.to_string())
.unwrap_or(String::from("<unknown>")),
)
}
Loading