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