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