core/
panicking.rs

1//! Panic support for core
2//!
3//! In core, panicking is always done with a message, resulting in a `core::panic::PanicInfo`
4//! containing a `fmt::Arguments`. In std, however, panicking can be done with panic_any, which
5//! throws a `Box<dyn Any>` containing any type of value. Because of this,
6//! `std::panic::PanicHookInfo` is a different type, which contains a `&dyn Any` instead of a
7//! `fmt::Arguments`. std's panic handler will convert the `fmt::Arguments` to a `&dyn Any`
8//! containing either a `&'static str` or `String` containing the formatted message.
9//!
10//! The core library cannot define any panic handler, but it can invoke it.
11//! This means that the functions inside of core are allowed to panic, but to be
12//! useful an upstream crate must define panicking for core to use. The current
13//! interface for panicking is:
14//!
15//! ```
16//! fn panic_impl(pi: &core::panic::PanicInfo<'_>) -> !
17//! # { loop {} }
18//! ```
19//!
20//! This module contains a few other panicking functions, but these are just the
21//! necessary lang items for the compiler. All panics are funneled through this
22//! one function. The actual symbol is declared through the `#[panic_handler]` attribute.
23
24#![allow(dead_code, missing_docs)]
25#![unstable(
26    feature = "panic_internals",
27    reason = "internal details of the implementation of the `panic!` and related macros",
28    issue = "none"
29)]
30
31#[cfg(not(feature = "ferrocene_certified"))]
32use crate::fmt;
33use crate::intrinsics::const_eval_select;
34#[cfg(not(feature = "ferrocene_certified"))]
35use crate::panic::{Location, PanicInfo};
36
37// Ferrocene addition: imports for certified subset
38#[cfg(feature = "ferrocene_certified")]
39#[rustfmt::skip]
40use crate::panic::PanicInfo;
41
42/// Ferrocene addition: Alias used in our panic-related patches to avoid having to certify `fmt`.
43#[cfg(not(feature = "ferrocene_certified"))]
44pub(crate) type PanicFmt<'a> = fmt::Arguments<'a>;
45#[cfg(feature = "ferrocene_certified")]
46pub(crate) type PanicFmt<'a> = &'a &'static str;
47
48#[cfg(feature = "panic_immediate_abort")]
49compile_error!(
50    "panic_immediate_abort is now a real panic strategy! \
51    Enable it with `panic = \"immediate-abort\"` in Cargo.toml, \
52    or with the compiler flags `-Zunstable-options -Cpanic=immediate-abort`. \
53    In both cases, you still need to build core, e.g. with `-Zbuild-std`"
54);
55
56// First we define the two main entry points that all panics go through.
57// In the end both are just convenience wrappers around `panic_impl`.
58
59/// The entry point for panicking with a formatted message.
60///
61/// This is designed to reduce the amount of code required at the call
62/// site as much as possible (so that `panic!()` has as low an impact
63/// on (e.g.) the inlining of other functions as possible), by moving
64/// the actual formatting into this shared place.
65// If panic=immediate-abort, inline the abort call,
66// otherwise avoid inlining because of it is cold path.
67#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold)]
68#[cfg_attr(panic = "immediate-abort", inline)]
69#[track_caller]
70#[lang = "panic_fmt"] // needed for const-evaluated panics
71#[rustc_do_not_const_check] // hooked by const-eval
72#[rustc_const_stable_indirect] // must follow stable const rules since it is exposed to stable
73// Ferrocene change: `fmt` is a type alias to accomodate certified core
74pub const fn panic_fmt(fmt: PanicFmt<'_>) -> ! {
75    #[ferrocene::annotation(
76        "The `immediate-abort` behavior is not certified, we only support `abort`."
77    )]
78    if cfg!(panic = "immediate-abort") {
79        super::intrinsics::abort()
80    };
81
82    // NOTE This function never crosses the FFI boundary; it's a Rust-to-Rust call
83    // that gets resolved to the `#[panic_handler]` function.
84    unsafe extern "Rust" {
85        #[lang = "panic_impl"]
86        fn panic_impl(pi: &PanicInfo<'_>) -> !;
87    }
88
89    #[cfg(not(feature = "ferrocene_certified"))]
90    let pi = PanicInfo::new(
91        &fmt,
92        Location::caller(),
93        /* can_unwind */ true,
94        /* force_no_backtrace */ false,
95    );
96    #[cfg(feature = "ferrocene_certified")]
97    let pi = PanicInfo::new(&fmt);
98    // SAFETY: `panic_impl` is defined in safe Rust code and thus is safe to call.
99    unsafe { panic_impl(&pi) }
100}
101
102/// Like `panic_fmt`, but for non-unwinding panics.
103///
104/// Has to be a separate function so that it can carry the `rustc_nounwind` attribute.
105#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold)]
106#[cfg_attr(panic = "immediate-abort", inline)]
107#[track_caller]
108// This attribute has the key side-effect that if the panic handler ignores `can_unwind`
109// and unwinds anyway, we will hit the "unwinding out of nounwind function" guard,
110// which causes a "panic in a function that cannot unwind".
111#[rustc_nounwind]
112#[rustc_const_stable_indirect] // must follow stable const rules since it is exposed to stable
113#[rustc_allow_const_fn_unstable(const_eval_select)]
114#[ferrocene::annotation("Cannot be covered as it causes an unwinding panic")]
115pub const fn panic_nounwind_fmt(fmt: PanicFmt<'_>, _force_no_backtrace: bool) -> ! {
116    const_eval_select!(
117        @capture { fmt: PanicFmt<'_>, _force_no_backtrace: bool } -> !:
118        if const #[track_caller] {
119            // We don't unwind anyway at compile-time so we can call the regular `panic_fmt`.
120            panic_fmt(fmt)
121        } else #[track_caller] {
122            if cfg!(panic = "immediate-abort") {
123                super::intrinsics::abort()
124            }
125
126            // NOTE This function never crosses the FFI boundary; it's a Rust-to-Rust call
127            // that gets resolved to the `#[panic_handler]` function.
128            unsafe extern "Rust" {
129                #[lang = "panic_impl"]
130                fn panic_impl(pi: &PanicInfo<'_>) -> !;
131            }
132
133            // PanicInfo with the `can_unwind` flag set to false forces an abort.
134            #[cfg(not(feature = "ferrocene_certified"))]
135            let pi = PanicInfo::new(
136                &fmt,
137                Location::caller(),
138                /* can_unwind */ false,
139                _force_no_backtrace,
140            );
141            #[cfg(feature = "ferrocene_certified")]
142            let pi = PanicInfo::new(&fmt);
143
144            // SAFETY: `panic_impl` is defined in safe Rust code and thus is safe to call.
145            unsafe { panic_impl(&pi) }
146        }
147    )
148}
149
150// Next we define a bunch of higher-level wrappers that all bottom out in the two core functions
151// above.
152
153/// The underlying implementation of core's `panic!` macro when no formatting is used.
154// Never inline unless panic=immediate-abort to avoid code
155// bloat at the call sites as much as possible.
156#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold)]
157#[cfg_attr(panic = "immediate-abort", inline)]
158#[track_caller]
159#[rustc_const_stable_indirect] // must follow stable const rules since it is exposed to stable
160#[lang = "panic"] // used by lints and miri for panics
161pub const fn panic(expr: &'static str) -> ! {
162    // Use Arguments::from_str instead of format_args!("{expr}") to potentially
163    // reduce size overhead. The format_args! macro uses str's Display trait to
164    // write expr, which calls Formatter::pad, which must accommodate string
165    // truncation and padding (even though none is used here). Using
166    // Arguments::from_str may allow the compiler to omit Formatter::pad from the
167    // output binary, saving up to a few kilobytes.
168    // However, this optimization only works for `'static` strings: `from_str` also makes this
169    // message return `Some` from `Arguments::as_str`, which means it can become part of the panic
170    // payload without any allocation or copying. Shorter-lived strings would become invalid as
171    // stack frames get popped during unwinding, and couldn't be directly referenced from the
172    // payload.
173    #[cfg(not(feature = "ferrocene_certified"))]
174    panic_fmt(fmt::Arguments::from_str(expr));
175    #[cfg(feature = "ferrocene_certified")]
176    panic_fmt(&expr)
177}
178
179// We generate functions for usage by compiler-generated assertions.
180//
181// Placing these functions in libcore means that all Rust programs can generate a jump into this
182// code rather than expanding to panic("...") above, which adds extra bloat to call sites (for the
183// constant string argument's pointer and length).
184//
185// This is especially important when this code is called often (e.g., with -Coverflow-checks) for
186// reducing binary size impact.
187macro_rules! panic_const {
188    ($($lang:ident = $message:expr,)+) => {
189        $(
190            /// This is a panic called with a message that's a result of a MIR-produced Assert.
191            //
192            // never inline unless panic=immediate-abort to avoid code
193            // bloat at the call sites as much as possible
194            #[cfg_attr(not(panic = "immediate-abort"), inline(never), cold)]
195            #[cfg_attr(panic = "immediate-abort", inline)]
196            #[track_caller]
197            #[rustc_const_stable_indirect] // must follow stable const rules since it is exposed to stable
198            #[lang = stringify!($lang)]
199            #[ferrocene::annotation("Cannot be covered as this code cannot be reached during runtime.")]
200            pub const fn $lang() -> ! {
201                // See the comment in `panic(&'static str)` for why we use `Arguments::from_str` here.
202                #[cfg(not(feature = "ferrocene_certified"))]
203                panic_fmt(fmt::Arguments::from_str($message));
204                #[cfg(feature = "ferrocene_certified")]
205                panic_fmt(&$message);
206            }
207        )+
208    }
209}
210
211// Unfortunately this set of strings is replicated here and in a few places in the compiler in
212// slightly different forms. It's not clear if there's a good way to deduplicate without adding
213// special cases to the compiler (e.g., a const generic function wouldn't have a single definition
214// shared across crates, which is exactly what we want here).
215pub mod panic_const {
216    use super::*;
217    panic_const! {
218        panic_const_add_overflow = "attempt to add with overflow",
219        panic_const_sub_overflow = "attempt to subtract with overflow",
220        panic_const_mul_overflow = "attempt to multiply with overflow",
221        panic_const_div_overflow = "attempt to divide with overflow",
222        panic_const_rem_overflow = "attempt to calculate the remainder with overflow",
223        panic_const_neg_overflow = "attempt to negate with overflow",
224        panic_const_shr_overflow = "attempt to shift right with overflow",
225        panic_const_shl_overflow = "attempt to shift left with overflow",
226        panic_const_div_by_zero = "attempt to divide by zero",
227        panic_const_rem_by_zero = "attempt to calculate the remainder with a divisor of zero",
228        panic_const_coroutine_resumed = "coroutine resumed after completion",
229        panic_const_async_fn_resumed = "`async fn` resumed after completion",
230        panic_const_async_gen_fn_resumed = "`async gen fn` resumed after completion",
231        panic_const_gen_fn_none = "`gen fn` should just keep returning `None` after completion",
232        panic_const_coroutine_resumed_panic = "coroutine resumed after panicking",
233        panic_const_async_fn_resumed_panic = "`async fn` resumed after panicking",
234        panic_const_async_gen_fn_resumed_panic = "`async gen fn` resumed after panicking",
235        panic_const_gen_fn_none_panic = "`gen fn` should just keep returning `None` after panicking",
236    }
237    // Separated panic constants list for async drop feature
238    // (May be joined when the corresponding lang items will be in the bootstrap)
239    panic_const! {
240        panic_const_coroutine_resumed_drop = "coroutine resumed after async drop",
241        panic_const_async_fn_resumed_drop = "`async fn` resumed after async drop",
242        panic_const_async_gen_fn_resumed_drop = "`async gen fn` resumed after async drop",
243        panic_const_gen_fn_none_drop = "`gen fn` resumed after async drop",
244    }
245}
246
247/// Like `panic`, but without unwinding and track_caller to reduce the impact on codesize on the caller.
248/// If you want `#[track_caller]` for nicer errors, call `panic_nounwind_fmt` directly.
249#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold)]
250#[cfg_attr(panic = "immediate-abort", inline)]
251#[lang = "panic_nounwind"] // needed by codegen for non-unwinding panics
252#[rustc_nounwind]
253#[rustc_const_stable_indirect] // must follow stable const rules since it is exposed to stable
254#[ferrocene::annotation("Cannot be covered as it causes an unwinding panic")]
255pub const fn panic_nounwind(expr: &'static str) -> ! {
256    #[cfg(not(feature = "ferrocene_certified"))]
257    panic_nounwind_fmt(fmt::Arguments::from_str(expr), /* force_no_backtrace */ false);
258    #[cfg(feature = "ferrocene_certified")]
259    panic_nounwind_fmt(&expr, /* force_no_backtrace */ false);
260}
261
262/// Like `panic_nounwind`, but also inhibits showing a backtrace.
263#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold)]
264#[cfg_attr(panic = "immediate-abort", inline)]
265#[rustc_nounwind]
266#[cfg(not(feature = "ferrocene_certified"))]
267pub fn panic_nounwind_nobacktrace(expr: &'static str) -> ! {
268    panic_nounwind_fmt(fmt::Arguments::from_str(expr), /* force_no_backtrace */ true);
269}
270
271#[inline]
272#[track_caller]
273#[rustc_diagnostic_item = "unreachable_display"] // needed for `non-fmt-panics` lint
274#[cfg(not(feature = "ferrocene_certified"))]
275pub fn unreachable_display<T: fmt::Display>(x: &T) -> ! {
276    panic_fmt(format_args!("internal error: entered unreachable code: {}", *x));
277}
278
279/// This exists solely for the 2015 edition `panic!` macro to trigger
280/// a lint on `panic!(my_str_variable);`.
281#[inline]
282#[track_caller]
283#[rustc_diagnostic_item = "panic_str_2015"]
284#[rustc_const_stable_indirect] // must follow stable const rules since it is exposed to stable
285#[cfg(not(feature = "ferrocene_certified"))]
286pub const fn panic_str_2015(expr: &str) -> ! {
287    panic_display(&expr);
288}
289
290#[inline]
291#[track_caller]
292#[lang = "panic_display"] // needed for const-evaluated panics
293#[rustc_do_not_const_check] // hooked by const-eval
294#[rustc_const_stable_indirect] // must follow stable const rules since it is exposed to stable
295#[cfg(not(feature = "ferrocene_certified"))]
296pub const fn panic_display<T: fmt::Display>(x: &T) -> ! {
297    panic_fmt(format_args!("{}", *x));
298}
299
300#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
301#[cfg_attr(panic = "immediate-abort", inline)]
302#[track_caller]
303#[lang = "panic_bounds_check"] // needed by codegen for panic on OOB array/slice access
304#[cfg_attr(feature = "ferrocene_certified", expect(unused_variables))]
305fn panic_bounds_check(index: usize, len: usize) -> ! {
306    if cfg!(panic = "immediate-abort") {
307        super::intrinsics::abort()
308    }
309    panic!("index out of bounds: the len is {len} but the index is {index}")
310}
311
312#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
313#[cfg_attr(panic = "immediate-abort", inline)]
314#[track_caller]
315#[lang = "panic_misaligned_pointer_dereference"] // needed by codegen for panic on misaligned pointer deref
316#[rustc_nounwind] // `CheckAlignment` MIR pass requires this function to never unwind
317#[cfg(not(feature = "ferrocene_certified"))]
318fn panic_misaligned_pointer_dereference(required: usize, found: usize) -> ! {
319    if cfg!(panic = "immediate-abort") {
320        super::intrinsics::abort()
321    }
322
323    panic_nounwind_fmt(
324        format_args!(
325            "misaligned pointer dereference: address must be a multiple of {required:#x} but is {found:#x}"
326        ),
327        /* force_no_backtrace */ false,
328    )
329}
330
331#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
332#[cfg_attr(panic = "immediate-abort", inline)]
333#[track_caller]
334#[lang = "panic_null_pointer_dereference"] // needed by codegen for panic on null pointer deref
335#[rustc_nounwind] // `CheckNull` MIR pass requires this function to never unwind
336#[cfg(not(feature = "ferrocene_certified"))]
337fn panic_null_pointer_dereference() -> ! {
338    if cfg!(panic = "immediate-abort") {
339        super::intrinsics::abort()
340    }
341
342    panic_nounwind_fmt(
343        format_args!("null pointer dereference occurred"),
344        /* force_no_backtrace */ false,
345    )
346}
347
348#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
349#[cfg_attr(panic = "immediate-abort", inline)]
350#[track_caller]
351#[lang = "panic_invalid_enum_construction"] // needed by codegen for panic on invalid enum construction.
352#[rustc_nounwind] // `CheckEnums` MIR pass requires this function to never unwind
353#[cfg(not(feature = "ferrocene_certified"))]
354fn panic_invalid_enum_construction(source: u128) -> ! {
355    if cfg!(panic = "immediate-abort") {
356        super::intrinsics::abort()
357    }
358
359    panic_nounwind_fmt(
360        format_args!("trying to construct an enum from an invalid value {source:#x}"),
361        /* force_no_backtrace */ false,
362    )
363}
364
365/// Panics because we cannot unwind out of a function.
366///
367/// This is a separate function to avoid the codesize impact of each crate containing the string to
368/// pass to `panic_nounwind`.
369///
370/// This function is called directly by the codegen backend, and must not have
371/// any extra arguments (including those synthesized by track_caller).
372#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
373#[cfg_attr(panic = "immediate-abort", inline)]
374#[lang = "panic_cannot_unwind"] // needed by codegen for panic in nounwind function
375#[rustc_nounwind]
376#[ferrocene::annotation("Cannot be covered as it causes an unwinding panic")]
377fn panic_cannot_unwind() -> ! {
378    // Keep the text in sync with `UnwindTerminateReason::as_str` in `rustc_middle`.
379    panic_nounwind("panic in a function that cannot unwind")
380}
381
382/// Panics because we are unwinding out of a destructor during cleanup.
383///
384/// This is a separate function to avoid the codesize impact of each crate containing the string to
385/// pass to `panic_nounwind`.
386///
387/// This function is called directly by the codegen backend, and must not have
388/// any extra arguments (including those synthesized by track_caller).
389#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
390#[cfg_attr(panic = "immediate-abort", inline)]
391#[lang = "panic_in_cleanup"] // needed by codegen for panic in nounwind function
392#[rustc_nounwind]
393#[cfg(not(feature = "ferrocene_certified"))]
394fn panic_in_cleanup() -> ! {
395    // Keep the text in sync with `UnwindTerminateReason::as_str` in `rustc_middle`.
396    panic_nounwind_nobacktrace("panic in a destructor during cleanup")
397}
398
399/// This function is used instead of panic_fmt in const eval.
400#[lang = "const_panic_fmt"] // needed by const-eval machine to replace calls to `panic_fmt` lang item
401#[rustc_const_stable_indirect] // must follow stable const rules since it is exposed to stable
402#[cfg(not(feature = "ferrocene_certified"))]
403pub const fn const_panic_fmt(fmt: fmt::Arguments<'_>) -> ! {
404    if let Some(msg) = fmt.as_str() {
405        // The panic_display function is hooked by const eval.
406        panic_display(&msg);
407    } else {
408        // SAFETY: This is only evaluated at compile time, which reliably
409        // handles this UB (in case this branch turns out to be reachable
410        // somehow).
411        unsafe { crate::hint::unreachable_unchecked() };
412    }
413}
414
415#[derive(Debug)]
416#[doc(hidden)]
417#[cfg(not(feature = "ferrocene_certified"))]
418pub enum AssertKind {
419    Eq,
420    Ne,
421    Match,
422}
423
424/// Internal function for `assert_eq!` and `assert_ne!` macros
425#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
426#[cfg_attr(panic = "immediate-abort", inline)]
427#[track_caller]
428#[doc(hidden)]
429#[cfg(not(feature = "ferrocene_certified"))]
430pub fn assert_failed<T, U>(
431    kind: AssertKind,
432    left: &T,
433    right: &U,
434    args: Option<fmt::Arguments<'_>>,
435) -> !
436where
437    T: fmt::Debug + ?Sized,
438    U: fmt::Debug + ?Sized,
439{
440    assert_failed_inner(kind, &left, &right, args)
441}
442
443/// Internal function for `assert_match!`
444#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
445#[cfg_attr(panic = "immediate-abort", inline)]
446#[track_caller]
447#[doc(hidden)]
448#[cfg(not(feature = "ferrocene_certified"))]
449pub fn assert_matches_failed<T: fmt::Debug + ?Sized>(
450    left: &T,
451    right: &str,
452    args: Option<fmt::Arguments<'_>>,
453) -> ! {
454    // The pattern is a string so it can be displayed directly.
455    struct Pattern<'a>(&'a str);
456    impl fmt::Debug for Pattern<'_> {
457        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
458            f.write_str(self.0)
459        }
460    }
461    assert_failed_inner(AssertKind::Match, &left, &Pattern(right), args);
462}
463
464/// Non-generic version of the above functions, to avoid code bloat.
465#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
466#[cfg_attr(panic = "immediate-abort", inline)]
467#[track_caller]
468#[cfg(not(feature = "ferrocene_certified"))]
469fn assert_failed_inner(
470    kind: AssertKind,
471    left: &dyn fmt::Debug,
472    right: &dyn fmt::Debug,
473    args: Option<fmt::Arguments<'_>>,
474) -> ! {
475    let op = match kind {
476        AssertKind::Eq => "==",
477        AssertKind::Ne => "!=",
478        AssertKind::Match => "matches",
479    };
480
481    match args {
482        Some(args) => panic!(
483            r#"assertion `left {op} right` failed: {args}
484  left: {left:?}
485 right: {right:?}"#
486        ),
487        None => panic!(
488            r#"assertion `left {op} right` failed
489  left: {left:?}
490 right: {right:?}"#
491        ),
492    }
493}