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