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