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