1use core::char;
2use core::fmt;
34/// Representation of a demangled symbol name.
5pub struct Demangle<'a> {
6 inner: &'a str,
7/// The number of ::-separated elements in the original name.
8elements: usize,
9}
1011/// De-mangles a Rust symbol into a more readable version
12///
13/// All Rust symbols by default are mangled as they contain characters that
14/// cannot be represented in all object files. The mangling mechanism is similar
15/// to C++'s, but Rust has a few specifics to handle items like lifetimes in
16/// symbols.
17///
18/// This function will take a **mangled** symbol and return a value. When printed,
19/// the de-mangled version will be written. If the symbol does not look like
20/// a mangled symbol, the original value will be written instead.
21///
22/// # Examples
23///
24/// ```
25/// use rustc_demangle::demangle;
26///
27/// assert_eq!(demangle("_ZN4testE").to_string(), "test");
28/// assert_eq!(demangle("_ZN3foo3barE").to_string(), "foo::bar");
29/// assert_eq!(demangle("foo").to_string(), "foo");
30/// ```
3132// All Rust symbols are in theory lists of "::"-separated identifiers. Some
33// assemblers, however, can't handle these characters in symbol names. To get
34// around this, we use C++-style mangling. The mangling method is:
35//
36// 1. Prefix the symbol with "_ZN"
37// 2. For each element of the path, emit the length plus the element
38// 3. End the path with "E"
39//
40// For example, "_ZN4testE" => "test" and "_ZN3foo3barE" => "foo::bar".
41//
42// We're the ones printing our backtraces, so we can't rely on anything else to
43// demangle our symbols. It's *much* nicer to look at demangled symbols, so
44// this function is implemented to give us nice pretty output.
45//
46// Note that this demangler isn't quite as fancy as it could be. We have lots
47// of other information in our symbols like hashes, version, type information,
48// etc. Additionally, this doesn't handle glue symbols at all.
49pub fn demangle(s: &str) -> Result<(Demangle, &str), ()> {
50// First validate the symbol. If it doesn't look like anything we're
51 // expecting, we just print it literally. Note that we must handle non-Rust
52 // symbols because we could have any function in the backtrace.
53let inner = if s.starts_with("_ZN") {
54&s[3..]
55 } else if s.starts_with("ZN") {
56// On Windows, dbghelp strips leading underscores, so we accept "ZN...E"
57 // form too.
58&s[2..]
59 } else if s.starts_with("__ZN") {
60// On OSX, symbols are prefixed with an extra _
61&s[4..]
62 } else {
63return Err(());
64 };
6566// only work with ascii text
67if inner.bytes().any(|c| c & 0x80 != 0) {
68return Err(());
69 }
7071let mut elements = 0;
72let mut chars = inner.chars();
73let mut c = chars.next().ok_or(())?;
74while c != 'E' {
75// Decode an identifier element's length.
76if !c.is_digit(10) {
77return Err(());
78 }
79let mut len = 0usize;
80while let Some(d) = c.to_digit(10) {
81 len = len
82 .checked_mul(10)
83 .and_then(|len| len.checked_add(d as usize))
84 .ok_or(())?;
85 c = chars.next().ok_or(())?;
86 }
8788// `c` already contains the first character of this identifier, skip it and
89 // all the other characters of this identifier, to reach the next element.
90for _ in 0..len {
91 c = chars.next().ok_or(())?;
92 }
9394 elements += 1;
95 }
9697Ok((Demangle { inner, elements }, chars.as_str()))
98}
99100// Rust hashes are hex digits with an `h` prepended.
101fn is_rust_hash(s: &str) -> bool {
102 s.starts_with('h') && s[1..].chars().all(|c| c.is_digit(16))
103}
104105impl<'a> fmt::Display for Demangle<'a> {
106fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
107// Alright, let's do this.
108let mut inner = self.inner;
109for element in 0..self.elements {
110let mut rest = inner;
111while rest.chars().next().unwrap().is_digit(10) {
112 rest = &rest[1..];
113 }
114let i: usize = inner[..(inner.len() - rest.len())].parse().unwrap();
115 inner = &rest[i..];
116 rest = &rest[..i];
117// Skip printing the hash if alternate formatting
118 // was requested.
119if f.alternate() && element + 1 == self.elements && is_rust_hash(&rest) {
120break;
121 }
122if element != 0 {
123 f.write_str("::")?;
124 }
125if rest.starts_with("_$") {
126 rest = &rest[1..];
127 }
128loop {
129if rest.starts_with('.') {
130if let Some('.') = rest[1..].chars().next() {
131 f.write_str("::")?;
132 rest = &rest[2..];
133 } else {
134 f.write_str(".")?;
135 rest = &rest[1..];
136 }
137 } else if rest.starts_with('$') {
138let (escape, after_escape) = if let Some(end) = rest[1..].find('$') {
139 (&rest[1..=end], &rest[end + 2..])
140 } else {
141break;
142 };
143144// see src/librustc_codegen_utils/symbol_names/legacy.rs for these mappings
145let unescaped = match escape {
146"SP" => "@",
147"BP" => "*",
148"RF" => "&",
149"LT" => "<",
150"GT" => ">",
151"LP" => "(",
152"RP" => ")",
153"C" => ",",
154155_ => {
156if escape.starts_with('u') {
157let digits = &escape[1..];
158let all_lower_hex = digits.chars().all(|c| match c {
159'0'..='9' | 'a'..='f' => true,
160_ => false,
161 });
162let c = u32::from_str_radix(digits, 16)
163 .ok()
164 .and_then(char::from_u32);
165if let (true, Some(c)) = (all_lower_hex, c) {
166// FIXME(eddyb) do we need to filter out control codepoints?
167if !c.is_control() {
168 c.fmt(f)?;
169 rest = after_escape;
170continue;
171 }
172 }
173 }
174break;
175 }
176 };
177 f.write_str(unescaped)?;
178 rest = after_escape;
179 } else if let Some(i) = rest.find(|c| c == '$' || c == '.') {
180 f.write_str(&rest[..i])?;
181 rest = &rest[i..];
182 } else {
183break;
184 }
185 }
186 f.write_str(rest)?;
187 }
188189Ok(())
190 }
191}
192193#[cfg(test)]
194mod tests {
195use std::prelude::v1::*;
196197macro_rules! t {
198 ($a:expr, $b:expr) => {
199assert!(ok($a, $b))
200 };
201 }
202203macro_rules! t_err {
204 ($a:expr) => {
205assert!(ok_err($a))
206 };
207 }
208209macro_rules! t_nohash {
210 ($a:expr, $b:expr) => {{
211assert_eq!(format!("{:#}", ::demangle($a)), $b);
212 }};
213 }
214215fn ok(sym: &str, expected: &str) -> bool {
216match ::try_demangle(sym) {
217Ok(s) => {
218if s.to_string() == expected {
219true
220} else {
221println!("\n{}\n!=\n{}\n", s, expected);
222false
223}
224 }
225Err(_) => {
226println!("error demangling");
227false
228}
229 }
230 }
231232fn ok_err(sym: &str) -> bool {
233match ::try_demangle(sym) {
234Ok(_) => {
235println!("succeeded in demangling");
236false
237}
238Err(_) => ::demangle(sym).to_string() == sym,
239 }
240 }
241242#[test]
243fn demangle() {
244t_err!("test");
245t!("_ZN4testE", "test");
246t_err!("_ZN4test");
247t!("_ZN4test1a2bcE", "test::a::bc");
248 }
249250#[test]
251fn demangle_dollars() {
252t!("_ZN4$RP$E", ")");
253t!("_ZN8$RF$testE", "&test");
254t!("_ZN8$BP$test4foobE", "*test::foob");
255t!("_ZN9$u20$test4foobE", " test::foob");
256t!("_ZN35Bar$LT$$u5b$u32$u3b$$u20$4$u5d$$GT$E", "Bar<[u32; 4]>");
257 }
258259#[test]
260fn demangle_many_dollars() {
261t!("_ZN13test$u20$test4foobE", "test test::foob");
262t!("_ZN12test$BP$test4foobE", "test*test::foob");
263 }
264265#[test]
266fn demangle_osx() {
267t!(
268"__ZN5alloc9allocator6Layout9for_value17h02a996811f781011E",
269"alloc::allocator::Layout::for_value::h02a996811f781011"
270);
271t!("__ZN38_$LT$core..option..Option$LT$T$GT$$GT$6unwrap18_MSG_FILE_LINE_COL17haf7cb8d5824ee659E", "<core::option::Option<T>>::unwrap::_MSG_FILE_LINE_COL::haf7cb8d5824ee659");
272t!("__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");
273 }
274275#[test]
276fn demangle_windows() {
277t!("ZN4testE", "test");
278t!("ZN13test$u20$test4foobE", "test test::foob");
279t!("ZN12test$RF$test4foobE", "test&test::foob");
280 }
281282#[test]
283fn demangle_elements_beginning_with_underscore() {
284t!("_ZN13_$LT$test$GT$E", "<test>");
285t!("_ZN28_$u7b$$u7b$closure$u7d$$u7d$E", "{{closure}}");
286t!("_ZN15__STATIC_FMTSTRE", "__STATIC_FMTSTR");
287 }
288289#[test]
290fn demangle_trait_impls() {
291t!(
292"_ZN71_$LT$Test$u20$$u2b$$u20$$u27$static$u20$as$u20$foo..Bar$LT$Test$GT$$GT$3barE",
293"<Test + 'static as foo::Bar<Test>>::bar"
294);
295 }
296297#[test]
298fn demangle_without_hash() {
299let s = "_ZN3foo17h05af221e174051e9E";
300t!(s, "foo::h05af221e174051e9");
301t_nohash!(s, "foo");
302 }
303304#[test]
305fn demangle_without_hash_edgecases() {
306// One element, no hash.
307t_nohash!("_ZN3fooE", "foo");
308// Two elements, no hash.
309t_nohash!("_ZN3foo3barE", "foo::bar");
310// Longer-than-normal hash.
311t_nohash!("_ZN3foo20h05af221e174051e9abcE", "foo");
312// Shorter-than-normal hash.
313t_nohash!("_ZN3foo5h05afE", "foo");
314// Valid hash, but not at the end.
315t_nohash!("_ZN17h05af221e174051e93fooE", "h05af221e174051e9::foo");
316// Not a valid hash, missing the 'h'.
317t_nohash!("_ZN3foo16ffaf221e174051e9E", "foo::ffaf221e174051e9");
318// Not a valid hash, has a non-hex-digit.
319t_nohash!("_ZN3foo17hg5af221e174051e9E", "foo::hg5af221e174051e9");
320 }
321322#[test]
323fn demangle_thinlto() {
324// One element, no hash.
325t!("_ZN3fooE.llvm.9D1C9369", "foo");
326t!("_ZN3fooE.llvm.9D1C9369@@16", "foo");
327t_nohash!(
328"_ZN9backtrace3foo17hbb467fcdaea5d79bE.llvm.A5310EB9",
329"backtrace::foo"
330);
331 }
332333#[test]
334fn demangle_llvm_ir_branch_labels() {
335t!("_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");
336t_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");
337 }
338339#[test]
340fn demangle_ignores_suffix_that_doesnt_look_like_a_symbol() {
341t_err!("_ZN3fooE.llvm moocow");
342 }
343344#[test]
345fn dont_panic() {
346 ::demangle("_ZN2222222222222222222222EE").to_string();
347 ::demangle("_ZN5*70527e27.ll34csaғE").to_string();
348 ::demangle("_ZN5*70527a54.ll34_$b.1E").to_string();
349 ::demangle(
350"\
351 _ZN5~saäb4e\n\
352 2734cOsbE\n\
353 5usage20h)3\0\0\0\0\0\0\07e2734cOsbE\
354 ",
355 )
356 .to_string();
357 }
358359#[test]
360fn invalid_no_chop() {
361t_err!("_ZNfooE");
362 }
363364#[test]
365fn handle_assoc_types() {
366t!("_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");
367 }
368369#[test]
370fn handle_bang() {
371t!(
372"_ZN88_$LT$core..result..Result$LT$$u21$$C$$u20$E$GT$$u20$as$u20$std..process..Termination$GT$6report17hfc41d0da4a40b3e8E",
373"<core::result::Result<!, E> as std::process::Termination>::report::hfc41d0da4a40b3e8"
374);
375 }
376377#[test]
378fn demangle_utf8_idents() {
379t_nohash!(
380"_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",
381"utf8_idents::საჭმელად_გემრიელი_სადილი"
382);
383 }
384385#[test]
386fn demangle_issue_60925() {
387t_nohash!(
388"_ZN11issue_609253foo37Foo$LT$issue_60925..llv$u6d$..Foo$GT$3foo17h059a991a004536adE",
389"issue_60925::foo::Foo<issue_60925::llvm::Foo>::foo"
390);
391 }
392}