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