1 //! Implementation of various bits and pieces of the `panic!` macro and
2 //! associated runtime pieces.
4 //! Specifically, this module contains the implementation of:
7 //! * Executing a panic up to doing the actual implementation
8 //! * Shims around "try"
10 use core::panic::{BoxMeUp, Location, PanicInfo};
14 use crate::intrinsics;
15 use crate::mem::{self, ManuallyDrop};
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};
25 use crate::io::set_panic;
26 // make sure to use the stderr output configured
27 // by libtest in the real copy of std
29 use realstd::io::set_panic;
31 // Binary interface to the panic runtime that the standard library depends on.
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
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)]
43 fn __rust_panic_cleanup(payload: *mut u8) -> *mut (dyn Any + Send + 'static);
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`.
49 fn __rust_start_panic(payload: usize) -> u32;
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.
56 #[rustc_std_internal_symbol]
57 extern "C" fn __rust_drop_panic() -> ! {
58 rtabort!("Rust panics must be rethrown");
61 #[derive(Copy, Clone)]
64 Custom(*mut (dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send)),
67 static HOOK_LOCK: RWLock = RWLock::new();
68 static mut HOOK: Hook = Hook::Default;
70 /// Registers a custom panic hook, replacing any that was previously registered.
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.
78 /// [`take_hook`]: ./fn.take_hook.html
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.
84 /// The panic hook is a global resource.
88 /// Panics if called from a panicking thread.
92 /// The following will print "Custom panic hook":
97 /// panic::set_hook(Box::new(|_| {
98 /// println!("Custom panic hook");
101 /// panic!("Normal panic");
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");
112 HOOK = Hook::Custom(Box::into_raw(hook));
113 HOOK_LOCK.write_unlock();
115 if let Hook::Custom(ptr) = old_hook {
116 #[allow(unused_must_use)]
124 /// Unregisters the current panic hook, returning it.
126 /// *See also the function [`set_hook`].*
128 /// [`set_hook`]: ./fn.set_hook.html
130 /// If no custom hook is registered, the default hook will be returned.
134 /// Panics if called from a panicking thread.
138 /// The following will print "Normal panic":
143 /// panic::set_hook(Box::new(|_| {
144 /// println!("Custom panic hook");
147 /// let _ = panic::take_hook();
149 /// panic!("Normal panic");
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");
160 HOOK = Hook::Default;
161 HOOK_LOCK.write_unlock();
164 Hook::Default => Box::new(default_hook),
165 Hook::Custom(ptr) => Box::from_raw(ptr),
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)
176 backtrace::rust_backtrace_env()
179 // The current implementation always returns `Some`.
180 let location = info.location().unwrap();
182 let msg = match info.payload().downcast_ref::<&'static str>() {
184 None => match info.payload().downcast_ref::<String>() {
189 let thread = thread_info::current_thread();
190 let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");
192 let write = |err: &mut dyn crate::io::Write| {
193 let _ = writeln!(err, "thread '{}' panicked at '{}', {}", name, msg, location);
195 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
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) {
204 "note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace"
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>`.
215 set_panic(Some(local));
216 } else if let Some(mut out) = panic_output() {
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};
228 // Panic count for the current thread.
229 thread_local! { static LOCAL_PANIC_COUNT: Cell<usize> = Cell::new(0) }
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);
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;
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;
256 pub fn get() -> usize {
257 LOCAL_PANIC_COUNT.with(|c| c.get())
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.
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).
278 // Slow path is in a separate function to reduce the amount of code
279 // inlined from `is_zero`.
282 fn is_zero_slow_path() -> bool {
283 LOCAL_PANIC_COUNT.with(|c| c.get() == 0)
288 pub use realstd::rt::panic_count;
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>> {
295 p: ManuallyDrop<Box<dyn Any + Send>>,
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
303 // We go through a transition where:
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:
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.
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) };
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))
328 Err(ManuallyDrop::into_inner(data.p))
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).
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();
343 fn do_call<F: FnOnce() -> R, R>(data: *mut u8) {
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());
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.
356 fn do_catch<F: FnOnce() -> R, R>(data: *mut u8, payload: *mut u8) {
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);
366 /// Determines whether the current thread is unwinding because of panic.
368 pub fn panicking() -> bool {
369 !panic_count::is_zero()
372 /// The entry point for panicking with a formatted message.
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")]
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") {
390 let info = PanicInfo::internal_constructor(Some(msg), Location::caller());
391 begin_panic_handler(&info)
394 /// Entry point of panics from the libcore crate (`panic_impl` lang item).
395 #[cfg_attr(not(test), panic_handler)]
397 pub fn begin_panic_handler(info: &PanicInfo<'_>) -> ! {
398 struct PanicPayload<'a> {
399 inner: &'a fmt::Arguments<'a>,
400 string: Option<String>,
403 impl<'a> PanicPayload<'a> {
404 fn new(inner: &'a fmt::Arguments<'a>) -> PanicPayload<'a> {
405 PanicPayload { inner, string: None }
408 fn fill(&mut self) -> &mut String {
409 use crate::fmt::Write;
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));
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))
430 fn get(&mut self) -> &(dyn Any + Send) {
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);
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))]
451 pub fn begin_panic<M: Any + Send>(msg: M) -> ! {
452 if cfg!(feature = "panic_immediate_abort") {
456 rust_panic_with_hook(&mut PanicPayload::new(msg), None, Location::caller());
458 struct PanicPayload<A> {
462 impl<A: Send + 'static> PanicPayload<A> {
463 fn new(inner: A) -> PanicPayload<A> {
464 PanicPayload { inner: Some(inner) }
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(),
482 fn get(&mut self) -> &(dyn Any + Send) {
485 None => process::abort(),
491 /// Central point for dispatching panics.
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
496 fn rust_panic_with_hook(
497 payload: &mut dyn BoxMeUp,
498 message: Option<&fmt::Arguments<'_>>,
499 location: &Location<'_>,
501 let panics = panic_count::increase();
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.
509 util::dumb_print(format_args!("thread panicked while processing panic. aborting.\n"));
514 let mut info = PanicInfo::internal_constructor(message, location);
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
523 Hook::Default if panic_output().is_none() => {}
525 info.set_payload(payload.get());
528 Hook::Custom(ptr) => {
529 info.set_payload(payload.get());
533 HOOK_LOCK.read_unlock();
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"));
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();
553 struct RewrapBox(Box<dyn Any + Send>);
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(())))
560 fn get(&mut self) -> &(dyn Any + Send) {
565 rust_panic(&mut RewrapBox(payload))
568 /// An unmangled function (through `rustc_std_internal_symbol`) on which to slap
571 #[cfg_attr(not(test), rustc_std_internal_symbol)]
572 fn rust_panic(mut msg: &mut dyn BoxMeUp) -> ! {
574 let obj = &mut msg as *mut &mut dyn BoxMeUp;
575 __rust_start_panic(obj as usize)
577 rtabort!("failed to initiate panic, error {}", code)