Skip to content

Add support for demangling C++ frames' symbols #31

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

Merged
merged 1 commit into from
Feb 27, 2017
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
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ script:
- cargo test --no-default-features --features 'serialize-serde'
- cargo test --no-default-features --features 'serialize-rustc'
- cargo test --no-default-features --features 'serialize-rustc serialize-serde'
- cd ./cpp_smoke_test && cargo test && cd ..
- cargo clean && cargo build
- rustdoc --test README.md -L target/debug/deps -L target/debug
- cargo doc --no-deps
Expand Down
7 changes: 5 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,15 @@ build = "build.rs"
[dependencies]
libc = "0.2"
cfg-if = "0.1"
rustc-demangle = "0.1"
rustc-demangle = "0.1.4"

# Optionally enable the ability to serialize a `Backtrace`
serde = { version = "0.8", optional = true }
rustc-serialize = { version = "0.3", optional = true }

# Optionally demangle C++ frames' symbols in backtraces.
cpp_demangle = { version = "0.2", optional = true }

[target.'cfg(windows)'.dependencies]
dbghelp-sys = { version = "0.2", optional = true }
kernel32-sys = { version = "0.2", optional = true }
Expand All @@ -42,7 +45,7 @@ serde_codegen = { version = "0.8", optional = true }
# Note that not all features are available on all platforms, so even though a
# feature is enabled some other feature may be used instead.
[features]
default = ["libunwind", "libbacktrace", "coresymbolication", "dladdr", "dbghelp"]
default = ["libunwind", "libbacktrace", "coresymbolication", "dladdr", "dbghelp", "cpp_demangle"]

#=======================================
# Methods of acquiring a backtrace
Expand Down
11 changes: 11 additions & 0 deletions cpp_smoke_test/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "cpp_smoke_test"
version = "0.1.0"
authors = ["Nick Fitzgerald <[email protected]>"]
build = "build.rs"

[build-dependencies]
gcc = "0.3.43"

[dependencies]
"backtrace" = { path = ".." }
16 changes: 16 additions & 0 deletions cpp_smoke_test/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
extern crate gcc;

fn main() {
compile_cpp();
}

fn compile_cpp() {
println!("cargo:rerun-if-changed=cpp/trampoline.cpp");

gcc::Config::new()
.cpp(true)
.debug(true)
.opt_level(0)
.file("cpp/trampoline.cpp")
.compile("libcpptrampoline.a");
}
14 changes: 14 additions & 0 deletions cpp_smoke_test/cpp/trampoline.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#include <stdio.h>

namespace space {
template <typename FuncT>
void templated_trampoline(FuncT func) {
func();
}
}

typedef void (*FuncPtr)();

extern "C" void cpp_trampoline(FuncPtr func) {
space::templated_trampoline(func);
}
3 changes: 3 additions & 0 deletions cpp_smoke_test/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#[test]
fn it_works() {
}
70 changes: 70 additions & 0 deletions cpp_smoke_test/tests/smoke.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
extern crate cpp_smoke_test;
extern crate backtrace;

use std::sync::atomic::{ATOMIC_BOOL_INIT, AtomicBool, Ordering};

extern "C" {
fn cpp_trampoline(func: extern "C" fn()) -> ();
}

#[test]
#[cfg(not(target_os = "windows"))]
fn smoke_test_cpp() {
static RAN_ASSERTS: AtomicBool = ATOMIC_BOOL_INIT;

extern "C" fn assert_cpp_frames() {
let mut physical_frames = Vec::new();
backtrace::trace(|cx| {
physical_frames.push(cx.ip());

// We only want to capture this closure's frame, assert_cpp_frames,
// space::templated_trampoline, and cpp_trampoline. Those are
// logical frames, which might be inlined into fewer physical
// frames, so we may end up with extra logical frames after
// resolving these.
physical_frames.len() < 4
});

let names: Vec<_> = physical_frames.into_iter()
.flat_map(|ip| {
let mut logical_frame_names = vec![];

backtrace::resolve(ip, |sym| {
let sym_name = sym.name().expect("Should have a symbol name");
let demangled = sym_name.to_string();
logical_frame_names.push(demangled);
});

assert!(!logical_frame_names.is_empty(),
"Should have resolved at least one symbol for the physical frame");

logical_frame_names
})
// Skip the backtrace::trace closure and assert_cpp_frames, and then
// take the two C++ frame names.
.skip_while(|name| !name.contains("trampoline"))
.take(2)
.collect();

println!("actual names = {:#?}", names);

let expected = [
"void space::templated_trampoline<void (*)()>(void (*)())",
"cpp_trampoline",
];
println!("expected names = {:#?}", expected);

assert_eq!(names.len(), expected.len());
for (actual, expected) in names.iter().zip(expected.iter()) {
assert_eq!(actual, expected);
}

RAN_ASSERTS.store(true, Ordering::SeqCst);
}

assert!(!RAN_ASSERTS.load(Ordering::SeqCst));
unsafe {
cpp_trampoline(assert_cpp_frames);
}
assert!(RAN_ASSERTS.load(Ordering::SeqCst));
}
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ extern crate cfg_if;

