1//! Implementation of various bits and pieces of the `panic!` macro and
2//! associated runtime pieces.
3//!
4//! Specifically, this module contains the implementation of:
5//!
6//! * Panic hooks
7//! * Executing a panic up to doing the actual implementation
8//! * Shims around "try"
910#![deny(unsafe_op_in_unsafe_fn)]
1112use alloc::panicking::PanicPayload;
13use core::panic::Location;
1415// make sure to use the stderr output configured
16// by libtest in the real copy of std
17#[cfg(test)]
18use realstd::io::try_set_output_capture;
1920use crate::any::Any;
21#[cfg(not(test))]
22use crate::io::try_set_output_capture;
23use crate::mem::{self, ManuallyDrop};
24use crate::panic::{BacktraceStyle, PanicHookInfo};
25use crate::sync::atomic::{Atomic, AtomicBool, Ordering};
26use crate::sync::nonpoison::RwLock;
27use crate::sys::backtrace;
28use crate::sys::stdio::panic_output;
29use crate::{fmt, intrinsics, process, thread};
3031// This forces codegen of the function called by panic!() inside the std crate, rather than in
32// downstream crates. Primarily this is useful for rustc's codegen tests, which rely on noticing
33// complete removal of panic from generated IR. Since begin_panic is inline(never), it's only
34// codegen'd once per crate-graph so this pushes that to std rather than our codegen test crates.
35//
36// (See https://github.com/rust-lang/rust/pull/123244 for more info on why).
37//
38// If this is causing problems we can also modify those codegen tests to use a crate type like
39// cdylib which doesn't export "Rust" symbols to downstream linkage units.
40#[unstable(feature = "libstd_sys_internals", reason = "used by the panic! macro", issue = "none")]
41#[doc(hidden)]
42#[allow(dead_code)]
43#[used(compiler)]
44pub static EMPTY_PANIC: fn(&'static str) -> ! =
45begin_panic::<&'static str> as fn(&'static str) -> !;
4647// Binary interface to the panic runtime that the standard library depends on.
48//
49// The standard library is tagged with `#![needs_panic_runtime]` (introduced in
50// RFC 1513) to indicate that it requires some other crate tagged with
51// `#![panic_runtime]` to exist somewhere. Each panic runtime is intended to
52// implement these symbols (with the same signatures) so we can get matched up
53// to them.
54//
55// One day this may look a little less ad-hoc with the compiler helping out to
56// hook up these functions, but it is not this day!
57unsafe extern "Rust" {
58#[rustc_std_internal_symbol]
59fn __rust_panic_cleanup(payload: *mut u8) -> Box<dyn Any + Send + 'static>;
6061/// `PanicPayload` lazily performs allocation only when needed (this avoids
62 /// allocations when using the "abort" panic runtime).
63#[rustc_std_internal_symbol]
64safe fn __rust_start_panic(payload: &mut dyn PanicPayload) -> u32;
65}
6667/// This function is called by the panic runtime if FFI code catches a Rust
68/// panic but doesn't rethrow it. We don't support this case since it messes
69/// with our panic count.
70#[cfg(not(test))]
71#[rustc_std_internal_symbol]
72fn __rust_drop_panic() -> ! {
73{
if let Some(mut out) = crate::sys::stdio::panic_output() {
let _ =
crate::io::Write::write_fmt(&mut out,
format_args!("fatal runtime error: {0}, aborting\n",
format_args!("Rust panics must be rethrown")));
};
crate::process::abort();
};rtabort!("Rust panics must be rethrown");
74}
7576/// This function is called by the panic runtime if it catches an exception
77/// object which does not correspond to a Rust panic.
78#[cfg(not(test))]
79#[rustc_std_internal_symbol]
80fn __rust_foreign_exception() -> ! {
81{
if let Some(mut out) = crate::sys::stdio::panic_output() {
let _ =
crate::io::Write::write_fmt(&mut out,
format_args!("fatal runtime error: {0}, aborting\n",
format_args!("Rust cannot catch foreign exceptions")));
};
crate::process::abort();
};rtabort!("Rust cannot catch foreign exceptions");
82}
8384#[derive(#[automatically_derived]
impl ::core::default::Default for Hook {
#[inline]
fn default() -> Hook { Self::Default }
}Default)]
85enum Hook {
86#[default]
87Default,
88 Custom(Box<dyn Fn(&PanicHookInfo<'_>) + 'static + Sync + Send>),
89}
9091impl Hook {
92#[inline]
93fn into_box(self) -> Box<dyn Fn(&PanicHookInfo<'_>) + 'static + Sync + Send> {
94match self {
95 Hook::Default => Box::new(default_hook),
96 Hook::Custom(hook) => hook,
97 }
98 }
99}
100101static HOOK: RwLock<Hook> = RwLock::new(Hook::Default);
102103/// Registers a custom panic hook, replacing the previously registered hook.
104///
105/// The panic hook is invoked when a thread panics, but before the panic runtime
106/// is invoked. As such, the hook will run with both the aborting and unwinding
107/// runtimes.
108///
109/// The default hook, which is registered at startup, prints a message to standard error and
110/// generates a backtrace if requested. This behavior can be customized using the `set_hook` function.
111/// The current hook can be retrieved while reinstating the default hook with the [`take_hook`]
112/// function.
113///
114/// [`take_hook`]: ./fn.take_hook.html
115///
116/// The hook is provided with a `PanicHookInfo` struct which contains information
117/// about the origin of the panic, including the payload passed to `panic!` and
118/// the source code location from which the panic originated.
119///
120/// The panic hook is a global resource.
121///
122/// # Panics
123///
124/// Panics if called from a panicking thread.
125///
126/// # Examples
127///
128/// The following will print "Custom panic hook":
129///
130/// ```should_panic
131/// use std::panic;
132///
133/// panic::set_hook(Box::new(|_| {
134/// println!("Custom panic hook");
135/// }));
136///
137/// panic!("Normal panic");
138/// ```
139#[stable(feature = "panic_hooks", since = "1.10.0")]
140pub fn set_hook(hook: Box<dyn Fn(&PanicHookInfo<'_>) + 'static + Sync + Send>) {
141if thread::panicking() {
142{
::core::panicking::panic_fmt(format_args!("cannot modify the panic hook from a panicking thread"));
};panic!("cannot modify the panic hook from a panicking thread");
143 }
144145// Drop the old hook after changing the hook to avoid deadlocking if its
146 // destructor panics.
147drop(HOOK.replace(Hook::Custom(hook)));
148}
149150/// Unregisters the current panic hook and returns it, registering the default hook
151/// in its place.
152///
153/// *See also the function [`set_hook`].*
154///
155/// [`set_hook`]: ./fn.set_hook.html
156///
157/// If the default hook is registered it will be returned, but remain registered.
158///
159/// # Panics
160///
161/// Panics if called from a panicking thread.
162///
163/// # Examples
164///
165/// The following will print "Normal panic":
166///
167/// ```should_panic
168/// use std::panic;
169///
170/// panic::set_hook(Box::new(|_| {
171/// println!("Custom panic hook");
172/// }));
173///
174/// let _ = panic::take_hook();
175///
176/// panic!("Normal panic");
177/// ```
178#[stable(feature = "panic_hooks", since = "1.10.0")]
179pub fn take_hook() -> Box<dyn Fn(&PanicHookInfo<'_>) + 'static + Sync + Send> {
180if thread::panicking() {
181{
::core::panicking::panic_fmt(format_args!("cannot modify the panic hook from a panicking thread"));
};panic!("cannot modify the panic hook from a panicking thread");
182 }
183184HOOK.replace(Hook::Default).into_box()
185}
186187/// Atomic combination of [`take_hook`] and [`set_hook`]. Use this to replace the panic handler with
188/// a new panic handler that does something and then executes the old handler.
189///
190/// [`take_hook`]: ./fn.take_hook.html
191/// [`set_hook`]: ./fn.set_hook.html
192///
193/// # Panics
194///
195/// Panics if called from a panicking thread.
196///
197/// # Examples
198///
199/// The following will print the custom message, and then the normal output of panic.
200///
201/// ```should_panic
202/// #![feature(panic_update_hook)]
203/// use std::panic;
204///
205/// // Equivalent to
206/// // let prev = panic::take_hook();
207/// // panic::set_hook(Box::new(move |info| {
208/// // println!("...");
209/// // prev(info);
210/// // }));
211/// panic::update_hook(move |prev, info| {
212/// println!("Print custom message and execute panic handler as usual");
213/// prev(info);
214/// });
215///
216/// panic!("Custom and then normal");
217/// ```
218#[unstable(feature = "panic_update_hook", issue = "92649")]
219pub fn update_hook<F>(hook_fn: F)
220where
221F: Fn(&(dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static), &PanicHookInfo<'_>)
222 + Sync223 + Send224 + 'static,
225{
226if thread::panicking() {
227{
::core::panicking::panic_fmt(format_args!("cannot modify the panic hook from a panicking thread"));
};panic!("cannot modify the panic hook from a panicking thread");
228 }
229230let mut hook = HOOK.write();
231let prev = mem::take(&mut *hook).into_box();
232*hook = Hook::Custom(Box::new(move |info| hook_fn(&prev, info)));
233}
234235/// The default panic handler.
236#[optimize(size)]
237fn default_hook(info: &PanicHookInfo<'_>) {
238// If this is a double panic, make sure that we print a backtrace
239 // for this panic. Otherwise only print it if logging is enabled.
240let backtrace = if info.force_no_backtrace() {
241None242 } else if panic_count::get_count() >= 2 {
243BacktraceStyle::full()
244 } else {
245crate::panic::get_backtrace_style()
246 };
247248// The current implementation always returns `Some`.
249let location = info.location().unwrap();
250251let msg = payload_as_str(info.payload());
252253let write = #[optimize(size)]
254|err: &mut dyn crate::io::Write| {
255// Use a lock to prevent mixed output in multithreading context.
256 // Some platforms also require it when printing a backtrace, like `SymFromAddr` on Windows.
257let mut lock = backtrace::lock();
258259 thread::with_current_name(|name| {
260let name = name.unwrap_or("<unnamed>");
261let tid = thread::current_os_id();
262263// Try to write the panic message to a buffer first to prevent other concurrent outputs
264 // interleaving with it.
265let mut buffer = [0u8; 512];
266let mut cursor = crate::io::Cursor::new(&mut buffer[..]);
267268let write_msg = |dst: &mut dyn crate::io::Write| {
269// We add a newline to ensure the panic message appears at the start of a line.
270dst.write_fmt(format_args!("\nthread \'{0}\' ({1}) panicked at {2}:\n{3}\n",
name, tid, location, msg))writeln!(dst, "\nthread '{name}' ({tid}) panicked at {location}:\n{msg}")271 };
272273if write_msg(&mut cursor).is_ok() {
274let pos = cursor.position() as usize;
275let _ = err.write_all(&buffer[0..pos]);
276 } else {
277// The message did not fit into the buffer, write it directly instead.
278let _ = write_msg(err);
279 };
280 });
281282static FIRST_PANIC: Atomic<bool> = AtomicBool::new(true);
283284match backtrace {
285Some(BacktraceStyle::Short) => {
286drop(lock.print(err, crate::backtrace_rs::PrintFmt::Short))
287 }
288Some(BacktraceStyle::Full) => {
289drop(lock.print(err, crate::backtrace_rs::PrintFmt::Full))
290 }
291Some(BacktraceStyle::Off) => {
292if FIRST_PANIC.swap(false, Ordering::Relaxed) {
293let _ = err.write_fmt(format_args!("note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n"))writeln!(
294err,
295"note: run with `RUST_BACKTRACE=1` environment variable to display a \
296 backtrace"
297);
298if falsecfg!(miri) {
299let _ = err.write_fmt(format_args!("note: in Miri, you may have to set `MIRIFLAGS=-Zmiri-env-forward=RUST_BACKTRACE` for the environment variable to have an effect\n"))writeln!(
300err,
301"note: in Miri, you may have to set `MIRIFLAGS=-Zmiri-env-forward=RUST_BACKTRACE` \
302 for the environment variable to have an effect"
303);
304 }
305 }
306 }
307// If backtraces aren't supported or are forced-off, do nothing.
308None => {}
309 }
310 };
311312if let Ok(Some(local)) = try_set_output_capture(None) {
313write(&mut *local.lock().unwrap_or_else(|e| e.into_inner()));
314try_set_output_capture(Some(local)).ok();
315 } else if let Some(mut out) = panic_output() {
316write(&mut out);
317 }
318}
319320#[cfg(not(test))]
321#[doc(hidden)]
322#[cfg(panic = "immediate-abort")]
323#[unstable(feature = "update_panic_count", issue = "none")]
324pub mod panic_count {
325/// A reason for forcing an immediate abort on panic.
326#[derive(Debug)]
327pub enum MustAbort {
328 AlwaysAbort,
329 PanicInHook,
330 }
331332#[inline]
333pub fn increase(run_panic_hook: bool) -> Option<MustAbort> {
334None
335}
336337#[inline]
338pub fn finished_panic_hook() {}
339340#[inline]
341pub fn decrease() {}
342343#[inline]
344pub fn set_always_abort() {}
345346// Disregards ALWAYS_ABORT_FLAG
347#[inline]
348 #[must_use]
349pub fn get_count() -> usize {
3500
351}
352353#[must_use]
354 #[inline]
355pub fn count_is_zero() -> bool {
356true
357}
358}
359360#[cfg(not(test))]
361#[doc(hidden)]
362#[cfg(not(panic = "immediate-abort"))]
363#[unstable(feature = "update_panic_count", issue = "none")]
364pub mod panic_count {
365use crate::cell::Cell;
366use crate::sync::atomic::{Atomic, AtomicUsize, Ordering};
367368const ALWAYS_ABORT_FLAG: usize = 1 << (usize::BITS - 1);
369370/// A reason for forcing an immediate abort on panic.
371#[derive(#[automatically_derived]
impl ::core::fmt::Debug for MustAbort {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
MustAbort::AlwaysAbort => "AlwaysAbort",
MustAbort::PanicInHook => "PanicInHook",
})
}
}Debug)]
372pub enum MustAbort {
373 AlwaysAbort,
374 PanicInHook,
375 }
376377// Panic count for the current thread and whether a panic hook is currently
378 // being executed..
379const LOCAL_PANIC_COUNT: crate::thread::LocalKey<Cell<(usize, bool)>> =
{
const __RUST_STD_INTERNAL_INIT: Cell<(usize, bool)> =
{ Cell::new((0, false)) };
unsafe {
crate::thread::LocalKey::new(const {
if crate::mem::needs_drop::<Cell<(usize, bool)>>() {
|_|
{
#[thread_local]
static __RUST_STD_INTERNAL_VAL:
crate::thread::local_impl::EagerStorage<Cell<(usize, bool)>>
=
crate::thread::local_impl::EagerStorage::new(__RUST_STD_INTERNAL_INIT);
__RUST_STD_INTERNAL_VAL.get()
}
} else {
|_|
{
#[thread_local]
static __RUST_STD_INTERNAL_VAL: Cell<(usize, bool)> =
__RUST_STD_INTERNAL_INIT;
&__RUST_STD_INTERNAL_VAL
}
}
})
}
};thread_local! {
380static LOCAL_PANIC_COUNT: Cell<(usize, bool)> = const { Cell::new((0, false)) }
381 }382383// Sum of panic counts from all threads. The purpose of this is to have
384 // a fast path in `count_is_zero` (which is used by `panicking`). In any particular
385 // thread, if that thread currently views `GLOBAL_PANIC_COUNT` as being zero,
386 // then `LOCAL_PANIC_COUNT` in that thread is zero. This invariant holds before
387 // and after increase and decrease, but not necessarily during their execution.
388 //
389 // Additionally, the top bit of GLOBAL_PANIC_COUNT (GLOBAL_ALWAYS_ABORT_FLAG)
390 // records whether panic::always_abort() has been called. This can only be
391 // set, never cleared.
392 // panic::always_abort() is usually called to prevent memory allocations done by
393 // the panic handling in the child created by `libc::fork`.
394 // Memory allocations performed in a child created with `libc::fork` are undefined
395 // behavior in most operating systems.
396 // Accessing LOCAL_PANIC_COUNT in a child created by `libc::fork` would lead to a memory
397 // allocation. Only GLOBAL_PANIC_COUNT can be accessed in this situation. This is
398 // sufficient because a child process will always have exactly one thread only.
399 // See also #85261 for details.
400 //
401 // This could be viewed as a struct containing a single bit and an n-1-bit
402 // value, but if we wrote it like that it would be more than a single word,
403 // and even a newtype around usize would be clumsy because we need atomics.
404 // But we use such a tuple for the return type of increase().
405 //
406 // Stealing a bit is fine because it just amounts to assuming that each
407 // panicking thread consumes at least 2 bytes of address space.
408static GLOBAL_PANIC_COUNT: Atomic<usize> = AtomicUsize::new(0);
409410// Increases the global and local panic count, and returns whether an
411 // immediate abort is required.
412 //
413 // This also updates thread-local state to keep track of whether a panic
414 // hook is currently executing.
415#[must_use = "MustAbort may not be ignored"]
416pub fn increase(run_panic_hook: bool) -> Option<MustAbort> {
417let global_count = GLOBAL_PANIC_COUNT.fetch_add(1, Ordering::Relaxed);
418if global_count & ALWAYS_ABORT_FLAG != 0 {
419// Do *not* access thread-local state, we might be after a `fork`.
420return Some(MustAbort::AlwaysAbort);
421 }
422423LOCAL_PANIC_COUNT.with(|c| {
424let (count, in_panic_hook) = c.get();
425if in_panic_hook {
426return Some(MustAbort::PanicInHook);
427 }
428c.set((count + 1, run_panic_hook));
429None430 })
431 }
432433pub fn finished_panic_hook() {
434LOCAL_PANIC_COUNT.with(|c| {
435let (count, _) = c.get();
436c.set((count, false));
437 });
438 }
439440pub fn decrease() {
441GLOBAL_PANIC_COUNT.fetch_sub(1, Ordering::Relaxed);
442LOCAL_PANIC_COUNT.with(|c| {
443let (count, _) = c.get();
444c.set((count - 1, false));
445 });
446 }
447448pub fn set_always_abort() {
449GLOBAL_PANIC_COUNT.fetch_or(ALWAYS_ABORT_FLAG, Ordering::Relaxed);
450 }
451452// Disregards ALWAYS_ABORT_FLAG
453#[must_use]
454pub fn get_count() -> usize {
455LOCAL_PANIC_COUNT.with(|c| c.get().0)
456 }
457458// Disregards ALWAYS_ABORT_FLAG
459#[must_use]
460 #[inline]
461pub fn count_is_zero() -> bool {
462if GLOBAL_PANIC_COUNT.load(Ordering::Relaxed) & !ALWAYS_ABORT_FLAG == 0 {
463// Fast path: if `GLOBAL_PANIC_COUNT` is zero, all threads
464 // (including the current one) will have `LOCAL_PANIC_COUNT`
465 // equal to zero, so TLS access can be avoided.
466 //
467 // In terms of performance, a relaxed atomic load is similar to a normal
468 // aligned memory read (e.g., a mov instruction in x86), but with some
469 // compiler optimization restrictions. On the other hand, a TLS access
470 // might require calling a non-inlinable function (such as `__tls_get_addr`
471 // when using the GD TLS model).
472true
473} else {
474is_zero_slow_path()
475 }
476 }
477478// Slow path is in a separate function to reduce the amount of code
479 // inlined from `count_is_zero`.
480#[inline(never)]
481 #[cold]
482fn is_zero_slow_path() -> bool {
483LOCAL_PANIC_COUNT.with(|c| c.get().0 == 0)
484 }
485}
486487#[cfg(test)]
488pub use realstd::rt::panic_count;
489490/// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
491#[cfg(panic = "immediate-abort")]
492pub unsafe fn catch_unwind<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>> {
493Ok(f())
494}
495496/// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
497#[cfg(not(panic = "immediate-abort"))]
498pub unsafe fn catch_unwind<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>> {
499union Data<F, R> {
500 f: ManuallyDrop<F>,
501 r: ManuallyDrop<R>,
502 p: ManuallyDrop<Box<dyn Any + Send>>,
503 }
504505// We do some sketchy operations with ownership here for the sake of
506 // performance. We can only pass pointers down to `do_call` (can't pass
507 // objects by value), so we do all the ownership tracking here manually
508 // using a union.
509 //
510 // We go through a transition where:
511 //
512 // * First, we set the data field `f` to be the argumentless closure that we're going to call.
513 // * When we make the function call, the `do_call` function below, we take
514 // ownership of the function pointer. At this point the `data` union is
515 // entirely uninitialized.
516 // * If the closure successfully returns, we write the return value into the
517 // data's return slot (field `r`).
518 // * If the closure panics (`do_catch` below), we write the panic payload into field `p`.
519 // * Finally, when we come back out of the `try` intrinsic we're
520 // in one of two states:
521 //
522 // 1. The closure didn't panic, in which case the return value was
523 // filled in. We move it out of `data.r` and return it.
524 // 2. The closure panicked, in which case the panic payload was
525 // filled in. We move it out of `data.p` and return it.
526 //
527 // Once we stack all that together we should have the "most efficient'
528 // method of calling a catch panic whilst juggling ownership.
529let mut data = Data { f: ManuallyDrop::new(f) };
530531// SAFETY:
532 //
533 // Access to the union's fields: this is `std` and we know that the `catch_unwind`
534 // intrinsic fills in the `r` or `p` union field based on its return value.
535 //
536 // The call to `intrinsics::catch_unwind` is made safe by:
537 // - `do_call`, the first argument, can be called with the initial `data_ptr`.
538 // - `do_catch`, the second argument, can be called with the `data_ptr` as well.
539 // See their safety preconditions for more information
540unsafe {
541return if intrinsics::catch_unwind(do_call, &raw mut data, do_catch) {
542Err(ManuallyDrop::into_inner(data.p))
543 } else {
544Ok(ManuallyDrop::into_inner(data.r))
545 };
546 }
547548// We consider unwinding to be rare, so mark this function as cold. However,
549 // do not mark it no-inline -- that decision is best to leave to the
550 // optimizer (in most cases this function is not inlined even as a normal,
551 // non-cold function, though, as of the writing of this comment).
552#[cold]
553 #[optimize(size)]
554unsafe fn cleanup(payload: *mut u8) -> Box<dyn Any + Send + 'static> {
555// SAFETY: The whole unsafe block hinges on a correct implementation of
556 // the panic handler `__rust_panic_cleanup`. As such we can only
557 // assume it returns the correct thing for `Box::from_raw` to work
558 // without undefined behavior.
559let obj = unsafe { __rust_panic_cleanup(payload) };
560 panic_count::decrease();
561obj562 }
563564// SAFETY:
565 // data must be non-NUL, correctly aligned, and a pointer to a `Data<F, R>`
566 // Its must contains a valid `f` (type: F) value that can be use to fill
567 // `data.r`.
568#[inline]
569unsafe fn do_call<F: FnOnce() -> R, R>(data: *mut Data<F, R>) {
570// SAFETY: this is the responsibility of the caller, see above.
571unsafe {
572let f = ManuallyDrop::take(&mut (*data).f);
573 (*data).r = ManuallyDrop::new(f());
574 }
575 }
576577// We *do* want this part of the catch to be inlined: this allows the
578 // compiler to properly track accesses to the Data union and optimize it
579 // away most of the time.
580 //
581 // SAFETY:
582 // data must be non-NUL, correctly aligned, and a pointer to a `Data<F, R>`
583 // Since this uses `cleanup` it also hinges on a correct implementation of
584 // `__rustc_panic_cleanup`.
585#[inline]
586 #[rustc_nounwind] // `intrinsic::catch_unwind` requires catch fn to be nounwind
587unsafe fn do_catch<F: FnOnce() -> R, R>(data: *mut Data<F, R>, payload: *mut u8) {
588// SAFETY: this is the responsibility of the caller, see above.
589 //
590 // When `__rustc_panic_cleaner` is correctly implemented we can rely
591 // on `obj` being the correct thing to pass to `data.p` (after wrapping
592 // in `ManuallyDrop`).
593unsafe {
594let obj = cleanup(payload);
595 (*data).p = ManuallyDrop::new(obj);
596 }
597 }
598}
599600/// Determines whether the current thread is unwinding because of panic.
601#[inline]
602pub fn panicking() -> bool {
603 !panic_count::count_is_zero()
604}
605606/// Entry point of panics from the core crate (`panic_impl` lang item).
607#[cfg(not(any(test, doctest)))]
608#[panic_handler]
609pub fn panic_handler(info: &core::panic::PanicInfo<'_>) -> ! {
610struct FormatStringPayload<'a> {
611 inner: &'a core::panic::PanicMessage<'a>,
612 string: Option<String>,
613 }
614615impl FormatStringPayload<'_> {
616fn fill(&mut self) -> &mut String {
617let inner = self.inner;
618// Lazily, the first time this gets called, run the actual string formatting.
619self.string.get_or_insert_with(|| {
620let mut s = String::new();
621let mut fmt = fmt::Formatter::new(&mut s, fmt::FormattingOptions::new());
622let _err = fmt::Display::fmt(&inner, &mut fmt);
623s624 })
625 }
626 }
627628impl PanicPayloadfor FormatStringPayload<'_> {
629fn take_box(&mut self) -> Box<dyn Any + Send> {
630// We do two allocations here, unfortunately. But (a) they're required with the current
631 // scheme, and (b) we don't handle panic + OOM properly anyway (see comment in
632 // begin_panic below).
633let contents = mem::take(self.fill());
634Box::new(contents)
635 }
636637fn get(&mut self) -> &(dyn Any + Send) {
638self.fill()
639 }
640 }
641642impl fmt::Displayfor FormatStringPayload<'_> {
643fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
644if let Some(s) = &self.string {
645f.write_str(s)
646 } else {
647 fmt::Display::fmt(&self.inner, f)
648 }
649 }
650 }
651652struct StaticStrPayload(&'static str);
653654impl PanicPayloadfor StaticStrPayload {
655fn take_box(&mut self) -> Box<dyn Any + Send> {
656Box::new(self.0)
657 }
658659fn get(&mut self) -> &(dyn Any + Send) {
660&self.0
661}
662663fn as_str(&mut self) -> Option<&str> {
664Some(self.0)
665 }
666 }
667668impl fmt::Displayfor StaticStrPayload {
669fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
670f.write_str(self.0)
671 }
672 }
673674let loc = info.location().unwrap(); // The current implementation always returns Some
675let msg = info.message();
676crate::sys::backtrace::__rust_end_short_backtrace(move || {
677if let Some(s) = msg.as_str() {
678panic_with_hook(
679&mut StaticStrPayload(s),
680loc,
681info.can_unwind(),
682info.force_no_backtrace(),
683 );
684 } else {
685panic_with_hook(
686&mut FormatStringPayload { inner: &msg, string: None },
687loc,
688info.can_unwind(),
689info.force_no_backtrace(),
690 );
691 }
692 })
693}
694695/// This is the entry point of panicking for the non-format-string variants of
696/// panic!() and assert!(). In particular, this is the only entry point that supports
697/// arbitrary payloads, not just format strings.
698#[unstable(feature = "libstd_sys_internals", reason = "used by the panic! macro", issue = "none")]
699#[cfg_attr(not(any(test, doctest)), lang = "begin_panic")]
700// lang item for CTFE panic support
701// never inline unless panic=immediate-abort to avoid code
702// bloat at the call sites as much as possible
703#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
704#[cfg_attr(panic = "immediate-abort", inline)]
705#[track_caller]
706#[rustc_do_not_const_check] // hooked by const-eval
707pub const fn begin_panic<M: Any + Send>(msg: M) -> ! {
708if falsecfg!(panic = "immediate-abort") {
709 intrinsics::abort()
710 }
711712struct Payload<A> {
713 inner: Option<A>,
714 }
715716impl<A: Send + 'static> PanicPayloadfor Payload<A> {
717fn take_box(&mut self) -> Box<dyn Any + Send> {
718// Note that this should be the only allocation performed in this code path. Currently
719 // this means that panic!() on OOM will invoke this code path, but then again we're not
720 // really ready for panic on OOM anyway. If we do start doing this, then we should
721 // propagate this allocation to be performed in the parent of this thread instead of the
722 // thread that's panicking.
723match self.inner.take() {
724Some(a) => Box::new(a) as Box<dyn Any + Send>,
725None => process::abort(),
726 }
727 }
728729fn get(&mut self) -> &(dyn Any + Send) {
730match self.inner {
731Some(ref a) => a,
732None => process::abort(),
733 }
734 }
735 }
736737impl<A: 'static> fmt::Displayfor Payload<A> {
738fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
739match &self.inner {
740Some(a) => f.write_str(payload_as_str(a)),
741None => process::abort(),
742 }
743 }
744 }
745746let loc = Location::caller();
747crate::sys::backtrace::__rust_end_short_backtrace(move || {
748panic_with_hook(
749&mut Payload { inner: Some(msg) },
750loc,
751/* can_unwind */ true,
752/* force_no_backtrace */ false,
753 )
754 })
755}
756757fn payload_as_str(payload: &dyn Any) -> &str {
758if let Some(&s) = payload.downcast_ref::<&'static str>() {
759s760 } else if let Some(s) = payload.downcast_ref::<String>() {
761s.as_str()
762 } else {
763"Box<dyn Any>"
764}
765}
766767/// Central point for dispatching panics.
768///
769/// Executes the primary logic for a panic, including checking for recursive
770/// panics, panic hooks, and finally dispatching to the panic runtime to either
771/// abort or unwind.
772#[optimize(size)]
773fn panic_with_hook(
774 payload: &mut dyn PanicPayload,
775 location: &'static Location<'static>,
776 can_unwind: bool,
777 force_no_backtrace: bool,
778) -> ! {
779let must_abort = panic_count::increase(true);
780781// Check if we need to abort immediately.
782if let Some(must_abort) = must_abort {
783match must_abort {
784 panic_count::MustAbort::PanicInHook => {
785// Don't try to format the message in this case, perhaps that is causing the
786 // recursive panics. However if the message is just a string, no user-defined
787 // code is involved in printing it, so that is risk-free.
788let message: &str = payload.as_str().unwrap_or_default();
789if let Some(mut out) = crate::sys::stdio::panic_output() {
let _ =
crate::io::Write::write_fmt(&mut out,
format_args!("panicked at {0}:\n{1}\nthread panicked while processing panic. aborting.\n",
location, message));
};rtprintpanic!(
790"panicked at {location}:\n{message}\nthread panicked while processing panic. aborting.\n"
791);
792 }
793 panic_count::MustAbort::AlwaysAbort => {
794// Unfortunately, this does not print a backtrace, because creating
795 // a `Backtrace` will allocate, which we must avoid here.
796if let Some(mut out) = crate::sys::stdio::panic_output() {
let _ =
crate::io::Write::write_fmt(&mut out,
format_args!("aborting due to panic at {0}:\n{1}\n", location,
payload));
};rtprintpanic!("aborting due to panic at {location}:\n{payload}\n");
797 }
798 }
799crate::process::abort();
800 }
801802match *HOOK.read() {
803// Some platforms (like wasm) know that printing to stderr won't ever actually
804 // print anything, and if that's the case we can skip the default
805 // hook. Since string formatting happens lazily when calling `payload`
806 // methods, this means we avoid formatting the string at all!
807 // (The panic runtime might still call `payload.take_box()` though and trigger
808 // formatting.)
809Hook::Defaultif panic_output().is_none() => {}
810 Hook::Default => {
811default_hook(&PanicHookInfo::new(
812location,
813payload.get(),
814can_unwind,
815force_no_backtrace,
816 ));
817 }
818 Hook::Custom(ref hook) => {
819hook(&PanicHookInfo::new(location, payload.get(), can_unwind, force_no_backtrace));
820 }
821 }
822823// Indicate that we have finished executing the panic hook. After this point
824 // it is fine if there is a panic while executing destructors, as long as it
825 // it contained within a `catch_unwind`.
826panic_count::finished_panic_hook();
827828if !can_unwind {
829// If a thread panics while running destructors or tries to unwind
830 // through a nounwind function (e.g. extern "C") then we cannot continue
831 // unwinding and have to abort immediately.
832if let Some(mut out) = crate::sys::stdio::panic_output() {
let _ =
crate::io::Write::write_fmt(&mut out,
format_args!("thread caused non-unwinding panic. aborting.\n"));
};rtprintpanic!("thread caused non-unwinding panic. aborting.\n");
833crate::process::abort();
834 }
835836rust_panic(payload)
837}
838839/// This is the entry point for `resume_unwind`.
840/// It just forwards the payload to the panic runtime.
841#[cfg_attr(panic = "immediate-abort", inline)]
842pub fn resume_unwind(payload: Box<dyn Any + Send>) -> ! {
843if let Some(must_abort) = panic_count::increase(false) {
844match must_abort {
845 panic_count::MustAbort::PanicInHook => {
846if let Some(mut out) = crate::sys::stdio::panic_output() {
let _ =
crate::io::Write::write_fmt(&mut out,
format_args!("thread panicked while processing panic. aborting.\n"));
};rtprintpanic!("thread panicked while processing panic. aborting.\n");
847 }
848 panic_count::MustAbort::AlwaysAbort => {
849if let Some(mut out) = crate::sys::stdio::panic_output() {
let _ =
crate::io::Write::write_fmt(&mut out,
format_args!("aborting due to panic\n"));
};rtprintpanic!("aborting due to panic\n");
850 }
851 }
852853crate::process::abort();
854 }
855856struct RewrapBox(Box<dyn Any + Send>);
857858impl PanicPayloadfor RewrapBox {
859fn take_box(&mut self) -> Box<dyn Any + Send> {
860 mem::replace(&mut self.0, Box::new(()))
861 }
862863fn get(&mut self) -> &(dyn Any + Send) {
864&*self.0
865}
866 }
867868impl fmt::Displayfor RewrapBox {
869fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
870f.write_str(payload_as_str(&self.0))
871 }
872 }
873874rust_panic(&mut RewrapBox(payload))
875}
876877/// A function with a fixed suffix (through `rustc_std_internal_symbol`)
878/// on which to slap yer breakpoints.
879#[inline(never)]
880#[cfg_attr(not(test), rustc_std_internal_symbol)]
881#[cfg(not(panic = "immediate-abort"))]
882fn rust_panic(msg: &mut dyn PanicPayload) -> ! {
883let code = __rust_start_panic(msg);
884{
if let Some(mut out) = crate::sys::stdio::panic_output() {
let _ =
crate::io::Write::write_fmt(&mut out,
format_args!("fatal runtime error: {0}, aborting\n",
format_args!("failed to initiate panic, error {0}", code)));
};
crate::process::abort();
}rtabort!("failed to initiate panic, error {code}")885}
886887#[cfg_attr(not(test), rustc_std_internal_symbol)]
888#[cfg(panic = "immediate-abort")]
889fn rust_panic(_: &mut dyn PanicPayload) -> ! {
890crate::intrinsics::abort();
891}