]> git.proxmox.com Git - rustc.git/blob - src/libstd/sys_common/backtrace.rs
New upstream version 1.19.0+dfsg1
[rustc.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 /// Returns a number of frames to remove at the beginning and at the end of the
97 /// backtrace, according to the backtrace format.
98 fn filter_frames(frames: &[Frame],
99 format: PrintFormat,
100 context: &BacktraceContext) -> (usize, usize)
101 {
102 if format == PrintFormat::Full {
103 return (0, 0);
104 }
105
106 let skipped_before = 0;
107
108 let skipped_after = frames.len() - frames.iter().position(|frame| {
109 let mut is_marker = false;
110 let _ = resolve_symname(*frame, |symname| {
111 if let Some(mangled_symbol_name) = symname {
112 // Use grep to find the concerned functions
113 if mangled_symbol_name.contains("__rust_begin_short_backtrace") {
114 is_marker = true;
115 }
116 }
117 Ok(())
118 }, context);
119 is_marker
120 }).unwrap_or(frames.len());
121
122 if skipped_before + skipped_after >= frames.len() {
123 // Avoid showing completely empty backtraces
124 return (0, 0);
125 }
126
127 (skipped_before, skipped_after)
128 }
129
130
131 /// Fixed frame used to clean the backtrace with `RUST_BACKTRACE=1`.
132 #[inline(never)]
133 pub fn __rust_begin_short_backtrace<F, T>(f: F) -> T
134 where F: FnOnce() -> T, F: Send + 'static, T: Send + 'static
135 {
136 f()
137 }
138
139 /// Controls how the backtrace should be formated.
140 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
141 pub enum PrintFormat {
142 /// Show all the frames with absolute path for files.
143 Full = 2,
144 /// Show only relevant data from the backtrace.
145 Short = 3,
146 }
147
148 // For now logging is turned off by default, and this function checks to see
149 // whether the magical environment variable is present to see if it's turned on.
150 pub fn log_enabled() -> Option<PrintFormat> {
151 static ENABLED: atomic::AtomicIsize = atomic::AtomicIsize::new(0);
152 match ENABLED.load(Ordering::SeqCst) {
153 0 => {},
154 1 => return None,
155 2 => return Some(PrintFormat::Full),
156 3 => return Some(PrintFormat::Short),
157 _ => unreachable!(),
158 }
159
160 let val = match env::var_os("RUST_BACKTRACE") {
161 Some(x) => if &x == "0" {
162 None
163 } else if &x == "full" {
164 Some(PrintFormat::Full)
165 } else {
166 Some(PrintFormat::Short)
167 },
168 None => None,
169 };
170 ENABLED.store(match val {
171 Some(v) => v as isize,
172 None => 1,
173 }, Ordering::SeqCst);
174 val
175 }
176
177 /// Print the symbol of the backtrace frame.
178 ///
179 /// These output functions should now be used everywhere to ensure consistency.
180 /// You may want to also use `output_fileline`.
181 fn output(w: &mut Write, idx: usize, frame: Frame,
182 s: Option<&str>, format: PrintFormat) -> io::Result<()> {
183 // Remove the `17: 0x0 - <unknown>` line.
184 if format == PrintFormat::Short && frame.exact_position == ptr::null() {
185 return Ok(());
186 }
187 match format {
188 PrintFormat::Full => write!(w,
189 " {:2}: {:2$?} - ",
190 idx,
191 frame.exact_position,
192 HEX_WIDTH)?,
193 PrintFormat::Short => write!(w, " {:2}: ", idx)?,
194 }
195 match s {
196 Some(string) => demangle(w, string, format)?,
197 None => w.write_all(b"<unknown>")?,
198 }
199 w.write_all(b"\n")
200 }
201
202 /// Print the filename and line number of the backtrace frame.
203 ///
204 /// See also `output`.
205 #[allow(dead_code)]
206 fn output_fileline(w: &mut Write, file: &[u8], line: libc::c_int,
207 format: PrintFormat) -> io::Result<()> {
208 // prior line: " ##: {:2$} - func"
209 w.write_all(b"")?;
210 match format {
211 PrintFormat::Full => write!(w,
212 " {:1$}",
213 "",
214 HEX_WIDTH)?,
215 PrintFormat::Short => write!(w, " ")?,
216 }
217
218 let file = str::from_utf8(file).unwrap_or("<unknown>");
219 let file_path = Path::new(file);
220 let mut already_printed = false;
221 if format == PrintFormat::Short && file_path.is_absolute() {
222 if let Ok(cwd) = env::current_dir() {
223 if let Ok(stripped) = file_path.strip_prefix(&cwd) {
224 if let Some(s) = stripped.to_str() {
225 write!(w, " at .{}{}:{}", path::MAIN_SEPARATOR, s, line)?;
226 already_printed = true;
227 }
228 }
229 }
230 }
231 if !already_printed {
232 write!(w, " at {}:{}", file, line)?;
233 }
234
235 w.write_all(b"\n")
236 }
237
238
239 // All rust symbols are in theory lists of "::"-separated identifiers. Some
240 // assemblers, however, can't handle these characters in symbol names. To get
241 // around this, we use C++-style mangling. The mangling method is:
242 //
243 // 1. Prefix the symbol with "_ZN"
244 // 2. For each element of the path, emit the length plus the element
245 // 3. End the path with "E"
246 //
247 // For example, "_ZN4testE" => "test" and "_ZN3foo3barE" => "foo::bar".
248 //
249 // We're the ones printing our backtraces, so we can't rely on anything else to
250 // demangle our symbols. It's *much* nicer to look at demangled symbols, so
251 // this function is implemented to give us nice pretty output.
252 //
253 // Note that this demangler isn't quite as fancy as it could be. We have lots
254 // of other information in our symbols like hashes, version, type information,
255 // etc. Additionally, this doesn't handle glue symbols at all.
256 pub fn demangle(writer: &mut Write, s: &str, format: PrintFormat) -> io::Result<()> {
257 // First validate the symbol. If it doesn't look like anything we're
258 // expecting, we just print it literally. Note that we must handle non-rust
259 // symbols because we could have any function in the backtrace.
260 let mut valid = true;
261 let mut inner = s;
262 if s.len() > 4 && s.starts_with("_ZN") && s.ends_with("E") {
263 inner = &s[3 .. s.len() - 1];
264 // On Windows, dbghelp strips leading underscores, so we accept "ZN...E" form too.
265 } else if s.len() > 3 && s.starts_with("ZN") && s.ends_with("E") {
266 inner = &s[2 .. s.len() - 1];
267 } else {
268 valid = false;
269 }
270
271 if valid {
272 let mut chars = inner.chars();
273 while valid {
274 let mut i = 0;
275 for c in chars.by_ref() {
276 if c.is_numeric() {
277 i = i * 10 + c as usize - '0' as usize;
278 } else {
279 break
280 }
281 }
282 if i == 0 {
283 valid = chars.next().is_none();
284 break
285 } else if chars.by_ref().take(i - 1).count() != i - 1 {
286 valid = false;
287 }
288 }
289 }
290
291 // Alright, let's do this.
292 if !valid {
293 writer.write_all(s.as_bytes())?;
294 } else {
295 // remove the `::hfc2edb670e5eda97` part at the end of the symbol.
296 if format == PrintFormat::Short {
297 // The symbol in still mangled.
298 let mut split = inner.rsplitn(2, "17h");
299 match (split.next(), split.next()) {
300 (Some(addr), rest) => {
301 if addr.len() == 16 &&
302 addr.chars().all(|c| c.is_digit(16))
303 {
304 inner = rest.unwrap_or("");
305 }
306 }
307 _ => (),
308 }
309 }
310
311 let mut first = true;
312 while !inner.is_empty() {
313 if !first {
314 writer.write_all(b"::")?;
315 } else {
316 first = false;
317 }
318 let mut rest = inner;
319 while rest.chars().next().unwrap().is_numeric() {
320 rest = &rest[1..];
321 }
322 let i: usize = inner[.. (inner.len() - rest.len())].parse().unwrap();
323 inner = &rest[i..];
324 rest = &rest[..i];
325 if rest.starts_with("_$") {
326 rest = &rest[1..];
327 }
328 while !rest.is_empty() {
329 if rest.starts_with(".") {
330 if let Some('.') = rest[1..].chars().next() {
331 writer.write_all(b"::")?;
332 rest = &rest[2..];
333 } else {
334 writer.write_all(b".")?;
335 rest = &rest[1..];
336 }
337 } else if rest.starts_with("$") {
338 macro_rules! demangle {
339 ($($pat:expr => $demangled:expr),*) => ({
340 $(if rest.starts_with($pat) {
341 writer.write_all($demangled)?;
342 rest = &rest[$pat.len()..];
343 } else)*
344 {
345 writer.write_all(rest.as_bytes())?;
346 break;
347 }
348
349 })
350 }
351
352 // see src/librustc/back/link.rs for these mappings
353 demangle! (
354 "$SP$" => b"@",
355 "$BP$" => b"*",
356 "$RF$" => b"&",
357 "$LT$" => b"<",
358 "$GT$" => b">",
359 "$LP$" => b"(",
360 "$RP$" => b")",
361 "$C$" => b",",
362
363 // in theory we can demangle any Unicode code point, but
364 // for simplicity we just catch the common ones.
365 "$u7e$" => b"~",
366 "$u20$" => b" ",
367 "$u27$" => b"'",
368 "$u5b$" => b"[",
369 "$u5d$" => b"]",
370 "$u7b$" => b"{",
371 "$u7d$" => b"}",
372 "$u3b$" => b";",
373 "$u2b$" => b"+",
374 "$u22$" => b"\""
375 )
376 } else {
377 let idx = match rest.char_indices().find(|&(_, c)| c == '$' || c == '.') {
378 None => rest.len(),
379 Some((i, _)) => i,
380 };
381 writer.write_all(rest[..idx].as_bytes())?;
382 rest = &rest[idx..];
383 }
384 }
385 }
386 }
387
388 Ok(())
389 }
390
391 #[cfg(test)]
392 mod tests {
393 use sys_common;
394 macro_rules! t { ($a:expr, $b:expr) => ({
395 let mut m = Vec::new();
396 sys_common::backtrace::demangle(&mut m,
397 $a,
398 super::PrintFormat::Full).unwrap();
399 assert_eq!(String::from_utf8(m).unwrap(), $b);
400 }) }
401
402 #[test]
403 fn demangle() {
404 t!("test", "test");
405 t!("_ZN4testE", "test");
406 t!("_ZN4test", "_ZN4test");
407 t!("_ZN4test1a2bcE", "test::a::bc");
408 }
409
410 #[test]
411 fn demangle_dollars() {
412 t!("_ZN4$RP$E", ")");
413 t!("_ZN8$RF$testE", "&test");
414 t!("_ZN8$BP$test4foobE", "*test::foob");
415 t!("_ZN9$u20$test4foobE", " test::foob");
416 t!("_ZN35Bar$LT$$u5b$u32$u3b$$u20$4$u5d$$GT$E", "Bar<[u32; 4]>");
417 }
418
419 #[test]
420 fn demangle_many_dollars() {
421 t!("_ZN13test$u20$test4foobE", "test test::foob");
422 t!("_ZN12test$BP$test4foobE", "test*test::foob");
423 }
424
425 #[test]
426 fn demangle_windows() {
427 t!("ZN4testE", "test");
428 t!("ZN13test$u20$test4foobE", "test test::foob");
429 t!("ZN12test$RF$test4foobE", "test&test::foob");
430 }
431
432 #[test]
433 fn demangle_elements_beginning_with_underscore() {
434 t!("_ZN13_$LT$test$GT$E", "<test>");
435 t!("_ZN28_$u7b$$u7b$closure$u7d$$u7d$E", "{{closure}}");
436 t!("_ZN15__STATIC_FMTSTRE", "__STATIC_FMTSTR");
437 }
438
439 #[test]
440 fn demangle_trait_impls() {
441 t!("_ZN71_$LT$Test$u20$$u2b$$u20$$u27$static$u20$as$u20$foo..Bar$LT$Test$GT$$GT$3barE",
442 "<Test + 'static as foo::Bar<Test>>::bar");
443 }
444 }