extern crate rustc_demangle;

#[cfg(feature = "cpp_demangle")]
extern crate cpp_demangle;

#[allow(dead_code)] // not used everywhere
#[cfg(unix)]
#[macro_use]
Expand Down
117 changes: 100 additions & 17 deletions src/symbolize/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use std::fmt;
#[cfg(not(feature = "cpp_demangle"))]
use std::marker::PhantomData;
use std::os::raw::c_void;
use std::path::Path;
use std::str;
use rustc_demangle::{demangle, Demangle};
use rustc_demangle::{try_demangle, Demangle};

/// Resolve an address to a symbol, passing the symbol to the specified
/// closure.
Expand Down Expand Up @@ -108,26 +110,76 @@ impl fmt::Debug for Symbol {
}
}


cfg_if! {
if #[cfg(feature = "cpp_demangle")] {
// Maybe a parsed C++ symbol, if parsing the mangled symbol as Rust
// failed.
struct OptionCppSymbol<'a>(Option<::cpp_demangle::BorrowedSymbol<'a>>);

impl<'a> OptionCppSymbol<'a> {
fn parse(input: &'a [u8]) -> OptionCppSymbol<'a> {
OptionCppSymbol(::cpp_demangle::BorrowedSymbol::new(input).ok())
}

fn none() -> OptionCppSymbol<'a> {
OptionCppSymbol(None)
}
}
} else {
// Make sure to keep this zero-sized, so that the `cpp_demangle` feature
// has no cost when disabled.
struct OptionCppSymbol<'a>(PhantomData<&'a ()>);

impl<'a> OptionCppSymbol<'a> {
fn parse(_: &'a [u8]) -> OptionCppSymbol<'a> {
OptionCppSymbol(PhantomData)
}

fn none() -> OptionCppSymbol<'a> {
OptionCppSymbol(PhantomData)
}
}
}
}

/// A wrapper around a symbol name to provide ergonomic accessors to the
/// demangled name, the raw bytes, the raw string, etc.
// Allow dead code for when the `cpp_demangle` feature is not enabled.
#[allow(dead_code)]
pub struct SymbolName<'a> {
bytes: &'a [u8],
demangled: Option<Demangle<'a>>,
cpp_demangled: OptionCppSymbol<'a>,
}

impl<'a> SymbolName<'a> {
/// Creates a new symbol name from the raw underlying bytes.
pub fn new(bytes: &'a [u8]) -> SymbolName<'a> {
let demangled = str::from_utf8(bytes).ok().map(demangle);
let str_bytes = str::from_utf8(bytes).ok();
let demangled = str_bytes.and_then(|s| try_demangle(s).ok());

let cpp = if demangled.is_none() {
OptionCppSymbol::parse(bytes)
} else {
OptionCppSymbol::none()
};

SymbolName {
bytes: bytes,
demangled: demangled,
cpp_demangled: cpp,
}
}

/// Returns the raw symbol name as `&str` if the symbols is valid utf-8.
/// Returns the raw symbol name as a `str` if the symbols is valid utf-8.
pub fn as_str(&self) -> Option<&'a str> {
self.demangled.as_ref().map(|s| s.as_str())
self.demangled
.as_ref()
.map(|s| s.as_str())
.or_else(|| {
str::from_utf8(self.bytes).ok()
})
}

/// Returns the raw symbol name as a list of bytes
Expand All @@ -136,22 +188,54 @@ impl<'a> SymbolName<'a> {
}
}

impl<'a> fmt::Display for SymbolName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(ref s) = self.demangled {
s.fmt(f)
} else {
String::from_utf8_lossy(self.bytes).fmt(f)
cfg_if! {
if #[cfg(feature = "cpp_demangle")] {
impl<'a> fmt::Display for SymbolName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(ref s) = self.demangled {
s.fmt(f)
} else if let Some(ref cpp) = self.cpp_demangled.0 {
cpp.fmt(f)
} else {
String::from_utf8_lossy(self.bytes).fmt(f)
}
}
}
} else {
impl<'a> fmt::Display for SymbolName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(ref s) = self.demangled {
s.fmt(f)
} else {
String::from_utf8_lossy(self.bytes).fmt(f)
}
}
}
}
}

impl<'a> fmt::Debug for SymbolName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(ref s) = self.demangled {
s.fmt(f)
} else {
String::from_utf8_lossy(self.bytes).fmt(f)
cfg_if! {
if #[cfg(feature = "cpp_demangle")] {
impl<'a> fmt::Debug for SymbolName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(ref s) = self.demangled {
s.fmt(f)
} else if let Some(ref cpp) = self.cpp_demangled.0 {
fmt::Display::fmt(cpp, f)
} else {
String::from_utf8_lossy(self.bytes).fmt(f)
}
}
}
} else {
impl<'a> fmt::Debug for SymbolName<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(ref s) = self.demangled {
s.fmt(f)
} else {
String::from_utf8_lossy(self.bytes).fmt(f)
}
}
}
}
}
Expand Down Expand Up @@ -185,4 +269,3 @@ cfg_if! {
use self::noop::Symbol as SymbolImp;
}
}