std/panicking.rs
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"
9
10#![deny(unsafe_op_in_unsafe_fn)]
11
12use alloc::panicking::PanicPayload;
13use core::panic::Location;
14
15// 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;
19
20use 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};
30
31// 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(crate) static EMPTY_PANIC: fn(&'static str) -> ! =
45 begin_panic::<&'static str> as fn(&'static str) -> !;
46
47// 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]
59 fn __rust_panic_cleanup(payload: *mut u8) -> Box<dyn Any + Send + 'static>;
60
61 /// `PanicPayload` lazily performs allocation only when needed (this avoids
62 /// allocations when using the "abort" panic runtime).
63 #[rustc_std_internal_symbol]
64 safe fn __rust_start_panic(payload: &mut dyn PanicPayload) -> u32;
65}
66
67/// 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 rtabort!("Rust panics must be rethrown");
74}
75
76/// 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 rtabort!("Rust cannot catch foreign exceptions");
82}
83
84#[derive(Default)]
85enum Hook {
86 #[default]
87 Default,
88 Custom(Box<dyn Fn(&PanicHookInfo<'_>) + 'static + Sync + Send>),
89}
90
91impl Hook {
92 #[inline]
93 fn into_box(self) -> Box<dyn Fn(&PanicHookInfo<'_>) + 'static + Sync + Send> {
94 match self {
95 Hook::Default => Box::new(default_hook),
96 Hook::Custom(hook) => hook,
97 }
98 }
99}
100
101static HOOK: RwLock<Hook> = RwLock::new(Hook::Default);
102
103/// 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>) {
141 if thread::panicking() {
142 panic!("cannot modify the panic hook from a panicking thread");
143 }
144
145 // Drop the old hook after changing the hook to avoid deadlocking if its
146 // destructor panics.
147 drop(HOOK.replace(Hook::Custom(hook)));
148}
149
150/// 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> {
180 if thread::panicking() {
181 panic!("cannot modify the panic hook from a panicking thread");
182 }
183
184 HOOK.replace(Hook::Default).into_box()
185}
186
187/// 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
221 F: Fn(&(dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static), &PanicHookInfo<'_>)
222 + Sync
223 + Send
224 + 'static,
225{
226 if thread::panicking() {
227 panic!("cannot modify the panic hook from a panicking thread");
228 }
229
230 let mut hook = HOOK.write();
231 let prev = mem::take(&mut *hook).into_box();
232 *hook = Hook::Custom(Box::new(move |info| hook_fn(&prev, info)));
233}
234
235/// 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.
240 let backtrace = if info.force_no_backtrace() {
241 None
242 } else if panic_count::get_count() >= 2 {
243 BacktraceStyle::full()
244 } else {
245 crate::panic::get_backtrace_style()
246 };
247
248 // The current implementation always returns `Some`.
249 let location = info.location().unwrap();
250
251 let msg = payload_as_str(info.payload());
252
253 let 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.
257 let mut lock = backtrace::lock();
258
259 thread::with_current_name(|name| {
260 let name = name.unwrap_or("<unnamed>");
261 let tid = thread::current_os_id();
262
263 // Try to write the panic message to a buffer first to prevent other concurrent outputs
264 // interleaving with it.
265 let mut buffer = [0u8; 512];
266 let mut cursor = crate::io::Cursor::new(&mut buffer[..]);
267
268 let 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.
270 writeln!(dst, "\nthread '{name}' ({tid}) panicked at {location}:\n{msg}")
271 };
272
273 if write_msg(&mut cursor).is_ok() {
274 let pos = cursor.position() as usize;
275 let _ = err.write_all(&buffer[0..pos]);
276 } else {
277 // The message did not fit into the buffer, write it directly instead.
278 let _ = write_msg(err);
279 };
280 });
281
282 static FIRST_PANIC: Atomic<bool> = AtomicBool::new(true);
283
284 match backtrace {
285 Some(BacktraceStyle::Short) => {
286 drop(lock.print(err, crate::backtrace_rs::PrintFmt::Short))
287 }
288 Some(BacktraceStyle::Full) => {
289 drop(lock.print(err, crate::backtrace_rs::PrintFmt::Full))
290 }
291 Some(BacktraceStyle::Off) => {
292 if FIRST_PANIC.swap(false, Ordering::Relaxed) {
293 let _ = writeln!(
294 err,
295 "note: run with `RUST_BACKTRACE=1` environment variable to display a \
296 backtrace"
297 );
298 if cfg!(miri) {
299 let _ = writeln!(
300 err,
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.
308 None => {}
309 }
310 };
311
312 if let Ok(Some(local)) = try_set_output_capture(None) {
313 write(&mut *local.lock().unwrap_or_else(|e| e.into_inner()));
314 try_set_output_capture(Some(local)).ok();
315 } else if let Some(mut out) = panic_output() {
316 write(&mut out);
317 }
318}
319
320#[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)]
327 pub enum MustAbort {
328 AlwaysAbort,
329 PanicInHook,
330 }
331
332 #[inline]
333 pub fn increase(run_panic_hook: bool) -> Option<MustAbort> {
334 None
335 }
336
337 #[inline]
338 pub fn finished_panic_hook() {}
339
340 #[inline]
341 pub fn decrease() {}
342
343 #[inline]
344 pub fn set_always_abort() {}
345
346 // Disregards ALWAYS_ABORT_FLAG
347 #[inline]
348 #[must_use]
349 pub fn get_count() -> usize {
350 0
351 }
352
353 #[must_use]
354 #[inline]
355 pub fn count_is_zero() -> bool {
356 true
357 }
358}
359
360#[cfg(not(test))]
361#[doc(hidden)]
362#[cfg(not(panic = "immediate-abort"))]
363#[unstable(feature = "update_panic_count", issue = "none")]
364pub mod panic_count {
365 use crate::cell::Cell;
366 use crate::sync::atomic::{Atomic, AtomicUsize, Ordering};
367
368 const ALWAYS_ABORT_FLAG: usize = 1 << (usize::BITS - 1);
369
370 /// A reason for forcing an immediate abort on panic.
371 #[derive(Debug)]
372 pub enum MustAbort {
373 AlwaysAbort,
374 PanicInHook,
375 }
376
377 // Panic count for the current thread and whether a panic hook is currently
378 // being executed..
379 thread_local! {
380 static LOCAL_PANIC_COUNT: Cell<(usize, bool)> = const { Cell::new((0, false)) }
381 }
382
383 // 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.
408 static GLOBAL_PANIC_COUNT: Atomic<usize> = AtomicUsize::new(0);
409
410 // 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"]
416 pub fn increase(run_panic_hook: bool) -> Option<MustAbort> {
417 let global_count = GLOBAL_PANIC_COUNT.fetch_add(1, Ordering::Relaxed);
418 if global_count & ALWAYS_ABORT_FLAG != 0 {
419 // Do *not* access thread-local state, we might be after a `fork`.
420 return Some(MustAbort::AlwaysAbort);
421 }
422
423 LOCAL_PANIC_COUNT.with(|c| {
424 let (count, in_panic_hook) = c.get();
425 if in_panic_hook {
426 return Some(MustAbort::PanicInHook);
427 }
428 c.set((count + 1, run_panic_hook));
429 None
430 })
431 }
432
433 pub fn finished_panic_hook() {
434 LOCAL_PANIC_COUNT.with(|c| {
435 let (count, _) = c.get();
436 c.set((count, false));
437 });
438 }
439
440 #[ferrocene::prevalidated]
441 pub fn decrease() {
442 GLOBAL_PANIC_COUNT.fetch_sub(1, Ordering::Relaxed);
443 LOCAL_PANIC_COUNT.with(|c| {
444 let (count, _) = c.get();
445 c.set((count - 1, false));
446 });
447 }
448
449 pub fn set_always_abort() {
450 GLOBAL_PANIC_COUNT.fetch_or(ALWAYS_ABORT_FLAG, Ordering::Relaxed);
451 }
452
453 // Disregards ALWAYS_ABORT_FLAG
454 #[must_use]
455 pub fn get_count() -> usize {
456 LOCAL_PANIC_COUNT.with(|c| c.get().0)
457 }
458
459 // Disregards ALWAYS_ABORT_FLAG
460 #[must_use]
461 #[inline]
462 pub fn count_is_zero() -> bool {
463 if GLOBAL_PANIC_COUNT.load(Ordering::Relaxed) & !ALWAYS_ABORT_FLAG == 0 {
464 // Fast path: if `GLOBAL_PANIC_COUNT` is zero, all threads
465 // (including the current one) will have `LOCAL_PANIC_COUNT`
466 // equal to zero, so TLS access can be avoided.
467 //
468 // In terms of performance, a relaxed atomic load is similar to a normal
469 // aligned memory read (e.g., a mov instruction in x86), but with some
470 // compiler optimization restrictions. On the other hand, a TLS access
471 // might require calling a non-inlinable function (such as `__tls_get_addr`
472 // when using the GD TLS model).
473 true
474 } else {
475 is_zero_slow_path()
476 }
477 }
478
479 // Slow path is in a separate function to reduce the amount of code
480 // inlined from `count_is_zero`.
481 #[inline(never)]
482 #[cold]
483 fn is_zero_slow_path() -> bool {
484 LOCAL_PANIC_COUNT.with(|c| c.get().0 == 0)
485 }
486}
487
488#[cfg(test)]
489pub use realstd::rt::panic_count;
490
491/// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
492#[cfg(panic = "immediate-abort")]
493pub unsafe fn catch_unwind<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>> {
494 Ok(f())
495}
496
497/// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
498#[ferrocene::prevalidated]
499#[cfg(not(panic = "immediate-abort"))]
500pub(crate) unsafe fn catch_unwind<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>> {
501 union Data<F, R> {
502 f: ManuallyDrop<F>,
503 r: ManuallyDrop<R>,
504 p: ManuallyDrop<Box<dyn Any + Send>>,
505 }
506
507 // We do some sketchy operations with ownership here for the sake of
508 // performance. We can only pass pointers down to `do_call` (can't pass
509 // objects by value), so we do all the ownership tracking here manually
510 // using a union.
511 //
512 // We go through a transition where:
513 //
514 // * First, we set the data field `f` to be the argumentless closure that we're going to call.
515 // * When we make the function call, the `do_call` function below, we take
516 // ownership of the function pointer. At this point the `data` union is
517 // entirely uninitialized.
518 // * If the closure successfully returns, we write the return value into the
519 // data's return slot (field `r`).
520 // * If the closure panics (`do_catch` below), we write the panic payload into field `p`.
521 // * Finally, when we come back out of the `try` intrinsic we're
522 // in one of two states:
523 //
524 // 1. The closure didn't panic, in which case the return value was
525 // filled in. We move it out of `data.r` and return it.
526 // 2. The closure panicked, in which case the panic payload was
527 // filled in. We move it out of `data.p` and return it.
528 //
529 // Once we stack all that together we should have the "most efficient'
530 // method of calling a catch panic whilst juggling ownership.
531 let mut data = Data { f: ManuallyDrop::new(f) };
532
533 // SAFETY:
534 //
535 // Access to the union's fields: this is `std` and we know that the `catch_unwind`
536 // intrinsic fills in the `r` or `p` union field based on its return value.
537 //
538 // The call to `intrinsics::catch_unwind` is made safe by:
539 // - `do_call`, the first argument, can be called with the initial `data_ptr`.
540 // - `do_catch`, the second argument, can be called with the `data_ptr` as well.
541 // See their safety preconditions for more information
542 unsafe {
543 return if intrinsics::catch_unwind(do_call, &raw mut data, do_catch) {
544 Err(ManuallyDrop::into_inner(data.p))
545 } else {
546 Ok(ManuallyDrop::into_inner(data.r))
547 };
548 }
549
550 // We consider unwinding to be rare, so mark this function as cold. However,
551 // do not mark it no-inline -- that decision is best to leave to the
552 // optimizer (in most cases this function is not inlined even as a normal,
553 // non-cold function, though, as of the writing of this comment).
554 #[cold]
555 #[optimize(size)]
556 unsafe fn cleanup(payload: *mut u8) -> Box<dyn Any + Send + 'static> {
557 // SAFETY: The whole unsafe block hinges on a correct implementation of
558 // the panic handler `__rust_panic_cleanup`. As such we can only
559 // assume it returns the correct thing for `Box::from_raw` to work
560 // without undefined behavior.
561 let obj = unsafe { __rust_panic_cleanup(payload) };
562 panic_count::decrease();
563 obj
564 }
565
566 // SAFETY:
567 // data must be non-NUL, correctly aligned, and a pointer to a `Data<F, R>`
568 // Its must contains a valid `f` (type: F) value that can be use to fill
569 // `data.r`.
570 #[inline]
571 unsafe fn do_call<F: FnOnce() -> R, R>(data: *mut Data<F, R>) {
572 // SAFETY: this is the responsibility of the caller, see above.
573 unsafe {
574 let f = ManuallyDrop::take(&mut (*data).f);
575 (*data).r = ManuallyDrop::new(f());
576 }
577 }
578
579 // We *do* want this part of the catch to be inlined: this allows the
580 // compiler to properly track accesses to the Data union and optimize it
581 // away most of the time.
582 //
583 // SAFETY:
584 // data must be non-NUL, correctly aligned, and a pointer to a `Data<F, R>`
585 // Since this uses `cleanup` it also hinges on a correct implementation of
586 // `__rustc_panic_cleanup`.
587 #[inline]
588 #[rustc_nounwind] // `intrinsic::catch_unwind` requires catch fn to be nounwind
589 unsafe fn do_catch<F: FnOnce() -> R, R>(data: *mut Data<F, R>, payload: *mut u8) {
590 // SAFETY: this is the responsibility of the caller, see above.
591 //
592 // When `__rustc_panic_cleaner` is correctly implemented we can rely
593 // on `obj` being the correct thing to pass to `data.p` (after wrapping
594 // in `ManuallyDrop`).
595 unsafe {
596 let obj = cleanup(payload);
597 (*data).p = ManuallyDrop::new(obj);
598 }
599 }
600}
601
602/// Determines whether the current thread is unwinding because of panic.
603#[inline]
604pub(crate) fn panicking() -> bool {
605 !panic_count::count_is_zero()
606}
607
608/// Entry point of panics from the core crate (`panic_impl` lang item).
609#[cfg(not(any(test, doctest)))]
610#[panic_handler]
611pub(crate) fn panic_handler(info: &core::panic::PanicInfo<'_>) -> ! {
612 struct FormatStringPayload<'a> {
613 inner: &'a core::panic::PanicMessage<'a>,
614 string: Option<String>,
615 }
616
617 impl FormatStringPayload<'_> {
618 fn fill(&mut self) -> &mut String {
619 let inner = self.inner;
620 // Lazily, the first time this gets called, run the actual string formatting.
621 self.string.get_or_insert_with(|| {
622 let mut s = String::new();
623 let mut fmt = fmt::Formatter::new(&mut s, fmt::FormattingOptions::new());
624 let _err = fmt::Display::fmt(&inner, &mut fmt);
625 s
626 })
627 }
628 }
629
630 impl PanicPayload for FormatStringPayload<'_> {
631 fn take_box(&mut self) -> Box<dyn Any + Send> {
632 // We do two allocations here, unfortunately. But (a) they're required with the current
633 // scheme, and (b) we don't handle panic + OOM properly anyway (see comment in
634 // begin_panic below).
635 let contents = mem::take(self.fill());
636 Box::new(contents)
637 }
638
639 fn get(&mut self) -> &(dyn Any + Send) {
640 self.fill()
641 }
642 }
643
644 impl fmt::Display for FormatStringPayload<'_> {
645 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
646 if let Some(s) = &self.string {
647 f.write_str(s)
648 } else {
649 fmt::Display::fmt(&self.inner, f)
650 }
651 }
652 }
653
654 struct StaticStrPayload(&'static str);
655
656 impl PanicPayload for StaticStrPayload {
657 fn take_box(&mut self) -> Box<dyn Any + Send> {
658 Box::new(self.0)
659 }
660
661 fn get(&mut self) -> &(dyn Any + Send) {
662 &self.0
663 }
664
665 fn as_str(&mut self) -> Option<&str> {
666 Some(self.0)
667 }
668 }
669
670 impl fmt::Display for StaticStrPayload {
671 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
672 f.write_str(self.0)
673 }
674 }
675
676 let loc = info.location().unwrap(); // The current implementation always returns Some
677 let msg = info.message();
678 crate::sys::backtrace::__rust_end_short_backtrace(move || {
679 if let Some(s) = msg.as_str() {
680 panic_with_hook(
681 &mut StaticStrPayload(s),
682 loc,
683 info.can_unwind(),
684 info.force_no_backtrace(),
685 );
686 } else {
687 panic_with_hook(
688 &mut FormatStringPayload { inner: &msg, string: None },
689 loc,
690 info.can_unwind(),
691 info.force_no_backtrace(),
692 );
693 }
694 })
695}
696
697/// This is the entry point of panicking for the non-format-string variants of
698/// panic!() and assert!(). In particular, this is the only entry point that supports
699/// arbitrary payloads, not just format strings.
700#[unstable(feature = "libstd_sys_internals", reason = "used by the panic! macro", issue = "none")]
701#[cfg_attr(not(any(test, doctest)), lang = "begin_panic")]
702// lang item for CTFE panic support
703// never inline unless panic=immediate-abort to avoid code
704// bloat at the call sites as much as possible
705#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))]
706#[cfg_attr(panic = "immediate-abort", inline)]
707#[track_caller]
708#[rustc_do_not_const_check] // hooked by const-eval
709pub const fn begin_panic<M: Any + Send>(msg: M) -> ! {
710 if cfg!(panic = "immediate-abort") {
711 intrinsics::abort_immediate()
712 }
713
714 struct Payload<A> {
715 inner: Option<A>,
716 }
717
718 impl<A: Send + 'static> PanicPayload for Payload<A> {
719 fn take_box(&mut self) -> Box<dyn Any + Send> {
720 // Note that this should be the only allocation performed in this code path. Currently
721 // this means that panic!() on OOM will invoke this code path, but then again we're not
722 // really ready for panic on OOM anyway. If we do start doing this, then we should
723 // propagate this allocation to be performed in the parent of this thread instead of the
724 // thread that's panicking.
725 match self.inner.take() {
726 Some(a) => Box::new(a) as Box<dyn Any + Send>,
727 None => process::abort(),
728 }
729 }
730
731 fn get(&mut self) -> &(dyn Any + Send) {
732 match self.inner {
733 Some(ref a) => a,
734 None => process::abort(),
735 }
736 }
737 }
738
739 impl<A: 'static> fmt::Display for Payload<A> {
740 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
741 match &self.inner {
742 Some(a) => f.write_str(payload_as_str(a)),
743 None => process::abort(),
744 }
745 }
746 }
747
748 let loc = Location::caller();
749 crate::sys::backtrace::__rust_end_short_backtrace(move || {
750 panic_with_hook(
751 &mut Payload { inner: Some(msg) },
752 loc,
753 /* can_unwind */ true,
754 /* force_no_backtrace */ false,
755 )
756 })
757}
758
759fn payload_as_str(payload: &dyn Any) -> &str {
760 if let Some(&s) = payload.downcast_ref::<&'static str>() {
761 s
762 } else if let Some(s) = payload.downcast_ref::<String>() {
763 s.as_str()
764 } else {
765 "Box<dyn Any>"
766 }
767}
768
769/// Central point for dispatching panics.
770///
771/// Executes the primary logic for a panic, including checking for recursive
772/// panics, panic hooks, and finally dispatching to the panic runtime to either
773/// abort or unwind.
774#[optimize(size)]
775fn panic_with_hook(
776 payload: &mut dyn PanicPayload,
777 location: &'static Location<'static>,
778 can_unwind: bool,
779 force_no_backtrace: bool,
780) -> ! {
781 let must_abort = panic_count::increase(true);
782
783 // Check if we need to abort immediately.
784 if let Some(must_abort) = must_abort {
785 match must_abort {
786 panic_count::MustAbort::PanicInHook => {
787 // Don't try to format the message in this case, perhaps that is causing the
788 // recursive panics. However if the message is just a string, no user-defined
789 // code is involved in printing it, so that is risk-free.
790 let message: &str = payload.as_str().unwrap_or_default();
791 rtprintpanic!(
792 "panicked at {location}:\n{message}\nthread panicked while processing panic. aborting.\n"
793 );
794 }
795 panic_count::MustAbort::AlwaysAbort => {
796 // Unfortunately, this does not print a backtrace, because creating
797 // a `Backtrace` will allocate, which we must avoid here.
798 rtprintpanic!("aborting due to panic at {location}:\n{payload}\n");
799 }
800 }
801 crate::process::abort();
802 }
803
804 match *HOOK.read() {
805 // Some platforms (like wasm) know that printing to stderr won't ever actually
806 // print anything, and if that's the case we can skip the default
807 // hook. Since string formatting happens lazily when calling `payload`
808 // methods, this means we avoid formatting the string at all!
809 // (The panic runtime might still call `payload.take_box()` though and trigger
810 // formatting.)
811 Hook::Default if panic_output().is_none() => {}
812 Hook::Default => {
813 default_hook(&PanicHookInfo::new(
814 location,
815 payload.get(),
816 can_unwind,
817 force_no_backtrace,
818 ));
819 }
820 Hook::Custom(ref hook) => {
821 hook(&PanicHookInfo::new(location, payload.get(), can_unwind, force_no_backtrace));
822 }
823 }
824
825 // Indicate that we have finished executing the panic hook. After this point
826 // it is fine if there is a panic while executing destructors, as long as it
827 // it contained within a `catch_unwind`.
828 panic_count::finished_panic_hook();
829
830 if !can_unwind {
831 // If a thread panics while running destructors or tries to unwind
832 // through a nounwind function (e.g. extern "C") then we cannot continue
833 // unwinding and have to abort immediately.
834 rtprintpanic!("thread caused non-unwinding panic. aborting.\n");
835 crate::process::abort();
836 }
837
838 rust_panic(payload)
839}
840
841/// This is the entry point for `resume_unwind`.
842/// It just forwards the payload to the panic runtime.
843#[cfg_attr(panic = "immediate-abort", inline)]
844pub(crate) fn resume_unwind(payload: Box<dyn Any + Send>) -> ! {
845 if let Some(must_abort) = panic_count::increase(false) {
846 match must_abort {
847 panic_count::MustAbort::PanicInHook => {
848 rtprintpanic!("thread panicked while processing panic. aborting.\n");
849 }
850 panic_count::MustAbort::AlwaysAbort => {
851 rtprintpanic!("aborting due to panic\n");
852 }
853 }
854
855 crate::process::abort();
856 }
857
858 struct RewrapBox(Box<dyn Any + Send>);
859
860 impl PanicPayload for RewrapBox {
861 fn take_box(&mut self) -> Box<dyn Any + Send> {
862 mem::replace(&mut self.0, Box::new(()))
863 }
864
865 fn get(&mut self) -> &(dyn Any + Send) {
866 &*self.0
867 }
868 }
869
870 impl fmt::Display for RewrapBox {
871 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
872 f.write_str(payload_as_str(&self.0))
873 }
874 }
875
876 rust_panic(&mut RewrapBox(payload))
877}
878
879/// A function with a fixed suffix (through `rustc_std_internal_symbol`)
880/// on which to slap yer breakpoints.
881#[inline(never)]
882#[cfg_attr(not(test), rustc_std_internal_symbol)]
883#[cfg(not(panic = "immediate-abort"))]
884fn rust_panic(msg: &mut dyn PanicPayload) -> ! {
885 let code = __rust_start_panic(msg);
886 rtabort!("failed to initiate panic, error {code}")
887}
888
889#[cfg_attr(not(test), rustc_std_internal_symbol)]
890#[cfg(panic = "immediate-abort")]
891fn rust_panic(_: &mut dyn PanicPayload) -> ! {
892 crate::intrinsics::abort_immediate();
893}