Skip to main content

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