]> git.lizzy.rs Git - rust.git/blob - src/libstd/panicking.rs
Rollup merge of #67507 - Mark-Simulacrum:purge-uninit, r=Centril
[rust.git] / src / libstd / panicking.rs
1 //! Implementation of various bits and pieces of the `panic!` macro and
2 //! associated runtime pieces.
3 //!
4 //! Specifically, this module contains the implementation of:
5 //!
6 //! * Panic hooks
7 //! * Executing a panic up to doing the actual implementation
8 //! * Shims around "try"
9
10 use core::panic::{BoxMeUp, Location, PanicInfo};
11
12 use crate::any::Any;
13 use crate::fmt;
14 use crate::intrinsics;
15 use crate::mem::{self, ManuallyDrop};
16 use crate::process;
17 use crate::raw;
18 use crate::sync::atomic::{AtomicBool, Ordering};
19 use crate::sys::stdio::panic_output;
20 use crate::sys_common::backtrace::{self, RustBacktrace};
21 use crate::sys_common::rwlock::RWLock;
22 use crate::sys_common::{thread_info, util};
23 use crate::thread;
24
25 #[cfg(not(test))]
26 use crate::io::set_panic;
27 // make sure to use the stderr output configured
28 // by libtest in the real copy of std
29 #[cfg(test)]
30 use realstd::io::set_panic;
31
32 // Binary interface to the panic runtime that the standard library depends on.
33 //
34 // The standard library is tagged with `#![needs_panic_runtime]` (introduced in
35 // RFC 1513) to indicate that it requires some other crate tagged with
36 // `#![panic_runtime]` to exist somewhere. Each panic runtime is intended to
37 // implement these symbols (with the same signatures) so we can get matched up
38 // to them.
39 //
40 // One day this may look a little less ad-hoc with the compiler helping out to
41 // hook up these functions, but it is not this day!
42 #[allow(improper_ctypes)]
43 extern "C" {
44     fn __rust_maybe_catch_panic(
45         f: fn(*mut u8),
46         data: *mut u8,
47         data_ptr: *mut usize,
48         vtable_ptr: *mut usize,
49     ) -> u32;
50
51     /// `payload` is actually a `*mut &mut dyn BoxMeUp` but that would cause FFI warnings.
52     /// It cannot be `Box<dyn BoxMeUp>` because the other end of this call does not depend
53     /// on liballoc, and thus cannot use `Box`.
54     #[unwind(allowed)]
55     fn __rust_start_panic(payload: usize) -> u32;
56 }
57
58 #[derive(Copy, Clone)]
59 enum Hook {
60     Default,
61     Custom(*mut (dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send)),
62 }
63
64 static HOOK_LOCK: RWLock = RWLock::new();
65 static mut HOOK: Hook = Hook::Default;
66
67 /// Registers a custom panic hook, replacing any that was previously registered.
68 ///
69 /// The panic hook is invoked when a thread panics, but before the panic runtime
70 /// is invoked. As such, the hook will run with both the aborting and unwinding
71 /// runtimes. The default hook prints a message to standard error and generates
72 /// a backtrace if requested, but this behavior can be customized with the
73 /// `set_hook` and [`take_hook`] functions.
74 ///
75 /// [`take_hook`]: ./fn.take_hook.html
76 ///
77 /// The hook is provided with a `PanicInfo` struct which contains information
78 /// about the origin of the panic, including the payload passed to `panic!` and
79 /// the source code location from which the panic originated.
80 ///
81 /// The panic hook is a global resource.
82 ///
83 /// # Panics
84 ///
85 /// Panics if called from a panicking thread.
86 ///
87 /// # Examples
88 ///
89 /// The following will print "Custom panic hook":
90 ///
91 /// ```should_panic
92 /// use std::panic;
93 ///
94 /// panic::set_hook(Box::new(|_| {
95 ///     println!("Custom panic hook");
96 /// }));
97 ///
98 /// panic!("Normal panic");
99 /// ```
100 #[stable(feature = "panic_hooks", since = "1.10.0")]
101 pub fn set_hook(hook: Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send>) {
102     if thread::panicking() {
103         panic!("cannot modify the panic hook from a panicking thread");
104     }
105
106     unsafe {
107         HOOK_LOCK.write();
108         let old_hook = HOOK;
109         HOOK = Hook::Custom(Box::into_raw(hook));
110         HOOK_LOCK.write_unlock();
111
112         if let Hook::Custom(ptr) = old_hook {
113             #[allow(unused_must_use)]
114             {
115                 Box::from_raw(ptr);
116             }
117         }
118     }
119 }
120
121 /// Unregisters the current panic hook, returning it.
122 ///
123 /// *See also the function [`set_hook`].*
124 ///
125 /// [`set_hook`]: ./fn.set_hook.html
126 ///
127 /// If no custom hook is registered, the default hook will be returned.
128 ///
129 /// # Panics
130 ///
131 /// Panics if called from a panicking thread.
132 ///
133 /// # Examples
134 ///
135 /// The following will print "Normal panic":
136 ///
137 /// ```should_panic
138 /// use std::panic;
139 ///
140 /// panic::set_hook(Box::new(|_| {
141 ///     println!("Custom panic hook");
142 /// }));
143 ///
144 /// let _ = panic::take_hook();
145 ///
146 /// panic!("Normal panic");
147 /// ```
148 #[stable(feature = "panic_hooks", since = "1.10.0")]
149 pub fn take_hook() -> Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send> {
150     if thread::panicking() {
151         panic!("cannot modify the panic hook from a panicking thread");
152     }
153
154     unsafe {
155         HOOK_LOCK.write();
156         let hook = HOOK;
157         HOOK = Hook::Default;
158         HOOK_LOCK.write_unlock();
159
160         match hook {
161             Hook::Default => Box::new(default_hook),
162             Hook::Custom(ptr) => Box::from_raw(ptr),
163         }
164     }
165 }
166
167 fn default_hook(info: &PanicInfo<'_>) {
168     // If this is a double panic, make sure that we print a backtrace
169     // for this panic. Otherwise only print it if logging is enabled.
170     let backtrace_env = if update_panic_count(0) >= 2 {
171         RustBacktrace::Print(backtrace_rs::PrintFmt::Full)
172     } else {
173         backtrace::rust_backtrace_env()
174     };
175
176     // The current implementation always returns `Some`.
177     let location = info.location().unwrap();
178
179     let msg = match info.payload().downcast_ref::<&'static str>() {
180         Some(s) => *s,
181         None => match info.payload().downcast_ref::<String>() {
182             Some(s) => &s[..],
183             None => "Box<Any>",
184         },
185     };
186     let thread = thread_info::current_thread();
187     let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");
188
189     let write = |err: &mut dyn crate::io::Write| {
190         let _ = writeln!(err, "thread '{}' panicked at '{}', {}", name, msg, location);
191
192         static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
193
194         match backtrace_env {
195             RustBacktrace::Print(format) => drop(backtrace::print(err, format)),
196             RustBacktrace::Disabled => {}
197             RustBacktrace::RuntimeDisabled => {
198                 if FIRST_PANIC.swap(false, Ordering::SeqCst) {
199                     let _ = writeln!(
200                         err,
201                         "note: run with `RUST_BACKTRACE=1` \
202                                            environment variable to display a backtrace."
203                     );
204                 }
205             }
206         }
207     };
208
209     if let Some(mut local) = set_panic(None) {
210         // NB. In `cfg(test)` this uses the forwarding impl
211         // for `Box<dyn (::realstd::io::Write) + Send>`.
212         write(&mut local);
213         set_panic(Some(local));
214     } else if let Some(mut out) = panic_output() {
215         write(&mut out);
216     }
217 }
218
219 #[cfg(not(test))]
220 #[doc(hidden)]
221 #[unstable(feature = "update_panic_count", issue = "none")]
222 pub fn update_panic_count(amt: isize) -> usize {
223     use crate::cell::Cell;
224     thread_local! { static PANIC_COUNT: Cell<usize> = Cell::new(0) }
225
226     PANIC_COUNT.with(|c| {
227         let next = (c.get() as isize + amt) as usize;
228         c.set(next);
229         next
230     })
231 }
232
233 #[cfg(test)]
234 pub use realstd::rt::update_panic_count;
235
236 /// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
237 pub unsafe fn r#try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>> {
238     union Data<F, R> {
239         f: ManuallyDrop<F>,
240         r: ManuallyDrop<R>,
241     }
242
243     // We do some sketchy operations with ownership here for the sake of
244     // performance. We can only  pass pointers down to
245     // `__rust_maybe_catch_panic` (can't pass objects by value), so we do all
246     // the ownership tracking here manually using a union.
247     //
248     // We go through a transition where:
249     //
250     // * First, we set the data to be the closure that we're going to call.
251     // * When we make the function call, the `do_call` function below, we take
252     //   ownership of the function pointer. At this point the `Data` union is
253     //   entirely uninitialized.
254     // * If the closure successfully returns, we write the return value into the
255     //   data's return slot. Note that `ptr::write` is used as it's overwriting
256     //   uninitialized data.
257     // * Finally, when we come back out of the `__rust_maybe_catch_panic` we're
258     //   in one of two states:
259     //
260     //      1. The closure didn't panic, in which case the return value was
261     //         filled in. We move it out of `data` and return it.
262     //      2. The closure panicked, in which case the return value wasn't
263     //         filled in. In this case the entire `data` union is invalid, so
264     //         there is no need to drop anything.
265     //
266     // Once we stack all that together we should have the "most efficient'
267     // method of calling a catch panic whilst juggling ownership.
268     let mut any_data = 0;
269     let mut any_vtable = 0;
270     let mut data = Data { f: ManuallyDrop::new(f) };
271
272     let r = __rust_maybe_catch_panic(
273         do_call::<F, R>,
274         &mut data as *mut _ as *mut u8,
275         &mut any_data,
276         &mut any_vtable,
277     );
278
279     return if r == 0 {
280         debug_assert!(update_panic_count(0) == 0);
281         Ok(ManuallyDrop::into_inner(data.r))
282     } else {
283         update_panic_count(-1);
284         debug_assert!(update_panic_count(0) == 0);
285         Err(mem::transmute(raw::TraitObject {
286             data: any_data as *mut _,
287             vtable: any_vtable as *mut _,
288         }))
289     };
290
291     fn do_call<F: FnOnce() -> R, R>(data: *mut u8) {
292         unsafe {
293             let data = data as *mut Data<F, R>;
294             let data = &mut (*data);
295             let f = ManuallyDrop::take(&mut data.f);
296             data.r = ManuallyDrop::new(f());
297         }
298     }
299 }
300
301 /// Determines whether the current thread is unwinding because of panic.
302 pub fn panicking() -> bool {
303     update_panic_count(0) != 0
304 }
305
306 /// The entry point for panicking with a formatted message.
307 ///
308 /// This is designed to reduce the amount of code required at the call
309 /// site as much as possible (so that `panic!()` has as low an impact
310 /// on (e.g.) the inlining of other functions as possible), by moving
311 /// the actual formatting into this shared place.
312 #[unstable(feature = "libstd_sys_internals", reason = "used by the panic! macro", issue = "none")]
313 #[cold]
314 // If panic_immediate_abort, inline the abort call,
315 // otherwise avoid inlining because of it is cold path.
316 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
317 #[cfg_attr(feature = "panic_immediate_abort", inline)]
318 pub fn begin_panic_fmt(msg: &fmt::Arguments<'_>, file_line_col: &(&'static str, u32, u32)) -> ! {
319     if cfg!(feature = "panic_immediate_abort") {
320         unsafe { intrinsics::abort() }
321     }
322
323     // Just package everything into a `PanicInfo` and continue like libcore panics.
324     let (file, line, col) = *file_line_col;
325     let location = Location::internal_constructor(file, line, col);
326     let info = PanicInfo::internal_constructor(Some(msg), &location);
327     begin_panic_handler(&info)
328 }
329
330 /// Entry point of panics from the libcore crate (`panic_impl` lang item).
331 #[cfg_attr(not(test), panic_handler)]
332 #[unwind(allowed)]
333 pub fn begin_panic_handler(info: &PanicInfo<'_>) -> ! {
334     struct PanicPayload<'a> {
335         inner: &'a fmt::Arguments<'a>,
336         string: Option<String>,
337     }
338
339     impl<'a> PanicPayload<'a> {
340         fn new(inner: &'a fmt::Arguments<'a>) -> PanicPayload<'a> {
341             PanicPayload { inner, string: None }
342         }
343
344         fn fill(&mut self) -> &mut String {
345             use crate::fmt::Write;
346
347             let inner = self.inner;
348             // Lazily, the first time this gets called, run the actual string formatting.
349             self.string.get_or_insert_with(|| {
350                 let mut s = String::new();
351                 drop(s.write_fmt(*inner));
352                 s
353             })
354         }
355     }
356
357     unsafe impl<'a> BoxMeUp for PanicPayload<'a> {
358         fn take_box(&mut self) -> *mut (dyn Any + Send) {
359             let contents = mem::take(self.fill());
360             Box::into_raw(Box::new(contents))
361         }
362
363         fn get(&mut self) -> &(dyn Any + Send) {
364             self.fill()
365         }
366     }
367
368     // We do two allocations here, unfortunately. But (a) they're
369     // required with the current scheme, and (b) we don't handle
370     // panic + OOM properly anyway (see comment in begin_panic
371     // below).
372
373     let loc = info.location().unwrap(); // The current implementation always returns Some
374     let msg = info.message().unwrap(); // The current implementation always returns Some
375     let file_line_col = (loc.file(), loc.line(), loc.column());
376     rust_panic_with_hook(&mut PanicPayload::new(msg), info.message(), &file_line_col);
377 }
378
379 /// This is the entry point of panicking for the non-format-string variants of
380 /// panic!() and assert!(). In particular, this is the only entry point that supports
381 /// arbitrary payloads, not just format strings.
382 #[unstable(feature = "libstd_sys_internals", reason = "used by the panic! macro", issue = "none")]
383 #[cfg_attr(not(test), lang = "begin_panic")]
384 // lang item for CTFE panic support
385 // never inline unless panic_immediate_abort to avoid code
386 // bloat at the call sites as much as possible
387 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
388 #[cold]
389 pub fn begin_panic<M: Any + Send>(msg: M, file_line_col: &(&'static str, u32, u32)) -> ! {
390     if cfg!(feature = "panic_immediate_abort") {
391         unsafe { intrinsics::abort() }
392     }
393
394     // Note that this should be the only allocation performed in this code path.
395     // Currently this means that panic!() on OOM will invoke this code path,
396     // but then again we're not really ready for panic on OOM anyway. If
397     // we do start doing this, then we should propagate this allocation to
398     // be performed in the parent of this thread instead of the thread that's
399     // panicking.
400
401     rust_panic_with_hook(&mut PanicPayload::new(msg), None, file_line_col);
402
403     struct PanicPayload<A> {
404         inner: Option<A>,
405     }
406
407     impl<A: Send + 'static> PanicPayload<A> {
408         fn new(inner: A) -> PanicPayload<A> {
409             PanicPayload { inner: Some(inner) }
410         }
411     }
412
413     unsafe impl<A: Send + 'static> BoxMeUp for PanicPayload<A> {
414         fn take_box(&mut self) -> *mut (dyn Any + Send) {
415             let data = match self.inner.take() {
416                 Some(a) => Box::new(a) as Box<dyn Any + Send>,
417                 None => process::abort(),
418             };
419             Box::into_raw(data)
420         }
421
422         fn get(&mut self) -> &(dyn Any + Send) {
423             match self.inner {
424                 Some(ref a) => a,
425                 None => process::abort(),
426             }
427         }
428     }
429 }
430
431 /// Central point for dispatching panics.
432 ///
433 /// Executes the primary logic for a panic, including checking for recursive
434 /// panics, panic hooks, and finally dispatching to the panic runtime to either
435 /// abort or unwind.
436 fn rust_panic_with_hook(
437     payload: &mut dyn BoxMeUp,
438     message: Option<&fmt::Arguments<'_>>,
439     file_line_col: &(&str, u32, u32),
440 ) -> ! {
441     let (file, line, col) = *file_line_col;
442
443     let panics = update_panic_count(1);
444
445     // If this is the third nested call (e.g., panics == 2, this is 0-indexed),
446     // the panic hook probably triggered the last panic, otherwise the
447     // double-panic check would have aborted the process. In this case abort the
448     // process real quickly as we don't want to try calling it again as it'll
449     // probably just panic again.
450     if panics > 2 {
451         util::dumb_print(format_args!(
452             "thread panicked while processing \
453                                        panic. aborting.\n"
454         ));
455         unsafe { intrinsics::abort() }
456     }
457
458     unsafe {
459         let location = Location::internal_constructor(file, line, col);
460         let mut info = PanicInfo::internal_constructor(message, &location);
461         HOOK_LOCK.read();
462         match HOOK {
463             // Some platforms (like wasm) know that printing to stderr won't ever actually
464             // print anything, and if that's the case we can skip the default
465             // hook. Since string formatting happens lazily when calling `payload`
466             // methods, this means we avoid formatting the string at all!
467             // (The panic runtime might still call `payload.take_box()` though and trigger
468             // formatting.)
469             Hook::Default if panic_output().is_none() => {}
470             Hook::Default => {
471                 info.set_payload(payload.get());
472                 default_hook(&info);
473             }
474             Hook::Custom(ptr) => {
475                 info.set_payload(payload.get());
476                 (*ptr)(&info);
477             }
478         };
479         HOOK_LOCK.read_unlock();
480     }
481
482     if panics > 1 {
483         // If a thread panics while it's already unwinding then we
484         // have limited options. Currently our preference is to
485         // just abort. In the future we may consider resuming
486         // unwinding or otherwise exiting the thread cleanly.
487         util::dumb_print(format_args!(
488             "thread panicked while panicking. \
489                                        aborting.\n"
490         ));
491         unsafe { intrinsics::abort() }
492     }
493
494     rust_panic(payload)
495 }
496
497 /// This is the entry point for `resume_unwind`.
498 /// It just forwards the payload to the panic runtime.
499 pub fn rust_panic_without_hook(payload: Box<dyn Any + Send>) -> ! {
500     update_panic_count(1);
501
502     struct RewrapBox(Box<dyn Any + Send>);
503
504     unsafe impl BoxMeUp for RewrapBox {
505         fn take_box(&mut self) -> *mut (dyn Any + Send) {
506             Box::into_raw(mem::replace(&mut self.0, Box::new(())))
507         }
508
509         fn get(&mut self) -> &(dyn Any + Send) {
510             &*self.0
511         }
512     }
513
514     rust_panic(&mut RewrapBox(payload))
515 }
516
517 /// An unmangled function (through `rustc_std_internal_symbol`) on which to slap
518 /// yer breakpoints.
519 #[inline(never)]
520 #[cfg_attr(not(test), rustc_std_internal_symbol)]
521 fn rust_panic(mut msg: &mut dyn BoxMeUp) -> ! {
522     let code = unsafe {
523         let obj = &mut msg as *mut &mut dyn BoxMeUp;
524         __rust_start_panic(obj as usize)
525     };
526     rtabort!("failed to initiate panic, error {}", code)
527 }