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