1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![cfg_attr(target_os = "nacl", allow(dead_code))]
13 /// Common code for printing the backtrace in the same way across the different
14 /// supported platforms.
21 use sync::atomic::{self, Ordering};
22 use path::{self, Path};
23 use sys::mutex::Mutex;
26 pub use sys::backtrace::{
29 foreach_symbol_fileline,
33 #[cfg(target_pointer_width = "64")]
34 pub const HEX_WIDTH: usize = 18;
36 #[cfg(target_pointer_width = "32")]
37 pub const HEX_WIDTH: usize = 10;
39 /// Represents an item in the backtrace list. See `unwind_backtrace` for how
41 #[derive(Debug, Copy, Clone)]
43 /// Exact address of the call that failed.
44 pub exact_position: *const libc::c_void,
45 /// Address of the enclosing function.
46 pub symbol_addr: *const libc::c_void,
49 /// Max number of frames to print.
50 const MAX_NB_FRAMES: usize = 100;
52 /// Prints the current backtrace.
53 pub fn print(w: &mut Write, format: PrintFormat) -> io::Result<()> {
54 static LOCK: Mutex = Mutex::new();
56 // Use a lock to prevent mixed output in multithreading context.
57 // Some platforms also requires it, like `SymFromAddr` on Windows.
60 let res = _print(w, format);
66 fn _print(w: &mut Write, format: PrintFormat) -> io::Result<()> {
67 let mut frames = [Frame {
68 exact_position: ptr::null(),
69 symbol_addr: ptr::null(),
71 let (nb_frames, context) = unwind_backtrace(&mut frames)?;
72 let (skipped_before, skipped_after) =
73 filter_frames(&frames[..nb_frames], format, &context);
74 if skipped_before + skipped_after > 0 {
75 writeln!(w, "note: Some details are omitted, \
76 run with `RUST_BACKTRACE=full` for a verbose backtrace.")?;
78 writeln!(w, "stack backtrace:")?;
80 let filtered_frames = &frames[..nb_frames - skipped_after];
81 for (index, frame) in filtered_frames.iter().skip(skipped_before).enumerate() {
82 resolve_symname(*frame, |symname| {
83 output(w, index, *frame, symname, format)
85 let has_more_filenames = foreach_symbol_fileline(*frame, |file, line| {
86 output_fileline(w, file, line, format)
88 if has_more_filenames {
89 w.write_all(b" <... and possibly more>")?;
96 fn filter_frames(_frames: &[Frame],
98 _context: &BacktraceContext) -> (usize, usize)
103 /// Controls how the backtrace should be formated.
104 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
105 pub enum PrintFormat {
106 /// Show all the frames with absolute path for files.
108 /// Show only relevant data from the backtrace.
112 // For now logging is turned off by default, and this function checks to see
113 // whether the magical environment variable is present to see if it's turned on.
114 pub fn log_enabled() -> Option<PrintFormat> {
115 static ENABLED: atomic::AtomicIsize = atomic::AtomicIsize::new(0);
116 match ENABLED.load(Ordering::SeqCst) {
119 2 => return Some(PrintFormat::Full),
120 3 => return Some(PrintFormat::Short),
124 let val = match env::var_os("RUST_BACKTRACE") {
125 Some(x) => if &x == "0" {
127 } else if &x == "full" {
128 Some(PrintFormat::Full)
130 Some(PrintFormat::Short)
134 ENABLED.store(match val {
135 Some(v) => v as isize,
137 }, Ordering::SeqCst);
141 /// Print the symbol of the backtrace frame.
143 /// These output functions should now be used everywhere to ensure consistency.
144 /// You may want to also use `output_fileline`.
145 fn output(w: &mut Write, idx: usize, frame: Frame,
146 s: Option<&str>, format: PrintFormat) -> io::Result<()> {
147 // Remove the `17: 0x0 - <unknown>` line.
148 if format == PrintFormat::Short && frame.exact_position == ptr::null() {
152 PrintFormat::Full => write!(w,
155 frame.exact_position,
157 PrintFormat::Short => write!(w, " {:2}: ", idx)?,
160 Some(string) => demangle(w, string, format)?,
161 None => w.write_all(b"<unknown>")?,
166 /// Print the filename and line number of the backtrace frame.
168 /// See also `output`.
170 fn output_fileline(w: &mut Write, file: &[u8], line: libc::c_int,
171 format: PrintFormat) -> io::Result<()> {
172 // prior line: " ##: {:2$} - func"
175 PrintFormat::Full => write!(w,
179 PrintFormat::Short => write!(w, " ")?,
182 let file = str::from_utf8(file).unwrap_or("<unknown>");
183 let file_path = Path::new(file);
184 let mut already_printed = false;
185 if format == PrintFormat::Short && file_path.is_absolute() {
186 if let Ok(cwd) = env::current_dir() {
187 if let Ok(stripped) = file_path.strip_prefix(&cwd) {
188 if let Some(s) = stripped.to_str() {
189 write!(w, " at .{}{}:{}", path::MAIN_SEPARATOR, s, line)?;
190 already_printed = true;
195 if !already_printed {
196 write!(w, " at {}:{}", file, line)?;
203 // All rust symbols are in theory lists of "::"-separated identifiers. Some
204 // assemblers, however, can't handle these characters in symbol names. To get
205 // around this, we use C++-style mangling. The mangling method is:
207 // 1. Prefix the symbol with "_ZN"
208 // 2. For each element of the path, emit the length plus the element
209 // 3. End the path with "E"
211 // For example, "_ZN4testE" => "test" and "_ZN3foo3barE" => "foo::bar".
213 // We're the ones printing our backtraces, so we can't rely on anything else to
214 // demangle our symbols. It's *much* nicer to look at demangled symbols, so
215 // this function is implemented to give us nice pretty output.
217 // Note that this demangler isn't quite as fancy as it could be. We have lots
218 // of other information in our symbols like hashes, version, type information,
219 // etc. Additionally, this doesn't handle glue symbols at all.
220 pub fn demangle(writer: &mut Write, s: &str, format: PrintFormat) -> io::Result<()> {
221 // First validate the symbol. If it doesn't look like anything we're
222 // expecting, we just print it literally. Note that we must handle non-rust
223 // symbols because we could have any function in the backtrace.
224 let mut valid = true;
226 if s.len() > 4 && s.starts_with("_ZN") && s.ends_with("E") {
227 inner = &s[3 .. s.len() - 1];
228 // On Windows, dbghelp strips leading underscores, so we accept "ZN...E" form too.
229 } else if s.len() > 3 && s.starts_with("ZN") && s.ends_with("E") {
230 inner = &s[2 .. s.len() - 1];
236 let mut chars = inner.chars();
239 for c in chars.by_ref() {
241 i = i * 10 + c as usize - '0' as usize;
247 valid = chars.next().is_none();
249 } else if chars.by_ref().take(i - 1).count() != i - 1 {
255 // Alright, let's do this.
257 writer.write_all(s.as_bytes())?;
259 // remove the `::hfc2edb670e5eda97` part at the end of the symbol.
260 if format == PrintFormat::Short {
261 // The symbol in still mangled.
262 let mut split = inner.rsplitn(2, "17h");
263 match (split.next(), split.next()) {
264 (Some(addr), rest) => {
265 if addr.len() == 16 &&
266 addr.chars().all(|c| c.is_digit(16))
268 inner = rest.unwrap_or("");
275 let mut first = true;
276 while !inner.is_empty() {
278 writer.write_all(b"::")?;
282 let mut rest = inner;
283 while rest.chars().next().unwrap().is_numeric() {
286 let i: usize = inner[.. (inner.len() - rest.len())].parse().unwrap();
289 if rest.starts_with("_$") {
292 while !rest.is_empty() {
293 if rest.starts_with(".") {
294 if let Some('.') = rest[1..].chars().next() {
295 writer.write_all(b"::")?;
298 writer.write_all(b".")?;
301 } else if rest.starts_with("$") {
302 macro_rules! demangle {
303 ($($pat:expr => $demangled:expr),*) => ({
304 $(if rest.starts_with($pat) {
305 writer.write_all($demangled)?;
306 rest = &rest[$pat.len()..];
309 writer.write_all(rest.as_bytes())?;
316 // see src/librustc/back/link.rs for these mappings
327 // in theory we can demangle any Unicode code point, but
328 // for simplicity we just catch the common ones.
341 let idx = match rest.char_indices().find(|&(_, c)| c == '$' || c == '.') {
345 writer.write_all(rest[..idx].as_bytes())?;
358 macro_rules! t { ($a:expr, $b:expr) => ({
359 let mut m = Vec::new();
360 sys_common::backtrace::demangle(&mut m,
362 super::PrintFormat::Full).unwrap();
363 assert_eq!(String::from_utf8(m).unwrap(), $b);
369 t!("_ZN4testE", "test");
370 t!("_ZN4test", "_ZN4test");
371 t!("_ZN4test1a2bcE", "test::a::bc");
375 fn demangle_dollars() {
376 t!("_ZN4$RP$E", ")");
377 t!("_ZN8$RF$testE", "&test");
378 t!("_ZN8$BP$test4foobE", "*test::foob");
379 t!("_ZN9$u20$test4foobE", " test::foob");
380 t!("_ZN35Bar$LT$$u5b$u32$u3b$$u20$4$u5d$$GT$E", "Bar<[u32; 4]>");
384 fn demangle_many_dollars() {
385 t!("_ZN13test$u20$test4foobE", "test test::foob");
386 t!("_ZN12test$BP$test4foobE", "test*test::foob");
390 fn demangle_windows() {
391 t!("ZN4testE", "test");
392 t!("ZN13test$u20$test4foobE", "test test::foob");
393 t!("ZN12test$RF$test4foobE", "test&test::foob");
397 fn demangle_elements_beginning_with_underscore() {
398 t!("_ZN13_$LT$test$GT$E", "<test>");
399 t!("_ZN28_$u7b$$u7b$closure$u7d$$u7d$E", "{{closure}}");
400 t!("_ZN15__STATIC_FMTSTRE", "__STATIC_FMTSTR");
404 fn demangle_trait_impls() {
405 t!("_ZN71_$LT$Test$u20$$u2b$$u20$$u27$static$u20$as$u20$foo..Bar$LT$Test$GT$$GT$3barE",
406 "<Test + 'static as foo::Bar<Test>>::bar");