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::new_const 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::new_const 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: `new_const` 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::new_const(&[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                // Use Arguments::new_const instead of format_args!("{expr}") to potentially
202                // reduce size overhead. The format_args! macro uses str's Display trait to
203                // write expr, which calls Formatter::pad, which must accommodate string
204                // truncation and padding (even though none is used here). Using
205                // Arguments::new_const may allow the compiler to omit Formatter::pad from the
206                // output binary, saving up to a few kilobytes.
207                #[cfg(not(feature = "ferrocene_certified"))]
208                panic_fmt(fmt::Arguments::new_const(&[$message]));
209                #[cfg(feature = "ferrocene_certified")]
210                panic_fmt(&$message);
211            }
212        )+
213    }
214}
215
216// Unfortunately this set of strings is replicated here and in a few places in the compiler in
217// slightly different forms. It's not clear if there's a good way to deduplicate without adding
218// special cases to the compiler (e.g., a const generic function wouldn't have a single definition
219// shared across crates, which is exactly what we want here).
220pub mod panic_const {
221    use super::*;
222    panic_const! {
223        panic_const_add_overflow = "attempt to add with overflow",
224        panic_const_sub_overflow = "attempt to subtract with overflow",
225        panic_const_mul_overflow = "attempt to multiply with overflow",
226        panic_const_div_overflow = "attempt to divide with overflow",
227        panic_const_rem_overflow = "attempt to calculate the remainder with overflow",
228        panic_const_neg_overflow = "attempt to negate with overflow",
229        panic_const_shr_overflow = "attempt to shift right with overflow",
230        panic_const_shl_overflow = "attempt to shift left with overflow",
231        panic_const_div_by_zero = "attempt to divide by zero",
232        panic_const_rem_by_zero = "attempt to calculate the remainder with a divisor of zero",
233        panic_const_coroutine_resumed = "coroutine resumed after completion",
234        panic_const_async_fn_resumed = "`async fn` resumed after completion",
235        panic_const_async_gen_fn_resumed = "`async gen fn` resumed after completion",
236        panic_const_gen_fn_none = "`gen fn` should just keep returning `None` after completion",
237        panic_const_coroutine_resumed_panic = "coroutine resumed after panicking",
238        panic_const_async_fn_resumed_panic = "`async fn` resumed after panicking",
239        panic_const_async_gen_fn_resumed_panic = "`async gen fn` resumed after panicking",
240        panic_const_gen_fn_none_panic = "`gen fn` should just keep returning `None` after panicking",
241    }
242    // Separated panic constants list for async drop feature
243    // (May be joined when the corresponding lang items will be in the bootstrap)
244    panic_const! {
245        panic_const_coroutine_resumed_drop = "coroutine resumed after async drop",
246        panic_const_async_fn_resumed_drop = "`async fn` resumed after async drop",
247        panic_const_async_gen_fn_resumed_drop = "`async gen fn` resumed after async drop",
248        panic_const_gen_fn_none_drop = "`gen fn` resumed after async drop",
249    }
250}
251
252/// Like `panic`, but without unwinding and track_caller to reduce the impact on codesize on the caller.
253/// If you want `#[track_caller]` for nicer errors, call `panic_nounwind_fmt` directly.
254#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold)]
255#[cfg_attr(panic = "immediate-abort", inline)]
256#[lang = "panic_nounwind"] // needed by codegen for non-unwinding panics
257#[rustc_nounwind]
258#[rustc_const_stable_indirect] // must follow stable const rules since it is exposed to stable
259#[ferrocene::annotation("Cannot be covered as it causes an unwinding panic")]
260pub const fn panic_nounwind(expr: &'static str) -> ! {
261    #[cfg(not(feature = "ferrocene_certified"))]
262    panic_nounwind_fmt(fmt::Arguments::new_const(&[expr]), /* force_no_backtrace */ false);
263    #[cfg(feature = "ferrocene_certified")]
264    panic_nounwind_fmt(&expr, /* force_no_backtrace */ false);
265}
266
267/// Like `panic_nounwind`, but also inhibits showing a backtrace.
268#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold)]
269#[cfg_attr(panic = "immediate-abort", inline)]
270#[rustc_nounwind]
271#[cfg(not(feature = "ferrocene_certified"))]
272pub fn panic_nounwind_nobacktrace(expr: &'static str) -> ! {
273    panic_nounwind_fmt(fmt::Arguments::new_const(&[expr]), /* force_no_backtrace */ true);
274}
275
276#[inline]
277#[track_caller]
278#[rustc_diagnostic_item = "unreachable_display"] // needed for `non-fmt-panics` lint
279#[cfg(not(feature = "ferrocene_certified"))]
280pub fn unreachable_display<T: fmt::Display>(x: &T) -> ! {
281    panic_fmt(format_args!("internal error: entered unreachable code: {}", *x));
282}
283
284/// This exists solely for the 2015 edition `panic!` macro to trigger
285/// a lint on `panic!(my_str_variable);`.
286#[inline]
287#[track_caller]
288#[rustc_diagnostic_item = "panic_str_2015"]
289#[rustc_const_stable_indirect] // must follow stable const rules since it is exposed to stable
290#[cfg(not(feature = "ferrocene_certified"))]
291pub const fn panic_str_2015(expr: &str) -> ! {
292    panic_display(&expr);
293}
294
295#[inline]
296#[track_caller]
297#[lang = "panic_display"] // needed for const-evaluated panics
298#[rustc_do_not_const_check] // hooked by const-eval
299#[rustc_const_stable_indirect] // must follow stable const rules since it is exposed to stable
300#[cfg(not(feature = "ferrocene_certified"))]
301pub const fn panic_display<T: fmt::Display>(x: &T) -> ! {
302    panic_fmt(format_args!("{}", *x));
303}
304
305#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
306#[cfg_attr(panic = "immediate-abort", inline)]
307#[track_caller]
308#[lang = "panic_bounds_check"] // needed by codegen for panic on OOB array/slice access
309#[cfg_attr(feature = "ferrocene_certified", expect(unused_variables))]
310fn panic_bounds_check(index: usize, len: usize) -> ! {
311    if cfg!(panic = "immediate-abort") {
312        super::intrinsics::abort()
313    }
314    panic!("index out of bounds: the len is {len} but the index is {index}")
315}
316
317#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
318#[cfg_attr(panic = "immediate-abort", inline)]
319#[track_caller]
320#[lang = "panic_misaligned_pointer_dereference"] // needed by codegen for panic on misaligned pointer deref
321#[rustc_nounwind] // `CheckAlignment` MIR pass requires this function to never unwind
322#[cfg(not(feature = "ferrocene_certified"))]
323fn panic_misaligned_pointer_dereference(required: usize, found: usize) -> ! {
324    if cfg!(panic = "immediate-abort") {
325        super::intrinsics::abort()
326    }
327
328    panic_nounwind_fmt(
329        format_args!(
330            "misaligned pointer dereference: address must be a multiple of {required:#x} but is {found:#x}"
331        ),
332        /* force_no_backtrace */ false,
333    )
334}
335
336#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
337#[cfg_attr(panic = "immediate-abort", inline)]
338#[track_caller]
339#[lang = "panic_null_pointer_dereference"] // needed by codegen for panic on null pointer deref
340#[rustc_nounwind] // `CheckNull` MIR pass requires this function to never unwind
341#[cfg(not(feature = "ferrocene_certified"))]
342fn panic_null_pointer_dereference() -> ! {
343    if cfg!(panic = "immediate-abort") {
344        super::intrinsics::abort()
345    }
346
347    panic_nounwind_fmt(
348        format_args!("null pointer dereference occurred"),
349        /* force_no_backtrace */ false,
350    )
351}
352
353#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
354#[cfg_attr(panic = "immediate-abort", inline)]
355#[track_caller]
356#[lang = "panic_invalid_enum_construction"] // needed by codegen for panic on invalid enum construction.
357#[rustc_nounwind] // `CheckEnums` MIR pass requires this function to never unwind
358#[cfg(not(feature = "ferrocene_certified"))]
359fn panic_invalid_enum_construction(source: u128) -> ! {
360    if cfg!(panic = "immediate-abort") {
361        super::intrinsics::abort()
362    }
363
364    panic_nounwind_fmt(
365        format_args!("trying to construct an enum from an invalid value {source:#x}"),
366        /* force_no_backtrace */ false,
367    )
368}
369
370/// Panics because we cannot unwind out of a function.
371///
372/// This is a separate function to avoid the codesize impact of each crate containing the string to
373/// pass to `panic_nounwind`.
374///
375/// This function is called directly by the codegen backend, and must not have
376/// any extra arguments (including those synthesized by track_caller).
377#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
378#[cfg_attr(panic = "immediate-abort", inline)]
379#[lang = "panic_cannot_unwind"] // needed by codegen for panic in nounwind function
380#[rustc_nounwind]
381#[ferrocene::annotation("Cannot be covered as it causes an unwinding panic")]
382fn panic_cannot_unwind() -> ! {
383    // Keep the text in sync with `UnwindTerminateReason::as_str` in `rustc_middle`.
384    panic_nounwind("panic in a function that cannot unwind")
385}
386
387/// Panics because we are unwinding out of a destructor during cleanup.
388///
389/// This is a separate function to avoid the codesize impact of each crate containing the string to
390/// pass to `panic_nounwind`.
391///
392/// This function is called directly by the codegen backend, and must not have
393/// any extra arguments (including those synthesized by track_caller).
394#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
395#[cfg_attr(panic = "immediate-abort", inline)]
396#[lang = "panic_in_cleanup"] // needed by codegen for panic in nounwind function
397#[rustc_nounwind]
398#[cfg(not(feature = "ferrocene_certified"))]
399fn panic_in_cleanup() -> ! {
400    // Keep the text in sync with `UnwindTerminateReason::as_str` in `rustc_middle`.
401    panic_nounwind_nobacktrace("panic in a destructor during cleanup")
402}
403
404/// This function is used instead of panic_fmt in const eval.
405#[lang = "const_panic_fmt"] // needed by const-eval machine to replace calls to `panic_fmt` lang item
406#[rustc_const_stable_indirect] // must follow stable const rules since it is exposed to stable
407#[cfg(not(feature = "ferrocene_certified"))]
408pub const fn const_panic_fmt(fmt: fmt::Arguments<'_>) -> ! {
409    if let Some(msg) = fmt.as_str() {
410        // The panic_display function is hooked by const eval.
411        panic_display(&msg);
412    } else {
413        // SAFETY: This is only evaluated at compile time, which reliably
414        // handles this UB (in case this branch turns out to be reachable
415        // somehow).
416        unsafe { crate::hint::unreachable_unchecked() };
417    }
418}
419
420#[derive(Debug)]
421#[doc(hidden)]
422#[cfg(not(feature = "ferrocene_certified"))]
423pub enum AssertKind {
424    Eq,
425    Ne,
426    Match,
427}
428
429/// Internal function for `assert_eq!` and `assert_ne!` macros
430#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
431#[cfg_attr(panic = "immediate-abort", inline)]
432#[track_caller]
433#[doc(hidden)]
434#[cfg(not(feature = "ferrocene_certified"))]
435pub fn assert_failed<T, U>(
436    kind: AssertKind,
437    left: &T,
438    right: &U,
439    args: Option<fmt::Arguments<'_>>,
440) -> !
441where
442    T: fmt::Debug + ?Sized,
443    U: fmt::Debug + ?Sized,
444{
445    assert_failed_inner(kind, &left, &right, args)
446}
447
448/// Internal function for `assert_match!`
449#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
450#[cfg_attr(panic = "immediate-abort", inline)]
451#[track_caller]
452#[doc(hidden)]
453#[cfg(not(feature = "ferrocene_certified"))]
454pub fn assert_matches_failed<T: fmt::Debug + ?Sized>(
455    left: &T,
456    right: &str,
457    args: Option<fmt::Arguments<'_>>,
458) -> ! {
459    // The pattern is a string so it can be displayed directly.
460    struct Pattern<'a>(&'a str);
461    impl fmt::Debug for Pattern<'_> {
462        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
463            f.write_str(self.0)
464        }
465    }
466    assert_failed_inner(AssertKind::Match, &left, &Pattern(right), args);
467}
468
469/// Non-generic version of the above functions, to avoid code bloat.
470#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
471#[cfg_attr(panic = "immediate-abort", inline)]
472#[track_caller]
473#[cfg(not(feature = "ferrocene_certified"))]
474fn assert_failed_inner(
475    kind: AssertKind,
476    left: &dyn fmt::Debug,
477    right: &dyn fmt::Debug,
478    args: Option<fmt::Arguments<'_>>,
479) -> ! {
480    let op = match kind {
481        AssertKind::Eq => "==",
482        AssertKind::Ne => "!=",
483        AssertKind::Match => "matches",
484    };
485
486    match args {
487        Some(args) => panic!(
488            r#"assertion `left {op} right` failed: {args}
489  left: {left:?}
490 right: {right:?}"#
491        ),
492        None => panic!(
493            r#"assertion `left {op} right` failed
494  left: {left:?}
495 right: {right:?}"#
496        ),
497    }
498}