]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys_common/backtrace.rs
std: Back out backtrace pruning logic
[rust.git] / src / libstd / sys_common / backtrace.rs
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.
4 //
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.
10
11 #![cfg_attr(target_os = "nacl", allow(dead_code))]
12
13 /// Common code for printing the backtrace in the same way across the different
14 /// supported platforms.
15
16 use env;
17 use io::prelude::*;
18 use io;
19 use libc;
20 use str;
21 use sync::atomic::{self, Ordering};
22 use path::{self, Path};
23 use sys::mutex::Mutex;
24 use ptr;
25
26 pub use sys::backtrace::{
27     unwind_backtrace,
28     resolve_symname,
29     foreach_symbol_fileline,
30     BacktraceContext
31 };
32
33 #[cfg(target_pointer_width = "64")]
34 pub const HEX_WIDTH: usize = 18;
35
36 #[cfg(target_pointer_width = "32")]
37 pub const HEX_WIDTH: usize = 10;
38
39 /// Represents an item in the backtrace list. See `unwind_backtrace` for how
40 /// it is created.
41 #[derive(Debug, Copy, Clone)]
42 pub struct Frame {
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,
47 }
48
49 /// Max number of frames to print.
50 const MAX_NB_FRAMES: usize = 100;
51
52 /// Prints the current backtrace.
53 pub fn print(w: &mut Write, format: PrintFormat) -> io::Result<()> {
54     static LOCK: Mutex = Mutex::new();
55
56     // Use a lock to prevent mixed output in multithreading context.
57     // Some platforms also requires it, like `SymFromAddr` on Windows.
58     unsafe {
59         LOCK.lock();
60         let res = _print(w, format);
61         LOCK.unlock();
62         res
63     }
64 }
65
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(),
70     }; MAX_NB_FRAMES];
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.")?;
77     }
78     writeln!(w, "stack backtrace:")?;
79
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)
84         }, &context)?;
85         let has_more_filenames = foreach_symbol_fileline(*frame, |file, line| {
86             output_fileline(w, file, line, format)
87         }, &context)?;
88         if has_more_filenames {
89             w.write_all(b" <... and possibly more>")?;
90         }
91     }
92
93     Ok(())
94 }
95
96 fn filter_frames(_frames: &[Frame],
97                  _format: PrintFormat,
98                  _context: &BacktraceContext) -> (usize, usize)
99 {
100     (0, 0)
101 }
102
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.
107     Full = 2,
108     /// Show only relevant data from the backtrace.
109     Short = 3,
110 }
111
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) {
117         0 => {},
118         1 => return None,
119         2 => return Some(PrintFormat::Full),
120         3 => return Some(PrintFormat::Short),
121         _ => unreachable!(),
122     }
123
124     let val = match env::var_os("RUST_BACKTRACE") {
125         Some(x) => if &x == "0" {
126             None
127         } else if &x == "full" {
128             Some(PrintFormat::Full)
129         } else {
130             Some(PrintFormat::Short)
131         },
132         None => None,
133     };
134     ENABLED.store(match val {
135         Some(v) => v as isize,
136         None => 1,
137     }, Ordering::SeqCst);
138     val
139 }
140
141 /// Print the symbol of the backtrace frame.
142 ///
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() {
149         return Ok(());
150     }
151     match format {
152         PrintFormat::Full => write!(w,
153                                     "  {:2}: {:2$?} - ",
154                                     idx,
155                                     frame.exact_position,
156                                     HEX_WIDTH)?,
157         PrintFormat::Short => write!(w, "  {:2}: ", idx)?,
158     }
159     match s {
160         Some(string) => demangle(w, string, format)?,
161         None => w.write_all(b"<unknown>")?,
162     }
163     w.write_all(b"\n")
164 }
165
166 /// Print the filename and line number of the backtrace frame.
167 ///
168 /// See also `output`.
169 #[allow(dead_code)]
170 fn output_fileline(w: &mut Write, file: &[u8], line: libc::c_int,
171                        format: PrintFormat) -> io::Result<()> {
172     // prior line: "  ##: {:2$} - func"
173     w.write_all(b"")?;
174     match format {
175         PrintFormat::Full => write!(w,
176                                     "           {:1$}",
177                                     "",
178                                     HEX_WIDTH)?,
179         PrintFormat::Short => write!(w, "           ")?,
180     }
181
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;
191                 }
192             }
193         }
194     }
195     if !already_printed {
196         write!(w, "  at {}:{}", file, line)?;
197     }
198
199     w.write_all(b"\n")
200 }
201
202
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:
206 //
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"
210 //
211 // For example, "_ZN4testE" => "test" and "_ZN3foo3barE" => "foo::bar".
212 //
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.
216 //
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;
225     let mut inner = s;
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];
231     } else {
232         valid = false;
233     }
234
235     if valid {
236         let mut chars = inner.chars();
237         while valid {
238             let mut i = 0;
239             for c in chars.by_ref() {
240                 if c.is_numeric() {
241                     i = i * 10 + c as usize - '0' as usize;
242                 } else {
243                     break
244                 }
245             }
246             if i == 0 {
247                 valid = chars.next().is_none();
248                 break
249             } else if chars.by_ref().take(i - 1).count() != i - 1 {
250                 valid = false;
251             }
252         }
253     }
254
255     // Alright, let's do this.
256     if !valid {
257         writer.write_all(s.as_bytes())?;
258     } else {
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))
267                     {
268                         inner = rest.unwrap_or("");
269                     }
270                 }
271                 _ => (),
272             }
273         }
274
275         let mut first = true;
276         while !inner.is_empty() {
277             if !first {
278                 writer.write_all(b"::")?;
279             } else {
280                 first = false;
281             }
282             let mut rest = inner;
283             while rest.chars().next().unwrap().is_numeric() {
284                 rest = &rest[1..];
285             }
286             let i: usize = inner[.. (inner.len() - rest.len())].parse().unwrap();
287             inner = &rest[i..];
288             rest = &rest[..i];
289             if rest.starts_with("_$") {
290                 rest = &rest[1..];
291             }
292             while !rest.is_empty() {
293                 if rest.starts_with(".") {
294                     if let Some('.') = rest[1..].chars().next() {
295                         writer.write_all(b"::")?;
296                         rest = &rest[2..];
297                     } else {
298                         writer.write_all(b".")?;
299                         rest = &rest[1..];
300                     }
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()..];
307                               } else)*
308                             {
309                                 writer.write_all(rest.as_bytes())?;
310                                 break;
311                             }
312
313                         })
314                     }
315
316                     // see src/librustc/back/link.rs for these mappings
317                     demangle! (
318                         "$SP$" => b"@",
319                         "$BP$" => b"*",
320                         "$RF$" => b"&",
321                         "$LT$" => b"<",
322                         "$GT$" => b">",
323                         "$LP$" => b"(",
324                         "$RP$" => b")",
325                         "$C$" => b",",
326
327                         // in theory we can demangle any Unicode code point, but
328                         // for simplicity we just catch the common ones.
329                         "$u7e$" => b"~",
330                         "$u20$" => b" ",
331                         "$u27$" => b"'",
332                         "$u5b$" => b"[",
333                         "$u5d$" => b"]",
334                         "$u7b$" => b"{",
335                         "$u7d$" => b"}",
336                         "$u3b$" => b";",
337                         "$u2b$" => b"+",
338                         "$u22$" => b"\""
339                     )
340                 } else {
341                     let idx = match rest.char_indices().find(|&(_, c)| c == '$' || c == '.') {
342                         None => rest.len(),
343                         Some((i, _)) => i,
344                     };
345                     writer.write_all(rest[..idx].as_bytes())?;
346                     rest = &rest[idx..];
347                 }
348             }
349         }
350     }
351
352     Ok(())
353 }
354
355 #[cfg(test)]
356 mod tests {
357     use sys_common;
358     macro_rules! t { ($a:expr, $b:expr) => ({
359         let mut m = Vec::new();
360         sys_common::backtrace::demangle(&mut m,
361                                         $a,
362                                         super::PrintFormat::Full).unwrap();
363         assert_eq!(String::from_utf8(m).unwrap(), $b);
364     }) }
365
366     #[test]
367     fn demangle() {
368         t!("test", "test");
369         t!("_ZN4testE", "test");
370         t!("_ZN4test", "_ZN4test");
371         t!("_ZN4test1a2bcE", "test::a::bc");
372     }
373
374     #[test]
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]>");
381     }
382
383     #[test]
384     fn demangle_many_dollars() {
385         t!("_ZN13test$u20$test4foobE", "test test::foob");
386         t!("_ZN12test$BP$test4foobE", "test*test::foob");
387     }
388
389     #[test]
390     fn demangle_windows() {
391         t!("ZN4testE", "test");
392         t!("ZN13test$u20$test4foobE", "test test::foob");
393         t!("ZN12test$RF$test4foobE", "test&test::foob");
394     }
395
396     #[test]
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");
401     }
402
403     #[test]
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");
407     }
408 }