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