]> git.lizzy.rs Git - rust.git/blob - library/std/src/panicking.rs
Merge branch 'master' into feature/incorporate-tracing
[rust.git] / library / std / src / 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 panic_count::get() >= 2 {
174         RustBacktrace::Print(crate::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` environment variable to display a backtrace"
205                     );
206                 }
207             }
208         }
209     };
210
211     if let Some(mut local) = set_panic(None) {
212         // NB. In `cfg(test)` this uses the forwarding impl
213         // for `Box<dyn (::realstd::io::Write) + Send>`.
214         write(&mut local);
215         set_panic(Some(local));
216     } else if let Some(mut out) = panic_output() {
217         write(&mut out);
218     }
219 }
220
221 #[cfg(not(test))]
222 #[doc(hidden)]
223 #[unstable(feature = "update_panic_count", issue = "none")]
224 pub mod panic_count {
225     use crate::cell::Cell;
226     use crate::sync::atomic::{AtomicUsize, Ordering};
227
228     // Panic count for the current thread.
229     thread_local! { static LOCAL_PANIC_COUNT: Cell<usize> = Cell::new(0) }
230
231     // Sum of panic counts from all threads. The purpose of this is to have
232     // a fast path in `is_zero` (which is used by `panicking`). In any particular
233     // thread, if that thread currently views `GLOBAL_PANIC_COUNT` as being zero,
234     // then `LOCAL_PANIC_COUNT` in that thread is zero. This invariant holds before
235     // and after increase and decrease, but not necessarily during their execution.
236     static GLOBAL_PANIC_COUNT: AtomicUsize = AtomicUsize::new(0);
237
238     pub fn increase() -> usize {
239         GLOBAL_PANIC_COUNT.fetch_add(1, Ordering::Relaxed);
240         LOCAL_PANIC_COUNT.with(|c| {
241             let next = c.get() + 1;
242             c.set(next);
243             next
244         })
245     }
246
247     pub fn decrease() -> usize {
248         GLOBAL_PANIC_COUNT.fetch_sub(1, Ordering::Relaxed);
249         LOCAL_PANIC_COUNT.with(|c| {
250             let next = c.get() - 1;
251             c.set(next);
252             next
253         })
254     }
255
256     pub fn get() -> usize {
257         LOCAL_PANIC_COUNT.with(|c| c.get())
258     }
259
260     #[inline]
261     pub fn is_zero() -> bool {
262         if GLOBAL_PANIC_COUNT.load(Ordering::Relaxed) == 0 {
263             // Fast path: if `GLOBAL_PANIC_COUNT` is zero, all threads
264             // (including the current one) will have `LOCAL_PANIC_COUNT`
265             // equal to zero, so TLS access can be avoided.
266             //
267             // In terms of performance, a relaxed atomic load is similar to a normal
268             // aligned memory read (e.g., a mov instruction in x86), but with some
269             // compiler optimization restrictions. On the other hand, a TLS access
270             // might require calling a non-inlinable function (such as `__tls_get_addr`
271             // when using the GD TLS model).
272             true
273         } else {
274             is_zero_slow_path()
275         }
276     }
277
278     // Slow path is in a separate function to reduce the amount of code
279     // inlined from `is_zero`.
280     #[inline(never)]
281     #[cold]
282     fn is_zero_slow_path() -> bool {
283         LOCAL_PANIC_COUNT.with(|c| c.get() == 0)
284     }
285 }
286
287 #[cfg(test)]
288 pub use realstd::rt::panic_count;
289
290 /// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
291 pub unsafe fn r#try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>> {
292     union Data<F, R> {
293         f: ManuallyDrop<F>,
294         r: ManuallyDrop<R>,
295         p: ManuallyDrop<Box<dyn Any + Send>>,
296     }
297
298     // We do some sketchy operations with ownership here for the sake of
299     // performance. We can only pass pointers down to `do_call` (can't pass
300     // objects by value), so we do all the ownership tracking here manually
301     // using a union.
302     //
303     // We go through a transition where:
304     //
305     // * First, we set the data field `f` to be the argumentless closure that we're going to call.
306     // * When we make the function call, the `do_call` function below, we take
307     //   ownership of the function pointer. At this point the `data` union is
308     //   entirely uninitialized.
309     // * If the closure successfully returns, we write the return value into the
310     //   data's return slot (field `r`).
311     // * If the closure panics (`do_catch` below), we write the panic payload into field `p`.
312     // * Finally, when we come back out of the `try` intrinsic we're
313     //   in one of two states:
314     //
315     //      1. The closure didn't panic, in which case the return value was
316     //         filled in. We move it out of `data.r` and return it.
317     //      2. The closure panicked, in which case the panic payload was
318     //         filled in. We move it out of `data.p` and return it.
319     //
320     // Once we stack all that together we should have the "most efficient'
321     // method of calling a catch panic whilst juggling ownership.
322     let mut data = Data { f: ManuallyDrop::new(f) };
323
324     let data_ptr = &mut data as *mut _ as *mut u8;
325     return if intrinsics::r#try(do_call::<F, R>, data_ptr, do_catch::<F, R>) == 0 {
326         Ok(ManuallyDrop::into_inner(data.r))
327     } else {
328         Err(ManuallyDrop::into_inner(data.p))
329     };
330
331     // We consider unwinding to be rare, so mark this function as cold. However,
332     // do not mark it no-inline -- that decision is best to leave to the
333     // optimizer (in most cases this function is not inlined even as a normal,
334     // non-cold function, though, as of the writing of this comment).
335     #[cold]
336     unsafe fn cleanup(payload: *mut u8) -> Box<dyn Any + Send + 'static> {
337         let obj = Box::from_raw(__rust_panic_cleanup(payload));
338         panic_count::decrease();
339         obj
340     }
341
342     #[inline]
343     fn do_call<F: FnOnce() -> R, R>(data: *mut u8) {
344         unsafe {
345             let data = data as *mut Data<F, R>;
346             let data = &mut (*data);
347             let f = ManuallyDrop::take(&mut data.f);
348             data.r = ManuallyDrop::new(f());
349         }
350     }
351
352     // We *do* want this part of the catch to be inlined: this allows the
353     // compiler to properly track accesses to the Data union and optimize it
354     // away most of the time.
355     #[inline]
356     fn do_catch<F: FnOnce() -> R, R>(data: *mut u8, payload: *mut u8) {
357         unsafe {
358             let data = data as *mut Data<F, R>;
359             let data = &mut (*data);
360             let obj = cleanup(payload);
361             data.p = ManuallyDrop::new(obj);
362         }
363     }
364 }
365
366 /// Determines whether the current thread is unwinding because of panic.
367 #[inline]
368 pub fn panicking() -> bool {
369     !panic_count::is_zero()
370 }
371
372 /// The entry point for panicking with a formatted message.
373 ///
374 /// This is designed to reduce the amount of code required at the call
375 /// site as much as possible (so that `panic!()` has as low an impact
376 /// on (e.g.) the inlining of other functions as possible), by moving
377 /// the actual formatting into this shared place.
378 #[unstable(feature = "libstd_sys_internals", reason = "used by the panic! macro", issue = "none")]
379 #[cold]
380 // If panic_immediate_abort, inline the abort call,
381 // otherwise avoid inlining because of it is cold path.
382 #[cfg_attr(not(feature = "panic_immediate_abort"), track_caller)]
383 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
384 #[cfg_attr(feature = "panic_immediate_abort", inline)]
385 pub fn begin_panic_fmt(msg: &fmt::Arguments<'_>) -> ! {
386     if cfg!(feature = "panic_immediate_abort") {
387         intrinsics::abort()
388     }
389
390     let info = PanicInfo::internal_constructor(Some(msg), Location::caller());
391     begin_panic_handler(&info)
392 }
393
394 /// Entry point of panics from the libcore crate (`panic_impl` lang item).
395 #[cfg_attr(not(test), panic_handler)]
396 #[unwind(allowed)]
397 pub fn begin_panic_handler(info: &PanicInfo<'_>) -> ! {
398     struct PanicPayload<'a> {
399         inner: &'a fmt::Arguments<'a>,
400         string: Option<String>,
401     }
402
403     impl<'a> PanicPayload<'a> {
404         fn new(inner: &'a fmt::Arguments<'a>) -> PanicPayload<'a> {
405             PanicPayload { inner, string: None }
406         }
407
408         fn fill(&mut self) -> &mut String {
409             use crate::fmt::Write;
410
411             let inner = self.inner;
412             // Lazily, the first time this gets called, run the actual string formatting.
413             self.string.get_or_insert_with(|| {
414                 let mut s = String::new();
415                 drop(s.write_fmt(*inner));
416                 s
417             })
418         }
419     }
420
421     unsafe impl<'a> BoxMeUp for PanicPayload<'a> {
422         fn take_box(&mut self) -> *mut (dyn Any + Send) {
423             // We do two allocations here, unfortunately. But (a) they're required with the current
424             // scheme, and (b) we don't handle panic + OOM properly anyway (see comment in
425             // begin_panic below).
426             let contents = mem::take(self.fill());
427             Box::into_raw(Box::new(contents))
428         }
429
430         fn get(&mut self) -> &(dyn Any + Send) {
431             self.fill()
432         }
433     }
434
435     let loc = info.location().unwrap(); // The current implementation always returns Some
436     let msg = info.message().unwrap(); // The current implementation always returns Some
437     rust_panic_with_hook(&mut PanicPayload::new(msg), info.message(), loc);
438 }
439
440 /// This is the entry point of panicking for the non-format-string variants of
441 /// panic!() and assert!(). In particular, this is the only entry point that supports
442 /// arbitrary payloads, not just format strings.
443 #[unstable(feature = "libstd_sys_internals", reason = "used by the panic! macro", issue = "none")]
444 #[cfg_attr(not(test), lang = "begin_panic")]
445 // lang item for CTFE panic support
446 // never inline unless panic_immediate_abort to avoid code
447 // bloat at the call sites as much as possible
448 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
449 #[cold]
450 #[track_caller]
451 pub fn begin_panic<M: Any + Send>(msg: M) -> ! {
452     if cfg!(feature = "panic_immediate_abort") {
453         intrinsics::abort()
454     }
455
456     rust_panic_with_hook(&mut PanicPayload::new(msg), None, Location::caller());
457
458     struct PanicPayload<A> {
459         inner: Option<A>,
460     }
461
462     impl<A: Send + 'static> PanicPayload<A> {
463         fn new(inner: A) -> PanicPayload<A> {
464             PanicPayload { inner: Some(inner) }
465         }
466     }
467
468     unsafe impl<A: Send + 'static> BoxMeUp for PanicPayload<A> {
469         fn take_box(&mut self) -> *mut (dyn Any + Send) {
470             // Note that this should be the only allocation performed in this code path. Currently
471             // this means that panic!() on OOM will invoke this code path, but then again we're not
472             // really ready for panic on OOM anyway. If we do start doing this, then we should
473             // propagate this allocation to be performed in the parent of this thread instead of the
474             // thread that's panicking.
475             let data = match self.inner.take() {
476                 Some(a) => Box::new(a) as Box<dyn Any + Send>,
477                 None => process::abort(),
478             };
479             Box::into_raw(data)
480         }
481
482         fn get(&mut self) -> &(dyn Any + Send) {
483             match self.inner {
484                 Some(ref a) => a,
485                 None => process::abort(),
486             }
487         }
488     }
489 }
490
491 /// Central point for dispatching panics.
492 ///
493 /// Executes the primary logic for a panic, including checking for recursive
494 /// panics, panic hooks, and finally dispatching to the panic runtime to either
495 /// abort or unwind.
496 fn rust_panic_with_hook(
497     payload: &mut dyn BoxMeUp,
498     message: Option<&fmt::Arguments<'_>>,
499     location: &Location<'_>,
500 ) -> ! {
501     let panics = panic_count::increase();
502
503     // If this is the third nested call (e.g., panics == 2, this is 0-indexed),
504     // the panic hook probably triggered the last panic, otherwise the
505     // double-panic check would have aborted the process. In this case abort the
506     // process real quickly as we don't want to try calling it again as it'll
507     // probably just panic again.
508     if panics > 2 {
509         util::dumb_print(format_args!("thread panicked while processing panic. aborting.\n"));
510         intrinsics::abort()
511     }
512
513     unsafe {
514         let mut info = PanicInfo::internal_constructor(message, location);
515         HOOK_LOCK.read();
516         match HOOK {
517             // Some platforms (like wasm) know that printing to stderr won't ever actually
518             // print anything, and if that's the case we can skip the default
519             // hook. Since string formatting happens lazily when calling `payload`
520             // methods, this means we avoid formatting the string at all!
521             // (The panic runtime might still call `payload.take_box()` though and trigger
522             // formatting.)
523             Hook::Default if panic_output().is_none() => {}
524             Hook::Default => {
525                 info.set_payload(payload.get());
526                 default_hook(&info);
527             }
528             Hook::Custom(ptr) => {
529                 info.set_payload(payload.get());
530                 (*ptr)(&info);
531             }
532         };
533         HOOK_LOCK.read_unlock();
534     }
535
536     if panics > 1 {
537         // If a thread panics while it's already unwinding then we
538         // have limited options. Currently our preference is to
539         // just abort. In the future we may consider resuming
540         // unwinding or otherwise exiting the thread cleanly.
541         util::dumb_print(format_args!("thread panicked while panicking. aborting.\n"));
542         intrinsics::abort()
543     }
544
545     rust_panic(payload)
546 }
547
548 /// This is the entry point for `resume_unwind`.
549 /// It just forwards the payload to the panic runtime.
550 pub fn rust_panic_without_hook(payload: Box<dyn Any + Send>) -> ! {
551     panic_count::increase();
552
553     struct RewrapBox(Box<dyn Any + Send>);
554
555     unsafe impl BoxMeUp for RewrapBox {
556         fn take_box(&mut self) -> *mut (dyn Any + Send) {
557             Box::into_raw(mem::replace(&mut self.0, Box::new(())))
558         }
559
560         fn get(&mut self) -> &(dyn Any + Send) {
561             &*self.0
562         }
563     }
564
565     rust_panic(&mut RewrapBox(payload))
566 }
567
568 /// An unmangled function (through `rustc_std_internal_symbol`) on which to slap
569 /// yer breakpoints.
570 #[inline(never)]
571 #[cfg_attr(not(test), rustc_std_internal_symbol)]
572 fn rust_panic(mut msg: &mut dyn BoxMeUp) -> ! {
573     let code = unsafe {
574         let obj = &mut msg as *mut &mut dyn BoxMeUp;
575         __rust_start_panic(obj as usize)
576     };
577     rtabort!("failed to initiate panic, error {}", code)
578 }