]> git.lizzy.rs Git - rust.git/blob - src/libstd/backtrace.rs
remove unnecessary derives
[rust.git] / src / libstd / backtrace.rs
1 //! Support for capturing a stack backtrace of an OS thread
2 //!
3 //! This module contains the support necessary to capture a stack backtrace of a
4 //! running OS thread from the OS thread itself. The `Backtrace` type supports
5 //! capturing a stack trace via the `Backtrace::capture` and
6 //! `Backtrace::force_capture` functions.
7 //!
8 //! A backtrace is typically quite handy to attach to errors (e.g. types
9 //! implementing `std::error::Error`) to get a causal chain of where an error
10 //! was generated.
11 //!
12 //! > **Note**: this module is unstable and is designed in [RFC 2504], and you
13 //! > can learn more about its status in the [tracking issue].
14 //!
15 //! [RFC 2504]: https://github.com/rust-lang/rfcs/blob/master/text/2504-fix-error.md
16 //! [tracking issue]: https://github.com/rust-lang/rust/issues/53487
17 //!
18 //! ## Accuracy
19 //!
20 //! Backtraces are attempted to be as accurate as possible, but no guarantees
21 //! are provided about the exact accuracy of a backtrace. Instruction pointers,
22 //! symbol names, filenames, line numbers, etc, may all be incorrect when
23 //! reported. Accuracy is attempted on a best-effort basis, however, and bugs
24 //! are always welcome to indicate areas of improvement!
25 //!
26 //! For most platforms a backtrace with a filename/line number requires that
27 //! programs be compiled with debug information. Without debug information
28 //! filenames/line numbers will not be reported.
29 //!
30 //! ## Platform support
31 //!
32 //! Not all platforms that libstd compiles for support capturing backtraces.
33 //! Some platforms simply do nothing when capturing a backtrace. To check
34 //! whether the platform supports capturing backtraces you can consult the
35 //! `BacktraceStatus` enum as a result of `Backtrace::status`.
36 //!
37 //! Like above with accuracy platform support is done on a best effort basis.
38 //! Sometimes libraries may not be available at runtime or something may go
39 //! wrong which would cause a backtrace to not be captured. Please feel free to
40 //! report issues with platforms where a backtrace cannot be captured though!
41 //!
42 //! ## Environment Variables
43 //!
44 //! The `Backtrace::capture` function may not actually capture a backtrace by
45 //! default. Its behavior is governed by two environment variables:
46 //!
47 //! * `RUST_LIB_BACKTRACE` - if this is set to `0` then `Backtrace::capture`
48 //!   will never capture a backtrace. Any other value this is set to will enable
49 //!   `Backtrace::capture`.
50 //!
51 //! * `RUST_BACKTRACE` - if `RUST_LIB_BACKTRACE` is not set, then this variable
52 //!   is consulted with the same rules of `RUST_LIB_BACKTRACE`.
53 //!
54 //! * If neither of the above env vars are set, then `Backtrace::capture` will
55 //!   be disabled.
56 //!
57 //! Capturing a backtrace can be a quite expensive runtime operation, so the
58 //! environment variables allow either forcibly disabling this runtime
59 //! performance hit or allow selectively enabling it in some programs.
60 //!
61 //! Note that the `Backtrace::force_capture` function can be used to ignore
62 //! these environment variables. Also note that the state of environment
63 //! variables is cached once the first backtrace is created, so altering
64 //! `RUST_LIB_BACKTRACE` or `RUST_BACKTRACE` at runtime may not actually change
65 //! how backtraces are captured.
66
67 #![unstable(feature = "backtrace", issue = "53487")]
68
69 // NB: A note on resolution of a backtrace:
70 //
71 // Backtraces primarily happen in two steps, one is where we actually capture
72 // the stack backtrace, giving us a list of instruction pointers corresponding
73 // to stack frames. Next we take these instruction pointers and, one-by-one,
74 // turn them into a human readable name (like `main`).
75 //
76 // The first phase can be somewhat expensive (walking the stack), especially
77 // on MSVC where debug information is consulted to return inline frames each as
78 // their own frame. The second phase, however, is almost always extremely
79 // expensive (on the order of milliseconds sometimes) when it's consulting debug
80 // information.
81 //
82 // We attempt to amortize this cost as much as possible by delaying resolution
83 // of an address to a human readable name for as long as possible. When
84 // `Backtrace::create` is called to capture a backtrace it doesn't actually
85 // perform any symbol resolution, but rather we lazily resolve symbols only just
86 // before they're needed for printing. This way we can make capturing a
87 // backtrace and throwing it away much cheaper, but actually printing a
88 // backtrace is still basically the same cost.
89 //
90 // This strategy comes at the cost of some synchronization required inside of a
91 // `Backtrace`, but that's a relatively small price to pay relative to capturing
92 // a backtrace or actually symbolizing it.
93
94 use crate::env;
95 use crate::fmt;
96 use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst};
97 use crate::sync::Mutex;
98 use crate::sys_common::backtrace::{lock, output_filename};
99 use crate::vec::Vec;
100 use backtrace::BytesOrWideString;
101 use backtrace_rs as backtrace;
102
103 /// A captured OS thread stack backtrace.
104 ///
105 /// This type represents a stack backtrace for an OS thread captured at a
106 /// previous point in time. In some instances the `Backtrace` type may
107 /// internally be empty due to configuration. For more information see
108 /// `Backtrace::capture`.
109 pub struct Backtrace {
110     inner: Inner,
111 }
112
113 /// The current status of a backtrace, indicating whether it was captured or
114 /// whether it is empty for some other reason.
115 #[non_exhaustive]
116 #[derive(Debug, PartialEq, Eq)]
117 pub enum BacktraceStatus {
118     /// Capturing a backtrace is not supported, likely because it's not
119     /// implemented for the current platform.
120     Unsupported,
121     /// Capturing a backtrace has been disabled through either the
122     /// `RUST_LIB_BACKTRACE` or `RUST_BACKTRACE` environment variables.
123     Disabled,
124     /// A backtrace has been captured and the `Backtrace` should print
125     /// reasonable information when rendered.
126     Captured,
127 }
128
129 enum Inner {
130     Unsupported,
131     Disabled,
132     Captured(Mutex<Capture>),
133 }
134
135 struct Capture {
136     actual_start: usize,
137     resolved: bool,
138     frames: Vec<BacktraceFrame>,
139 }
140
141 fn _assert_send_sync() {
142     fn _assert<T: Send + Sync>() {}
143     _assert::<Backtrace>();
144 }
145
146 struct BacktraceFrame {
147     frame: backtrace::Frame,
148     symbols: Vec<BacktraceSymbol>,
149 }
150
151 struct BacktraceSymbol {
152     name: Option<Vec<u8>>,
153     filename: Option<BytesOrWide>,
154     lineno: Option<u32>,
155 }
156
157 enum BytesOrWide {
158     Bytes(Vec<u8>),
159     Wide(Vec<u16>),
160 }
161
162 impl fmt::Debug for Backtrace {
163     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
164         let mut capture = match &self.inner {
165             Inner::Unsupported => return fmt.write_str("unsupported backtrace"),
166             Inner::Disabled => return fmt.write_str("disabled backtrace"),
167             Inner::Captured(c) => c.lock().unwrap(),
168         };
169         capture.resolve();
170
171         let mut dbg = fmt.debug_list();
172
173         for frame in &capture.frames {
174             dbg.entries(&frame.symbols);
175         }
176
177         dbg.finish()
178     }
179 }
180
181 impl fmt::Debug for BacktraceFrame {
182     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
183         fmt.debug_list().entries(&self.symbols).finish()
184     }
185 }
186
187 impl fmt::Debug for BacktraceSymbol {
188     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
189         let mut dbg = fmt.debug_struct("");
190         dbg.field("fn", &self.name.as_ref().map(|b| backtrace::SymbolName::new(b)));
191
192         if let Some(fname) = self.filename.as_ref() {
193             dbg.field("file", fname);
194         }
195
196         if let Some(line) = self.lineno.as_ref() {
197             dbg.field("line", &self.lineno);
198         }
199
200         dbg.finish()
201     }
202 }
203
204 impl fmt::Debug for BytesOrWide {
205     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
206         output_filename(
207             fmt,
208             match self {
209                 BytesOrWide::Bytes(w) => BytesOrWideString::Bytes(w),
210                 BytesOrWide::Wide(w) => BytesOrWideString::Wide(w),
211             },
212             backtrace::PrintFmt::Full,
213             crate::env::current_dir().as_ref().ok(),
214         )
215     }
216 }
217
218 impl Backtrace {
219     /// Returns whether backtrace captures are enabled through environment
220     /// variables.
221     fn enabled() -> bool {
222         // Cache the result of reading the environment variables to make
223         // backtrace captures speedy, because otherwise reading environment
224         // variables every time can be somewhat slow.
225         static ENABLED: AtomicUsize = AtomicUsize::new(0);
226         match ENABLED.load(SeqCst) {
227             0 => {}
228             1 => return false,
229             _ => return true,
230         }
231         let enabled = match env::var("RUST_LIB_BACKTRACE") {
232             Ok(s) => s != "0",
233             Err(_) => match env::var("RUST_BACKTRACE") {
234                 Ok(s) => s != "0",
235                 Err(_) => false,
236             },
237         };
238         ENABLED.store(enabled as usize + 1, SeqCst);
239         return enabled;
240     }
241
242     /// Capture a stack backtrace of the current thread.
243     ///
244     /// This function will capture a stack backtrace of the current OS thread of
245     /// execution, returning a `Backtrace` type which can be later used to print
246     /// the entire stack trace or render it to a string.
247     ///
248     /// This function will be a noop if the `RUST_BACKTRACE` or
249     /// `RUST_LIB_BACKTRACE` backtrace variables are both not set. If either
250     /// environment variable is set and enabled then this function will actually
251     /// capture a backtrace. Capturing a backtrace can be both memory intensive
252     /// and slow, so these environment variables allow liberally using
253     /// `Backtrace::capture` and only incurring a slowdown when the environment
254     /// variables are set.
255     ///
256     /// To forcibly capture a backtrace regardless of environment variables, use
257     /// the `Backtrace::force_capture` function.
258     #[inline(never)] // want to make sure there's a frame here to remove
259     pub fn capture() -> Backtrace {
260         if !Backtrace::enabled() {
261             return Backtrace { inner: Inner::Disabled };
262         }
263         Backtrace::create(Backtrace::capture as usize)
264     }
265
266     /// Forcibly captures a full backtrace, regardless of environment variable
267     /// configuration.
268     ///
269     /// This function behaves the same as `capture` except that it ignores the
270     /// values of the `RUST_BACKTRACE` and `RUST_LIB_BACKTRACE` environment
271     /// variables, always capturing a backtrace.
272     ///
273     /// Note that capturing a backtrace can be an expensive operation on some
274     /// platforms, so this should be used with caution in performance-sensitive
275     /// parts of code.
276     #[inline(never)] // want to make sure there's a frame here to remove
277     pub fn force_capture() -> Backtrace {
278         Backtrace::create(Backtrace::force_capture as usize)
279     }
280
281     // Capture a backtrace which start just before the function addressed by
282     // `ip`
283     fn create(ip: usize) -> Backtrace {
284         let _lock = lock();
285         let mut frames = Vec::new();
286         let mut actual_start = None;
287         unsafe {
288             backtrace::trace_unsynchronized(|frame| {
289                 frames.push(BacktraceFrame { frame: frame.clone(), symbols: Vec::new() });
290                 if frame.symbol_address() as usize == ip && actual_start.is_none() {
291                     actual_start = Some(frames.len());
292                 }
293                 true
294             });
295         }
296
297         // If no frames came out assume that this is an unsupported platform
298         // since `backtrace` doesn't provide a way of learning this right now,
299         // and this should be a good enough approximation.
300         let inner = if frames.len() == 0 {
301             Inner::Unsupported
302         } else {
303             Inner::Captured(Mutex::new(Capture {
304                 actual_start: actual_start.unwrap_or(0),
305                 frames,
306                 resolved: false,
307             }))
308         };
309
310         Backtrace { inner }
311     }
312
313     /// Returns the status of this backtrace, indicating whether this backtrace
314     /// request was unsupported, disabled, or a stack trace was actually
315     /// captured.
316     pub fn status(&self) -> BacktraceStatus {
317         match self.inner {
318             Inner::Unsupported => BacktraceStatus::Unsupported,
319             Inner::Disabled => BacktraceStatus::Disabled,
320             Inner::Captured(_) => BacktraceStatus::Captured,
321         }
322     }
323 }
324
325 impl fmt::Display for Backtrace {
326     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
327         let mut capture = match &self.inner {
328             Inner::Unsupported => return fmt.write_str("unsupported backtrace"),
329             Inner::Disabled => return fmt.write_str("disabled backtrace"),
330             Inner::Captured(c) => c.lock().unwrap(),
331         };
332         capture.resolve();
333
334         let full = fmt.alternate();
335         let (frames, style) = if full {
336             (&capture.frames[..], backtrace::PrintFmt::Full)
337         } else {
338             (&capture.frames[capture.actual_start..], backtrace::PrintFmt::Short)
339         };
340
341         // When printing paths we try to strip the cwd if it exists, otherwise
342         // we just print the path as-is. Note that we also only do this for the
343         // short format, because if it's full we presumably want to print
344         // everything.
345         let cwd = crate::env::current_dir();
346         let mut print_path = move |fmt: &mut fmt::Formatter<'_>, path: BytesOrWideString<'_>| {
347             output_filename(fmt, path, style, cwd.as_ref().ok())
348         };
349
350         let mut f = backtrace::BacktraceFmt::new(fmt, style, &mut print_path);
351         f.add_context()?;
352         for frame in frames {
353             let mut f = f.frame();
354             if frame.symbols.is_empty() {
355                 f.print_raw(frame.frame.ip(), None, None, None)?;
356             } else {
357                 for symbol in frame.symbols.iter() {
358                     f.print_raw(
359                         frame.frame.ip(),
360                         symbol.name.as_ref().map(|b| backtrace::SymbolName::new(b)),
361                         symbol.filename.as_ref().map(|b| match b {
362                             BytesOrWide::Bytes(w) => BytesOrWideString::Bytes(w),
363                             BytesOrWide::Wide(w) => BytesOrWideString::Wide(w),
364                         }),
365                         symbol.lineno,
366                     )?;
367                 }
368             }
369         }
370         f.finish()?;
371         Ok(())
372     }
373 }
374
375 impl Capture {
376     fn resolve(&mut self) {
377         // If we're already resolved, nothing to do!
378         if self.resolved {
379             return;
380         }
381         self.resolved = true;
382
383         // Use the global backtrace lock to synchronize this as it's a
384         // requirement of the `backtrace` crate, and then actually resolve
385         // everything.
386         let _lock = lock();
387         for frame in self.frames.iter_mut() {
388             let symbols = &mut frame.symbols;
389             unsafe {
390                 backtrace::resolve_frame_unsynchronized(&frame.frame, |symbol| {
391                     symbols.push(BacktraceSymbol {
392                         name: symbol.name().map(|m| m.as_bytes().to_vec()),
393                         filename: symbol.filename_raw().map(|b| match b {
394                             BytesOrWideString::Bytes(b) => BytesOrWide::Bytes(b.to_owned()),
395                             BytesOrWideString::Wide(b) => BytesOrWide::Wide(b.to_owned()),
396                         }),
397                         lineno: symbol.lineno(),
398                     });
399                 });
400             }
401         }
402     }
403 }
404
405 #[cfg(test)]
406 mod tests {
407     use super::*;
408
409     #[test]
410     fn debug_backtrace_fmt() {
411         let bt = Backtrace::capture();
412         eprintln!("uncaptured: {:?}", bt);
413         let bt = Backtrace::force_capture();
414         eprintln!("captured: {:?}", bt);
415         eprintln!("display print: {}", bt);
416         eprintln!("resolved: {:?}", bt);
417         unimplemented!();
418     }
419 }