Bug 1716518 - Upgrade rustc-demangle to v0.1.19.

Differential Revision: https://phabricator.services.mozilla.com/D117847

Depends on D117846
This commit is contained in:
Mike Hommey 2021-06-15 09:24:47 +00:00
parent 56e1ee0ba7
commit 4420c3c09d
8 changed files with 1826 additions and 207 deletions

4
Cargo.lock generated
View File

@ -4391,9 +4391,9 @@ dependencies = [
[[package]] [[package]]
name = "rustc-demangle" name = "rustc-demangle"
version = "0.1.8" version = "0.1.19"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76d7ba1feafada44f2d38eed812bd2489a03c0f5abb975799251518b68848649" checksum = "410f7acf3cb3a44527c5d9546bad4bf4e6c460915d5f9f2fc524498bfe8f70ce"
[[package]] [[package]]
name = "rustc-hash" name = "rustc-hash"

View File

@ -1 +1 @@
{"files":{"Cargo.toml":"8ceaf60013499028a9d0ec93e4b0c5cef763c1bc31dfa117e5ab6989b3ebda6a","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"378f5840b258e2779c39418f3f2d7b2ba96f1c7917dd6be0713f88305dbda397","README.md":"7bb7dbc6378a31b5b925a0cff628a69006c77a4cdf3533f7507b7c8fbe3492b0","src/lib.rs":"2a6aaafcc0c6e398321b33187b47b3ee70ad35f44a22e9d4e1e1d24c5c223f3f","src/main.rs":"b84cf381d0ac832be4fb13f6bbec2fd0a0d0c12d1d68aaa84db7a6d76b1466cb"},"package":"76d7ba1feafada44f2d38eed812bd2489a03c0f5abb975799251518b68848649"} {"files":{"Cargo.toml":"14e6ccb02b4ad07261df1dfd0325460a546c049249f01fc49589543071f70402","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"378f5840b258e2779c39418f3f2d7b2ba96f1c7917dd6be0713f88305dbda397","README.md":"3bb7af78423e95b207beebd452cdd973d65663cf25a0fc9358c588f53783293c","src/legacy.rs":"b4d5a140ed0bf2d792431961d6fd44a21c99235489a2c9f6717d1577a42c09ce","src/lib.rs":"84d6a85f1f1d5a68904a814b3bc59fcba00caafce83208cc4d6d53ed8c3e4cc3","src/v0.rs":"8d4e4862942045210bae59e4458526ca0784f7504447f74197870df3254c6489"},"package":"410f7acf3cb3a44527c5d9546bad4bf4e6c460915d5f9f2fc524498bfe8f70ce"}

View File

@ -3,7 +3,7 @@
# When uploading crates to the registry Cargo will automatically # When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility # "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies # with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g. crates.io) dependencies # to registry (e.g., crates.io) dependencies
# #
# If you believe there's an error in this file please file an # If you believe there's an error in this file please file an
# issue against the rust-lang/cargo repository. If you're # issue against the rust-lang/cargo repository. If you're
@ -12,7 +12,7 @@
[package] [package]
name = "rustc-demangle" name = "rustc-demangle"
version = "0.1.8" version = "0.1.19"
authors = ["Alex Crichton <alex@alexcrichton.com>"] authors = ["Alex Crichton <alex@alexcrichton.com>"]
description = "Rust compiler symbol demangling.\n" description = "Rust compiler symbol demangling.\n"
homepage = "https://github.com/alexcrichton/rustc-demangle" homepage = "https://github.com/alexcrichton/rustc-demangle"
@ -20,3 +20,16 @@ documentation = "https://docs.rs/rustc-demangle"
readme = "README.md" readme = "README.md"
license = "MIT/Apache-2.0" license = "MIT/Apache-2.0"
repository = "https://github.com/alexcrichton/rustc-demangle" repository = "https://github.com/alexcrichton/rustc-demangle"
[profile.release]
lto = true
[dependencies.compiler_builtins]
version = "0.1.2"
optional = true
[dependencies.core]
version = "1.0.0"
optional = true
package = "rustc-std-workspace-core"
[features]
rustc-dep-of-std = ["core", "compiler_builtins"]

View File

@ -1,11 +1,35 @@
# rustc-demangle # rustc-demangle
Symbol demangling for Rust Demangling for Rust symbols, written in Rust.
[![Build Status](https://travis-ci.org/alexcrichton/rustc-demangle.svg?branch=master)](https://travis-ci.org/alexcrichton/rustc-demangle)
[Documentation](https://docs.rs/rustc-demangle) [Documentation](https://docs.rs/rustc-demangle)
## Usage
You can add this as a dependency via your `Cargo.toml`
```toml
[dependencies]
rustc-demangle = "0.1"
```
and then be sure to check out the [crate
documentation](https://docs.rs/rustc-demangle) for usage.
## Usage from non-Rust languages
You can also use this crate from other languages via the C API wrapper in the
`crates/capi` directory. This can be build with:
```sh
$ cargo build -p rustc-demangle-capi --release
```
You'll then find `target/release/librustc_demangle.a` and
`target/release/librustc_demangle.so` (or a different name depending on your
platform). These objects implement the interface specified in
`crates/capi/include/rustc_demangle.h`.
# License # License
This project is licensed under either of This project is licensed under either of

View File

@ -0,0 +1,392 @@
use core::char;
use core::fmt;
/// Representation of a demangled symbol name.
pub struct Demangle<'a> {
inner: &'a str,
/// The number of ::-separated elements in the original name.
elements: usize,
}
/// De-mangles a Rust symbol into a more readable version
///
/// All Rust symbols by default are mangled as they contain characters that
/// cannot be represented in all object files. The mangling mechanism is similar
/// to C++'s, but Rust has a few specifics to handle items like lifetimes in
/// symbols.
///
/// This function will take a **mangled** symbol and return a value. When printed,
/// the de-mangled version will be written. If the symbol does not look like
/// a mangled symbol, the original value will be written instead.
///
/// # Examples
///
/// ```
/// use rustc_demangle::demangle;
///
/// assert_eq!(demangle("_ZN4testE").to_string(), "test");
/// assert_eq!(demangle("_ZN3foo3barE").to_string(), "foo::bar");
/// assert_eq!(demangle("foo").to_string(), "foo");
/// ```
// All Rust symbols are in theory lists of "::"-separated identifiers. Some
// assemblers, however, can't handle these characters in symbol names. To get
// around this, we use C++-style mangling. The mangling method is:
//
// 1. Prefix the symbol with "_ZN"
// 2. For each element of the path, emit the length plus the element
// 3. End the path with "E"
//
// For example, "_ZN4testE" => "test" and "_ZN3foo3barE" => "foo::bar".
//
// We're the ones printing our backtraces, so we can't rely on anything else to
// demangle our symbols. It's *much* nicer to look at demangled symbols, so
// this function is implemented to give us nice pretty output.
//
// Note that this demangler isn't quite as fancy as it could be. We have lots
// of other information in our symbols like hashes, version, type information,
// etc. Additionally, this doesn't handle glue symbols at all.
pub fn demangle(s: &str) -> Result<(Demangle, &str), ()> {
// First validate the symbol. If it doesn't look like anything we're
// expecting, we just print it literally. Note that we must handle non-Rust
// symbols because we could have any function in the backtrace.
let inner = if s.starts_with("_ZN") {
&s[3..]
} else if s.starts_with("ZN") {
// On Windows, dbghelp strips leading underscores, so we accept "ZN...E"
// form too.
&s[2..]
} else if s.starts_with("__ZN") {
// On OSX, symbols are prefixed with an extra _
&s[4..]
} else {
return Err(());
};
// only work with ascii text
if inner.bytes().any(|c| c & 0x80 != 0) {
return Err(());
}
let mut elements = 0;
let mut chars = inner.chars();
let mut c = chars.next().ok_or(())?;
while c != 'E' {
// Decode an identifier element's length.
if !c.is_digit(10) {
return Err(());
}
let mut len = 0usize;
while let Some(d) = c.to_digit(10) {
len = len
.checked_mul(10)
.and_then(|len| len.checked_add(d as usize))
.ok_or(())?;
c = chars.next().ok_or(())?;
}
// `c` already contains the first character of this identifier, skip it and
// all the other characters of this identifier, to reach the next element.
for _ in 0..len {
c = chars.next().ok_or(())?;
}
elements += 1;
}
Ok((Demangle { inner, elements }, chars.as_str()))
}
// Rust hashes are hex digits with an `h` prepended.
fn is_rust_hash(s: &str) -> bool {
s.starts_with('h') && s[1..].chars().all(|c| c.is_digit(16))
}
impl<'a> fmt::Display for Demangle<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Alright, let's do this.
let mut inner = self.inner;
for element in 0..self.elements {
let mut rest = inner;
while rest.chars().next().unwrap().is_digit(10) {
rest = &rest[1..];
}
let i: usize = inner[..(inner.len() - rest.len())].parse().unwrap();
inner = &rest[i..];
rest = &rest[..i];
// Skip printing the hash if alternate formatting
// was requested.
if f.alternate() && element + 1 == self.elements && is_rust_hash(&rest) {
break;
}
if element != 0 {
f.write_str("::")?;
}
if rest.starts_with("_$") {
rest = &rest[1..];
}
loop {
if rest.starts_with('.') {
if let Some('.') = rest[1..].chars().next() {
f.write_str("::")?;
rest = &rest[2..];
} else {
f.write_str(".")?;
rest = &rest[1..];
}
} else if rest.starts_with('$') {
let (escape, after_escape) = if let Some(end) = rest[1..].find('$') {
(&rest[1..=end], &rest[end + 2..])
} else {
break;
};
// see src/librustc_codegen_utils/symbol_names/legacy.rs for these mappings
let unescaped = match escape {
"SP" => "@",
"BP" => "*",
"RF" => "&",
"LT" => "<",
"GT" => ">",
"LP" => "(",
"RP" => ")",
"C" => ",",
_ => {
if escape.starts_with('u') {
let digits = &escape[1..];
let all_lower_hex = digits.chars().all(|c| match c {
'0'..='9' | 'a'..='f' => true,
_ => false,
});
let c = u32::from_str_radix(digits, 16)
.ok()
.and_then(char::from_u32);
if let (true, Some(c)) = (all_lower_hex, c) {
// FIXME(eddyb) do we need to filter out control codepoints?
if !c.is_control() {
c.fmt(f)?;
rest = after_escape;
continue;
}
}
}
break;
}
};
f.write_str(unescaped)?;
rest = after_escape;
} else if let Some(i) = rest.find(|c| c == '$' || c == '.') {
f.write_str(&rest[..i])?;
rest = &rest[i..];
} else {
break;
}
}
f.write_str(rest)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::prelude::v1::*;
macro_rules! t {
($a:expr, $b:expr) => {
assert!(ok($a, $b))
};
}
macro_rules! t_err {
($a:expr) => {
assert!(ok_err($a))
};
}
macro_rules! t_nohash {
($a:expr, $b:expr) => {{
assert_eq!(format!("{:#}", ::demangle($a)), $b);
}};
}
fn ok(sym: &str, expected: &str) -> bool {
match ::try_demangle(sym) {
Ok(s) => {
if s.to_string() == expected {
true
} else {
println!("\n{}\n!=\n{}\n", s, expected);
false
}
}
Err(_) => {
println!("error demangling");
false
}
}
}
fn ok_err(sym: &str) -> bool {
match ::try_demangle(sym) {
Ok(_) => {
println!("succeeded in demangling");
false
}
Err(_) => ::demangle(sym).to_string() == sym,
}
}
#[test]
fn demangle() {
t_err!("test");
t!("_ZN4testE", "test");
t_err!("_ZN4test");
t!("_ZN4test1a2bcE", "test::a::bc");
}
#[test]
fn demangle_dollars() {
t!("_ZN4$RP$E", ")");
t!("_ZN8$RF$testE", "&test");
t!("_ZN8$BP$test4foobE", "*test::foob");
t!("_ZN9$u20$test4foobE", " test::foob");
t!("_ZN35Bar$LT$$u5b$u32$u3b$$u20$4$u5d$$GT$E", "Bar<[u32; 4]>");
}
#[test]
fn demangle_many_dollars() {
t!("_ZN13test$u20$test4foobE", "test test::foob");
t!("_ZN12test$BP$test4foobE", "test*test::foob");
}
#[test]
fn demangle_osx() {
t!(
"__ZN5alloc9allocator6Layout9for_value17h02a996811f781011E",
"alloc::allocator::Layout::for_value::h02a996811f781011"
);
t!("__ZN38_$LT$core..option..Option$LT$T$GT$$GT$6unwrap18_MSG_FILE_LINE_COL17haf7cb8d5824ee659E", "<core::option::Option<T>>::unwrap::_MSG_FILE_LINE_COL::haf7cb8d5824ee659");
t!("__ZN4core5slice89_$LT$impl$u20$core..iter..traits..IntoIterator$u20$for$u20$$RF$$u27$a$u20$$u5b$T$u5d$$GT$9into_iter17h450e234d27262170E", "core::slice::<impl core::iter::traits::IntoIterator for &'a [T]>::into_iter::h450e234d27262170");
}
#[test]
fn demangle_windows() {
t!("ZN4testE", "test");
t!("ZN13test$u20$test4foobE", "test test::foob");
t!("ZN12test$RF$test4foobE", "test&test::foob");
}
#[test]
fn demangle_elements_beginning_with_underscore() {
t!("_ZN13_$LT$test$GT$E", "<test>");
t!("_ZN28_$u7b$$u7b$closure$u7d$$u7d$E", "{{closure}}");
t!("_ZN15__STATIC_FMTSTRE", "__STATIC_FMTSTR");
}
#[test]
fn demangle_trait_impls() {
t!(
"_ZN71_$LT$Test$u20$$u2b$$u20$$u27$static$u20$as$u20$foo..Bar$LT$Test$GT$$GT$3barE",
"<Test + 'static as foo::Bar<Test>>::bar"
);
}
#[test]
fn demangle_without_hash() {
let s = "_ZN3foo17h05af221e174051e9E";
t!(s, "foo::h05af221e174051e9");
t_nohash!(s, "foo");
}
#[test]
fn demangle_without_hash_edgecases() {
// One element, no hash.
t_nohash!("_ZN3fooE", "foo");
// Two elements, no hash.
t_nohash!("_ZN3foo3barE", "foo::bar");
// Longer-than-normal hash.
t_nohash!("_ZN3foo20h05af221e174051e9abcE", "foo");
// Shorter-than-normal hash.
t_nohash!("_ZN3foo5h05afE", "foo");
// Valid hash, but not at the end.
t_nohash!("_ZN17h05af221e174051e93fooE", "h05af221e174051e9::foo");
// Not a valid hash, missing the 'h'.
t_nohash!("_ZN3foo16ffaf221e174051e9E", "foo::ffaf221e174051e9");
// Not a valid hash, has a non-hex-digit.
t_nohash!("_ZN3foo17hg5af221e174051e9E", "foo::hg5af221e174051e9");
}
#[test]
fn demangle_thinlto() {
// One element, no hash.
t!("_ZN3fooE.llvm.9D1C9369", "foo");
t!("_ZN3fooE.llvm.9D1C9369@@16", "foo");
t_nohash!(
"_ZN9backtrace3foo17hbb467fcdaea5d79bE.llvm.A5310EB9",
"backtrace::foo"
);
}
#[test]
fn demangle_llvm_ir_branch_labels() {
t!("_ZN4core5slice77_$LT$impl$u20$core..ops..index..IndexMut$LT$I$GT$$u20$for$u20$$u5b$T$u5d$$GT$9index_mut17haf9727c2edfbc47bE.exit.i.i", "core::slice::<impl core::ops::index::IndexMut<I> for [T]>::index_mut::haf9727c2edfbc47b.exit.i.i");
t_nohash!("_ZN4core5slice77_$LT$impl$u20$core..ops..index..IndexMut$LT$I$GT$$u20$for$u20$$u5b$T$u5d$$GT$9index_mut17haf9727c2edfbc47bE.exit.i.i", "core::slice::<impl core::ops::index::IndexMut<I> for [T]>::index_mut.exit.i.i");
}
#[test]
fn demangle_ignores_suffix_that_doesnt_look_like_a_symbol() {
t_err!("_ZN3fooE.llvm moocow");
}
#[test]
fn dont_panic() {
::demangle("_ZN2222222222222222222222EE").to_string();
::demangle("_ZN5*70527e27.ll34csaғE").to_string();
::demangle("_ZN5*70527a54.ll34_$b.1E").to_string();
::demangle(
"\
_ZN5~saäb4e\n\
2734cOsbE\n\
5usage20h)3\0\0\0\0\0\0\07e2734cOsbE\
",
)
.to_string();
}
#[test]
fn invalid_no_chop() {
t_err!("_ZNfooE");
}
#[test]
fn handle_assoc_types() {
t!("_ZN151_$LT$alloc..boxed..Box$LT$alloc..boxed..FnBox$LT$A$C$$u20$Output$u3d$R$GT$$u20$$u2b$$u20$$u27$a$GT$$u20$as$u20$core..ops..function..FnOnce$LT$A$GT$$GT$9call_once17h69e8f44b3723e1caE", "<alloc::boxed::Box<alloc::boxed::FnBox<A, Output=R> + 'a> as core::ops::function::FnOnce<A>>::call_once::h69e8f44b3723e1ca");
}
#[test]
fn handle_bang() {
t!(
"_ZN88_$LT$core..result..Result$LT$$u21$$C$$u20$E$GT$$u20$as$u20$std..process..Termination$GT$6report17hfc41d0da4a40b3e8E",
"<core::result::Result<!, E> as std::process::Termination>::report::hfc41d0da4a40b3e8"
);
}
#[test]
fn demangle_utf8_idents() {
t_nohash!(
"_ZN11utf8_idents157_$u10e1$$u10d0$$u10ed$$u10db$$u10d4$$u10da$$u10d0$$u10d3$_$u10d2$$u10d4$$u10db$$u10e0$$u10d8$$u10d4$$u10da$$u10d8$_$u10e1$$u10d0$$u10d3$$u10d8$$u10da$$u10d8$17h21634fd5714000aaE",
"utf8_idents::საჭმელად_გემრიელი_სადილი"
);
}
#[test]
fn demangle_issue_60925() {
t_nohash!(
"_ZN11issue_609253foo37Foo$LT$issue_60925..llv$u6d$..Foo$GT$3foo17h059a991a004536adE",
"issue_60925::foo::Foo<issue_60925::llvm::Foo>::foo"
);
}
}

View File

@ -30,28 +30,28 @@
#[macro_use] #[macro_use]
extern crate std; extern crate std;
mod legacy;
mod v0;
use core::fmt; use core::fmt;
/// Representation of a demangled symbol name. /// Representation of a demangled symbol name.
pub struct Demangle<'a> { pub struct Demangle<'a> {
style: Option<DemangleStyle<'a>>,
original: &'a str, original: &'a str,
inner: &'a str, suffix: &'a str,
valid: bool, }
/// The number of ::-separated elements in the original name.
elements: usize, enum DemangleStyle<'a> {
Legacy(legacy::Demangle<'a>),
V0(v0::Demangle<'a>),
} }
/// De-mangles a Rust symbol into a more readable version /// De-mangles a Rust symbol into a more readable version
/// ///
/// All rust symbols by default are mangled as they contain characters that /// This function will take a **mangled** symbol and return a value. When printed,
/// cannot be represented in all object files. The mangling mechanism is similar /// the de-mangled version will be written. If the symbol does not look like
/// to C++'s, but Rust has a few specifics to handle items like lifetimes in /// a mangled symbol, the original value will be written instead.
/// symbols.
///
/// This function will take a **mangled** symbol (typically acquired from a
/// `Symbol` which is in turn resolved from a `Frame`) and then writes the
/// de-mangled version into the given `writer`. If the symbol does not look like
/// a mangled symbol, it is still written to `writer`.
/// ///
/// # Examples /// # Examples
/// ///
@ -62,36 +62,16 @@ pub struct Demangle<'a> {
/// assert_eq!(demangle("_ZN3foo3barE").to_string(), "foo::bar"); /// assert_eq!(demangle("_ZN3foo3barE").to_string(), "foo::bar");
/// assert_eq!(demangle("foo").to_string(), "foo"); /// assert_eq!(demangle("foo").to_string(), "foo");
/// ``` /// ```
// All rust symbols are in theory lists of "::"-separated identifiers. Some
// assemblers, however, can't handle these characters in symbol names. To get
// around this, we use C++-style mangling. The mangling method is:
//
// 1. Prefix the symbol with "_ZN"
// 2. For each element of the path, emit the length plus the element
// 3. End the path with "E"
//
// For example, "_ZN4testE" => "test" and "_ZN3foo3barE" => "foo::bar".
//
// We're the ones printing our backtraces, so we can't rely on anything else to
// demangle our symbols. It's *much* nicer to look at demangled symbols, so
// this function is implemented to give us nice pretty output.
//
// Note that this demangler isn't quite as fancy as it could be. We have lots
// of other information in our symbols like hashes, version, type information,
// etc. Additionally, this doesn't handle glue symbols at all.
pub fn demangle(mut s: &str) -> Demangle { pub fn demangle(mut s: &str) -> Demangle {
// During ThinLTO LLVM may import and rename internal symbols, so strip out // During ThinLTO LLVM may import and rename internal symbols, so strip out
// those endings first as they're on of the last manglings applied to symbol // those endings first as they're one of the last manglings applied to symbol
// names. // names.
let llvm = ".llvm."; let llvm = ".llvm.";
if let Some(i) = s.find(llvm) { if let Some(i) = s.find(llvm) {
let candidate = &s[i + llvm.len()..]; let candidate = &s[i + llvm.len()..];
let all_hex = candidate.chars().all(|c| { let all_hex = candidate.chars().all(|c| match c {
match c { 'A'..='F' | '0'..='9' | '@' => true,
'A' ... 'F' | '0' ... '9' | '@' => true, _ => false,
_ => false,
}
}); });
if all_hex { if all_hex {
@ -99,66 +79,37 @@ pub fn demangle(mut s: &str) -> Demangle {
} }
} }
// First validate the symbol. If it doesn't look like anything we're let mut suffix = "";
// expecting, we just print it literally. Note that we must handle non-rust let mut style = match legacy::demangle(s) {
// symbols because we could have any function in the backtrace. Ok((d, s)) => {
let mut valid = true; suffix = s;
let mut inner = s; Some(DemangleStyle::Legacy(d))
if s.len() > 4 && s.starts_with("_ZN") && s.ends_with('E') { }
inner = &s[3..s.len() - 1]; Err(()) => match v0::demangle(s) {
} else if s.len() > 3 && s.starts_with("ZN") && s.ends_with('E') { Ok((d, s)) => {
// On Windows, dbghelp strips leading underscores, so we accept "ZN...E" suffix = s;
// form too. Some(DemangleStyle::V0(d))
inner = &s[2..s.len() - 1];
} else if s.len() > 5 && s.starts_with("__ZN") && s.ends_with('E') {
// On OSX, symbols are prefixed with an extra _
inner = &s[4..s.len() - 1];
} else {
valid = false;
}
// only work with ascii text
if inner.bytes().any(|c| c & 0x80 != 0) {
valid = false;
}
let mut elements = 0;
if valid {
let mut chars = inner.chars().peekable();
while valid {
let mut i = 0usize;
while let Some(&c) = chars.peek() {
if !c.is_digit(10) {
break
}
chars.next();
let next = i.checked_mul(10)
.and_then(|i| i.checked_add(c as usize - '0' as usize));
i = match next {
Some(i) => i,
None => {
valid = false;
break
}
};
} }
Err(v0::Invalid) => None,
},
};
if i == 0 { // Output like LLVM IR adds extra period-delimited words. See if
valid = chars.next().is_none(); // we are in that case and save the trailing words if so.
break; if !suffix.is_empty() {
} else if chars.by_ref().take(i).count() != i { if suffix.starts_with('.') && is_symbol_like(suffix) {
valid = false; // Keep the suffix.
} else { } else {
elements += 1; // Reset the suffix and invalidate the demangling.
} suffix = "";
style = None;
} }
} }
Demangle { Demangle {
inner: inner, style,
valid: valid,
elements: elements,
original: s, original: s,
suffix,
} }
} }
@ -184,7 +135,7 @@ pub struct TryDemangleError {
/// ``` /// ```
pub fn try_demangle(s: &str) -> Result<Demangle, TryDemangleError> { pub fn try_demangle(s: &str) -> Result<Demangle, TryDemangleError> {
let sym = demangle(s); let sym = demangle(s);
if sym.valid { if sym.style.is_some() {
Ok(sym) Ok(sym)
} else { } else {
Err(TryDemangleError { _priv: () }) Err(TryDemangleError { _priv: () })
@ -198,98 +149,41 @@ impl<'a> Demangle<'a> {
} }
} }
// Rust hashes are hex digits with an `h` prepended. fn is_symbol_like(s: &str) -> bool {
fn is_rust_hash(s: &str) -> bool { s.chars().all(|c| {
s.starts_with('h') && s[1..].chars().all(|c| c.is_digit(16)) // Once `char::is_ascii_punctuation` and `char::is_ascii_alphanumeric`
// have been stable for long enough, use those instead for clarity
is_ascii_alphanumeric(c) || is_ascii_punctuation(c)
})
}
// Copied from the documentation of `char::is_ascii_alphanumeric`
fn is_ascii_alphanumeric(c: char) -> bool {
match c {
'\u{0041}'..='\u{005A}' | '\u{0061}'..='\u{007A}' | '\u{0030}'..='\u{0039}' => true,
_ => false,
}
}
// Copied from the documentation of `char::is_ascii_punctuation`
fn is_ascii_punctuation(c: char) -> bool {
match c {
'\u{0021}'..='\u{002F}'
| '\u{003A}'..='\u{0040}'
| '\u{005B}'..='\u{0060}'
| '\u{007B}'..='\u{007E}' => true,
_ => false,
}
} }
impl<'a> fmt::Display for Demangle<'a> { impl<'a> fmt::Display for Demangle<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Alright, let's do this. match self.style {
if !self.valid { None => f.write_str(self.original)?,
return f.write_str(self.inner); Some(DemangleStyle::Legacy(ref d)) => fmt::Display::fmt(d, f)?,
Some(DemangleStyle::V0(ref d)) => fmt::Display::fmt(d, f)?,
} }
f.write_str(self.suffix)
let mut inner = self.inner;
for element in 0..self.elements {
let mut rest = inner;
while rest.chars().next().unwrap().is_digit(10) {
rest = &rest[1..];
}
let i: usize = inner[..(inner.len() - rest.len())].parse().unwrap();
inner = &rest[i..];
rest = &rest[..i];
// Skip printing the hash if alternate formatting
// was requested.
if f.alternate() && element+1 == self.elements && is_rust_hash(&rest) {
break;
}
if element != 0 {
try!(f.write_str("::"));
}
if rest.starts_with("_$") {
rest = &rest[1..];
}
while !rest.is_empty() {
if rest.starts_with('.') {
if let Some('.') = rest[1..].chars().next() {
try!(f.write_str("::"));
rest = &rest[2..];
} else {
try!(f.write_str("."));
rest = &rest[1..];
}
} else if rest.starts_with('$') {
macro_rules! demangle {
($($pat:expr => $demangled:expr),*) => ({
$(if rest.starts_with($pat) {
try!(f.write_str($demangled));
rest = &rest[$pat.len()..];
} else)*
{
try!(f.write_str(rest));
break;
}
})
}
// see src/librustc/back/link.rs for these mappings
demangle! {
"$SP$" => "@",
"$BP$" => "*",
"$RF$" => "&",
"$LT$" => "<",
"$GT$" => ">",
"$LP$" => "(",
"$RP$" => ")",
"$C$" => ",",
// in theory we can demangle any Unicode code point, but
// for simplicity we just catch the common ones.
"$u7e$" => "~",
"$u20$" => " ",
"$u27$" => "'",
"$u5b$" => "[",
"$u5d$" => "]",
"$u7b$" => "{",
"$u7d$" => "}",
"$u3b$" => ";",
"$u2b$" => "+",
"$u22$" => "\""
}
} else {
let idx = match rest.char_indices().find(|&(_, c)| c == '$' || c == '.') {
None => rest.len(),
Some((i, _)) => i,
};
try!(f.write_str(&rest[..idx]));
rest = &rest[idx..];
}
}
}
Ok(())
} }
} }
@ -304,22 +198,55 @@ mod tests {
use std::prelude::v1::*; use std::prelude::v1::*;
macro_rules! t { macro_rules! t {
($a:expr, $b:expr) => ({ ($a:expr, $b:expr) => {
assert_eq!(super::demangle($a).to_string(), $b); assert!(ok($a, $b))
}) };
}
macro_rules! t_err {
($a:expr) => {
assert!(ok_err($a))
};
} }
macro_rules! t_nohash { macro_rules! t_nohash {
($a:expr, $b:expr) => ({ ($a:expr, $b:expr) => {{
assert_eq!(format!("{:#}", super::demangle($a)), $b); assert_eq!(format!("{:#}", super::demangle($a)), $b);
}) }};
}
fn ok(sym: &str, expected: &str) -> bool {
match super::try_demangle(sym) {
Ok(s) => {
if s.to_string() == expected {
true
} else {
println!("\n{}\n!=\n{}\n", s, expected);
false
}
}
Err(_) => {
println!("error demangling");
false
}
}
}
fn ok_err(sym: &str) -> bool {
match super::try_demangle(sym) {
Ok(_) => {
println!("succeeded in demangling");
false
}
Err(_) => super::demangle(sym).to_string() == sym,
}
} }
#[test] #[test]
fn demangle() { fn demangle() {
t!("test", "test"); t_err!("test");
t!("_ZN4testE", "test"); t!("_ZN4testE", "test");
t!("_ZN4test", "_ZN4test"); t_err!("_ZN4test");
t!("_ZN4test1a2bcE", "test::a::bc"); t!("_ZN4test1a2bcE", "test::a::bc");
} }
@ -338,10 +265,12 @@ mod tests {
t!("_ZN12test$BP$test4foobE", "test*test::foob"); t!("_ZN12test$BP$test4foobE", "test*test::foob");
} }
#[test] #[test]
fn demangle_osx() { fn demangle_osx() {
t!("__ZN5alloc9allocator6Layout9for_value17h02a996811f781011E", "alloc::allocator::Layout::for_value::h02a996811f781011"); t!(
"__ZN5alloc9allocator6Layout9for_value17h02a996811f781011E",
"alloc::allocator::Layout::for_value::h02a996811f781011"
);
t!("__ZN38_$LT$core..option..Option$LT$T$GT$$GT$6unwrap18_MSG_FILE_LINE_COL17haf7cb8d5824ee659E", "<core::option::Option<T>>::unwrap::_MSG_FILE_LINE_COL::haf7cb8d5824ee659"); t!("__ZN38_$LT$core..option..Option$LT$T$GT$$GT$6unwrap18_MSG_FILE_LINE_COL17haf7cb8d5824ee659E", "<core::option::Option<T>>::unwrap::_MSG_FILE_LINE_COL::haf7cb8d5824ee659");
t!("__ZN4core5slice89_$LT$impl$u20$core..iter..traits..IntoIterator$u20$for$u20$$RF$$u27$a$u20$$u5b$T$u5d$$GT$9into_iter17h450e234d27262170E", "core::slice::<impl core::iter::traits::IntoIterator for &'a [T]>::into_iter::h450e234d27262170"); t!("__ZN4core5slice89_$LT$impl$u20$core..iter..traits..IntoIterator$u20$for$u20$$RF$$u27$a$u20$$u5b$T$u5d$$GT$9into_iter17h450e234d27262170E", "core::slice::<impl core::iter::traits::IntoIterator for &'a [T]>::into_iter::h450e234d27262170");
} }
@ -362,8 +291,10 @@ mod tests {
#[test] #[test]
fn demangle_trait_impls() { fn demangle_trait_impls() {
t!("_ZN71_$LT$Test$u20$$u2b$$u20$$u27$static$u20$as$u20$foo..Bar$LT$Test$GT$$GT$3barE", t!(
"<Test + 'static as foo::Bar<Test>>::bar"); "_ZN71_$LT$Test$u20$$u2b$$u20$$u27$static$u20$as$u20$foo..Bar$LT$Test$GT$$GT$3barE",
"<Test + 'static as foo::Bar<Test>>::bar"
);
} }
#[test] #[test]
@ -396,7 +327,21 @@ mod tests {
// One element, no hash. // One element, no hash.
t!("_ZN3fooE.llvm.9D1C9369", "foo"); t!("_ZN3fooE.llvm.9D1C9369", "foo");
t!("_ZN3fooE.llvm.9D1C9369@@16", "foo"); t!("_ZN3fooE.llvm.9D1C9369@@16", "foo");
t_nohash!("_ZN9backtrace3foo17hbb467fcdaea5d79bE.llvm.A5310EB9", "backtrace::foo"); t_nohash!(
"_ZN9backtrace3foo17hbb467fcdaea5d79bE.llvm.A5310EB9",
"backtrace::foo"
);
}
#[test]
fn demangle_llvm_ir_branch_labels() {
t!("_ZN4core5slice77_$LT$impl$u20$core..ops..index..IndexMut$LT$I$GT$$u20$for$u20$$u5b$T$u5d$$GT$9index_mut17haf9727c2edfbc47bE.exit.i.i", "core::slice::<impl core::ops::index::IndexMut<I> for [T]>::index_mut::haf9727c2edfbc47b.exit.i.i");
t_nohash!("_ZN4core5slice77_$LT$impl$u20$core..ops..index..IndexMut$LT$I$GT$$u20$for$u20$$u5b$T$u5d$$GT$9index_mut17haf9727c2edfbc47bE.exit.i.i", "core::slice::<impl core::ops::index::IndexMut<I> for [T]>::index_mut.exit.i.i");
}
#[test]
fn demangle_ignores_suffix_that_doesnt_look_like_a_symbol() {
t_err!("_ZN3fooE.llvm moocow");
} }
#[test] #[test]
@ -404,10 +349,50 @@ mod tests {
super::demangle("_ZN2222222222222222222222EE").to_string(); super::demangle("_ZN2222222222222222222222EE").to_string();
super::demangle("_ZN5*70527e27.ll34csaғE").to_string(); super::demangle("_ZN5*70527e27.ll34csaғE").to_string();
super::demangle("_ZN5*70527a54.ll34_$b.1E").to_string(); super::demangle("_ZN5*70527a54.ll34_$b.1E").to_string();
super::demangle("\ super::demangle(
_ZN5~saäb4e\n\ "\
2734cOsbE\n\ _ZN5~saäb4e\n\
5usage20h)3\0\0\0\0\0\0\07e2734cOsbE\ 2734cOsbE\n\
").to_string(); 5usage20h)3\0\0\0\0\0\0\07e2734cOsbE\
",
)
.to_string();
}
#[test]
fn invalid_no_chop() {
t_err!("_ZNfooE");
}
#[test]
fn handle_assoc_types() {
t!("_ZN151_$LT$alloc..boxed..Box$LT$alloc..boxed..FnBox$LT$A$C$$u20$Output$u3d$R$GT$$u20$$u2b$$u20$$u27$a$GT$$u20$as$u20$core..ops..function..FnOnce$LT$A$GT$$GT$9call_once17h69e8f44b3723e1caE", "<alloc::boxed::Box<alloc::boxed::FnBox<A, Output=R> + 'a> as core::ops::function::FnOnce<A>>::call_once::h69e8f44b3723e1ca");
}
#[test]
fn handle_bang() {
t!(
"_ZN88_$LT$core..result..Result$LT$$u21$$C$$u20$E$GT$$u20$as$u20$std..process..Termination$GT$6report17hfc41d0da4a40b3e8E",
"<core::result::Result<!, E> as std::process::Termination>::report::hfc41d0da4a40b3e8"
);
}
#[test]
fn limit_recursion() {
use std::fmt::Write;
let mut s = String::new();
assert!(write!(s, "{}", super::demangle("_RNvB_1a")).is_err());
}
#[test]
fn limit_output() {
use std::fmt::Write;
let mut s = String::new();
assert!(write!(
s,
"{}",
super::demangle("RYFG_FGyyEvRYFF_EvRYFFEvERLB_B_B_ERLRjB_B_B_")
)
.is_err());
} }
} }

View File

@ -1,4 +0,0 @@
extern crate rustc_demangle;
fn main() {
}

1209
third_party/rust/rustc-demangle/src/v0.rs vendored Normal file

File diff suppressed because it is too large Load Diff