]> git.lizzy.rs Git - rust.git/blob - src/libstd/panicking.rs
Update links to WASI docs in time.rs module
[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 /// This function is called by the panic runtime if FFI code catches a Rust
59 /// panic but doesn't rethrow it. We don't support this case since it messes
60 /// with our panic count.
61 #[cfg(not(test))]
62 #[rustc_std_internal_symbol]
63 extern "C" fn __rust_drop_panic() -> ! {
64     rtabort!("Rust panics must be rethrown");
65 }
66
67 #[derive(Copy, Clone)]
68 enum Hook {
69     Default,
70     Custom(*mut (dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send)),
71 }
72
73 static HOOK_LOCK: RWLock = RWLock::new();
74 static mut HOOK: Hook = Hook::Default;
75
76 /// Registers a custom panic hook, replacing any that was previously registered.
77 ///
78 /// The panic hook is invoked when a thread panics, but before the panic runtime
79 /// is invoked. As such, the hook will run with both the aborting and unwinding
80 /// runtimes. The default hook prints a message to standard error and generates
81 /// a backtrace if requested, but this behavior can be customized with the
82 /// `set_hook` and [`take_hook`] functions.
83 ///
84 /// [`take_hook`]: ./fn.take_hook.html
85 ///
86 /// The hook is provided with a `PanicInfo` struct which contains information
87 /// about the origin of the panic, including the payload passed to `panic!` and
88 /// the source code location from which the panic originated.
89 ///
90 /// The panic hook is a global resource.
91 ///
92 /// # Panics
93 ///
94 /// Panics if called from a panicking thread.
95 ///
96 /// # Examples
97 ///
98 /// The following will print "Custom panic hook":
99 ///
100 /// ```should_panic
101 /// use std::panic;
102 ///
103 /// panic::set_hook(Box::new(|_| {
104 ///     println!("Custom panic hook");
105 /// }));
106 ///
107 /// panic!("Normal panic");
108 /// ```
109 #[stable(feature = "panic_hooks", since = "1.10.0")]
110 pub fn set_hook(hook: Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send>) {
111     if thread::panicking() {
112         panic!("cannot modify the panic hook from a panicking thread");
113     }
114
115     unsafe {
116         HOOK_LOCK.write();
117         let old_hook = HOOK;
118         HOOK = Hook::Custom(Box::into_raw(hook));
119         HOOK_LOCK.write_unlock();
120
121         if let Hook::Custom(ptr) = old_hook {
122             #[allow(unused_must_use)]
123             {
124                 Box::from_raw(ptr);
125             }
126         }
127     }
128 }
129
130 /// Unregisters the current panic hook, returning it.
131 ///
132 /// *See also the function [`set_hook`].*
133 ///
134 /// [`set_hook`]: ./fn.set_hook.html
135 ///
136 /// If no custom hook is registered, the default hook will be returned.
137 ///
138 /// # Panics
139 ///
140 /// Panics if called from a panicking thread.
141 ///
142 /// # Examples
143 ///
144 /// The following will print "Normal panic":
145 ///
146 /// ```should_panic
147 /// use std::panic;
148 ///
149 /// panic::set_hook(Box::new(|_| {
150 ///     println!("Custom panic hook");
151 /// }));
152 ///
153 /// let _ = panic::take_hook();
154 ///
155 /// panic!("Normal panic");
156 /// ```
157 #[stable(feature = "panic_hooks", since = "1.10.0")]
158 pub fn take_hook() -> Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send> {
159     if thread::panicking() {
160         panic!("cannot modify the panic hook from a panicking thread");
161     }
162
163     unsafe {
164         HOOK_LOCK.write();
165         let hook = HOOK;
166         HOOK = Hook::Default;
167         HOOK_LOCK.write_unlock();
168
169         match hook {
170             Hook::Default => Box::new(default_hook),
171             Hook::Custom(ptr) => Box::from_raw(ptr),
172         }
173     }
174 }
175
176 fn default_hook(info: &PanicInfo<'_>) {
177     // If this is a double panic, make sure that we print a backtrace
178     // for this panic. Otherwise only print it if logging is enabled.
179     let backtrace_env = if update_panic_count(0) >= 2 {
180         RustBacktrace::Print(backtrace_rs::PrintFmt::Full)
181     } else {
182         backtrace::rust_backtrace_env()
183     };
184
185     // The current implementation always returns `Some`.
186     let location = info.location().unwrap();
187
188     let msg = match info.payload().downcast_ref::<&'static str>() {
189         Some(s) => *s,
190         None => match info.payload().downcast_ref::<String>() {
191             Some(s) => &s[..],
192             None => "Box<Any>",
193         },
194     };
195     let thread = thread_info::current_thread();
196     let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");
197
198     let write = |err: &mut dyn crate::io::Write| {
199         let _ = writeln!(err, "thread '{}' panicked at '{}', {}", name, msg, location);
200
201         static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
202
203         match backtrace_env {
204             RustBacktrace::Print(format) => drop(backtrace::print(err, format)),
205             RustBacktrace::Disabled => {}
206             RustBacktrace::RuntimeDisabled => {
207                 if FIRST_PANIC.swap(false, Ordering::SeqCst) {
208                     let _ = writeln!(
209                         err,
210                         "note: run with `RUST_BACKTRACE=1` \
211                                            environment variable to display a backtrace"
212                     );
213                 }
214             }
215         }
216     };
217
218     if let Some(mut local) = set_panic(None) {
219         // NB. In `cfg(test)` this uses the forwarding impl
220         // for `Box<dyn (::realstd::io::Write) + Send>`.
221         write(&mut local);
222         set_panic(Some(local));
223     } else if let Some(mut out) = panic_output() {
224         write(&mut out);
225     }
226 }
227
228 #[cfg(not(test))]
229 #[doc(hidden)]
230 #[unstable(feature = "update_panic_count", issue = "none")]
231 pub fn update_panic_count(amt: isize) -> usize {
232     use crate::cell::Cell;
233     thread_local! { static PANIC_COUNT: Cell<usize> = Cell::new(0) }
234
235     PANIC_COUNT.with(|c| {
236         let next = (c.get() as isize + amt) as usize;
237         c.set(next);
238         next
239     })
240 }
241
242 #[cfg(test)]
243 pub use realstd::rt::update_panic_count;
244
245 /// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
246 pub unsafe fn r#try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>> {
247     union Data<F, R> {
248         f: ManuallyDrop<F>,
249         r: ManuallyDrop<R>,
250     }
251
252     // We do some sketchy operations with ownership here for the sake of
253     // performance. We can only  pass pointers down to
254     // `__rust_maybe_catch_panic` (can't pass objects by value), so we do all
255     // the ownership tracking here manually using a union.
256     //
257     // We go through a transition where:
258     //
259     // * First, we set the data to be the closure that we're going to call.
260     // * When we make the function call, the `do_call` function below, we take
261     //   ownership of the function pointer. At this point the `Data` union is
262     //   entirely uninitialized.
263     // * If the closure successfully returns, we write the return value into the
264     //   data's return slot. Note that `ptr::write` is used as it's overwriting
265     //   uninitialized data.
266     // * Finally, when we come back out of the `__rust_maybe_catch_panic` we're
267     //   in one of two states:
268     //
269     //      1. The closure didn't panic, in which case the return value was
270     //         filled in. We move it out of `data` and return it.
271     //      2. The closure panicked, in which case the return value wasn't
272     //         filled in. In this case the entire `data` union is invalid, so
273     //         there is no need to drop anything.
274     //
275     // Once we stack all that together we should have the "most efficient'
276     // method of calling a catch panic whilst juggling ownership.
277     let mut any_data = 0;
278     let mut any_vtable = 0;
279     let mut data = Data { f: ManuallyDrop::new(f) };
280
281     let r = __rust_maybe_catch_panic(
282         do_call::<F, R>,
283         &mut data as *mut _ as *mut u8,
284         &mut any_data,
285         &mut any_vtable,
286     );
287
288     return if r == 0 {
289         debug_assert!(update_panic_count(0) == 0);
290         Ok(ManuallyDrop::into_inner(data.r))
291     } else {
292         update_panic_count(-1);
293         debug_assert!(update_panic_count(0) == 0);
294         Err(mem::transmute(raw::TraitObject {
295             data: any_data as *mut _,
296             vtable: any_vtable as *mut _,
297         }))
298     };
299
300     fn do_call<F: FnOnce() -> R, R>(data: *mut u8) {
301         unsafe {
302             let data = data as *mut Data<F, R>;
303             let data = &mut (*data);
304             let f = ManuallyDrop::take(&mut data.f);
305             data.r = ManuallyDrop::new(f());
306         }
307     }
308 }
309
310 /// Determines whether the current thread is unwinding because of panic.
311 pub fn panicking() -> bool {
312     update_panic_count(0) != 0
313 }
314
315 /// The entry point for panicking with a formatted message.
316 ///
317 /// This is designed to reduce the amount of code required at the call
318 /// site as much as possible (so that `panic!()` has as low an impact
319 /// on (e.g.) the inlining of other functions as possible), by moving
320 /// the actual formatting into this shared place.
321 #[unstable(feature = "libstd_sys_internals", reason = "used by the panic! macro", issue = "none")]
322 #[cold]
323 // If panic_immediate_abort, inline the abort call,
324 // otherwise avoid inlining because of it is cold path.
325 #[cfg_attr(not(feature = "panic_immediate_abort"), track_caller)]
326 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
327 #[cfg_attr(feature = "panic_immediate_abort", inline)]
328 pub fn begin_panic_fmt(msg: &fmt::Arguments<'_>) -> ! {
329     if cfg!(feature = "panic_immediate_abort") {
330         unsafe { intrinsics::abort() }
331     }
332
333     let info = PanicInfo::internal_constructor(Some(msg), Location::caller());
334     begin_panic_handler(&info)
335 }
336
337 /// Entry point of panics from the libcore crate (`panic_impl` lang item).
338 #[cfg_attr(not(test), panic_handler)]
339 #[unwind(allowed)]
340 pub fn begin_panic_handler(info: &PanicInfo<'_>) -> ! {
341     struct PanicPayload<'a> {
342         inner: &'a fmt::Arguments<'a>,
343         string: Option<String>,
344     }
345
346     impl<'a> PanicPayload<'a> {
347         fn new(inner: &'a fmt::Arguments<'a>) -> PanicPayload<'a> {
348             PanicPayload { inner, string: None }
349         }
350
351         fn fill(&mut self) -> &mut String {
352             use crate::fmt::Write;
353
354             let inner = self.inner;
355             // Lazily, the first time this gets called, run the actual string formatting.
356             self.string.get_or_insert_with(|| {
357                 let mut s = String::new();
358                 drop(s.write_fmt(*inner));
359                 s
360             })
361         }
362     }
363
364     unsafe impl<'a> BoxMeUp for PanicPayload<'a> {
365         fn take_box(&mut self) -> *mut (dyn Any + Send) {
366             // We do two allocations here, unfortunately. But (a) they're required with the current
367             // scheme, and (b) we don't handle panic + OOM properly anyway (see comment in
368             // begin_panic below).
369             let contents = mem::take(self.fill());
370             Box::into_raw(Box::new(contents))
371         }
372
373         fn get(&mut self) -> &(dyn Any + Send) {
374             self.fill()
375         }
376     }
377
378     let loc = info.location().unwrap(); // The current implementation always returns Some
379     let msg = info.message().unwrap(); // The current implementation always returns Some
380     rust_panic_with_hook(&mut PanicPayload::new(msg), info.message(), loc);
381 }
382
383 /// This is the entry point of panicking for the non-format-string variants of
384 /// panic!() and assert!(). In particular, this is the only entry point that supports
385 /// arbitrary payloads, not just format strings.
386 #[unstable(feature = "libstd_sys_internals", reason = "used by the panic! macro", issue = "none")]
387 #[cfg_attr(not(test), lang = "begin_panic")]
388 // lang item for CTFE panic support
389 // never inline unless panic_immediate_abort to avoid code
390 // bloat at the call sites as much as possible
391 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
392 #[cold]
393 #[track_caller]
394 pub fn begin_panic<M: Any + Send>(msg: M, #[cfg(bootstrap)] _: &(&str, u32, u32)) -> ! {
395     if cfg!(feature = "panic_immediate_abort") {
396         unsafe { intrinsics::abort() }
397     }
398
399     rust_panic_with_hook(&mut PanicPayload::new(msg), None, Location::caller());
400
401     struct PanicPayload<A> {
402         inner: Option<A>,
403     }
404
405     impl<A: Send + 'static> PanicPayload<A> {
406         fn new(inner: A) -> PanicPayload<A> {
407             PanicPayload { inner: Some(inner) }
408         }
409     }
410
411     unsafe impl<A: Send + 'static> BoxMeUp for PanicPayload<A> {
412         fn take_box(&mut self) -> *mut (dyn Any + Send) {
413             // Note that this should be the only allocation performed in this code path. Currently
414             // this means that panic!() on OOM will invoke this code path, but then again we're not
415             // really ready for panic on OOM anyway. If we do start doing this, then we should
416             // propagate this allocation to be performed in the parent of this thread instead of the
417             // thread that's panicking.
418             let data = match self.inner.take() {
419                 Some(a) => Box::new(a) as Box<dyn Any + Send>,
420                 None => process::abort(),
421             };
422             Box::into_raw(data)
423         }
424
425         fn get(&mut self) -> &(dyn Any + Send) {
426             match self.inner {
427                 Some(ref a) => a,
428                 None => process::abort(),
429             }
430         }
431     }
432 }
433
434 /// Central point for dispatching panics.
435 ///
436 /// Executes the primary logic for a panic, including checking for recursive
437 /// panics, panic hooks, and finally dispatching to the panic runtime to either
438 /// abort or unwind.
439 fn rust_panic_with_hook(
440     payload: &mut dyn BoxMeUp,
441     message: Option<&fmt::Arguments<'_>>,
442     location: &Location<'_>,
443 ) -> ! {
444     let panics = update_panic_count(1);
445
446     // If this is the third nested call (e.g., panics == 2, this is 0-indexed),
447     // the panic hook probably triggered the last panic, otherwise the
448     // double-panic check would have aborted the process. In this case abort the
449     // process real quickly as we don't want to try calling it again as it'll
450     // probably just panic again.
451     if panics > 2 {
452         util::dumb_print(format_args!(
453             "thread panicked while processing \
454                                        panic. aborting.\n"
455         ));
456         unsafe { intrinsics::abort() }
457     }
458
459     unsafe {
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 }