Skip to main content

std/
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#![deny(unsafe_op_in_unsafe_fn)]
11
12use alloc::panicking::PanicPayload;
13use core::panic::Location;
14
15// make sure to use the stderr output configured
16// by libtest in the real copy of std
17#[cfg(test)]
18use realstd::io::try_set_output_capture;
19
20use crate::any::Any;
21#[cfg(not(test))]
22use crate::io::try_set_output_capture;
23use crate::mem::{self, ManuallyDrop};
24use crate::panic::{BacktraceStyle, PanicHookInfo};
25use crate::sync::atomic::{Atomic, AtomicBool, Ordering};
26use crate::sync::nonpoison::RwLock;
27use crate::sys::backtrace;
28use crate::sys::stdio::panic_output;
29use crate::{fmt, intrinsics, process, thread};
30
31// This forces codegen of the function called by panic!() inside the std crate, rather than in
32// downstream crates. Primarily this is useful for rustc's codegen tests, which rely on noticing
33// complete removal of panic from generated IR. Since begin_panic is inline(never), it's only
34// codegen'd once per crate-graph so this pushes that to std rather than our codegen test crates.
35//
36// (See https://github.com/rust-lang/rust/pull/123244 for more info on why).
37//
38// If this is causing problems we can also modify those codegen tests to use a crate type like
39// cdylib which doesn't export "Rust" symbols to downstream linkage units.
40#[unstable(feature = "libstd_sys_internals", reason = "used by the panic! macro", issue = "none")]
41#[doc(hidden)]
42#[allow(dead_code)]
43#[used(compiler)]
44pub static EMPTY_PANIC: fn(&'static str) -> ! =
45    begin_panic::<&'static str> as fn(&'static str) -> !;
46
47// Binary interface to the panic runtime that the standard library depends on.
48//
49// The standard library is tagged with `#![needs_panic_runtime]` (introduced in
50// RFC 1513) to indicate that it requires some other crate tagged with
51// `#![panic_runtime]` to exist somewhere. Each panic runtime is intended to
52// implement these symbols (with the same signatures) so we can get matched up
53// to them.
54//
55// One day this may look a little less ad-hoc with the compiler helping out to
56// hook up these functions, but it is not this day!
57unsafe extern "Rust" {
58    #[rustc_std_internal_symbol]
59    fn __rust_panic_cleanup(payload: *mut u8) -> Box<dyn Any + Send + 'static>;
60
61    /// `PanicPayload` lazily performs allocation only when needed (this avoids
62    /// allocations when using the "abort" panic runtime).
63    #[rustc_std_internal_symbol]
64    safe fn __rust_start_panic(payload: &mut dyn PanicPayload) -> u32;
65}
66
67/// This function is called by the panic runtime if FFI code catches a Rust
68/// panic but doesn't rethrow it. We don't support this case since it messes
69/// with our panic count.
70#[cfg(not(test))]
71#[rustc_std_internal_symbol]
72fn __rust_drop_panic() -> ! {
73    {
    if let Some(mut out) = crate::sys::stdio::panic_output() {
        let _ =
            crate::io::Write::write_fmt(&mut out,
                format_args!("fatal runtime error: {0}, aborting\n",
                    format_args!("Rust panics must be rethrown")));
    };
    crate::process::abort();
};rtabort!("Rust panics must be rethrown");
74}
75
76/// This function is called by the panic runtime if it catches an exception
77/// object which does not correspond to a Rust panic.
78#[cfg(not(test))]
79#[rustc_std_internal_symbol]
80fn __rust_foreign_exception() -> ! {
81    {
    if let Some(mut out) = crate::sys::stdio::panic_output() {
        let _ =
            crate::io::Write::write_fmt(&mut out,
                format_args!("fatal runtime error: {0}, aborting\n",
                    format_args!("Rust cannot catch foreign exceptions")));
    };
    crate::process::abort();
};rtabort!("Rust cannot catch foreign exceptions");
82}
83
84#[derive(#[automatically_derived]
impl ::core::default::Default for Hook {
    #[inline]
    fn default() -> Hook { Self::Default }
}Default)]
85enum Hook {
86    #[default]
87    Default,
88    Custom(Box<dyn Fn(&PanicHookInfo<'_>) + 'static + Sync + Send>),
89}
90
91impl Hook {
92    #[inline]
93    fn into_box(self) -> Box<dyn Fn(&PanicHookInfo<'_>) + 'static + Sync + Send> {
94        match self {
95            Hook::Default => Box::new(default_hook),
96            Hook::Custom(hook) => hook,
97        }
98    }
99}
100
101static HOOK: RwLock<Hook> = RwLock::new(Hook::Default);
102
103/// Registers a custom panic hook, replacing the previously registered hook.
104///
105/// The panic hook is invoked when a thread panics, but before the panic runtime
106/// is invoked. As such, the hook will run with both the aborting and unwinding
107/// runtimes.
108///
109/// The default hook, which is registered at startup, prints a message to standard error and
110/// generates a backtrace if requested. This behavior can be customized using the `set_hook` function.
111/// The current hook can be retrieved while reinstating the default hook with the [`take_hook`]
112/// function.
113///
114/// [`take_hook`]: ./fn.take_hook.html
115///
116/// The hook is provided with a `PanicHookInfo` struct which contains information
117/// about the origin of the panic, including the payload passed to `panic!` and
118/// the source code location from which the panic originated.
119///
120/// The panic hook is a global resource.
121///
122/// # Panics
123///
124/// Panics if called from a panicking thread.
125///
126/// # Examples
127///
128/// The following will print "Custom panic hook":
129///
130/// ```should_panic
131/// use std::panic;
132///
133/// panic::set_hook(Box::new(|_| {
134///     println!("Custom panic hook");
135/// }));
136///
137/// panic!("Normal panic");
138/// ```
139#[stable(feature = "panic_hooks", since = "1.10.0")]
140pub fn set_hook(hook: Box<dyn Fn(&PanicHookInfo<'_>) + 'static + Sync + Send>) {
141    if thread::panicking() {
142        {
    ::core::panicking::panic_fmt(format_args!("cannot modify the panic hook from a panicking thread"));
};panic!("cannot modify the panic hook from a panicking thread");
143    }
144
145    // Drop the old hook after changing the hook to avoid deadlocking if its
146    // destructor panics.
147    drop(HOOK.replace(Hook::Custom(hook)));
148}
149
150/// Unregisters the current panic hook and returns it, registering the default hook
151/// in its place.
152///
153/// *See also the function [`set_hook`].*
154///
155/// [`set_hook`]: ./fn.set_hook.html
156///
157/// If the default hook is registered it will be returned, but remain registered.
158///
159/// # Panics
160///
161/// Panics if called from a panicking thread.
162///
163/// # Examples
164///
165/// The following will print "Normal panic":
166///
167/// ```should_panic
168/// use std::panic;
169///
170/// panic::set_hook(Box::new(|_| {
171///     println!("Custom panic hook");
172/// }));
173///
174/// let _ = panic::take_hook();
175///
176/// panic!("Normal panic");
177/// ```
178#[stable(feature = "panic_hooks", since = "1.10.0")]
179pub fn take_hook() -> Box<dyn Fn(&PanicHookInfo<'_>) + 'static + Sync + Send> {
180    if thread::panicking() {
181        {
    ::core::panicking::panic_fmt(format_args!("cannot modify the panic hook from a panicking thread"));
};panic!("cannot modify the panic hook from a panicking thread");
182    }
183
184    HOOK.replace(Hook::Default).into_box()
185}
186
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.
189///
190/// [`take_hook`]: ./fn.take_hook.html
191/// [`set_hook`]: ./fn.set_hook.html
192///
193/// # Panics
194///
195/// Panics if called from a panicking thread.
196///
197/// # Examples
198///
199/// The following will print the custom message, and then the normal output of panic.
200///
201/// ```should_panic
202/// #![feature(panic_update_hook)]
203/// use std::panic;
204///
205/// // Equivalent to
206/// // let prev = panic::take_hook();
207/// // panic::set_hook(Box::new(move |info| {
208/// //     println!("...");
209/// //     prev(info);
210/// // }));
211/// panic::update_hook(move |prev, info| {
212///     println!("Print custom message and execute panic handler as usual");
213///     prev(info);
214/// });
215///
216/// panic!("Custom and then normal");
217/// ```
218#[unstable(feature = "panic_update_hook", issue = "92649")]
219pub fn update_hook<F>(hook_fn: F)
220where
221    F: Fn(&(dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static), &PanicHookInfo<'_>)
222        + Sync
223        + Send
224        + 'static,
225{
226    if thread::panicking() {
227        {
    ::core::panicking::panic_fmt(format_args!("cannot modify the panic hook from a panicking thread"));
};panic!("cannot modify the panic hook from a panicking thread");
228    }
229
230    let mut hook = HOOK.write();
231    let prev = mem::take(&mut *hook).into_box();
232    *hook = Hook::Custom(Box::new(move |info| hook_fn(&prev, info)));
233}
234
235/// The default panic handler.
236#[optimize(size)]
237fn default_hook(info: &PanicHookInfo<'_>) {
238    // If this is a double panic, make sure that we print a backtrace
239    // for this panic. Otherwise only print it if logging is enabled.
240    let backtrace = if info.force_no_backtrace() {
241        None
242    } else if panic_count::get_count() >= 2 {
243        BacktraceStyle::full()
244    } else {
245        crate::panic::get_backtrace_style()
246    };
247
248    // The current implementation always returns `Some`.
249    let location = info.location().unwrap();
250
251    let msg = payload_as_str(info.payload());
252
253    let write = #[optimize(size)]
254    |err: &mut dyn crate::io::Write| {
255        // Use a lock to prevent mixed output in multithreading context.
256        // Some platforms also require it when printing a backtrace, like `SymFromAddr` on Windows.
257        let mut lock = backtrace::lock();
258
259        thread::with_current_name(|name| {
260            let name = name.unwrap_or("<unnamed>");
261            let tid = thread::current_os_id();
262
263            // Try to write the panic message to a buffer first to prevent other concurrent outputs
264            // interleaving with it.
265            let mut buffer = [0u8; 512];
266            let mut cursor = crate::io::Cursor::new(&mut buffer[..]);
267
268            let write_msg = |dst: &mut dyn crate::io::Write| {
269                // We add a newline to ensure the panic message appears at the start of a line.
270                dst.write_fmt(format_args!("\nthread \'{0}\' ({1}) panicked at {2}:\n{3}\n",
        name, tid, location, msg))writeln!(dst, "\nthread '{name}' ({tid}) panicked at {location}:\n{msg}")
271            };
272
273            if write_msg(&mut cursor).is_ok() {
274                let pos = cursor.position() as usize;
275                let _ = err.write_all(&buffer[0..pos]);
276            } else {
277                // The message did not fit into the buffer, write it directly instead.
278                let _ = write_msg(err);
279            };
280        });
281
282        static FIRST_PANIC: Atomic<bool> = AtomicBool::new(true);
283
284        match backtrace {
285            Some(BacktraceStyle::Short) => {
286                drop(lock.print(err, crate::backtrace_rs::PrintFmt::Short))
287            }
288            Some(BacktraceStyle::Full) => {
289                drop(lock.print(err, crate::backtrace_rs::PrintFmt::Full))
290            }
291            Some(BacktraceStyle::Off) => {
292                if FIRST_PANIC.swap(false, Ordering::Relaxed) {
293                    let _ = err.write_fmt(format_args!("note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n"))writeln!(
294                        err,
295                        "note: run with `RUST_BACKTRACE=1` environment variable to display a \
296                             backtrace"
297                    );
298                    if falsecfg!(miri) {
299                        let _ = err.write_fmt(format_args!("note: in Miri, you may have to set `MIRIFLAGS=-Zmiri-env-forward=RUST_BACKTRACE` for the environment variable to have an effect\n"))writeln!(
300                            err,
301                            "note: in Miri, you may have to set `MIRIFLAGS=-Zmiri-env-forward=RUST_BACKTRACE` \
302                                for the environment variable to have an effect"
303                        );
304                    }
305                }
306            }
307            // If backtraces aren't supported or are forced-off, do nothing.
308            None => {}
309        }
310    };
311
312    if let Ok(Some(local)) = try_set_output_capture(None) {
313        write(&mut *local.lock().unwrap_or_else(|e| e.into_inner()));
314        try_set_output_capture(Some(local)).ok();
315    } else if let Some(mut out) = panic_output() {
316        write(&mut out);
317    }
318}
319
320#[cfg(not(test))]
321#[doc(hidden)]
322#[cfg(panic = "immediate-abort")]
323#[unstable(feature = "update_panic_count", issue = "none")]
324pub mod panic_count {
325    /// A reason for forcing an immediate abort on panic.
326    #[derive(Debug)]
327    pub enum MustAbort {
328        AlwaysAbort,
329        PanicInHook,
330    }
331
332    #[inline]
333    pub fn increase(run_panic_hook: bool) -> Option<MustAbort> {
334        None
335    }
336
337    #[inline]
338    pub fn finished_panic_hook() {}
339
340    #[inline]
341    pub fn decrease() {}
342
343    #[inline]
344    pub fn set_always_abort() {}
345
346    // Disregards ALWAYS_ABORT_FLAG
347    #[inline]
348    #[must_use]
349    pub fn get_count() -> usize {
350        0
351    }
352
353    #[must_use]
354    #[inline]
355    pub fn count_is_zero() -> bool {
356        true
357    }
358}
359
360#[cfg(not(test))]
361#[doc(hidden)]
362#[cfg(not(panic = "immediate-abort"))]
363#[unstable(feature = "update_panic_count", issue = "none")]
364pub mod panic_count {
365    use crate::cell::Cell;
366    use crate::sync::atomic::{Atomic, AtomicUsize, Ordering};
367
368    const ALWAYS_ABORT_FLAG: usize = 1 << (usize::BITS - 1);
369
370    /// A reason for forcing an immediate abort on panic.
371    #[derive(#[automatically_derived]
impl ::core::fmt::Debug for MustAbort {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                MustAbort::AlwaysAbort => "AlwaysAbort",
                MustAbort::PanicInHook => "PanicInHook",
            })
    }
}Debug)]
372    pub enum MustAbort {
373        AlwaysAbort,
374        PanicInHook,
375    }
376
377    // Panic count for the current thread and whether a panic hook is currently
378    // being executed..
379    const LOCAL_PANIC_COUNT: crate::thread::LocalKey<Cell<(usize, bool)>> =
    {
        const __RUST_STD_INTERNAL_INIT: Cell<(usize, bool)> =
            { Cell::new((0, false)) };
        unsafe {
            crate::thread::LocalKey::new(const {
                        if crate::mem::needs_drop::<Cell<(usize, bool)>>() {
                            |_|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL:
                                        crate::thread::local_impl::EagerStorage<Cell<(usize, bool)>>
                                        =
                                        crate::thread::local_impl::EagerStorage::new(__RUST_STD_INTERNAL_INIT);
                                    __RUST_STD_INTERNAL_VAL.get()
                                }
                        } else {
                            |_|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL: Cell<(usize, bool)> =
                                        __RUST_STD_INTERNAL_INIT;
                                    &__RUST_STD_INTERNAL_VAL
                                }
                        }
                    })
        }
    };thread_local! {
380        static LOCAL_PANIC_COUNT: Cell<(usize, bool)> = const { Cell::new((0, false)) }
381    }
382
383    // Sum of panic counts from all threads. The purpose of this is to have
384    // a fast path in `count_is_zero` (which is used by `panicking`). In any particular
385    // thread, if that thread currently views `GLOBAL_PANIC_COUNT` as being zero,
386    // then `LOCAL_PANIC_COUNT` in that thread is zero. This invariant holds before
387    // and after increase and decrease, but not necessarily during their execution.
388    //
389    // Additionally, the top bit of GLOBAL_PANIC_COUNT (GLOBAL_ALWAYS_ABORT_FLAG)
390    // records whether panic::always_abort() has been called. This can only be
391    // set, never cleared.
392    // panic::always_abort() is usually called to prevent memory allocations done by
393    // the panic handling in the child created by `libc::fork`.
394    // Memory allocations performed in a child created with `libc::fork` are undefined
395    // behavior in most operating systems.
396    // Accessing LOCAL_PANIC_COUNT in a child created by `libc::fork` would lead to a memory
397    // allocation. Only GLOBAL_PANIC_COUNT can be accessed in this situation. This is
398    // sufficient because a child process will always have exactly one thread only.
399    // See also #85261 for details.
400    //
401    // This could be viewed as a struct containing a single bit and an n-1-bit
402    // value, but if we wrote it like that it would be more than a single word,
403    // and even a newtype around usize would be clumsy because we need atomics.
404    // But we use such a tuple for the return type of increase().
405    //
406    // Stealing a bit is fine because it just amounts to assuming that each
407    // panicking thread consumes at least 2 bytes of address space.
408    static GLOBAL_PANIC_COUNT: Atomic<usize> = AtomicUsize::new(0);
409
410    // Increases the global and local panic count, and returns whether an
411    // immediate abort is required.
412    //
413    // This also updates thread-local state to keep track of whether a panic
414    // hook is currently executing.
415    #[must_use = "MustAbort may not be ignored"]
416    pub fn increase(run_panic_hook: bool) -> Option<MustAbort> {
417        let global_count = GLOBAL_PANIC_COUNT.fetch_add(1, Ordering::Relaxed);
418        if global_count & ALWAYS_ABORT_FLAG != 0 {
419            // Do *not* access thread-local state, we might be after a `fork`.
420            return Some(MustAbort::AlwaysAbort);
421        }
422
423        LOCAL_PANIC_COUNT.with(|c| {
424            let (count, in_panic_hook) = c.get();
425            if in_panic_hook {
426                return Some(MustAbort::PanicInHook);
427            }
428            c.set((count + 1, run_panic_hook));
429            None
430        })
431    }
432
433    pub fn finished_panic_hook() {
434        LOCAL_PANIC_COUNT.with(|c| {
435            let (count, _) = c.get();
436            c.set((count, false));
437        });
438    }
439
440    pub fn decrease() {
441        GLOBAL_PANIC_COUNT.fetch_sub(1, Ordering::Relaxed);
442        LOCAL_PANIC_COUNT.with(|c| {
443            let (count, _) = c.get();
444            c.set((count - 1, false));
445        });
446    }
447
448    pub fn set_always_abort() {
449        GLOBAL_PANIC_COUNT.fetch_or(ALWAYS_ABORT_FLAG, Ordering::Relaxed);
450    }
451
452    // Disregards ALWAYS_ABORT_FLAG
453    #[must_use]
454    pub fn get_count() -> usize {
455        LOCAL_PANIC_COUNT.with(|c| c.get().0)
456    }
457
458    // Disregards ALWAYS_ABORT_FLAG
459    #[must_use]
460    #[inline]
461    pub fn count_is_zero() -> bool {
462        if GLOBAL_PANIC_COUNT.load(Ordering::Relaxed) & !ALWAYS_ABORT_FLAG == 0 {
463            // Fast path: if `GLOBAL_PANIC_COUNT` is zero, all threads
464            // (including the current one) will have `LOCAL_PANIC_COUNT`
465            // equal to zero, so TLS access can be avoided.
466            //
467            // In terms of performance, a relaxed atomic load is similar to a normal
468            // aligned memory read (e.g., a mov instruction in x86), but with some
469            // compiler optimization restrictions. On the other hand, a TLS access
470            // might require calling a non-inlinable function (such as `__tls_get_addr`
471            // when using the GD TLS model).
472            true
473        } else {
474            is_zero_slow_path()
475        }
476    }
477
478    // Slow path is in a separate function to reduce the amount of code
479    // inlined from `count_is_zero`.
480    #[inline(never)]
481    #[cold]
482    fn is_zero_slow_path() -> bool {
483        LOCAL_PANIC_COUNT.with(|c| c.get().0 == 0)
484    }
485}
486
487#[cfg(test)]
488pub use realstd::rt::panic_count;
489
490/// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
491#[cfg(panic = "immediate-abort")]
492pub unsafe fn catch_unwind<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>> {
493    Ok(f())
494}
495
496/// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
497#[cfg(not(panic = "immediate-abort"))]
498pub unsafe fn catch_unwind<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>> {
499    union Data<F, R> {
500        f: ManuallyDrop<F>,
501        r: ManuallyDrop<R>,
502        p: ManuallyDrop<Box<dyn Any + Send>>,
503    }
504
505    // We do some sketchy operations with ownership here for the sake of
506    // performance. We can only pass pointers down to `do_call` (can't pass
507    // objects by value), so we do all the ownership tracking here manually
508    // using a union.
509    //
510    // We go through a transition where:
511    //
512    // * First, we set the data field `f` to be the argumentless closure that we're going to call.
513    // * When we make the function call, the `do_call` function below, we take
514    //   ownership of the function pointer. At this point the `data` union is
515    //   entirely uninitialized.
516    // * If the closure successfully returns, we write the return value into the
517    //   data's return slot (field `r`).
518    // * If the closure panics (`do_catch` below), we write the panic payload into field `p`.
519    // * Finally, when we come back out of the `try` intrinsic we're
520    //   in one of two states:
521    //
522    //      1. The closure didn't panic, in which case the return value was
523    //         filled in. We move it out of `data.r` and return it.
524    //      2. The closure panicked, in which case the panic payload was
525    //         filled in. We move it out of `data.p` and return it.
526    //
527    // Once we stack all that together we should have the "most efficient'
528    // method of calling a catch panic whilst juggling ownership.
529    let mut data = Data { f: ManuallyDrop::new(f) };
530
531    // SAFETY:
532    //
533    // Access to the union's fields: this is `std` and we know that the `catch_unwind`
534    // intrinsic fills in the `r` or `p` union field based on its return value.
535    //
536    // The call to `intrinsics::catch_unwind` is made safe by:
537    // - `do_call`, the first argument, can be called with the initial `data_ptr`.
538    // - `do_catch`, the second argument, can be called with the `data_ptr` as well.
539    // See their safety preconditions for more information
540    unsafe {
541        return if intrinsics::catch_unwind(do_call, &raw mut data, do_catch) {
542            Err(ManuallyDrop::into_inner(data.p))
543        } else {
544            Ok(ManuallyDrop::into_inner(data.r))
545        };
546    }
547
548    // We consider unwinding to be rare, so mark this function as cold. However,
549    // do not mark it no-inline -- that decision is best to leave to the
550    // optimizer (in most cases this function is not inlined even as a normal,
551    // non-cold function, though, as of the writing of this comment).
552    #[cold]
553    #[optimize(size)]
554    unsafe fn cleanup(payload: *mut u8) -> Box<dyn Any + Send + 'static> {
555        // SAFETY: The whole unsafe block hinges on a correct implementation of
556        // the panic handler `__rust_panic_cleanup`. As such we can only
557        // assume it returns the correct thing for `Box::from_raw` to work
558        // without undefined behavior.
559        let obj = unsafe { __rust_panic_cleanup(payload) };
560        panic_count::decrease();
561        obj
562    }
563
564    // SAFETY:
565    // data must be non-NUL, correctly aligned, and a pointer to a `Data<F, R>`
566    // Its must contains a valid `f` (type: F) value that can be use to fill
567    // `data.r`.
568    #[inline]
569    unsafe fn do_call<F: FnOnce() -> R, R>(data: *mut Data<F, R>) {
570        // SAFETY: this is the responsibility of the caller, see above.
571        unsafe {
572            let f = ManuallyDrop::take(&mut (*data).f);
573            (*data).r = ManuallyDrop::new(f());
574        }
575    }
576
577    // We *do* want this part of the catch to be inlined: this allows the
578    // compiler to properly track accesses to the Data union and optimize it
579    // away most of the time.
580    //
581    // SAFETY:
582    // data must be non-NUL, correctly aligned, and a pointer to a `Data<F, R>`
583    // Since this uses `cleanup` it also hinges on a correct implementation of
584    // `__rustc_panic_cleanup`.
585    #[inline]
586    #[rustc_nounwind] // `intrinsic::catch_unwind` requires catch fn to be nounwind
587    unsafe fn do_catch<F: FnOnce() -> R, R>(data: *mut Data<F, R>, payload: *mut u8) {
588        // SAFETY: this is the responsibility of the caller, see above.
589        //
590        // When `__rustc_panic_cleaner` is correctly implemented we can rely
591        // on `obj` being the correct thing to pass to `data.p` (after wrapping
592        // in `ManuallyDrop`).
593        unsafe {
594            let obj = cleanup(payload);
595            (*data).p = ManuallyDrop::new(obj);
596        }
597    }
598}
599
600/// Determines whether the current thread is unwinding because of panic.
601#[inline]
602pub fn panicking() -> bool {
603    !panic_count::count_is_zero()
604}
605
606/// Entry point of panics from the core crate (`panic_impl` lang item).
607#[cfg(not(any(test, doctest)))]
608#[panic_handler]
609pub fn panic_handler(info: &core::panic::PanicInfo<'_>) -> ! {
610    struct FormatStringPayload<'a> {
611        inner: &'a core::panic::PanicMessage<'a>,
612        string: Option<String>,
613    }
614
615    impl FormatStringPayload<'_> {
616        fn fill(&mut self) -> &mut String {
617            let inner = self.inner;
618            // Lazily, the first time this gets called, run the actual string formatting.
619            self.string.get_or_insert_with(|| {
620                let mut s = String::new();
621                let mut fmt = fmt::Formatter::new(&mut s, fmt::FormattingOptions::new());
622                let _err = fmt::Display::fmt(&inner, &mut fmt);
623                s
624            })
625        }
626    }
627
628    impl PanicPayload for FormatStringPayload<'_> {
629        fn take_box(&mut self) -> Box<dyn Any + Send> {
630            // We do two allocations here, unfortunately. But (a) they're required with the current
631            // scheme, and (b) we don't handle panic + OOM properly anyway (see comment in
632            // begin_panic below).
633            let contents = mem::take(self.fill());
634            Box::new(contents)
635        }
636
637        fn get(&mut self) -> &(dyn Any + Send) {
638            self.fill()
639        }
640    }
641
642    impl fmt::Display for FormatStringPayload<'_> {
643        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
644            if let Some(s) = &self.string {
645                f.write_str(s)
646            } else {
647                fmt::Display::fmt(&self.inner, f)
648            }
649        }
650    }
651
652    struct StaticStrPayload(&'static str);
653
654    impl PanicPayload for StaticStrPayload {
655        fn take_box(&mut self) -> Box<dyn Any + Send> {
656            Box::new(self.0)
657        }
658
659        fn get(&mut self) -> &(dyn Any + Send) {
660            &self.0
661        }
662
663        fn as_str(&mut self) -> Option<&str> {
664            Some(self.0)
665        }
666    }
667
668    impl fmt::Display for StaticStrPayload {
669        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
670            f.write_str(self.0)
671        }
672    }
673
674    let loc = info.location().unwrap(); // The current implementation always returns Some
675    let msg = info.message();
676    crate::sys::backtrace::__rust_end_short_backtrace(move || {
677        if let Some(s) = msg.as_str() {
678            panic_with_hook(
679                &mut StaticStrPayload(s),
680                loc,
681                info.can_unwind(),
682                info.force_no_backtrace(),
683            );
684        } else {
685            panic_with_hook(
686                &mut FormatStringPayload { inner: &msg, string: None },
687                loc,
688                info.can_unwind(),
689                info.force_no_backtrace(),
690            );
691        }
692    })
693}
694
695/// This is the entry point of panicking for the non-format-string variants of
696/// panic!() and assert!(). In particular, this is the only entry point that supports
697/// arbitrary payloads, not just format strings.
698#[unstable(feature = "libstd_sys_internals", reason = "used by the panic! macro", issue = "none")]
699#[cfg_attr(not(any(test, doctest)), lang = "begin_panic")]
700// lang item for CTFE panic support
701// never inline unless panic=immediate-abort to avoid code
702// bloat at the call sites as much as possible
703#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
704#[cfg_attr(panic = "immediate-abort", inline)]
705#[track_caller]
706#[rustc_do_not_const_check] // hooked by const-eval
707pub const fn begin_panic<M: Any + Send>(msg: M) -> ! {
708    if falsecfg!(panic = "immediate-abort") {
709        intrinsics::abort()
710    }
711
712    struct Payload<A> {
713        inner: Option<A>,
714    }
715
716    impl<A: Send + 'static> PanicPayload for Payload<A> {
717        fn take_box(&mut self) -> Box<dyn Any + Send> {
718            // Note that this should be the only allocation performed in this code path. Currently
719            // this means that panic!() on OOM will invoke this code path, but then again we're not
720            // really ready for panic on OOM anyway. If we do start doing this, then we should
721            // propagate this allocation to be performed in the parent of this thread instead of the
722            // thread that's panicking.
723            match self.inner.take() {
724                Some(a) => Box::new(a) as Box<dyn Any + Send>,
725                None => process::abort(),
726            }
727        }
728
729        fn get(&mut self) -> &(dyn Any + Send) {
730            match self.inner {
731                Some(ref a) => a,
732                None => process::abort(),
733            }
734        }
735    }
736
737    impl<A: 'static> fmt::Display for Payload<A> {
738        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
739            match &self.inner {
740                Some(a) => f.write_str(payload_as_str(a)),
741                None => process::abort(),
742            }
743        }
744    }
745
746    let loc = Location::caller();
747    crate::sys::backtrace::__rust_end_short_backtrace(move || {
748        panic_with_hook(
749            &mut Payload { inner: Some(msg) },
750            loc,
751            /* can_unwind */ true,
752            /* force_no_backtrace */ false,
753        )
754    })
755}
756
757fn payload_as_str(payload: &dyn Any) -> &str {
758    if let Some(&s) = payload.downcast_ref::<&'static str>() {
759        s
760    } else if let Some(s) = payload.downcast_ref::<String>() {
761        s.as_str()
762    } else {
763        "Box<dyn Any>"
764    }
765}
766
767/// Central point for dispatching panics.
768///
769/// Executes the primary logic for a panic, including checking for recursive
770/// panics, panic hooks, and finally dispatching to the panic runtime to either
771/// abort or unwind.
772#[optimize(size)]
773fn panic_with_hook(
774    payload: &mut dyn PanicPayload,
775    location: &'static Location<'static>,
776    can_unwind: bool,
777    force_no_backtrace: bool,
778) -> ! {
779    let must_abort = panic_count::increase(true);
780
781    // Check if we need to abort immediately.
782    if let Some(must_abort) = must_abort {
783        match must_abort {
784            panic_count::MustAbort::PanicInHook => {
785                // Don't try to format the message in this case, perhaps that is causing the
786                // recursive panics. However if the message is just a string, no user-defined
787                // code is involved in printing it, so that is risk-free.
788                let message: &str = payload.as_str().unwrap_or_default();
789                if let Some(mut out) = crate::sys::stdio::panic_output() {
    let _ =
        crate::io::Write::write_fmt(&mut out,
            format_args!("panicked at {0}:\n{1}\nthread panicked while processing panic. aborting.\n",
                location, message));
};rtprintpanic!(
790                    "panicked at {location}:\n{message}\nthread panicked while processing panic. aborting.\n"
791                );
792            }
793            panic_count::MustAbort::AlwaysAbort => {
794                // Unfortunately, this does not print a backtrace, because creating
795                // a `Backtrace` will allocate, which we must avoid here.
796                if let Some(mut out) = crate::sys::stdio::panic_output() {
    let _ =
        crate::io::Write::write_fmt(&mut out,
            format_args!("aborting due to panic at {0}:\n{1}\n", location,
                payload));
};rtprintpanic!("aborting due to panic at {location}:\n{payload}\n");
797            }
798        }
799        crate::process::abort();
800    }
801
802    match *HOOK.read() {
803        // Some platforms (like wasm) know that printing to stderr won't ever actually
804        // print anything, and if that's the case we can skip the default
805        // hook. Since string formatting happens lazily when calling `payload`
806        // methods, this means we avoid formatting the string at all!
807        // (The panic runtime might still call `payload.take_box()` though and trigger
808        // formatting.)
809        Hook::Default if panic_output().is_none() => {}
810        Hook::Default => {
811            default_hook(&PanicHookInfo::new(
812                location,
813                payload.get(),
814                can_unwind,
815                force_no_backtrace,
816            ));
817        }
818        Hook::Custom(ref hook) => {
819            hook(&PanicHookInfo::new(location, payload.get(), can_unwind, force_no_backtrace));
820        }
821    }
822
823    // Indicate that we have finished executing the panic hook. After this point
824    // it is fine if there is a panic while executing destructors, as long as it
825    // it contained within a `catch_unwind`.
826    panic_count::finished_panic_hook();
827
828    if !can_unwind {
829        // If a thread panics while running destructors or tries to unwind
830        // through a nounwind function (e.g. extern "C") then we cannot continue
831        // unwinding and have to abort immediately.
832        if let Some(mut out) = crate::sys::stdio::panic_output() {
    let _ =
        crate::io::Write::write_fmt(&mut out,
            format_args!("thread caused non-unwinding panic. aborting.\n"));
};rtprintpanic!("thread caused non-unwinding panic. aborting.\n");
833        crate::process::abort();
834    }
835
836    rust_panic(payload)
837}
838
839/// This is the entry point for `resume_unwind`.
840/// It just forwards the payload to the panic runtime.
841#[cfg_attr(panic = "immediate-abort", inline)]
842pub fn resume_unwind(payload: Box<dyn Any + Send>) -> ! {
843    if let Some(must_abort) = panic_count::increase(false) {
844        match must_abort {
845            panic_count::MustAbort::PanicInHook => {
846                if let Some(mut out) = crate::sys::stdio::panic_output() {
    let _ =
        crate::io::Write::write_fmt(&mut out,
            format_args!("thread panicked while processing panic. aborting.\n"));
};rtprintpanic!("thread panicked while processing panic. aborting.\n");
847            }
848            panic_count::MustAbort::AlwaysAbort => {
849                if let Some(mut out) = crate::sys::stdio::panic_output() {
    let _ =
        crate::io::Write::write_fmt(&mut out,
            format_args!("aborting due to panic\n"));
};rtprintpanic!("aborting due to panic\n");
850            }
851        }
852
853        crate::process::abort();
854    }
855
856    struct RewrapBox(Box<dyn Any + Send>);
857
858    impl PanicPayload for RewrapBox {
859        fn take_box(&mut self) -> Box<dyn Any + Send> {
860            mem::replace(&mut self.0, Box::new(()))
861        }
862
863        fn get(&mut self) -> &(dyn Any + Send) {
864            &*self.0
865        }
866    }
867
868    impl fmt::Display for RewrapBox {
869        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
870            f.write_str(payload_as_str(&self.0))
871        }
872    }
873
874    rust_panic(&mut RewrapBox(payload))
875}
876
877/// A function with a fixed suffix (through `rustc_std_internal_symbol`)
878/// on which to slap yer breakpoints.
879#[inline(never)]
880#[cfg_attr(not(test), rustc_std_internal_symbol)]
881#[cfg(not(panic = "immediate-abort"))]
882fn rust_panic(msg: &mut dyn PanicPayload) -> ! {
883    let code = __rust_start_panic(msg);
884    {
    if let Some(mut out) = crate::sys::stdio::panic_output() {
        let _ =
            crate::io::Write::write_fmt(&mut out,
                format_args!("fatal runtime error: {0}, aborting\n",
                    format_args!("failed to initiate panic, error {0}", code)));
    };
    crate::process::abort();
}rtabort!("failed to initiate panic, error {code}")
885}
886
887#[cfg_attr(not(test), rustc_std_internal_symbol)]
888#[cfg(panic = "immediate-abort")]
889fn rust_panic(_: &mut dyn PanicPayload) -> ! {
890    crate::intrinsics::abort();
891}