]> git.lizzy.rs Git - rust.git/blob - library/std/src/panicking.rs
Rollup merge of #102187 - b-naber:inline-const-source-info, r=eholk
[rust.git] / library / std / src / 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
12 use crate::panic::BacktraceStyle;
13 use core::panic::{BoxMeUp, Location, PanicInfo};
14
15 use crate::any::Any;
16 use crate::fmt;
17 use crate::intrinsics;
18 use crate::mem::{self, ManuallyDrop};
19 use crate::process;
20 use crate::sync::atomic::{AtomicBool, Ordering};
21 use crate::sync::{PoisonError, RwLock};
22 use crate::sys::stdio::panic_output;
23 use crate::sys_common::backtrace;
24 use crate::sys_common::thread_info;
25 use crate::thread;
26
27 #[cfg(not(test))]
28 use crate::io::set_output_capture;
29 // make sure to use the stderr output configured
30 // by libtest in the real copy of std
31 #[cfg(test)]
32 use realstd::io::set_output_capture;
33
34 // Binary interface to the panic runtime that the standard library depends on.
35 //
36 // The standard library is tagged with `#![needs_panic_runtime]` (introduced in
37 // RFC 1513) to indicate that it requires some other crate tagged with
38 // `#![panic_runtime]` to exist somewhere. Each panic runtime is intended to
39 // implement these symbols (with the same signatures) so we can get matched up
40 // to them.
41 //
42 // One day this may look a little less ad-hoc with the compiler helping out to
43 // hook up these functions, but it is not this day!
44 #[allow(improper_ctypes)]
45 extern "C" {
46     fn __rust_panic_cleanup(payload: *mut u8) -> *mut (dyn Any + Send + 'static);
47 }
48
49 #[allow(improper_ctypes)]
50 extern "Rust" {
51     /// `payload` is passed through another layer of raw pointers as `&mut dyn Trait` is not
52     /// FFI-safe. `BoxMeUp` lazily performs allocation only when needed (this avoids allocations
53     /// when using the "abort" panic runtime).
54     fn __rust_start_panic(payload: *mut &mut dyn BoxMeUp) -> u32;
55 }
56
57 /// This function is called by the panic runtime if FFI code catches a Rust
58 /// panic but doesn't rethrow it. We don't support this case since it messes
59 /// with our panic count.
60 #[cfg(not(test))]
61 #[rustc_std_internal_symbol]
62 extern "C" fn __rust_drop_panic() -> ! {
63     rtabort!("Rust panics must be rethrown");
64 }
65
66 /// This function is called by the panic runtime if it catches an exception
67 /// object which does not correspond to a Rust panic.
68 #[cfg(not(test))]
69 #[rustc_std_internal_symbol]
70 extern "C" fn __rust_foreign_exception() -> ! {
71     rtabort!("Rust cannot catch foreign exceptions");
72 }
73
74 enum Hook {
75     Default,
76     Custom(Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send>),
77 }
78
79 impl Hook {
80     #[inline]
81     fn into_box(self) -> Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send> {
82         match self {
83             Hook::Default => Box::new(default_hook),
84             Hook::Custom(hook) => hook,
85         }
86     }
87 }
88
89 impl Default for Hook {
90     #[inline]
91     fn default() -> Hook {
92         Hook::Default
93     }
94 }
95
96 static HOOK: RwLock<Hook> = RwLock::new(Hook::Default);
97
98 /// Registers a custom panic hook, replacing any that was previously registered.
99 ///
100 /// The panic hook is invoked when a thread panics, but before the panic runtime
101 /// is invoked. As such, the hook will run with both the aborting and unwinding
102 /// runtimes. The default hook prints a message to standard error and generates
103 /// a backtrace if requested, but this behavior can be customized with the
104 /// `set_hook` and [`take_hook`] functions.
105 ///
106 /// [`take_hook`]: ./fn.take_hook.html
107 ///
108 /// The hook is provided with a `PanicInfo` struct which contains information
109 /// about the origin of the panic, including the payload passed to `panic!` and
110 /// the source code location from which the panic originated.
111 ///
112 /// The panic hook is a global resource.
113 ///
114 /// # Panics
115 ///
116 /// Panics if called from a panicking thread.
117 ///
118 /// # Examples
119 ///
120 /// The following will print "Custom panic hook":
121 ///
122 /// ```should_panic
123 /// use std::panic;
124 ///
125 /// panic::set_hook(Box::new(|_| {
126 ///     println!("Custom panic hook");
127 /// }));
128 ///
129 /// panic!("Normal panic");
130 /// ```
131 #[stable(feature = "panic_hooks", since = "1.10.0")]
132 pub fn set_hook(hook: Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send>) {
133     if thread::panicking() {
134         panic!("cannot modify the panic hook from a panicking thread");
135     }
136
137     let new = Hook::Custom(hook);
138     let mut hook = HOOK.write().unwrap_or_else(PoisonError::into_inner);
139     let old = mem::replace(&mut *hook, new);
140     drop(hook);
141     // Only drop the old hook after releasing the lock to avoid deadlocking
142     // if its destructor panics.
143     drop(old);
144 }
145
146 /// Unregisters the current panic hook, returning it.
147 ///
148 /// *See also the function [`set_hook`].*
149 ///
150 /// [`set_hook`]: ./fn.set_hook.html
151 ///
152 /// If no custom hook is registered, the default hook will be returned.
153 ///
154 /// # Panics
155 ///
156 /// Panics if called from a panicking thread.
157 ///
158 /// # Examples
159 ///
160 /// The following will print "Normal panic":
161 ///
162 /// ```should_panic
163 /// use std::panic;
164 ///
165 /// panic::set_hook(Box::new(|_| {
166 ///     println!("Custom panic hook");
167 /// }));
168 ///
169 /// let _ = panic::take_hook();
170 ///
171 /// panic!("Normal panic");
172 /// ```
173 #[must_use]
174 #[stable(feature = "panic_hooks", since = "1.10.0")]
175 pub fn take_hook() -> Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send> {
176     if thread::panicking() {
177         panic!("cannot modify the panic hook from a panicking thread");
178     }
179
180     let mut hook = HOOK.write().unwrap_or_else(PoisonError::into_inner);
181     let old_hook = mem::take(&mut *hook);
182     drop(hook);
183
184     old_hook.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(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")]
219 pub fn update_hook<F>(hook_fn: F)
220 where
221     F: Fn(&(dyn Fn(&PanicInfo<'_>) + Send + Sync + 'static), &PanicInfo<'_>)
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().unwrap_or_else(PoisonError::into_inner);
231     let prev = mem::take(&mut *hook).into_box();
232     *hook = Hook::Custom(Box::new(move |info| hook_fn(&prev, info)));
233 }
234
235 fn default_hook(info: &PanicInfo<'_>) {
236     // If this is a double panic, make sure that we print a backtrace
237     // for this panic. Otherwise only print it if logging is enabled.
238     let backtrace = if panic_count::get_count() >= 2 {
239         BacktraceStyle::full()
240     } else {
241         crate::panic::get_backtrace_style()
242     };
243
244     // The current implementation always returns `Some`.
245     let location = info.location().unwrap();
246
247     let msg = match info.payload().downcast_ref::<&'static str>() {
248         Some(s) => *s,
249         None => match info.payload().downcast_ref::<String>() {
250             Some(s) => &s[..],
251             None => "Box<dyn Any>",
252         },
253     };
254     let thread = thread_info::current_thread();
255     let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");
256
257     let write = |err: &mut dyn crate::io::Write| {
258         let _ = writeln!(err, "thread '{name}' panicked at '{msg}', {location}");
259
260         static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
261
262         match backtrace {
263             Some(BacktraceStyle::Short) => {
264                 drop(backtrace::print(err, crate::backtrace_rs::PrintFmt::Short))
265             }
266             Some(BacktraceStyle::Full) => {
267                 drop(backtrace::print(err, crate::backtrace_rs::PrintFmt::Full))
268             }
269             Some(BacktraceStyle::Off) => {
270                 if FIRST_PANIC.swap(false, Ordering::SeqCst) {
271                     let _ = writeln!(
272                         err,
273                         "note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace"
274                     );
275                 }
276             }
277             // If backtraces aren't supported, do nothing.
278             None => {}
279         }
280     };
281
282     if let Some(local) = set_output_capture(None) {
283         write(&mut *local.lock().unwrap_or_else(|e| e.into_inner()));
284         set_output_capture(Some(local));
285     } else if let Some(mut out) = panic_output() {
286         write(&mut out);
287     }
288 }
289
290 #[cfg(not(test))]
291 #[doc(hidden)]
292 #[unstable(feature = "update_panic_count", issue = "none")]
293 pub mod panic_count {
294     use crate::cell::Cell;
295     use crate::sync::atomic::{AtomicUsize, Ordering};
296
297     pub const ALWAYS_ABORT_FLAG: usize = 1 << (usize::BITS - 1);
298
299     // Panic count for the current thread.
300     thread_local! { static LOCAL_PANIC_COUNT: Cell<usize> = const { Cell::new(0) } }
301
302     // Sum of panic counts from all threads. The purpose of this is to have
303     // a fast path in `count_is_zero` (which is used by `panicking`). In any particular
304     // thread, if that thread currently views `GLOBAL_PANIC_COUNT` as being zero,
305     // then `LOCAL_PANIC_COUNT` in that thread is zero. This invariant holds before
306     // and after increase and decrease, but not necessarily during their execution.
307     //
308     // Additionally, the top bit of GLOBAL_PANIC_COUNT (GLOBAL_ALWAYS_ABORT_FLAG)
309     // records whether panic::always_abort() has been called.  This can only be
310     // set, never cleared.
311     //
312     // This could be viewed as a struct containing a single bit and an n-1-bit
313     // value, but if we wrote it like that it would be more than a single word,
314     // and even a newtype around usize would be clumsy because we need atomics.
315     // But we use such a tuple for the return type of increase().
316     //
317     // Stealing a bit is fine because it just amounts to assuming that each
318     // panicking thread consumes at least 2 bytes of address space.
319     static GLOBAL_PANIC_COUNT: AtomicUsize = AtomicUsize::new(0);
320
321     pub fn increase() -> (bool, usize) {
322         (
323             GLOBAL_PANIC_COUNT.fetch_add(1, Ordering::Relaxed) & ALWAYS_ABORT_FLAG != 0,
324             LOCAL_PANIC_COUNT.with(|c| {
325                 let next = c.get() + 1;
326                 c.set(next);
327                 next
328             }),
329         )
330     }
331
332     pub fn decrease() {
333         GLOBAL_PANIC_COUNT.fetch_sub(1, Ordering::Relaxed);
334         LOCAL_PANIC_COUNT.with(|c| {
335             let next = c.get() - 1;
336             c.set(next);
337             next
338         });
339     }
340
341     pub fn set_always_abort() {
342         GLOBAL_PANIC_COUNT.fetch_or(ALWAYS_ABORT_FLAG, Ordering::Relaxed);
343     }
344
345     // Disregards ALWAYS_ABORT_FLAG
346     #[must_use]
347     pub fn get_count() -> usize {
348         LOCAL_PANIC_COUNT.with(|c| c.get())
349     }
350
351     // Disregards ALWAYS_ABORT_FLAG
352     #[must_use]
353     #[inline]
354     pub fn count_is_zero() -> bool {
355         if GLOBAL_PANIC_COUNT.load(Ordering::Relaxed) & !ALWAYS_ABORT_FLAG == 0 {
356             // Fast path: if `GLOBAL_PANIC_COUNT` is zero, all threads
357             // (including the current one) will have `LOCAL_PANIC_COUNT`
358             // equal to zero, so TLS access can be avoided.
359             //
360             // In terms of performance, a relaxed atomic load is similar to a normal
361             // aligned memory read (e.g., a mov instruction in x86), but with some
362             // compiler optimization restrictions. On the other hand, a TLS access
363             // might require calling a non-inlinable function (such as `__tls_get_addr`
364             // when using the GD TLS model).
365             true
366         } else {
367             is_zero_slow_path()
368         }
369     }
370
371     // Slow path is in a separate function to reduce the amount of code
372     // inlined from `count_is_zero`.
373     #[inline(never)]
374     #[cold]
375     fn is_zero_slow_path() -> bool {
376         LOCAL_PANIC_COUNT.with(|c| c.get() == 0)
377     }
378 }
379
380 #[cfg(test)]
381 pub use realstd::rt::panic_count;
382
383 /// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
384 pub unsafe fn r#try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>> {
385     union Data<F, R> {
386         f: ManuallyDrop<F>,
387         r: ManuallyDrop<R>,
388         p: ManuallyDrop<Box<dyn Any + Send>>,
389     }
390
391     // We do some sketchy operations with ownership here for the sake of
392     // performance. We can only pass pointers down to `do_call` (can't pass
393     // objects by value), so we do all the ownership tracking here manually
394     // using a union.
395     //
396     // We go through a transition where:
397     //
398     // * First, we set the data field `f` to be the argumentless closure that we're going to call.
399     // * When we make the function call, the `do_call` function below, we take
400     //   ownership of the function pointer. At this point the `data` union is
401     //   entirely uninitialized.
402     // * If the closure successfully returns, we write the return value into the
403     //   data's return slot (field `r`).
404     // * If the closure panics (`do_catch` below), we write the panic payload into field `p`.
405     // * Finally, when we come back out of the `try` intrinsic we're
406     //   in one of two states:
407     //
408     //      1. The closure didn't panic, in which case the return value was
409     //         filled in. We move it out of `data.r` and return it.
410     //      2. The closure panicked, in which case the panic payload was
411     //         filled in. We move it out of `data.p` and return it.
412     //
413     // Once we stack all that together we should have the "most efficient'
414     // method of calling a catch panic whilst juggling ownership.
415     let mut data = Data { f: ManuallyDrop::new(f) };
416
417     let data_ptr = &mut data as *mut _ as *mut u8;
418     // SAFETY:
419     //
420     // Access to the union's fields: this is `std` and we know that the `r#try`
421     // intrinsic fills in the `r` or `p` union field based on its return value.
422     //
423     // The call to `intrinsics::r#try` is made safe by:
424     // - `do_call`, the first argument, can be called with the initial `data_ptr`.
425     // - `do_catch`, the second argument, can be called with the `data_ptr` as well.
426     // See their safety preconditions for more information
427     unsafe {
428         return if intrinsics::r#try(do_call::<F, R>, data_ptr, do_catch::<F, R>) == 0 {
429             Ok(ManuallyDrop::into_inner(data.r))
430         } else {
431             Err(ManuallyDrop::into_inner(data.p))
432         };
433     }
434
435     // We consider unwinding to be rare, so mark this function as cold. However,
436     // do not mark it no-inline -- that decision is best to leave to the
437     // optimizer (in most cases this function is not inlined even as a normal,
438     // non-cold function, though, as of the writing of this comment).
439     #[cold]
440     unsafe fn cleanup(payload: *mut u8) -> Box<dyn Any + Send + 'static> {
441         // SAFETY: The whole unsafe block hinges on a correct implementation of
442         // the panic handler `__rust_panic_cleanup`. As such we can only
443         // assume it returns the correct thing for `Box::from_raw` to work
444         // without undefined behavior.
445         let obj = unsafe { Box::from_raw(__rust_panic_cleanup(payload)) };
446         panic_count::decrease();
447         obj
448     }
449
450     // SAFETY:
451     // data must be non-NUL, correctly aligned, and a pointer to a `Data<F, R>`
452     // Its must contains a valid `f` (type: F) value that can be use to fill
453     // `data.r`.
454     //
455     // This function cannot be marked as `unsafe` because `intrinsics::r#try`
456     // expects normal function pointers.
457     #[inline]
458     fn do_call<F: FnOnce() -> R, R>(data: *mut u8) {
459         // SAFETY: this is the responsibility of the caller, see above.
460         unsafe {
461             let data = data as *mut Data<F, R>;
462             let data = &mut (*data);
463             let f = ManuallyDrop::take(&mut data.f);
464             data.r = ManuallyDrop::new(f());
465         }
466     }
467
468     // We *do* want this part of the catch to be inlined: this allows the
469     // compiler to properly track accesses to the Data union and optimize it
470     // away most of the time.
471     //
472     // SAFETY:
473     // data must be non-NUL, correctly aligned, and a pointer to a `Data<F, R>`
474     // Since this uses `cleanup` it also hinges on a correct implementation of
475     // `__rustc_panic_cleanup`.
476     //
477     // This function cannot be marked as `unsafe` because `intrinsics::r#try`
478     // expects normal function pointers.
479     #[inline]
480     fn do_catch<F: FnOnce() -> R, R>(data: *mut u8, payload: *mut u8) {
481         // SAFETY: this is the responsibility of the caller, see above.
482         //
483         // When `__rustc_panic_cleaner` is correctly implemented we can rely
484         // on `obj` being the correct thing to pass to `data.p` (after wrapping
485         // in `ManuallyDrop`).
486         unsafe {
487             let data = data as *mut Data<F, R>;
488             let data = &mut (*data);
489             let obj = cleanup(payload);
490             data.p = ManuallyDrop::new(obj);
491         }
492     }
493 }
494
495 /// Determines whether the current thread is unwinding because of panic.
496 #[inline]
497 pub fn panicking() -> bool {
498     !panic_count::count_is_zero()
499 }
500
501 /// Entry point of panics from the libcore crate (`panic_impl` lang item).
502 #[cfg(not(test))]
503 #[panic_handler]
504 pub fn begin_panic_handler(info: &PanicInfo<'_>) -> ! {
505     struct PanicPayload<'a> {
506         inner: &'a fmt::Arguments<'a>,
507         string: Option<String>,
508     }
509
510     impl<'a> PanicPayload<'a> {
511         fn new(inner: &'a fmt::Arguments<'a>) -> PanicPayload<'a> {
512             PanicPayload { inner, string: None }
513         }
514
515         fn fill(&mut self) -> &mut String {
516             use crate::fmt::Write;
517
518             let inner = self.inner;
519             // Lazily, the first time this gets called, run the actual string formatting.
520             self.string.get_or_insert_with(|| {
521                 let mut s = String::new();
522                 drop(s.write_fmt(*inner));
523                 s
524             })
525         }
526     }
527
528     unsafe impl<'a> BoxMeUp for PanicPayload<'a> {
529         fn take_box(&mut self) -> *mut (dyn Any + Send) {
530             // We do two allocations here, unfortunately. But (a) they're required with the current
531             // scheme, and (b) we don't handle panic + OOM properly anyway (see comment in
532             // begin_panic below).
533             let contents = mem::take(self.fill());
534             Box::into_raw(Box::new(contents))
535         }
536
537         fn get(&mut self) -> &(dyn Any + Send) {
538             self.fill()
539         }
540     }
541
542     struct StrPanicPayload(&'static str);
543
544     unsafe impl BoxMeUp for StrPanicPayload {
545         fn take_box(&mut self) -> *mut (dyn Any + Send) {
546             Box::into_raw(Box::new(self.0))
547         }
548
549         fn get(&mut self) -> &(dyn Any + Send) {
550             &self.0
551         }
552     }
553
554     let loc = info.location().unwrap(); // The current implementation always returns Some
555     let msg = info.message().unwrap(); // The current implementation always returns Some
556     crate::sys_common::backtrace::__rust_end_short_backtrace(move || {
557         if let Some(msg) = msg.as_str() {
558             rust_panic_with_hook(&mut StrPanicPayload(msg), info.message(), loc, info.can_unwind());
559         } else {
560             rust_panic_with_hook(
561                 &mut PanicPayload::new(msg),
562                 info.message(),
563                 loc,
564                 info.can_unwind(),
565             );
566         }
567     })
568 }
569
570 /// This is the entry point of panicking for the non-format-string variants of
571 /// panic!() and assert!(). In particular, this is the only entry point that supports
572 /// arbitrary payloads, not just format strings.
573 #[unstable(feature = "libstd_sys_internals", reason = "used by the panic! macro", issue = "none")]
574 #[cfg_attr(not(test), lang = "begin_panic")]
575 // lang item for CTFE panic support
576 // never inline unless panic_immediate_abort to avoid code
577 // bloat at the call sites as much as possible
578 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
579 #[cold]
580 #[track_caller]
581 #[rustc_do_not_const_check] // hooked by const-eval
582 pub const fn begin_panic<M: Any + Send>(msg: M) -> ! {
583     if cfg!(feature = "panic_immediate_abort") {
584         intrinsics::abort()
585     }
586
587     let loc = Location::caller();
588     return crate::sys_common::backtrace::__rust_end_short_backtrace(move || {
589         rust_panic_with_hook(&mut PanicPayload::new(msg), None, loc, true)
590     });
591
592     struct PanicPayload<A> {
593         inner: Option<A>,
594     }
595
596     impl<A: Send + 'static> PanicPayload<A> {
597         fn new(inner: A) -> PanicPayload<A> {
598             PanicPayload { inner: Some(inner) }
599         }
600     }
601
602     unsafe impl<A: Send + 'static> BoxMeUp for PanicPayload<A> {
603         fn take_box(&mut self) -> *mut (dyn Any + Send) {
604             // Note that this should be the only allocation performed in this code path. Currently
605             // this means that panic!() on OOM will invoke this code path, but then again we're not
606             // really ready for panic on OOM anyway. If we do start doing this, then we should
607             // propagate this allocation to be performed in the parent of this thread instead of the
608             // thread that's panicking.
609             let data = match self.inner.take() {
610                 Some(a) => Box::new(a) as Box<dyn Any + Send>,
611                 None => process::abort(),
612             };
613             Box::into_raw(data)
614         }
615
616         fn get(&mut self) -> &(dyn Any + Send) {
617             match self.inner {
618                 Some(ref a) => a,
619                 None => process::abort(),
620             }
621         }
622     }
623 }
624
625 /// Central point for dispatching panics.
626 ///
627 /// Executes the primary logic for a panic, including checking for recursive
628 /// panics, panic hooks, and finally dispatching to the panic runtime to either
629 /// abort or unwind.
630 fn rust_panic_with_hook(
631     payload: &mut dyn BoxMeUp,
632     message: Option<&fmt::Arguments<'_>>,
633     location: &Location<'_>,
634     can_unwind: bool,
635 ) -> ! {
636     let (must_abort, panics) = panic_count::increase();
637
638     // If this is the third nested call (e.g., panics == 2, this is 0-indexed),
639     // the panic hook probably triggered the last panic, otherwise the
640     // double-panic check would have aborted the process. In this case abort the
641     // process real quickly as we don't want to try calling it again as it'll
642     // probably just panic again.
643     if must_abort || panics > 2 {
644         if panics > 2 {
645             // Don't try to print the message in this case
646             // - perhaps that is causing the recursive panics.
647             rtprintpanic!("thread panicked while processing panic. aborting.\n");
648         } else {
649             // Unfortunately, this does not print a backtrace, because creating
650             // a `Backtrace` will allocate, which we must to avoid here.
651             let panicinfo = PanicInfo::internal_constructor(message, location, can_unwind);
652             rtprintpanic!("{panicinfo}\npanicked after panic::always_abort(), aborting.\n");
653         }
654         crate::sys::abort_internal();
655     }
656
657     let mut info = PanicInfo::internal_constructor(message, location, can_unwind);
658     let hook = HOOK.read().unwrap_or_else(PoisonError::into_inner);
659     match *hook {
660         // Some platforms (like wasm) know that printing to stderr won't ever actually
661         // print anything, and if that's the case we can skip the default
662         // hook. Since string formatting happens lazily when calling `payload`
663         // methods, this means we avoid formatting the string at all!
664         // (The panic runtime might still call `payload.take_box()` though and trigger
665         // formatting.)
666         Hook::Default if panic_output().is_none() => {}
667         Hook::Default => {
668             info.set_payload(payload.get());
669             default_hook(&info);
670         }
671         Hook::Custom(ref hook) => {
672             info.set_payload(payload.get());
673             hook(&info);
674         }
675     };
676     drop(hook);
677
678     if panics > 1 || !can_unwind {
679         // If a thread panics while it's already unwinding then we
680         // have limited options. Currently our preference is to
681         // just abort. In the future we may consider resuming
682         // unwinding or otherwise exiting the thread cleanly.
683         rtprintpanic!("thread panicked while panicking. aborting.\n");
684         crate::sys::abort_internal();
685     }
686
687     rust_panic(payload)
688 }
689
690 /// This is the entry point for `resume_unwind`.
691 /// It just forwards the payload to the panic runtime.
692 pub fn rust_panic_without_hook(payload: Box<dyn Any + Send>) -> ! {
693     panic_count::increase();
694
695     struct RewrapBox(Box<dyn Any + Send>);
696
697     unsafe impl BoxMeUp for RewrapBox {
698         fn take_box(&mut self) -> *mut (dyn Any + Send) {
699             Box::into_raw(mem::replace(&mut self.0, Box::new(())))
700         }
701
702         fn get(&mut self) -> &(dyn Any + Send) {
703             &*self.0
704         }
705     }
706
707     rust_panic(&mut RewrapBox(payload))
708 }
709
710 /// An unmangled function (through `rustc_std_internal_symbol`) on which to slap
711 /// yer breakpoints.
712 #[inline(never)]
713 #[cfg_attr(not(test), rustc_std_internal_symbol)]
714 fn rust_panic(mut msg: &mut dyn BoxMeUp) -> ! {
715     let code = unsafe {
716         let obj = &mut msg as *mut &mut dyn BoxMeUp;
717         __rust_start_panic(obj)
718     };
719     rtabort!("failed to initiate panic, error {code}")
720 }