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    In both cases, you still need to build core, e.g. with `-Zbuild-std`"
51);
52
53// First we define the two main entry points that all panics go through.
54// In the end both are just convenience wrappers around `panic_impl`.
55
56/// The entry point for panicking with a formatted message.
57///
58/// This is designed to reduce the amount of code required at the call
59/// site as much as possible (so that `panic!()` has as low an impact
60/// on (e.g.) the inlining of other functions as possible), by moving
61/// the actual formatting into this shared place.
62// If panic=immediate-abort, inline the abort call,
63// otherwise avoid inlining because of it is cold path.
64#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold)]
65#[cfg_attr(panic = "immediate-abort", inline)]
66#[track_caller]
67#[lang = "panic_fmt"] // needed for const-evaluated panics
68#[rustc_do_not_const_check] // hooked by const-eval
69#[rustc_const_stable_indirect] // must follow stable const rules since it is exposed to stable
70// Ferrocene change: `fmt` is a type alias to accomodate certified core
71pub const fn panic_fmt(fmt: PanicFmt<'_>) -> ! {
72    // Ferrocene annotation: The `immediate-abort` behavior is not certified, we only support
73    // `abort`.
74    if cfg!(panic = "immediate-abort") {
75        super::intrinsics::abort()
76    }
77
78    // NOTE This function never crosses the FFI boundary; it's a Rust-to-Rust call
79    // that gets resolved to the `#[panic_handler]` function.
80    unsafe extern "Rust" {
81        #[lang = "panic_impl"]
82        fn panic_impl(pi: &PanicInfo<'_>) -> !;
83    }
84
85    #[cfg(not(feature = "ferrocene_certified"))]
86    let pi = PanicInfo::new(
87        &fmt,
88        Location::caller(),
89        /* can_unwind */ true,
90        /* force_no_backtrace */ false,
91    );
92    #[cfg(feature = "ferrocene_certified")]
93    let pi = PanicInfo::new(&fmt);
94    // SAFETY: `panic_impl` is defined in safe Rust code and thus is safe to call.
95    unsafe { panic_impl(&pi) }
96}
97
98/// Like `panic_fmt`, but for non-unwinding panics.
99///
100/// Has to be a separate function so that it can carry the `rustc_nounwind` attribute.
101#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold)]
102#[cfg_attr(panic = "immediate-abort", inline)]
103#[track_caller]
104// This attribute has the key side-effect that if the panic handler ignores `can_unwind`
105// and unwinds anyway, we will hit the "unwinding out of nounwind function" guard,
106// which causes a "panic in a function that cannot unwind".
107#[rustc_nounwind]
108#[rustc_const_stable_indirect] // must follow stable const rules since it is exposed to stable
109#[rustc_allow_const_fn_unstable(const_eval_select)]
110pub const fn panic_nounwind_fmt(fmt: PanicFmt<'_>, _force_no_backtrace: bool) -> ! {
111    // Ferrocene annotation: Cannot be covered as it causes an unwinding panic.
112
113    const_eval_select!(
114        @capture { fmt: PanicFmt<'_>, _force_no_backtrace: bool } -> !:
115        if const #[track_caller] {
116            // We don't unwind anyway at compile-time so we can call the regular `panic_fmt`.
117            panic_fmt(fmt)
118        } else #[track_caller] {
119            if cfg!(panic = "immediate-abort") {
120                super::intrinsics::abort()
121            }
122
123            // NOTE This function never crosses the FFI boundary; it's a Rust-to-Rust call
124            // that gets resolved to the `#[panic_handler]` function.
125            unsafe extern "Rust" {
126                #[lang = "panic_impl"]
127                fn panic_impl(pi: &PanicInfo<'_>) -> !;
128            }
129
130            // PanicInfo with the `can_unwind` flag set to false forces an abort.
131            #[cfg(not(feature = "ferrocene_certified"))]
132            let pi = PanicInfo::new(
133                &fmt,
134                Location::caller(),
135                /* can_unwind */ false,
136                _force_no_backtrace,
137            );
138            #[cfg(feature = "ferrocene_certified")]
139            let pi = PanicInfo::new(&fmt);
140
141            // SAFETY: `panic_impl` is defined in safe Rust code and thus is safe to call.
142            unsafe { panic_impl(&pi) }
143        }
144    )
145}
146
147// Next we define a bunch of higher-level wrappers that all bottom out in the two core functions
148// above.
149
150/// The underlying implementation of core's `panic!` macro when no formatting is used.
151// Never inline unless panic=immediate-abort to avoid code
152// bloat at the call sites as much as possible.
153#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold)]
154#[cfg_attr(panic = "immediate-abort", inline)]
155#[track_caller]
156#[rustc_const_stable_indirect] // must follow stable const rules since it is exposed to stable
157#[lang = "panic"] // used by lints and miri for panics
158pub const fn panic(expr: &'static str) -> ! {
159    // Use Arguments::new_const instead of format_args!("{expr}") to potentially
160    // reduce size overhead. The format_args! macro uses str's Display trait to
161    // write expr, which calls Formatter::pad, which must accommodate string
162    // truncation and padding (even though none is used here). Using
163    // Arguments::new_const may allow the compiler to omit Formatter::pad from the
164    // output binary, saving up to a few kilobytes.
165    // However, this optimization only works for `'static` strings: `new_const` also makes this
166    // message return `Some` from `Arguments::as_str`, which means it can become part of the panic
167    // payload without any allocation or copying. Shorter-lived strings would become invalid as
168    // stack frames get popped during unwinding, and couldn't be directly referenced from the
169    // payload.
170    #[cfg(not(feature = "ferrocene_certified"))]
171    panic_fmt(fmt::Arguments::new_const(&[expr]));
172    #[cfg(feature = "ferrocene_certified")]
173    panic_fmt(&expr)
174}
175
176// We generate functions for usage by compiler-generated assertions.
177//
178// Placing these functions in libcore means that all Rust programs can generate a jump into this
179// code rather than expanding to panic("...") above, which adds extra bloat to call sites (for the
180// constant string argument's pointer and length).
181//
182// This is especially important when this code is called often (e.g., with -Coverflow-checks) for
183// reducing binary size impact.
184#[cfg(not(feature = "ferrocene_certified"))]
185macro_rules! panic_const {
186    ($($lang:ident = $message:expr,)+) => {
187        $(
188            /// This is a panic called with a message that's a result of a MIR-produced Assert.
189            //
190            // never inline unless panic=immediate-abort to avoid code
191            // bloat at the call sites as much as possible
192            #[cfg_attr(not(panic = "immediate-abort"), inline(never), cold)]
193            #[cfg_attr(panic = "immediate-abort", inline)]
194            #[track_caller]
195            #[rustc_const_stable_indirect] // must follow stable const rules since it is exposed to stable
196            #[lang = stringify!($lang)]
197            pub const fn $lang() -> ! {
198                // Use Arguments::new_const instead of format_args!("{expr}") to potentially
199                // reduce size overhead. The format_args! macro uses str's Display trait to
200                // write expr, which calls Formatter::pad, which must accommodate string
201                // truncation and padding (even though none is used here). Using
202                // Arguments::new_const may allow the compiler to omit Formatter::pad from the
203                // output binary, saving up to a few kilobytes.
204                panic_fmt(fmt::Arguments::new_const(&[$message]));
205            }
206        )+
207    }
208}
209
210// Unfortunately this set of strings is replicated here and in a few places in the compiler in
211// slightly different forms. It's not clear if there's a good way to deduplicate without adding
212// special cases to the compiler (e.g., a const generic function wouldn't have a single definition
213// shared across crates, which is exactly what we want here).
214#[cfg(not(feature = "ferrocene_certified"))]
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
254pub const fn panic_nounwind(expr: &'static str) -> ! {
255    // Ferrocene annotation: Cannot be covered as it causes an unwinding panic.
256    #[cfg(not(feature = "ferrocene_certified"))]
257    panic_nounwind_fmt(fmt::Arguments::new_const(&[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::new_const(&[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(not(feature = "ferrocene_certified"))]
305fn panic_bounds_check(index: usize, len: usize) -> ! {
306    if cfg!(panic = "immediate-abort") {
307        super::intrinsics::abort()
308    }
309
310    panic!("index out of bounds: the len is {len} but the index is {index}")
311}
312
313#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
314#[cfg_attr(panic = "immediate-abort", inline)]
315#[track_caller]
316#[lang = "panic_misaligned_pointer_dereference"] // needed by codegen for panic on misaligned pointer deref
317#[rustc_nounwind] // `CheckAlignment` MIR pass requires this function to never unwind
318#[cfg(not(feature = "ferrocene_certified"))]
319fn panic_misaligned_pointer_dereference(required: usize, found: usize) -> ! {
320    if cfg!(panic = "immediate-abort") {
321        super::intrinsics::abort()
322    }
323
324    panic_nounwind_fmt(
325        format_args!(
326            "misaligned pointer dereference: address must be a multiple of {required:#x} but is {found:#x}"
327        ),
328        /* force_no_backtrace */ false,
329    )
330}
331
332#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
333#[cfg_attr(panic = "immediate-abort", inline)]
334#[track_caller]
335#[lang = "panic_null_pointer_dereference"] // needed by codegen for panic on null pointer deref
336#[rustc_nounwind] // `CheckNull` MIR pass requires this function to never unwind
337#[cfg(not(feature = "ferrocene_certified"))]
338fn panic_null_pointer_dereference() -> ! {
339    if cfg!(panic = "immediate-abort") {
340        super::intrinsics::abort()
341    }
342
343    panic_nounwind_fmt(
344        format_args!("null pointer dereference occurred"),
345        /* force_no_backtrace */ false,
346    )
347}
348
349#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
350#[cfg_attr(panic = "immediate-abort", inline)]
351#[track_caller]
352#[lang = "panic_invalid_enum_construction"] // needed by codegen for panic on invalid enum construction.
353#[rustc_nounwind] // `CheckEnums` MIR pass requires this function to never unwind
354#[cfg(not(feature = "ferrocene_certified"))]
355fn panic_invalid_enum_construction(source: u128) -> ! {
356    if cfg!(panic = "immediate-abort") {
357        super::intrinsics::abort()
358    }
359
360    panic_nounwind_fmt(
361        format_args!("trying to construct an enum from an invalid value {source:#x}"),
362        /* force_no_backtrace */ false,
363    )
364}
365
366/// Panics because we cannot unwind out of a function.
367///
368/// This is a separate function to avoid the codesize impact of each crate containing the string to
369/// pass to `panic_nounwind`.
370///
371/// This function is called directly by the codegen backend, and must not have
372/// any extra arguments (including those synthesized by track_caller).
373#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
374#[cfg_attr(panic = "immediate-abort", inline)]
375#[lang = "panic_cannot_unwind"] // needed by codegen for panic in nounwind function
376#[rustc_nounwind]
377fn panic_cannot_unwind() -> ! {
378    // Ferrocene annotation: Cannot be covered as it causes an unwinding panic.
379    //
380    // Not part of annotation:
381    // Keep the text in sync with `UnwindTerminateReason::as_str` in `rustc_middle`.
382    panic_nounwind("panic in a function that cannot unwind")
383}
384
385/// Panics because we are unwinding out of a destructor during cleanup.
386///
387/// This is a separate function to avoid the codesize impact of each crate containing the string to
388/// pass to `panic_nounwind`.
389///
390/// This function is called directly by the codegen backend, and must not have
391/// any extra arguments (including those synthesized by track_caller).
392#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
393#[cfg_attr(panic = "immediate-abort", inline)]
394#[lang = "panic_in_cleanup"] // needed by codegen for panic in nounwind function
395#[rustc_nounwind]
396#[cfg(not(feature = "ferrocene_certified"))]
397fn panic_in_cleanup() -> ! {
398    // Keep the text in sync with `UnwindTerminateReason::as_str` in `rustc_middle`.
399    panic_nounwind_nobacktrace("panic in a destructor during cleanup")
400}
401
402/// This function is used instead of panic_fmt in const eval.
403#[lang = "const_panic_fmt"] // needed by const-eval machine to replace calls to `panic_fmt` lang item
404#[rustc_const_stable_indirect] // must follow stable const rules since it is exposed to stable
405#[cfg(not(feature = "ferrocene_certified"))]
406pub const fn const_panic_fmt(fmt: fmt::Arguments<'_>) -> ! {
407    if let Some(msg) = fmt.as_str() {
408        // The panic_display function is hooked by const eval.
409        panic_display(&msg);
410    } else {
411        // SAFETY: This is only evaluated at compile time, which reliably
412        // handles this UB (in case this branch turns out to be reachable
413        // somehow).
414        unsafe { crate::hint::unreachable_unchecked() };
415    }
416}
417
418#[derive(Debug)]
419#[doc(hidden)]
420#[cfg(not(feature = "ferrocene_certified"))]
421pub enum AssertKind {
422    Eq,
423    Ne,
424    Match,
425}
426
427/// Internal function for `assert_eq!` and `assert_ne!` macros
428#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
429#[cfg_attr(panic = "immediate-abort", inline)]
430#[track_caller]
431#[doc(hidden)]
432#[cfg(not(feature = "ferrocene_certified"))]
433pub fn assert_failed<T, U>(
434    kind: AssertKind,
435    left: &T,
436    right: &U,
437    args: Option<fmt::Arguments<'_>>,
438) -> !
439where
440    T: fmt::Debug + ?Sized,
441    U: fmt::Debug + ?Sized,
442{
443    assert_failed_inner(kind, &left, &right, args)
444}
445
446/// Internal function for `assert_match!`
447#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
448#[cfg_attr(panic = "immediate-abort", inline)]
449#[track_caller]
450#[doc(hidden)]
451#[cfg(not(feature = "ferrocene_certified"))]
452pub fn assert_matches_failed<T: fmt::Debug + ?Sized>(
453    left: &T,
454    right: &str,
455    args: Option<fmt::Arguments<'_>>,
456) -> ! {
457    // The pattern is a string so it can be displayed directly.
458    struct Pattern<'a>(&'a str);
459    impl fmt::Debug for Pattern<'_> {
460        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
461            f.write_str(self.0)
462        }
463    }
464    assert_failed_inner(AssertKind::Match, &left, &Pattern(right), args);
465}
466
467/// Non-generic version of the above functions, to avoid code bloat.
468#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
469#[cfg_attr(panic = "immediate-abort", inline)]
470#[track_caller]
471#[cfg(not(feature = "ferrocene_certified"))]
472fn assert_failed_inner(
473    kind: AssertKind,
474    left: &dyn fmt::Debug,
475    right: &dyn fmt::Debug,
476    args: Option<fmt::Arguments<'_>>,
477) -> ! {
478    let op = match kind {
479        AssertKind::Eq => "==",
480        AssertKind::Ne => "!=",
481        AssertKind::Match => "matches",
482    };
483
484    match args {
485        Some(args) => panic!(
486            r#"assertion `left {op} right` failed: {args}
487  left: {left:?}
488 right: {right:?}"#
489        ),
490        None => panic!(
491            r#"assertion `left {op} right` failed
492  left: {left:?}
493 right: {right:?}"#
494        ),
495    }
496}