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