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