1 //! Panic support for core
3 //! The core library cannot define panicking, but it does *declare* panicking. This
4 //! means that the functions inside of core are allowed to panic, but to be
5 //! useful an upstream crate must define panicking for core to use. The current
6 //! interface for panicking is:
9 //! fn panic_impl(pi: &core::panic::PanicInfo<'_>) -> !
13 //! This definition allows for panicking with any general message, but it does not
14 //! allow for failing with a `Box<Any>` value. (`PanicInfo` just contains a `&(dyn Any + Send)`,
15 //! for which we fill in a dummy value in `PanicInfo::internal_constructor`.)
16 //! The reason for this is that core is not allowed to allocate.
18 //! This module contains a few other panicking functions, but these are just the
19 //! necessary lang items for the compiler. All panics are funneled through this
20 //! one function. The actual symbol is declared through the `#[panic_handler]` attribute.
22 #![allow(dead_code, missing_docs)]
24 feature = "core_panic",
25 reason = "internal details of the implementation of the `panic!` and related macros",
30 use crate::panic::{Location, PanicInfo};
32 // First we define the two main entry points that all panics go through.
33 // In the end both are just convenience wrappers around `panic_impl`.
35 /// The entry point for panicking with a formatted message.
37 /// This is designed to reduce the amount of code required at the call
38 /// site as much as possible (so that `panic!()` has as low an impact
39 /// on (e.g.) the inlining of other functions as possible), by moving
40 /// the actual formatting into this shared place.
41 // If panic_immediate_abort, inline the abort call,
42 // otherwise avoid inlining because of it is cold path.
43 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)]
44 #[cfg_attr(feature = "panic_immediate_abort", inline)]
46 #[lang = "panic_fmt"] // needed for const-evaluated panics
47 #[rustc_do_not_const_check] // hooked by const-eval
48 #[rustc_const_unstable(feature = "core_panic", issue = "none")]
49 pub const fn panic_fmt(fmt: fmt::Arguments<'_>) -> ! {
50 if cfg!(feature = "panic_immediate_abort") {
51 super::intrinsics::abort()
54 // NOTE This function never crosses the FFI boundary; it's a Rust-to-Rust call
55 // that gets resolved to the `#[panic_handler]` function.
57 #[lang = "panic_impl"]
58 fn panic_impl(pi: &PanicInfo<'_>) -> !;
61 let pi = PanicInfo::internal_constructor(Some(&fmt), Location::caller(), true);
63 // SAFETY: `panic_impl` is defined in safe Rust code and thus is safe to call.
64 unsafe { panic_impl(&pi) }
67 /// Like `panic`, but without unwinding and track_caller to reduce the impact on codesize.
68 /// (No `fmt` variant as a `fmt::Arguments` needs more space to be passed.)
69 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)]
70 #[cfg_attr(feature = "panic_immediate_abort", inline)]
71 #[cfg_attr(not(bootstrap), lang = "panic_nounwind")] // needed by codegen for non-unwinding panics
73 pub fn panic_nounwind(msg: &'static str) -> ! {
74 if cfg!(feature = "panic_immediate_abort") {
75 super::intrinsics::abort()
78 // NOTE This function never crosses the FFI boundary; it's a Rust-to-Rust call
79 // that gets resolved to the `#[panic_handler]` function.
81 #[lang = "panic_impl"]
82 fn panic_impl(pi: &PanicInfo<'_>) -> !;
85 // PanicInfo with the `can_unwind` flag set to false forces an abort.
87 let fmt = fmt::Arguments::new_v1(&pieces, &[]);
88 let pi = PanicInfo::internal_constructor(Some(&fmt), Location::caller(), false);
90 // SAFETY: `panic_impl` is defined in safe Rust code and thus is safe to call.
91 unsafe { panic_impl(&pi) }
94 // Next we define a bunch of higher-level wrappers that all bottom out in the two core functions
97 /// The underlying implementation of core's `panic!` macro when no formatting is used.
98 // never inline unless panic_immediate_abort to avoid code
99 // bloat at the call sites as much as possible
100 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)]
101 #[cfg_attr(feature = "panic_immediate_abort", inline)]
103 #[rustc_const_unstable(feature = "core_panic", issue = "none")]
104 #[lang = "panic"] // needed by codegen for panic on overflow and other `Assert` MIR terminators
105 pub const fn panic(expr: &'static str) -> ! {
106 // Use Arguments::new_v1 instead of format_args!("{expr}") to potentially
107 // reduce size overhead. The format_args! macro uses str's Display trait to
108 // write expr, which calls Formatter::pad, which must accommodate string
109 // truncation and padding (even though none is used here). Using
110 // Arguments::new_v1 may allow the compiler to omit Formatter::pad from the
111 // output binary, saving up to a few kilobytes.
112 panic_fmt(fmt::Arguments::new_v1(&[expr], &[]));
117 #[rustc_diagnostic_item = "panic_str"]
118 #[rustc_const_unstable(feature = "core_panic", issue = "none")]
119 pub const fn panic_str(expr: &str) -> ! {
120 panic_display(&expr);
125 #[rustc_diagnostic_item = "unreachable_display"] // needed for `non-fmt-panics` lint
126 pub fn unreachable_display<T: fmt::Display>(x: &T) -> ! {
127 panic_fmt(format_args!("internal error: entered unreachable code: {}", *x));
132 #[lang = "panic_display"] // needed for const-evaluated panics
133 #[rustc_do_not_const_check] // hooked by const-eval
134 #[rustc_const_unstable(feature = "core_panic", issue = "none")]
135 pub const fn panic_display<T: fmt::Display>(x: &T) -> ! {
136 panic_fmt(format_args!("{}", *x));
139 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)]
140 #[cfg_attr(feature = "panic_immediate_abort", inline)]
142 #[lang = "panic_bounds_check"] // needed by codegen for panic on OOB array/slice access
143 fn panic_bounds_check(index: usize, len: usize) -> ! {
144 if cfg!(feature = "panic_immediate_abort") {
145 super::intrinsics::abort()
148 panic!("index out of bounds: the len is {len} but the index is {index}")
151 /// Panic because we cannot unwind out of a function.
153 /// This function is called directly by the codegen backend, and must not have
154 /// any extra arguments (including those synthesized by track_caller).
155 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)]
156 #[cfg_attr(feature = "panic_immediate_abort", inline)]
157 #[cfg_attr(bootstrap, lang = "panic_no_unwind")] // needed by codegen for panic in nounwind function
158 #[cfg_attr(not(bootstrap), lang = "panic_cannot_unwind")] // needed by codegen for panic in nounwind function
160 fn panic_cannot_unwind() -> ! {
161 panic_nounwind("panic in a function that cannot unwind")
164 /// This function is used instead of panic_fmt in const eval.
165 #[lang = "const_panic_fmt"]
166 #[rustc_const_unstable(feature = "core_panic", issue = "none")]
167 pub const fn const_panic_fmt(fmt: fmt::Arguments<'_>) -> ! {
168 if let Some(msg) = fmt.as_str() {
171 // SAFETY: This is only evaluated at compile time, which reliably
172 // handles this UB (in case this branch turns out to be reachable
174 unsafe { crate::hint::unreachable_unchecked() };
180 pub enum AssertKind {
186 /// Internal function for `assert_eq!` and `assert_ne!` macros
187 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)]
188 #[cfg_attr(feature = "panic_immediate_abort", inline)]
191 pub fn assert_failed<T, U>(
195 args: Option<fmt::Arguments<'_>>,
198 T: fmt::Debug + ?Sized,
199 U: fmt::Debug + ?Sized,
201 assert_failed_inner(kind, &left, &right, args)
204 /// Internal function for `assert_match!`
205 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)]
206 #[cfg_attr(feature = "panic_immediate_abort", inline)]
209 pub fn assert_matches_failed<T: fmt::Debug + ?Sized>(
212 args: Option<fmt::Arguments<'_>>,
214 // The pattern is a string so it can be displayed directly.
215 struct Pattern<'a>(&'a str);
216 impl fmt::Debug for Pattern<'_> {
217 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221 assert_failed_inner(AssertKind::Match, &left, &Pattern(right), args);
224 /// Non-generic version of the above functions, to avoid code bloat.
225 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)]
226 #[cfg_attr(feature = "panic_immediate_abort", inline)]
228 fn assert_failed_inner(
230 left: &dyn fmt::Debug,
231 right: &dyn fmt::Debug,
232 args: Option<fmt::Arguments<'_>>,
234 let op = match kind {
235 AssertKind::Eq => "==",
236 AssertKind::Ne => "!=",
237 AssertKind::Match => "matches",
241 Some(args) => panic!(
242 r#"assertion failed: `(left {} right)`
245 op, left, right, args
248 r#"assertion failed: `(left {} right)`