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 core::panic::{Location, PanicPayload};
1314// make sure to use the stderr output configured
15// by libtest in the real copy of std
16#[cfg(test)]
17use realstd::io::try_set_output_capture;
1819use crate::any::Any;
20#[cfg(not(test))]
21use crate::io::try_set_output_capture;
22use crate::mem::{self, ManuallyDrop};
23use crate::panic::{BacktraceStyle, PanicHookInfo};
24use crate::sync::atomic::{Atomic, AtomicBool, Ordering};
25use crate::sync::nonpoison::RwLock;
26use crate::sys::backtrace;
27use crate::sys::stdio::panic_output;
28use crate::{fmt, intrinsics, process, thread};
2930// This forces codegen of the function called by panic!() inside the std crate, rather than in
31// downstream crates. Primarily this is useful for rustc's codegen tests, which rely on noticing
32// complete removal of panic from generated IR. Since begin_panic is inline(never), it's only
33// codegen'd once per crate-graph so this pushes that to std rather than our codegen test crates.
34//
35// (See https://github.com/rust-lang/rust/pull/123244 for more info on why).
36//
37// If this is causing problems we can also modify those codegen tests to use a crate type like
38// cdylib which doesn't export "Rust" symbols to downstream linkage units.
39#[unstable(feature = "libstd_sys_internals", reason = "used by the panic! macro", issue = "none")]
40#[doc(hidden)]
41#[allow(dead_code)]
42#[used(compiler)]
43pub static EMPTY_PANIC: fn(&'static str) -> ! =
44begin_panic::<&'static str> as fn(&'static str) -> !;
4546// Binary interface to the panic runtime that the standard library depends on.
47//
48// The standard library is tagged with `#![needs_panic_runtime]` (introduced in
49// RFC 1513) to indicate that it requires some other crate tagged with
50// `#![panic_runtime]` to exist somewhere. Each panic runtime is intended to
51// implement these symbols (with the same signatures) so we can get matched up
52// to them.
53//
54// One day this may look a little less ad-hoc with the compiler helping out to
55// hook up these functions, but it is not this day!
56#[allow(improper_ctypes)]
57unsafe extern "C" {
58#[rustc_std_internal_symbol]
59fn __rust_panic_cleanup(payload: *mut u8) -> *mut (dyn Any + Send + 'static);
60}
6162unsafe extern "Rust" {
63/// `PanicPayload` lazily performs allocation only when needed (this avoids
64 /// allocations when using the "abort" panic runtime).
65#[rustc_std_internal_symbol]
66fn __rust_start_panic(payload: &mut dyn PanicPayload) -> u32;
67}
6869/// This function is called by the panic runtime if FFI code catches a Rust
70/// panic but doesn't rethrow it. We don't support this case since it messes
71/// with our panic count.
72#[cfg(not(test))]
73#[rustc_std_internal_symbol]
74extern "C" fn __rust_drop_panic() -> ! {
75{
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");
76}
7778/// This function is called by the panic runtime if it catches an exception
79/// object which does not correspond to a Rust panic.
80#[cfg(not(test))]
81#[rustc_std_internal_symbol]
82extern "C" fn __rust_foreign_exception() -> ! {
83{
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");
84}
8586#[derive(#[automatically_derived]
impl ::core::default::Default for Hook {
#[inline]
fn default() -> Hook { Self::Default }
}Default)]
87enum Hook {
88#[default]
89Default,
90 Custom(Box<dyn Fn(&PanicHookInfo<'_>) + 'static + Sync + Send>),
91}
9293impl Hook {
94#[inline]
95fn into_box(self) -> Box<dyn Fn(&PanicHookInfo<'_>) + 'static + Sync + Send> {
96match self {
97 Hook::Default => Box::new(default_hook),
98 Hook::Custom(hook) => hook,
99 }
100 }
101}
102103static HOOK: RwLock<Hook> = RwLock::new(Hook::Default);
104105/// Registers a custom panic hook, replacing the previously registered hook.
106///
107/// The panic hook is invoked when a thread panics, but before the panic runtime
108/// is invoked. As such, the hook will run with both the aborting and unwinding
109/// runtimes.
110///
111/// The default hook, which is registered at startup, prints a message to standard error and
112/// generates a backtrace if requested. This behavior can be customized using the `set_hook` function.
113/// The current hook can be retrieved while reinstating the default hook with the [`take_hook`]
114/// function.
115///
116/// [`take_hook`]: ./fn.take_hook.html
117///
118/// The hook is provided with a `PanicHookInfo` struct which contains information
119/// about the origin of the panic, including the payload passed to `panic!` and
120/// the source code location from which the panic originated.
121///
122/// The panic hook is a global resource.
123///
124/// # Panics
125///
126/// Panics if called from a panicking thread.
127///
128/// # Examples
129///
130/// The following will print "Custom panic hook":
131///
132/// ```should_panic
133/// use std::panic;
134///
135/// panic::set_hook(Box::new(|_| {
136/// println!("Custom panic hook");
137/// }));
138///
139/// panic!("Normal panic");
140/// ```
141#[stable(feature = "panic_hooks", since = "1.10.0")]
142pub fn set_hook(hook: Box<dyn Fn(&PanicHookInfo<'_>) + 'static + Sync + Send>) {
143if thread::panicking() {
144{
::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");
145 }
146147// Drop the old hook after changing the hook to avoid deadlocking if its
148 // destructor panics.
149drop(HOOK.replace(Hook::Custom(hook)));
150}
151152/// Unregisters the current panic hook and returns it, registering the default hook
153/// in its place.
154///
155/// *See also the function [`set_hook`].*
156///
157/// [`set_hook`]: ./fn.set_hook.html
158///
159/// If the default hook is registered it will be returned, but remain registered.
160///
161/// # Panics
162///
163/// Panics if called from a panicking thread.
164///
165/// # Examples
166///
167/// The following will print "Normal panic":
168///
169/// ```should_panic
170/// use std::panic;
171///
172/// panic::set_hook(Box::new(|_| {
173/// println!("Custom panic hook");
174/// }));
175///
176/// let _ = panic::take_hook();
177///
178/// panic!("Normal panic");
179/// ```
180#[must_use]
181#[stable(feature = "panic_hooks", since = "1.10.0")]
182pub fn take_hook() -> Box<dyn Fn(&PanicHookInfo<'_>) + 'static + Sync + Send> {
183if thread::panicking() {
184{
::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");
185 }
186187HOOK.replace(Hook::Default).into_box()
188}
189190/// Atomic combination of [`take_hook`] and [`set_hook`]. Use this to replace the panic handler with
191/// a new panic handler that does something and then executes the old handler.
192///
193/// [`take_hook`]: ./fn.take_hook.html
194/// [`set_hook`]: ./fn.set_hook.html
195///
196/// # Panics
197///
198/// Panics if called from a panicking thread.
199///
200/// # Examples
201///
202/// The following will print the custom message, and then the normal output of panic.
203///
204/// ```should_panic
205/// #![feature(panic_update_hook)]
206/// use std::panic;
207///
208/// // Equivalent to
209/// // let prev = panic::take_hook();
210/// // panic::set_hook(Box::new(move |info| {
211/// // println!("...");
212/// // prev(info);
213/// // }));
214/// panic::update_hook(move |prev, info| {
215/// println!("Print custom message and execute panic handler as usual");
216/// prev(info);
217/// });
218///
219/// panic!("Custom and then normal");
220/// ```
221#[unstable(feature = "panic_update_hook", issue = "92649")]
222pub fn update_hook<F>(hook_fn: F)
223where
224F: Fn(&(dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static), &PanicHookInfo<'_>)
225 + Sync226 + Send227 + 'static,
228{
229if thread::panicking() {
230{
::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");
231 }
232233let mut hook = HOOK.write();
234let prev = mem::take(&mut *hook).into_box();
235*hook = Hook::Custom(Box::new(move |info| hook_fn(&prev, info)));
236}
237238/// The default panic handler.
239#[optimize(size)]
240fn default_hook(info: &PanicHookInfo<'_>) {
241// If this is a double panic, make sure that we print a backtrace
242 // for this panic. Otherwise only print it if logging is enabled.
243let backtrace = if info.force_no_backtrace() {
244None245 } else if panic_count::get_count() >= 2 {
246BacktraceStyle::full()
247 } else {
248crate::panic::get_backtrace_style()
249 };
250251// The current implementation always returns `Some`.
252let location = info.location().unwrap();
253254let msg = payload_as_str(info.payload());
255256let write = #[optimize(size)]
257|err: &mut dyn crate::io::Write| {
258// Use a lock to prevent mixed output in multithreading context.
259 // Some platforms also require it when printing a backtrace, like `SymFromAddr` on Windows.
260let mut lock = backtrace::lock();
261262 thread::with_current_name(|name| {
263let name = name.unwrap_or("<unnamed>");
264let tid = thread::current_os_id();
265266// Try to write the panic message to a buffer first to prevent other concurrent outputs
267 // interleaving with it.
268let mut buffer = [0u8; 512];
269let mut cursor = crate::io::Cursor::new(&mut buffer[..]);
270271let write_msg = |dst: &mut dyn crate::io::Write| {
272// We add a newline to ensure the panic message appears at the start of a line.
273dst.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}")274 };
275276if write_msg(&mut cursor).is_ok() {
277let pos = cursor.position() as usize;
278let _ = err.write_all(&buffer[0..pos]);
279 } else {
280// The message did not fit into the buffer, write it directly instead.
281let _ = write_msg(err);
282 };
283 });
284285static FIRST_PANIC: Atomic<bool> = AtomicBool::new(true);
286287match backtrace {
288Some(BacktraceStyle::Short) => {
289drop(lock.print(err, crate::backtrace_rs::PrintFmt::Short))
290 }
291Some(BacktraceStyle::Full) => {
292drop(lock.print(err, crate::backtrace_rs::PrintFmt::Full))
293 }
294Some(BacktraceStyle::Off) => {
295if FIRST_PANIC.swap(false, Ordering::Relaxed) {
296let _ = err.write_fmt(format_args!("note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n"))writeln!(
297err,
298"note: run with `RUST_BACKTRACE=1` environment variable to display a \
299 backtrace"
300);
301if falsecfg!(miri) {
302let _ = 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!(
303err,
304"note: in Miri, you may have to set `MIRIFLAGS=-Zmiri-env-forward=RUST_BACKTRACE` \
305 for the environment variable to have an effect"
306);
307 }
308 }
309 }
310// If backtraces aren't supported or are forced-off, do nothing.
311None => {}
312 }
313 };
314315if let Ok(Some(local)) = try_set_output_capture(None) {
316write(&mut *local.lock().unwrap_or_else(|e| e.into_inner()));
317try_set_output_capture(Some(local)).ok();
318 } else if let Some(mut out) = panic_output() {
319write(&mut out);
320 }
321}
322323#[cfg(not(test))]
324#[doc(hidden)]
325#[cfg(panic = "immediate-abort")]
326#[unstable(feature = "update_panic_count", issue = "none")]
327pub mod panic_count {
328/// A reason for forcing an immediate abort on panic.
329#[derive(Debug)]
330pub enum MustAbort {
331 AlwaysAbort,
332 PanicInHook,
333 }
334335#[inline]
336pub fn increase(run_panic_hook: bool) -> Option<MustAbort> {
337None
338}
339340#[inline]
341pub fn finished_panic_hook() {}
342343#[inline]
344pub fn decrease() {}
345346#[inline]
347pub fn set_always_abort() {}
348349// Disregards ALWAYS_ABORT_FLAG
350#[inline]
351 #[must_use]
352pub fn get_count() -> usize {
3530
354}
355356#[must_use]
357 #[inline]
358pub fn count_is_zero() -> bool {
359true
360}
361}
362363#[cfg(not(test))]
364#[doc(hidden)]
365#[cfg(not(panic = "immediate-abort"))]
366#[unstable(feature = "update_panic_count", issue = "none")]
367pub mod panic_count {
368use crate::cell::Cell;
369use crate::sync::atomic::{Atomic, AtomicUsize, Ordering};
370371const ALWAYS_ABORT_FLAG: usize = 1 << (usize::BITS - 1);
372373/// A reason for forcing an immediate abort on panic.
374#[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)]
375pub enum MustAbort {
376 AlwaysAbort,
377 PanicInHook,
378 }
379380// Panic count for the current thread and whether a panic hook is currently
381 // being executed..
382const 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! {
383static LOCAL_PANIC_COUNT: Cell<(usize, bool)> = const { Cell::new((0, false)) }
384 }385386// Sum of panic counts from all threads. The purpose of this is to have
387 // a fast path in `count_is_zero` (which is used by `panicking`). In any particular
388 // thread, if that thread currently views `GLOBAL_PANIC_COUNT` as being zero,
389 // then `LOCAL_PANIC_COUNT` in that thread is zero. This invariant holds before
390 // and after increase and decrease, but not necessarily during their execution.
391 //
392 // Additionally, the top bit of GLOBAL_PANIC_COUNT (GLOBAL_ALWAYS_ABORT_FLAG)
393 // records whether panic::always_abort() has been called. This can only be
394 // set, never cleared.
395 // panic::always_abort() is usually called to prevent memory allocations done by
396 // the panic handling in the child created by `libc::fork`.
397 // Memory allocations performed in a child created with `libc::fork` are undefined
398 // behavior in most operating systems.
399 // Accessing LOCAL_PANIC_COUNT in a child created by `libc::fork` would lead to a memory
400 // allocation. Only GLOBAL_PANIC_COUNT can be accessed in this situation. This is
401 // sufficient because a child process will always have exactly one thread only.
402 // See also #85261 for details.
403 //
404 // This could be viewed as a struct containing a single bit and an n-1-bit
405 // value, but if we wrote it like that it would be more than a single word,
406 // and even a newtype around usize would be clumsy because we need atomics.
407 // But we use such a tuple for the return type of increase().
408 //
409 // Stealing a bit is fine because it just amounts to assuming that each
410 // panicking thread consumes at least 2 bytes of address space.
411static GLOBAL_PANIC_COUNT: Atomic<usize> = AtomicUsize::new(0);
412413// Increases the global and local panic count, and returns whether an
414 // immediate abort is required.
415 //
416 // This also updates thread-local state to keep track of whether a panic
417 // hook is currently executing.
418#[must_use = "MustAbort may not be ignored"]
419pub fn increase(run_panic_hook: bool) -> Option<MustAbort> {
420let global_count = GLOBAL_PANIC_COUNT.fetch_add(1, Ordering::Relaxed);
421if global_count & ALWAYS_ABORT_FLAG != 0 {
422// Do *not* access thread-local state, we might be after a `fork`.
423return Some(MustAbort::AlwaysAbort);
424 }
425426LOCAL_PANIC_COUNT.with(|c| {
427let (count, in_panic_hook) = c.get();
428if in_panic_hook {
429return Some(MustAbort::PanicInHook);
430 }
431c.set((count + 1, run_panic_hook));
432None433 })
434 }
435436pub fn finished_panic_hook() {
437LOCAL_PANIC_COUNT.with(|c| {
438let (count, _) = c.get();
439c.set((count, false));
440 });
441 }
442443pub fn decrease() {
444GLOBAL_PANIC_COUNT.fetch_sub(1, Ordering::Relaxed);
445LOCAL_PANIC_COUNT.with(|c| {
446let (count, _) = c.get();
447c.set((count - 1, false));
448 });
449 }
450451pub fn set_always_abort() {
452GLOBAL_PANIC_COUNT.fetch_or(ALWAYS_ABORT_FLAG, Ordering::Relaxed);
453 }
454455// Disregards ALWAYS_ABORT_FLAG
456#[must_use]
457pub fn get_count() -> usize {
458LOCAL_PANIC_COUNT.with(|c| c.get().0)
459 }
460461// Disregards ALWAYS_ABORT_FLAG
462#[must_use]
463 #[inline]
464pub fn count_is_zero() -> bool {
465if GLOBAL_PANIC_COUNT.load(Ordering::Relaxed) & !ALWAYS_ABORT_FLAG == 0 {
466// Fast path: if `GLOBAL_PANIC_COUNT` is zero, all threads
467 // (including the current one) will have `LOCAL_PANIC_COUNT`
468 // equal to zero, so TLS access can be avoided.
469 //
470 // In terms of performance, a relaxed atomic load is similar to a normal
471 // aligned memory read (e.g., a mov instruction in x86), but with some
472 // compiler optimization restrictions. On the other hand, a TLS access
473 // might require calling a non-inlinable function (such as `__tls_get_addr`
474 // when using the GD TLS model).
475true
476} else {
477is_zero_slow_path()
478 }
479 }
480481// Slow path is in a separate function to reduce the amount of code
482 // inlined from `count_is_zero`.
483#[inline(never)]
484 #[cold]
485fn is_zero_slow_path() -> bool {
486LOCAL_PANIC_COUNT.with(|c| c.get().0 == 0)
487 }
488}
489490#[cfg(test)]
491pub use realstd::rt::panic_count;
492493/// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
494#[cfg(panic = "immediate-abort")]
495pub unsafe fn catch_unwind<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>> {
496Ok(f())
497}
498499/// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
500#[cfg(not(panic = "immediate-abort"))]
501pub unsafe fn catch_unwind<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>> {
502union Data<F, R> {
503 f: ManuallyDrop<F>,
504 r: ManuallyDrop<R>,
505 p: ManuallyDrop<Box<dyn Any + Send>>,
506 }
507508// We do some sketchy operations with ownership here for the sake of
509 // performance. We can only pass pointers down to `do_call` (can't pass
510 // objects by value), so we do all the ownership tracking here manually
511 // using a union.
512 //
513 // We go through a transition where:
514 //
515 // * First, we set the data field `f` to be the argumentless closure that we're going to call.
516 // * When we make the function call, the `do_call` function below, we take
517 // ownership of the function pointer. At this point the `data` union is
518 // entirely uninitialized.
519 // * If the closure successfully returns, we write the return value into the
520 // data's return slot (field `r`).
521 // * If the closure panics (`do_catch` below), we write the panic payload into field `p`.
522 // * Finally, when we come back out of the `try` intrinsic we're
523 // in one of two states:
524 //
525 // 1. The closure didn't panic, in which case the return value was
526 // filled in. We move it out of `data.r` and return it.
527 // 2. The closure panicked, in which case the panic payload was
528 // filled in. We move it out of `data.p` and return it.
529 //
530 // Once we stack all that together we should have the "most efficient'
531 // method of calling a catch panic whilst juggling ownership.
532let mut data = Data { f: ManuallyDrop::new(f) };
533534// SAFETY:
535 //
536 // Access to the union's fields: this is `std` and we know that the `catch_unwind`
537 // intrinsic fills in the `r` or `p` union field based on its return value.
538 //
539 // The call to `intrinsics::catch_unwind` is made safe by:
540 // - `do_call`, the first argument, can be called with the initial `data_ptr`.
541 // - `do_catch`, the second argument, can be called with the `data_ptr` as well.
542 // See their safety preconditions for more information
543unsafe {
544return if intrinsics::catch_unwind(do_call, &raw mut data, do_catch) {
545Err(ManuallyDrop::into_inner(data.p))
546 } else {
547Ok(ManuallyDrop::into_inner(data.r))
548 };
549 }
550551// We consider unwinding to be rare, so mark this function as cold. However,
552 // do not mark it no-inline -- that decision is best to leave to the
553 // optimizer (in most cases this function is not inlined even as a normal,
554 // non-cold function, though, as of the writing of this comment).
555#[cold]
556 #[optimize(size)]
557unsafe fn cleanup(payload: *mut u8) -> Box<dyn Any + Send + 'static> {
558// SAFETY: The whole unsafe block hinges on a correct implementation of
559 // the panic handler `__rust_panic_cleanup`. As such we can only
560 // assume it returns the correct thing for `Box::from_raw` to work
561 // without undefined behavior.
562let obj = unsafe { Box::from_raw(__rust_panic_cleanup(payload)) };
563 panic_count::decrease();
564obj565 }
566567// SAFETY:
568 // data must be non-NUL, correctly aligned, and a pointer to a `Data<F, R>`
569 // Its must contains a valid `f` (type: F) value that can be use to fill
570 // `data.r`.
571#[inline]
572unsafe fn do_call<F: FnOnce() -> R, R>(data: *mut Data<F, R>) {
573// SAFETY: this is the responsibility of the caller, see above.
574unsafe {
575let f = ManuallyDrop::take(&mut (*data).f);
576 (*data).r = ManuallyDrop::new(f());
577 }
578 }
579580// We *do* want this part of the catch to be inlined: this allows the
581 // compiler to properly track accesses to the Data union and optimize it
582 // away most of the time.
583 //
584 // SAFETY:
585 // data must be non-NUL, correctly aligned, and a pointer to a `Data<F, R>`
586 // Since this uses `cleanup` it also hinges on a correct implementation of
587 // `__rustc_panic_cleanup`.
588#[inline]
589 #[rustc_nounwind] // `intrinsic::catch_unwind` requires catch fn to be nounwind
590unsafe fn do_catch<F: FnOnce() -> R, R>(data: *mut Data<F, R>, payload: *mut u8) {
591// SAFETY: this is the responsibility of the caller, see above.
592 //
593 // When `__rustc_panic_cleaner` is correctly implemented we can rely
594 // on `obj` being the correct thing to pass to `data.p` (after wrapping
595 // in `ManuallyDrop`).
596unsafe {
597let obj = cleanup(payload);
598 (*data).p = ManuallyDrop::new(obj);
599 }
600 }
601}
602603/// Determines whether the current thread is unwinding because of panic.
604#[inline]
605pub fn panicking() -> bool {
606 !panic_count::count_is_zero()
607}
608609/// Entry point of panics from the core crate (`panic_impl` lang item).
610#[cfg(not(any(test, doctest)))]
611#[panic_handler]
612pub fn panic_handler(info: &core::panic::PanicInfo<'_>) -> ! {
613struct FormatStringPayload<'a> {
614 inner: &'a core::panic::PanicMessage<'a>,
615 string: Option<String>,
616 }
617618impl FormatStringPayload<'_> {
619fn fill(&mut self) -> &mut String {
620let inner = self.inner;
621// Lazily, the first time this gets called, run the actual string formatting.
622self.string.get_or_insert_with(|| {
623let mut s = String::new();
624let mut fmt = fmt::Formatter::new(&mut s, fmt::FormattingOptions::new());
625let _err = fmt::Display::fmt(&inner, &mut fmt);
626s627 })
628 }
629 }
630631unsafe impl PanicPayload for FormatStringPayload<'_> {
632fn take_box(&mut self) -> *mut (dyn Any + Send) {
633// We do two allocations here, unfortunately. But (a) they're required with the current
634 // scheme, and (b) we don't handle panic + OOM properly anyway (see comment in
635 // begin_panic below).
636let contents = mem::take(self.fill());
637Box::into_raw(Box::new(contents))
638 }
639640fn get(&mut self) -> &(dyn Any + Send) {
641self.fill()
642 }
643 }
644645impl fmt::Displayfor FormatStringPayload<'_> {
646fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
647if let Some(s) = &self.string {
648f.write_str(s)
649 } else {
650 fmt::Display::fmt(&self.inner, f)
651 }
652 }
653 }
654655struct StaticStrPayload(&'static str);
656657unsafe impl PanicPayload for StaticStrPayload {
658fn take_box(&mut self) -> *mut (dyn Any + Send) {
659Box::into_raw(Box::new(self.0))
660 }
661662fn get(&mut self) -> &(dyn Any + Send) {
663&self.0
664}
665666fn as_str(&mut self) -> Option<&str> {
667Some(self.0)
668 }
669 }
670671impl fmt::Displayfor StaticStrPayload {
672fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
673f.write_str(self.0)
674 }
675 }
676677let loc = info.location().unwrap(); // The current implementation always returns Some
678let msg = info.message();
679crate::sys::backtrace::__rust_end_short_backtrace(move || {
680if let Some(s) = msg.as_str() {
681panic_with_hook(
682&mut StaticStrPayload(s),
683loc,
684info.can_unwind(),
685info.force_no_backtrace(),
686 );
687 } else {
688panic_with_hook(
689&mut FormatStringPayload { inner: &msg, string: None },
690loc,
691info.can_unwind(),
692info.force_no_backtrace(),
693 );
694 }
695 })
696}
697698/// This is the entry point of panicking for the non-format-string variants of
699/// panic!() and assert!(). In particular, this is the only entry point that supports
700/// arbitrary payloads, not just format strings.
701#[unstable(feature = "libstd_sys_internals", reason = "used by the panic! macro", issue = "none")]
702#[cfg_attr(not(any(test, doctest)), lang = "begin_panic")]
703// lang item for CTFE panic support
704// never inline unless panic=immediate-abort to avoid code
705// bloat at the call sites as much as possible
706#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
707#[cfg_attr(panic = "immediate-abort", inline)]
708#[track_caller]
709#[rustc_do_not_const_check] // hooked by const-eval
710pub const fn begin_panic<M: Any + Send>(msg: M) -> ! {
711if falsecfg!(panic = "immediate-abort") {
712 intrinsics::abort()
713 }
714715struct Payload<A> {
716 inner: Option<A>,
717 }
718719unsafe impl<A: Send + 'static> PanicPayload for Payload<A> {
720fn take_box(&mut self) -> *mut (dyn Any + Send) {
721// Note that this should be the only allocation performed in this code path. Currently
722 // this means that panic!() on OOM will invoke this code path, but then again we're not
723 // really ready for panic on OOM anyway. If we do start doing this, then we should
724 // propagate this allocation to be performed in the parent of this thread instead of the
725 // thread that's panicking.
726let data = match self.inner.take() {
727Some(a) => Box::new(a) as Box<dyn Any + Send>,
728None => process::abort(),
729 };
730Box::into_raw(data)
731 }
732733fn get(&mut self) -> &(dyn Any + Send) {
734match self.inner {
735Some(ref a) => a,
736None => process::abort(),
737 }
738 }
739 }
740741impl<A: 'static> fmt::Displayfor Payload<A> {
742fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
743match &self.inner {
744Some(a) => f.write_str(payload_as_str(a)),
745None => process::abort(),
746 }
747 }
748 }
749750let loc = Location::caller();
751crate::sys::backtrace::__rust_end_short_backtrace(move || {
752panic_with_hook(
753&mut Payload { inner: Some(msg) },
754loc,
755/* can_unwind */ true,
756/* force_no_backtrace */ false,
757 )
758 })
759}
760761fn payload_as_str(payload: &dyn Any) -> &str {
762if let Some(&s) = payload.downcast_ref::<&'static str>() {
763s764 } else if let Some(s) = payload.downcast_ref::<String>() {
765s.as_str()
766 } else {
767"Box<dyn Any>"
768}
769}
770771/// Central point for dispatching panics.
772///
773/// Executes the primary logic for a panic, including checking for recursive
774/// panics, panic hooks, and finally dispatching to the panic runtime to either
775/// abort or unwind.
776#[optimize(size)]
777fn panic_with_hook(
778 payload: &mut dyn PanicPayload,
779 location: &'static Location<'static>,
780 can_unwind: bool,
781 force_no_backtrace: bool,
782) -> ! {
783let must_abort = panic_count::increase(true);
784785// Check if we need to abort immediately.
786if let Some(must_abort) = must_abort {
787match must_abort {
788 panic_count::MustAbort::PanicInHook => {
789// Don't try to format the message in this case, perhaps that is causing the
790 // recursive panics. However if the message is just a string, no user-defined
791 // code is involved in printing it, so that is risk-free.
792let message: &str = payload.as_str().unwrap_or_default();
793if 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!(
794"panicked at {location}:\n{message}\nthread panicked while processing panic. aborting.\n"
795);
796 }
797 panic_count::MustAbort::AlwaysAbort => {
798// Unfortunately, this does not print a backtrace, because creating
799 // a `Backtrace` will allocate, which we must avoid here.
800if 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");
801 }
802 }
803crate::process::abort();
804 }
805806match *HOOK.read() {
807// Some platforms (like wasm) know that printing to stderr won't ever actually
808 // print anything, and if that's the case we can skip the default
809 // hook. Since string formatting happens lazily when calling `payload`
810 // methods, this means we avoid formatting the string at all!
811 // (The panic runtime might still call `payload.take_box()` though and trigger
812 // formatting.)
813Hook::Defaultif panic_output().is_none() => {}
814 Hook::Default => {
815default_hook(&PanicHookInfo::new(
816location,
817payload.get(),
818can_unwind,
819force_no_backtrace,
820 ));
821 }
822 Hook::Custom(ref hook) => {
823hook(&PanicHookInfo::new(location, payload.get(), can_unwind, force_no_backtrace));
824 }
825 }
826827// Indicate that we have finished executing the panic hook. After this point
828 // it is fine if there is a panic while executing destructors, as long as it
829 // it contained within a `catch_unwind`.
830panic_count::finished_panic_hook();
831832if !can_unwind {
833// If a thread panics while running destructors or tries to unwind
834 // through a nounwind function (e.g. extern "C") then we cannot continue
835 // unwinding and have to abort immediately.
836if 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");
837crate::process::abort();
838 }
839840rust_panic(payload)
841}
842843/// This is the entry point for `resume_unwind`.
844/// It just forwards the payload to the panic runtime.
845#[cfg_attr(panic = "immediate-abort", inline)]
846pub fn resume_unwind(payload: Box<dyn Any + Send>) -> ! {
847if let Some(must_abort) = panic_count::increase(false) {
848match must_abort {
849 panic_count::MustAbort::PanicInHook => {
850if 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");
851 }
852 panic_count::MustAbort::AlwaysAbort => {
853if 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");
854 }
855 }
856857crate::process::abort();
858 }
859860struct RewrapBox(Box<dyn Any + Send>);
861862unsafe impl PanicPayload for RewrapBox {
863fn take_box(&mut self) -> *mut (dyn Any + Send) {
864Box::into_raw(mem::replace(&mut self.0, Box::new(())))
865 }
866867fn get(&mut self) -> &(dyn Any + Send) {
868&*self.0
869}
870 }
871872impl fmt::Displayfor RewrapBox {
873fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
874f.write_str(payload_as_str(&self.0))
875 }
876 }
877878rust_panic(&mut RewrapBox(payload))
879}
880881/// A function with a fixed suffix (through `rustc_std_internal_symbol`)
882/// on which to slap yer breakpoints.
883#[inline(never)]
884#[cfg_attr(not(test), rustc_std_internal_symbol)]
885#[cfg(not(panic = "immediate-abort"))]
886fn rust_panic(msg: &mut dyn PanicPayload) -> ! {
887let code = unsafe { __rust_start_panic(msg) };
888{
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}")889}
890891#[cfg_attr(not(test), rustc_std_internal_symbol)]
892#[cfg(panic = "immediate-abort")]
893fn rust_panic(_: &mut dyn PanicPayload) -> ! {
894crate::intrinsics::abort();
895}