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 #![deny(unsafe_op_in_unsafe_fn)]
12 use crate::panic::BacktraceStyle;
13 use core::panic::{BoxMeUp, Location, PanicInfo};
17 use crate::intrinsics;
18 use crate::mem::{self, ManuallyDrop};
20 use crate::sync::atomic::{AtomicBool, Ordering};
21 use crate::sync::{PoisonError, RwLock};
22 use crate::sys::stdio::panic_output;
23 use crate::sys_common::backtrace;
24 use crate::sys_common::thread_info;
28 use crate::io::set_output_capture;
29 // make sure to use the stderr output configured
30 // by libtest in the real copy of std
32 use realstd::io::set_output_capture;
34 // Binary interface to the panic runtime that the standard library depends on.
36 // The standard library is tagged with `#![needs_panic_runtime]` (introduced in
37 // RFC 1513) to indicate that it requires some other crate tagged with
38 // `#![panic_runtime]` to exist somewhere. Each panic runtime is intended to
39 // implement these symbols (with the same signatures) so we can get matched up
42 // One day this may look a little less ad-hoc with the compiler helping out to
43 // hook up these functions, but it is not this day!
44 #[allow(improper_ctypes)]
46 fn __rust_panic_cleanup(payload: *mut u8) -> *mut (dyn Any + Send + 'static);
49 #[allow(improper_ctypes)]
51 /// `payload` is passed through another layer of raw pointers as `&mut dyn Trait` is not
52 /// FFI-safe. `BoxMeUp` lazily performs allocation only when needed (this avoids allocations
53 /// when using the "abort" panic runtime).
54 fn __rust_start_panic(payload: *mut &mut dyn BoxMeUp) -> u32;
57 /// This function is called by the panic runtime if FFI code catches a Rust
58 /// panic but doesn't rethrow it. We don't support this case since it messes
59 /// with our panic count.
61 #[rustc_std_internal_symbol]
62 extern "C" fn __rust_drop_panic() -> ! {
63 rtabort!("Rust panics must be rethrown");
66 /// This function is called by the panic runtime if it catches an exception
67 /// object which does not correspond to a Rust panic.
69 #[rustc_std_internal_symbol]
70 extern "C" fn __rust_foreign_exception() -> ! {
71 rtabort!("Rust cannot catch foreign exceptions");
76 Custom(Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send>),
81 fn into_box(self) -> Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send> {
83 Hook::Default => Box::new(default_hook),
84 Hook::Custom(hook) => hook,
89 impl Default for Hook {
91 fn default() -> Hook {
96 static HOOK: RwLock<Hook> = RwLock::new(Hook::Default);
98 /// Registers a custom panic hook, replacing any that was previously registered.
100 /// The panic hook is invoked when a thread panics, but before the panic runtime
101 /// is invoked. As such, the hook will run with both the aborting and unwinding
102 /// runtimes. The default hook prints a message to standard error and generates
103 /// a backtrace if requested, but this behavior can be customized with the
104 /// `set_hook` and [`take_hook`] functions.
106 /// [`take_hook`]: ./fn.take_hook.html
108 /// The hook is provided with a `PanicInfo` struct which contains information
109 /// about the origin of the panic, including the payload passed to `panic!` and
110 /// the source code location from which the panic originated.
112 /// The panic hook is a global resource.
116 /// Panics if called from a panicking thread.
120 /// The following will print "Custom panic hook":
125 /// panic::set_hook(Box::new(|_| {
126 /// println!("Custom panic hook");
129 /// panic!("Normal panic");
131 #[stable(feature = "panic_hooks", since = "1.10.0")]
132 pub fn set_hook(hook: Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send>) {
133 if thread::panicking() {
134 panic!("cannot modify the panic hook from a panicking thread");
137 let new = Hook::Custom(hook);
138 let mut hook = HOOK.write().unwrap_or_else(PoisonError::into_inner);
139 let old = mem::replace(&mut *hook, new);
141 // Only drop the old hook after releasing the lock to avoid deadlocking
142 // if its destructor panics.
146 /// Unregisters the current panic hook, returning it.
148 /// *See also the function [`set_hook`].*
150 /// [`set_hook`]: ./fn.set_hook.html
152 /// If no custom hook is registered, the default hook will be returned.
156 /// Panics if called from a panicking thread.
160 /// The following will print "Normal panic":
165 /// panic::set_hook(Box::new(|_| {
166 /// println!("Custom panic hook");
169 /// let _ = panic::take_hook();
171 /// panic!("Normal panic");
174 #[stable(feature = "panic_hooks", since = "1.10.0")]
175 pub fn take_hook() -> Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send> {
176 if thread::panicking() {
177 panic!("cannot modify the panic hook from a panicking thread");
180 let mut hook = HOOK.write().unwrap_or_else(PoisonError::into_inner);
181 let old_hook = mem::take(&mut *hook);
187 /// Atomic combination of [`take_hook`] and [`set_hook`]. Use this to replace the panic handler with
188 /// a new panic handler that does something and then executes the old handler.
190 /// [`take_hook`]: ./fn.take_hook.html
191 /// [`set_hook`]: ./fn.set_hook.html
195 /// Panics if called from a panicking thread.
199 /// The following will print the custom message, and then the normal output of panic.
202 /// #![feature(panic_update_hook)]
206 /// // let prev = panic::take_hook();
207 /// // panic::set_hook(move |info| {
208 /// // println!("...");
211 /// panic::update_hook(move |prev, info| {
212 /// println!("Print custom message and execute panic handler as usual");
216 /// panic!("Custom and then normal");
218 #[unstable(feature = "panic_update_hook", issue = "92649")]
219 pub fn update_hook<F>(hook_fn: F)
221 F: Fn(&(dyn Fn(&PanicInfo<'_>) + Send + Sync + 'static), &PanicInfo<'_>)
226 if thread::panicking() {
227 panic!("cannot modify the panic hook from a panicking thread");
230 let mut hook = HOOK.write().unwrap_or_else(PoisonError::into_inner);
231 let prev = mem::take(&mut *hook).into_box();
232 *hook = Hook::Custom(Box::new(move |info| hook_fn(&prev, info)));
235 fn default_hook(info: &PanicInfo<'_>) {
236 // If this is a double panic, make sure that we print a backtrace
237 // for this panic. Otherwise only print it if logging is enabled.
238 let backtrace = if panic_count::get_count() >= 2 {
239 BacktraceStyle::full()
241 crate::panic::get_backtrace_style()
244 // The current implementation always returns `Some`.
245 let location = info.location().unwrap();
247 let msg = match info.payload().downcast_ref::<&'static str>() {
249 None => match info.payload().downcast_ref::<String>() {
251 None => "Box<dyn Any>",
254 let thread = thread_info::current_thread();
255 let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");
257 let write = |err: &mut dyn crate::io::Write| {
258 let _ = writeln!(err, "thread '{name}' panicked at '{msg}', {location}");
260 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
263 Some(BacktraceStyle::Short) => {
264 drop(backtrace::print(err, crate::backtrace_rs::PrintFmt::Short))
266 Some(BacktraceStyle::Full) => {
267 drop(backtrace::print(err, crate::backtrace_rs::PrintFmt::Full))
269 Some(BacktraceStyle::Off) => {
270 if FIRST_PANIC.swap(false, Ordering::SeqCst) {
273 "note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace"
277 // If backtraces aren't supported, do nothing.
282 if let Some(local) = set_output_capture(None) {
283 write(&mut *local.lock().unwrap_or_else(|e| e.into_inner()));
284 set_output_capture(Some(local));
285 } else if let Some(mut out) = panic_output() {
292 #[unstable(feature = "update_panic_count", issue = "none")]
293 pub mod panic_count {
294 use crate::cell::Cell;
295 use crate::sync::atomic::{AtomicUsize, Ordering};
297 pub const ALWAYS_ABORT_FLAG: usize = 1 << (usize::BITS - 1);
299 // Panic count for the current thread.
300 thread_local! { static LOCAL_PANIC_COUNT: Cell<usize> = const { Cell::new(0) } }
302 // Sum of panic counts from all threads. The purpose of this is to have
303 // a fast path in `count_is_zero` (which is used by `panicking`). In any particular
304 // thread, if that thread currently views `GLOBAL_PANIC_COUNT` as being zero,
305 // then `LOCAL_PANIC_COUNT` in that thread is zero. This invariant holds before
306 // and after increase and decrease, but not necessarily during their execution.
308 // Additionally, the top bit of GLOBAL_PANIC_COUNT (GLOBAL_ALWAYS_ABORT_FLAG)
309 // records whether panic::always_abort() has been called. This can only be
310 // set, never cleared.
311 // panic::always_abort() is usually called to prevent memory allocations done by
312 // the panic handling in the child created by `libc::fork`.
313 // Memory allocations performed in a child created with `libc::fork` are undefined
314 // behavior in most operating systems.
315 // Accessing LOCAL_PANIC_COUNT in a child created by `libc::fork` would lead to a memory
316 // allocation. Only GLOBAL_PANIC_COUNT can be accessed in this situation. This is
317 // sufficient because a child process will always have exactly one thread only.
318 // See also #85261 for details.
320 // This could be viewed as a struct containing a single bit and an n-1-bit
321 // value, but if we wrote it like that it would be more than a single word,
322 // and even a newtype around usize would be clumsy because we need atomics.
323 // But we use such a tuple for the return type of increase().
325 // Stealing a bit is fine because it just amounts to assuming that each
326 // panicking thread consumes at least 2 bytes of address space.
327 static GLOBAL_PANIC_COUNT: AtomicUsize = AtomicUsize::new(0);
329 // Return the state of the ALWAYS_ABORT_FLAG and number of panics.
331 // If ALWAYS_ABORT_FLAG is not set, the number is determined on a per-thread
332 // base (stored in LOCAL_PANIC_COUNT), i.e. it is the amount of recursive calls
333 // of the calling thread.
334 // If ALWAYS_ABORT_FLAG is set, the number equals the *global* number of panic
335 // calls. See above why LOCAL_PANIC_COUNT is not used.
336 pub fn increase() -> (bool, usize) {
337 let global_count = GLOBAL_PANIC_COUNT.fetch_add(1, Ordering::Relaxed);
338 let must_abort = global_count & ALWAYS_ABORT_FLAG != 0;
339 let panics = if must_abort {
340 global_count & !ALWAYS_ABORT_FLAG
342 LOCAL_PANIC_COUNT.with(|c| {
343 let next = c.get() + 1;
352 GLOBAL_PANIC_COUNT.fetch_sub(1, Ordering::Relaxed);
353 LOCAL_PANIC_COUNT.with(|c| {
354 let next = c.get() - 1;
360 pub fn set_always_abort() {
361 GLOBAL_PANIC_COUNT.fetch_or(ALWAYS_ABORT_FLAG, Ordering::Relaxed);
364 // Disregards ALWAYS_ABORT_FLAG
366 pub fn get_count() -> usize {
367 LOCAL_PANIC_COUNT.with(|c| c.get())
370 // Disregards ALWAYS_ABORT_FLAG
373 pub fn count_is_zero() -> bool {
374 if GLOBAL_PANIC_COUNT.load(Ordering::Relaxed) & !ALWAYS_ABORT_FLAG == 0 {
375 // Fast path: if `GLOBAL_PANIC_COUNT` is zero, all threads
376 // (including the current one) will have `LOCAL_PANIC_COUNT`
377 // equal to zero, so TLS access can be avoided.
379 // In terms of performance, a relaxed atomic load is similar to a normal
380 // aligned memory read (e.g., a mov instruction in x86), but with some
381 // compiler optimization restrictions. On the other hand, a TLS access
382 // might require calling a non-inlinable function (such as `__tls_get_addr`
383 // when using the GD TLS model).
390 // Slow path is in a separate function to reduce the amount of code
391 // inlined from `count_is_zero`.
394 fn is_zero_slow_path() -> bool {
395 LOCAL_PANIC_COUNT.with(|c| c.get() == 0)
400 pub use realstd::rt::panic_count;
402 /// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
403 pub unsafe fn r#try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>> {
407 p: ManuallyDrop<Box<dyn Any + Send>>,
410 // We do some sketchy operations with ownership here for the sake of
411 // performance. We can only pass pointers down to `do_call` (can't pass
412 // objects by value), so we do all the ownership tracking here manually
415 // We go through a transition where:
417 // * First, we set the data field `f` to be the argumentless closure that we're going to call.
418 // * When we make the function call, the `do_call` function below, we take
419 // ownership of the function pointer. At this point the `data` union is
420 // entirely uninitialized.
421 // * If the closure successfully returns, we write the return value into the
422 // data's return slot (field `r`).
423 // * If the closure panics (`do_catch` below), we write the panic payload into field `p`.
424 // * Finally, when we come back out of the `try` intrinsic we're
425 // in one of two states:
427 // 1. The closure didn't panic, in which case the return value was
428 // filled in. We move it out of `data.r` and return it.
429 // 2. The closure panicked, in which case the panic payload was
430 // filled in. We move it out of `data.p` and return it.
432 // Once we stack all that together we should have the "most efficient'
433 // method of calling a catch panic whilst juggling ownership.
434 let mut data = Data { f: ManuallyDrop::new(f) };
436 let data_ptr = &mut data as *mut _ as *mut u8;
439 // Access to the union's fields: this is `std` and we know that the `r#try`
440 // intrinsic fills in the `r` or `p` union field based on its return value.
442 // The call to `intrinsics::r#try` is made safe by:
443 // - `do_call`, the first argument, can be called with the initial `data_ptr`.
444 // - `do_catch`, the second argument, can be called with the `data_ptr` as well.
445 // See their safety preconditions for more information
447 return if intrinsics::r#try(do_call::<F, R>, data_ptr, do_catch::<F, R>) == 0 {
448 Ok(ManuallyDrop::into_inner(data.r))
450 Err(ManuallyDrop::into_inner(data.p))
454 // We consider unwinding to be rare, so mark this function as cold. However,
455 // do not mark it no-inline -- that decision is best to leave to the
456 // optimizer (in most cases this function is not inlined even as a normal,
457 // non-cold function, though, as of the writing of this comment).
459 unsafe fn cleanup(payload: *mut u8) -> Box<dyn Any + Send + 'static> {
460 // SAFETY: The whole unsafe block hinges on a correct implementation of
461 // the panic handler `__rust_panic_cleanup`. As such we can only
462 // assume it returns the correct thing for `Box::from_raw` to work
463 // without undefined behavior.
464 let obj = unsafe { Box::from_raw(__rust_panic_cleanup(payload)) };
465 panic_count::decrease();
470 // data must be non-NUL, correctly aligned, and a pointer to a `Data<F, R>`
471 // Its must contains a valid `f` (type: F) value that can be use to fill
474 // This function cannot be marked as `unsafe` because `intrinsics::r#try`
475 // expects normal function pointers.
477 fn do_call<F: FnOnce() -> R, R>(data: *mut u8) {
478 // SAFETY: this is the responsibility of the caller, see above.
480 let data = data as *mut Data<F, R>;
481 let data = &mut (*data);
482 let f = ManuallyDrop::take(&mut data.f);
483 data.r = ManuallyDrop::new(f());
487 // We *do* want this part of the catch to be inlined: this allows the
488 // compiler to properly track accesses to the Data union and optimize it
489 // away most of the time.
492 // data must be non-NUL, correctly aligned, and a pointer to a `Data<F, R>`
493 // Since this uses `cleanup` it also hinges on a correct implementation of
494 // `__rustc_panic_cleanup`.
496 // This function cannot be marked as `unsafe` because `intrinsics::r#try`
497 // expects normal function pointers.
499 fn do_catch<F: FnOnce() -> R, R>(data: *mut u8, payload: *mut u8) {
500 // SAFETY: this is the responsibility of the caller, see above.
502 // When `__rustc_panic_cleaner` is correctly implemented we can rely
503 // on `obj` being the correct thing to pass to `data.p` (after wrapping
504 // in `ManuallyDrop`).
506 let data = data as *mut Data<F, R>;
507 let data = &mut (*data);
508 let obj = cleanup(payload);
509 data.p = ManuallyDrop::new(obj);
514 /// Determines whether the current thread is unwinding because of panic.
516 pub fn panicking() -> bool {
517 !panic_count::count_is_zero()
520 /// Entry point of panics from the libcore crate (`panic_impl` lang item).
523 pub fn begin_panic_handler(info: &PanicInfo<'_>) -> ! {
524 struct PanicPayload<'a> {
525 inner: &'a fmt::Arguments<'a>,
526 string: Option<String>,
529 impl<'a> PanicPayload<'a> {
530 fn new(inner: &'a fmt::Arguments<'a>) -> PanicPayload<'a> {
531 PanicPayload { inner, string: None }
534 fn fill(&mut self) -> &mut String {
535 use crate::fmt::Write;
537 let inner = self.inner;
538 // Lazily, the first time this gets called, run the actual string formatting.
539 self.string.get_or_insert_with(|| {
540 let mut s = String::new();
541 drop(s.write_fmt(*inner));
547 unsafe impl<'a> BoxMeUp for PanicPayload<'a> {
548 fn take_box(&mut self) -> *mut (dyn Any + Send) {
549 // We do two allocations here, unfortunately. But (a) they're required with the current
550 // scheme, and (b) we don't handle panic + OOM properly anyway (see comment in
551 // begin_panic below).
552 let contents = mem::take(self.fill());
553 Box::into_raw(Box::new(contents))
556 fn get(&mut self) -> &(dyn Any + Send) {
561 struct StrPanicPayload(&'static str);
563 unsafe impl BoxMeUp for StrPanicPayload {
564 fn take_box(&mut self) -> *mut (dyn Any + Send) {
565 Box::into_raw(Box::new(self.0))
568 fn get(&mut self) -> &(dyn Any + Send) {
573 let loc = info.location().unwrap(); // The current implementation always returns Some
574 let msg = info.message().unwrap(); // The current implementation always returns Some
575 crate::sys_common::backtrace::__rust_end_short_backtrace(move || {
576 if let Some(msg) = msg.as_str() {
577 rust_panic_with_hook(&mut StrPanicPayload(msg), info.message(), loc, info.can_unwind());
579 rust_panic_with_hook(
580 &mut PanicPayload::new(msg),
589 /// This is the entry point of panicking for the non-format-string variants of
590 /// panic!() and assert!(). In particular, this is the only entry point that supports
591 /// arbitrary payloads, not just format strings.
592 #[unstable(feature = "libstd_sys_internals", reason = "used by the panic! macro", issue = "none")]
593 #[cfg_attr(not(test), lang = "begin_panic")]
594 // lang item for CTFE panic support
595 // never inline unless panic_immediate_abort to avoid code
596 // bloat at the call sites as much as possible
597 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)]
598 #[cfg_attr(feature = "panic_immediate_abort", inline)]
600 #[rustc_do_not_const_check] // hooked by const-eval
601 pub const fn begin_panic<M: Any + Send>(msg: M) -> ! {
602 if cfg!(feature = "panic_immediate_abort") {
606 let loc = Location::caller();
607 return crate::sys_common::backtrace::__rust_end_short_backtrace(move || {
608 rust_panic_with_hook(&mut PanicPayload::new(msg), None, loc, true)
611 struct PanicPayload<A> {
615 impl<A: Send + 'static> PanicPayload<A> {
616 fn new(inner: A) -> PanicPayload<A> {
617 PanicPayload { inner: Some(inner) }
621 unsafe impl<A: Send + 'static> BoxMeUp for PanicPayload<A> {
622 fn take_box(&mut self) -> *mut (dyn Any + Send) {
623 // Note that this should be the only allocation performed in this code path. Currently
624 // this means that panic!() on OOM will invoke this code path, but then again we're not
625 // really ready for panic on OOM anyway. If we do start doing this, then we should
626 // propagate this allocation to be performed in the parent of this thread instead of the
627 // thread that's panicking.
628 let data = match self.inner.take() {
629 Some(a) => Box::new(a) as Box<dyn Any + Send>,
630 None => process::abort(),
635 fn get(&mut self) -> &(dyn Any + Send) {
638 None => process::abort(),
644 /// Central point for dispatching panics.
646 /// Executes the primary logic for a panic, including checking for recursive
647 /// panics, panic hooks, and finally dispatching to the panic runtime to either
649 fn rust_panic_with_hook(
650 payload: &mut dyn BoxMeUp,
651 message: Option<&fmt::Arguments<'_>>,
652 location: &Location<'_>,
655 let (must_abort, panics) = panic_count::increase();
657 // If this is the third nested call (e.g., panics == 2, this is 0-indexed),
658 // the panic hook probably triggered the last panic, otherwise the
659 // double-panic check would have aborted the process. In this case abort the
660 // process real quickly as we don't want to try calling it again as it'll
661 // probably just panic again.
662 if must_abort || panics > 2 {
664 // Don't try to print the message in this case
665 // - perhaps that is causing the recursive panics.
666 rtprintpanic!("thread panicked while processing panic. aborting.\n");
668 // Unfortunately, this does not print a backtrace, because creating
669 // a `Backtrace` will allocate, which we must to avoid here.
670 let panicinfo = PanicInfo::internal_constructor(message, location, can_unwind);
671 rtprintpanic!("{panicinfo}\npanicked after panic::always_abort(), aborting.\n");
673 crate::sys::abort_internal();
676 let mut info = PanicInfo::internal_constructor(message, location, can_unwind);
677 let hook = HOOK.read().unwrap_or_else(PoisonError::into_inner);
679 // Some platforms (like wasm) know that printing to stderr won't ever actually
680 // print anything, and if that's the case we can skip the default
681 // hook. Since string formatting happens lazily when calling `payload`
682 // methods, this means we avoid formatting the string at all!
683 // (The panic runtime might still call `payload.take_box()` though and trigger
685 Hook::Default if panic_output().is_none() => {}
687 info.set_payload(payload.get());
690 Hook::Custom(ref hook) => {
691 info.set_payload(payload.get());
697 if panics > 1 || !can_unwind {
698 // If a thread panics while it's already unwinding then we
699 // have limited options. Currently our preference is to
700 // just abort. In the future we may consider resuming
701 // unwinding or otherwise exiting the thread cleanly.
702 rtprintpanic!("thread panicked while panicking. aborting.\n");
703 crate::sys::abort_internal();
709 /// This is the entry point for `resume_unwind`.
710 /// It just forwards the payload to the panic runtime.
711 pub fn rust_panic_without_hook(payload: Box<dyn Any + Send>) -> ! {
712 panic_count::increase();
714 struct RewrapBox(Box<dyn Any + Send>);
716 unsafe impl BoxMeUp for RewrapBox {
717 fn take_box(&mut self) -> *mut (dyn Any + Send) {
718 Box::into_raw(mem::replace(&mut self.0, Box::new(())))
721 fn get(&mut self) -> &(dyn Any + Send) {
726 rust_panic(&mut RewrapBox(payload))
729 /// An unmangled function (through `rustc_std_internal_symbol`) on which to slap
732 #[cfg_attr(not(test), rustc_std_internal_symbol)]
733 fn rust_panic(mut msg: &mut dyn BoxMeUp) -> ! {
735 let obj = &mut msg as *mut &mut dyn BoxMeUp;
736 __rust_start_panic(obj)
738 rtabort!("failed to initiate panic, error {code}")