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