]> git.lizzy.rs Git - rust.git/blob - library/std/src/backtrace.rs
Auto merge of #80715 - JulianKnodt:skip_opt, r=nagisa
[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 struct BacktraceFrame {
151     frame: RawFrame,
152     symbols: Vec<BacktraceSymbol>,
153 }
154
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 impl fmt::Debug for Backtrace {
174     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
175         let capture = match &self.inner {
176             Inner::Unsupported => return fmt.write_str("<unsupported>"),
177             Inner::Disabled => return fmt.write_str("<disabled>"),
178             Inner::Captured(c) => c.force(),
179         };
180
181         let frames = &capture.frames[capture.actual_start..];
182
183         write!(fmt, "Backtrace ")?;
184
185         let mut dbg = fmt.debug_list();
186
187         for frame in frames {
188             if frame.frame.ip().is_null() {
189                 continue;
190             }
191
192             dbg.entries(&frame.symbols);
193         }
194
195         dbg.finish()
196     }
197 }
198
199 impl fmt::Debug for BacktraceSymbol {
200     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
201         // FIXME: improve formatting: https://github.com/rust-lang/rust/issues/65280
202         // FIXME: Also, include column numbers into the debug format as Display already has them.
203         // Until there are stable per-frame accessors, the format shouldn't be changed:
204         // https://github.com/rust-lang/rust/issues/65280#issuecomment-638966585
205         write!(fmt, "{{ ")?;
206
207         if let Some(fn_name) = self.name.as_ref().map(|b| backtrace_rs::SymbolName::new(b)) {
208             write!(fmt, "fn: \"{:#}\"", fn_name)?;
209         } else {
210             write!(fmt, "fn: <unknown>")?;
211         }
212
213         if let Some(fname) = self.filename.as_ref() {
214             write!(fmt, ", file: \"{:?}\"", fname)?;
215         }
216
217         if let Some(line) = self.lineno {
218             write!(fmt, ", line: {:?}", line)?;
219         }
220
221         write!(fmt, " }}")
222     }
223 }
224
225 impl fmt::Debug for BytesOrWide {
226     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
227         output_filename(
228             fmt,
229             match self {
230                 BytesOrWide::Bytes(w) => BytesOrWideString::Bytes(w),
231                 BytesOrWide::Wide(w) => BytesOrWideString::Wide(w),
232             },
233             backtrace_rs::PrintFmt::Short,
234             crate::env::current_dir().as_ref().ok(),
235         )
236     }
237 }
238
239 impl Backtrace {
240     /// Returns whether backtrace captures are enabled through environment
241     /// variables.
242     fn enabled() -> bool {
243         // Cache the result of reading the environment variables to make
244         // backtrace captures speedy, because otherwise reading environment
245         // variables every time can be somewhat slow.
246         static ENABLED: AtomicUsize = AtomicUsize::new(0);
247         match ENABLED.load(SeqCst) {
248             0 => {}
249             1 => return false,
250             _ => return true,
251         }
252         let enabled = match env::var("RUST_LIB_BACKTRACE") {
253             Ok(s) => s != "0",
254             Err(_) => match env::var("RUST_BACKTRACE") {
255                 Ok(s) => s != "0",
256                 Err(_) => false,
257             },
258         };
259         ENABLED.store(enabled as usize + 1, SeqCst);
260         enabled
261     }
262
263     /// Capture a stack backtrace of the current thread.
264     ///
265     /// This function will capture a stack backtrace of the current OS thread of
266     /// execution, returning a `Backtrace` type which can be later used to print
267     /// the entire stack trace or render it to a string.
268     ///
269     /// This function will be a noop if the `RUST_BACKTRACE` or
270     /// `RUST_LIB_BACKTRACE` backtrace variables are both not set. If either
271     /// environment variable is set and enabled then this function will actually
272     /// capture a backtrace. Capturing a backtrace can be both memory intensive
273     /// and slow, so these environment variables allow liberally using
274     /// `Backtrace::capture` and only incurring a slowdown when the environment
275     /// variables are set.
276     ///
277     /// To forcibly capture a backtrace regardless of environment variables, use
278     /// the `Backtrace::force_capture` function.
279     #[inline(never)] // want to make sure there's a frame here to remove
280     pub fn capture() -> Backtrace {
281         if !Backtrace::enabled() {
282             return Backtrace { inner: Inner::Disabled };
283         }
284         Backtrace::create(Backtrace::capture as usize)
285     }
286
287     /// Forcibly captures a full backtrace, regardless of environment variable
288     /// configuration.
289     ///
290     /// This function behaves the same as `capture` except that it ignores the
291     /// values of the `RUST_BACKTRACE` and `RUST_LIB_BACKTRACE` environment
292     /// variables, always capturing a backtrace.
293     ///
294     /// Note that capturing a backtrace can be an expensive operation on some
295     /// platforms, so this should be used with caution in performance-sensitive
296     /// parts of code.
297     #[inline(never)] // want to make sure there's a frame here to remove
298     pub fn force_capture() -> Backtrace {
299         Backtrace::create(Backtrace::force_capture as usize)
300     }
301
302     /// Forcibly captures a disabled backtrace, regardless of environment
303     /// variable configuration.
304     pub const fn disabled() -> Backtrace {
305         Backtrace { inner: Inner::Disabled }
306     }
307
308     // Capture a backtrace which start just before the function addressed by
309     // `ip`
310     fn create(ip: usize) -> Backtrace {
311         // SAFETY: We don't attempt to lock this reentrantly.
312         let _lock = unsafe { lock() };
313         let mut frames = Vec::new();
314         let mut actual_start = None;
315         unsafe {
316             backtrace_rs::trace_unsynchronized(|frame| {
317                 frames.push(BacktraceFrame {
318                     frame: RawFrame::Actual(frame.clone()),
319                     symbols: Vec::new(),
320                 });
321                 if frame.symbol_address() as usize == ip && actual_start.is_none() {
322                     actual_start = Some(frames.len());
323                 }
324                 true
325             });
326         }
327
328         // If no frames came out assume that this is an unsupported platform
329         // since `backtrace` doesn't provide a way of learning this right now,
330         // and this should be a good enough approximation.
331         let inner = if frames.is_empty() {
332             Inner::Unsupported
333         } else {
334             Inner::Captured(LazilyResolvedCapture::new(Capture {
335                 actual_start: actual_start.unwrap_or(0),
336                 frames,
337                 resolved: false,
338             }))
339         };
340
341         Backtrace { inner }
342     }
343
344     /// Returns the status of this backtrace, indicating whether this backtrace
345     /// request was unsupported, disabled, or a stack trace was actually
346     /// captured.
347     pub fn status(&self) -> BacktraceStatus {
348         match self.inner {
349             Inner::Unsupported => BacktraceStatus::Unsupported,
350             Inner::Disabled => BacktraceStatus::Disabled,
351             Inner::Captured(_) => BacktraceStatus::Captured,
352         }
353     }
354 }
355
356 impl fmt::Display for Backtrace {
357     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
358         let capture = match &self.inner {
359             Inner::Unsupported => return fmt.write_str("unsupported backtrace"),
360             Inner::Disabled => return fmt.write_str("disabled backtrace"),
361             Inner::Captured(c) => c.force(),
362         };
363
364         let full = fmt.alternate();
365         let (frames, style) = if full {
366             (&capture.frames[..], backtrace_rs::PrintFmt::Full)
367         } else {
368             (&capture.frames[capture.actual_start..], backtrace_rs::PrintFmt::Short)
369         };
370
371         // When printing paths we try to strip the cwd if it exists, otherwise
372         // we just print the path as-is. Note that we also only do this for the
373         // short format, because if it's full we presumably want to print
374         // everything.
375         let cwd = crate::env::current_dir();
376         let mut print_path = move |fmt: &mut fmt::Formatter<'_>, path: BytesOrWideString<'_>| {
377             output_filename(fmt, path, style, cwd.as_ref().ok())
378         };
379
380         let mut f = backtrace_rs::BacktraceFmt::new(fmt, style, &mut print_path);
381         f.add_context()?;
382         for frame in frames {
383             let mut f = f.frame();
384             if frame.symbols.is_empty() {
385                 f.print_raw(frame.frame.ip(), None, None, None)?;
386             } else {
387                 for symbol in frame.symbols.iter() {
388                     f.print_raw_with_column(
389                         frame.frame.ip(),
390                         symbol.name.as_ref().map(|b| backtrace_rs::SymbolName::new(b)),
391                         symbol.filename.as_ref().map(|b| match b {
392                             BytesOrWide::Bytes(w) => BytesOrWideString::Bytes(w),
393                             BytesOrWide::Wide(w) => BytesOrWideString::Wide(w),
394                         }),
395                         symbol.lineno,
396                         symbol.colno,
397                     )?;
398                 }
399             }
400         }
401         f.finish()?;
402         Ok(())
403     }
404 }
405
406 struct LazilyResolvedCapture {
407     sync: Once,
408     capture: UnsafeCell<Capture>,
409 }
410
411 impl LazilyResolvedCapture {
412     fn new(capture: Capture) -> Self {
413         LazilyResolvedCapture { sync: Once::new(), capture: UnsafeCell::new(capture) }
414     }
415
416     fn force(&self) -> &Capture {
417         self.sync.call_once(|| {
418             // SAFETY: This exclusive reference can't overlap with any others
419             // `Once` guarantees callers will block until this closure returns
420             // `Once` also guarantees only a single caller will enter this closure
421             unsafe { &mut *self.capture.get() }.resolve();
422         });
423
424         // SAFETY: This shared reference can't overlap with the exclusive reference above
425         unsafe { &*self.capture.get() }
426     }
427 }
428
429 // SAFETY: Access to the inner value is synchronized using a thread-safe `Once`
430 // So long as `Capture` is `Sync`, `LazilyResolvedCapture` is too
431 unsafe impl Sync for LazilyResolvedCapture where Capture: Sync {}
432
433 impl Capture {
434     fn resolve(&mut self) {
435         // If we're already resolved, nothing to do!
436         if self.resolved {
437             return;
438         }
439         self.resolved = true;
440
441         // Use the global backtrace lock to synchronize this as it's a
442         // requirement of the `backtrace` crate, and then actually resolve
443         // everything.
444         // SAFETY: We don't attempt to lock this reentrantly.
445         let _lock = unsafe { lock() };
446         for frame in self.frames.iter_mut() {
447             let symbols = &mut frame.symbols;
448             let frame = match &frame.frame {
449                 RawFrame::Actual(frame) => frame,
450                 #[cfg(test)]
451                 RawFrame::Fake => unimplemented!(),
452             };
453             unsafe {
454                 backtrace_rs::resolve_frame_unsynchronized(frame, |symbol| {
455                     symbols.push(BacktraceSymbol {
456                         name: symbol.name().map(|m| m.as_bytes().to_vec()),
457                         filename: symbol.filename_raw().map(|b| match b {
458                             BytesOrWideString::Bytes(b) => BytesOrWide::Bytes(b.to_owned()),
459                             BytesOrWideString::Wide(b) => BytesOrWide::Wide(b.to_owned()),
460                         }),
461                         lineno: symbol.lineno(),
462                         colno: symbol.colno(),
463                     });
464                 });
465             }
466         }
467     }
468 }
469
470 impl RawFrame {
471     fn ip(&self) -> *mut c_void {
472         match self {
473             RawFrame::Actual(frame) => frame.ip(),
474             #[cfg(test)]
475             RawFrame::Fake => 1 as *mut c_void,
476         }
477     }
478 }