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