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