1 //! Implementation of various bits and pieces of the `panic!` macro and
2 //! associated runtime pieces.
4 //! Specifically, this module contains the implementation of:
7 //! * Executing a panic up to doing the actual implementation
8 //! * Shims around "try"
10 #![deny(unsafe_op_in_unsafe_fn)]
12 use core::panic::{BoxMeUp, Location, PanicInfo};
16 use crate::intrinsics;
17 use crate::mem::{self, ManuallyDrop};
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::RWLock;
23 use crate::sys_common::{thread_info, util};
27 use crate::io::set_panic;
28 // make sure to use the stderr output configured
29 // by libtest in the real copy of std
31 use realstd::io::set_panic;
33 // Binary interface to the panic runtime that the standard library depends on.
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
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)]
45 fn __rust_panic_cleanup(payload: *mut u8) -> *mut (dyn Any + Send + 'static);
47 /// `payload` is actually a `*mut &mut dyn BoxMeUp` but that would cause FFI warnings.
48 /// It cannot be `Box<dyn BoxMeUp>` because the other end of this call does not depend
49 /// on liballoc, and thus cannot use `Box`.
51 fn __rust_start_panic(payload: usize) -> u32;
54 /// This function is called by the panic runtime if FFI code catches a Rust
55 /// panic but doesn't rethrow it. We don't support this case since it messes
56 /// with our panic count.
58 #[rustc_std_internal_symbol]
59 extern "C" fn __rust_drop_panic() -> ! {
60 rtabort!("Rust panics must be rethrown");
63 /// This function is called by the panic runtime if it catches an exception
64 /// object which does not correspond to a Rust panic.
66 #[rustc_std_internal_symbol]
67 extern "C" fn __rust_foreign_exception() -> ! {
68 rtabort!("Rust cannot catch foreign exceptions");
71 #[derive(Copy, Clone)]
74 Custom(*mut (dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send)),
77 static HOOK_LOCK: RWLock = RWLock::new();
78 static mut HOOK: Hook = Hook::Default;
80 /// Registers a custom panic hook, replacing any that was previously registered.
82 /// The panic hook is invoked when a thread panics, but before the panic runtime
83 /// is invoked. As such, the hook will run with both the aborting and unwinding
84 /// runtimes. The default hook prints a message to standard error and generates
85 /// a backtrace if requested, but this behavior can be customized with the
86 /// `set_hook` and [`take_hook`] functions.
88 /// [`take_hook`]: ./fn.take_hook.html
90 /// The hook is provided with a `PanicInfo` struct which contains information
91 /// about the origin of the panic, including the payload passed to `panic!` and
92 /// the source code location from which the panic originated.
94 /// The panic hook is a global resource.
98 /// Panics if called from a panicking thread.
102 /// The following will print "Custom panic hook":
107 /// panic::set_hook(Box::new(|_| {
108 /// println!("Custom panic hook");
111 /// panic!("Normal panic");
113 #[stable(feature = "panic_hooks", since = "1.10.0")]
114 pub fn set_hook(hook: Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send>) {
115 if thread::panicking() {
116 panic!("cannot modify the panic hook from a panicking thread");
122 HOOK = Hook::Custom(Box::into_raw(hook));
123 HOOK_LOCK.write_unlock();
125 if let Hook::Custom(ptr) = old_hook {
126 #[allow(unused_must_use)]
134 /// Unregisters the current panic hook, returning it.
136 /// *See also the function [`set_hook`].*
138 /// [`set_hook`]: ./fn.set_hook.html
140 /// If no custom hook is registered, the default hook will be returned.
144 /// Panics if called from a panicking thread.
148 /// The following will print "Normal panic":
153 /// panic::set_hook(Box::new(|_| {
154 /// println!("Custom panic hook");
157 /// let _ = panic::take_hook();
159 /// panic!("Normal panic");
161 #[stable(feature = "panic_hooks", since = "1.10.0")]
162 pub fn take_hook() -> Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send> {
163 if thread::panicking() {
164 panic!("cannot modify the panic hook from a panicking thread");
170 HOOK = Hook::Default;
171 HOOK_LOCK.write_unlock();
174 Hook::Default => Box::new(default_hook),
175 Hook::Custom(ptr) => Box::from_raw(ptr),
180 fn default_hook(info: &PanicInfo<'_>) {
181 // If this is a double panic, make sure that we print a backtrace
182 // for this panic. Otherwise only print it if logging is enabled.
183 let backtrace_env = if panic_count::get() >= 2 {
184 RustBacktrace::Print(crate::backtrace_rs::PrintFmt::Full)
186 backtrace::rust_backtrace_env()
189 // The current implementation always returns `Some`.
190 let location = info.location().unwrap();
192 let msg = match info.payload().downcast_ref::<&'static str>() {
194 None => match info.payload().downcast_ref::<String>() {
199 let thread = thread_info::current_thread();
200 let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");
202 let write = |err: &mut dyn crate::io::Write| {
203 let _ = writeln!(err, "thread '{}' panicked at '{}', {}", name, msg, location);
205 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
207 match backtrace_env {
208 RustBacktrace::Print(format) => drop(backtrace::print(err, format)),
209 RustBacktrace::Disabled => {}
210 RustBacktrace::RuntimeDisabled => {
211 if FIRST_PANIC.swap(false, Ordering::SeqCst) {
214 "note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace"
221 if let Some(local) = set_panic(None) {
222 let mut stream = local.lock().unwrap_or_else(|e| e.into_inner());
227 struct Wrapper<'a>(&'a mut (dyn ::realstd::io::Write + Send));
228 impl io::Write for Wrapper<'_> {
229 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
230 self.0.write(buf).map_err(|_| io::ErrorKind::Other.into())
232 fn flush(&mut self) -> io::Result<()> {
233 self.0.flush().map_err(|_| io::ErrorKind::Other.into())
236 write(&mut Wrapper(&mut *stream));
244 set_panic(Some(local));
245 } else if let Some(mut out) = panic_output() {
252 #[unstable(feature = "update_panic_count", issue = "none")]
253 pub mod panic_count {
254 use crate::cell::Cell;
255 use crate::sync::atomic::{AtomicUsize, Ordering};
257 // Panic count for the current thread.
258 thread_local! { static LOCAL_PANIC_COUNT: Cell<usize> = Cell::new(0) }
260 // Sum of panic counts from all threads. The purpose of this is to have
261 // a fast path in `is_zero` (which is used by `panicking`). In any particular
262 // thread, if that thread currently views `GLOBAL_PANIC_COUNT` as being zero,
263 // then `LOCAL_PANIC_COUNT` in that thread is zero. This invariant holds before
264 // and after increase and decrease, but not necessarily during their execution.
265 static GLOBAL_PANIC_COUNT: AtomicUsize = AtomicUsize::new(0);
267 pub fn increase() -> usize {
268 GLOBAL_PANIC_COUNT.fetch_add(1, Ordering::Relaxed);
269 LOCAL_PANIC_COUNT.with(|c| {
270 let next = c.get() + 1;
276 pub fn decrease() -> usize {
277 GLOBAL_PANIC_COUNT.fetch_sub(1, Ordering::Relaxed);
278 LOCAL_PANIC_COUNT.with(|c| {
279 let next = c.get() - 1;
285 pub fn get() -> usize {
286 LOCAL_PANIC_COUNT.with(|c| c.get())
290 pub fn is_zero() -> bool {
291 if GLOBAL_PANIC_COUNT.load(Ordering::Relaxed) == 0 {
292 // Fast path: if `GLOBAL_PANIC_COUNT` is zero, all threads
293 // (including the current one) will have `LOCAL_PANIC_COUNT`
294 // equal to zero, so TLS access can be avoided.
296 // In terms of performance, a relaxed atomic load is similar to a normal
297 // aligned memory read (e.g., a mov instruction in x86), but with some
298 // compiler optimization restrictions. On the other hand, a TLS access
299 // might require calling a non-inlinable function (such as `__tls_get_addr`
300 // when using the GD TLS model).
307 // Slow path is in a separate function to reduce the amount of code
308 // inlined from `is_zero`.
311 fn is_zero_slow_path() -> bool {
312 LOCAL_PANIC_COUNT.with(|c| c.get() == 0)
317 pub use realstd::rt::panic_count;
319 /// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
320 pub unsafe fn r#try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>> {
324 p: ManuallyDrop<Box<dyn Any + Send>>,
327 // We do some sketchy operations with ownership here for the sake of
328 // performance. We can only pass pointers down to `do_call` (can't pass
329 // objects by value), so we do all the ownership tracking here manually
332 // We go through a transition where:
334 // * First, we set the data field `f` to be the argumentless closure that we're going to call.
335 // * When we make the function call, the `do_call` function below, we take
336 // ownership of the function pointer. At this point the `data` union is
337 // entirely uninitialized.
338 // * If the closure successfully returns, we write the return value into the
339 // data's return slot (field `r`).
340 // * If the closure panics (`do_catch` below), we write the panic payload into field `p`.
341 // * Finally, when we come back out of the `try` intrinsic we're
342 // in one of two states:
344 // 1. The closure didn't panic, in which case the return value was
345 // filled in. We move it out of `data.r` and return it.
346 // 2. The closure panicked, in which case the panic payload was
347 // filled in. We move it out of `data.p` and return it.
349 // Once we stack all that together we should have the "most efficient'
350 // method of calling a catch panic whilst juggling ownership.
351 let mut data = Data { f: ManuallyDrop::new(f) };
353 let data_ptr = &mut data as *mut _ as *mut u8;
356 // Access to the union's fields: this is `std` and we know that the `r#try`
357 // intrinsic fills in the `r` or `p` union field based on its return value.
359 // The call to `intrinsics::r#try` is made safe by:
360 // - `do_call`, the first argument, can be called with the initial `data_ptr`.
361 // - `do_catch`, the second argument, can be called with the `data_ptr` as well.
362 // See their safety preconditions for more informations
364 return if intrinsics::r#try(do_call::<F, R>, data_ptr, do_catch::<F, R>) == 0 {
365 Ok(ManuallyDrop::into_inner(data.r))
367 Err(ManuallyDrop::into_inner(data.p))
371 // We consider unwinding to be rare, so mark this function as cold. However,
372 // do not mark it no-inline -- that decision is best to leave to the
373 // optimizer (in most cases this function is not inlined even as a normal,
374 // non-cold function, though, as of the writing of this comment).
376 unsafe fn cleanup(payload: *mut u8) -> Box<dyn Any + Send + 'static> {
377 // SAFETY: The whole unsafe block hinges on a correct implementation of
378 // the panic handler `__rust_panic_cleanup`. As such we can only
379 // assume it returns the correct thing for `Box::from_raw` to work
380 // without undefined behavior.
381 let obj = unsafe { Box::from_raw(__rust_panic_cleanup(payload)) };
382 panic_count::decrease();
387 // data must be non-NUL, correctly aligned, and a pointer to a `Data<F, R>`
388 // Its must contains a valid `f` (type: F) value that can be use to fill
391 // This function cannot be marked as `unsafe` because `intrinsics::r#try`
392 // expects normal function pointers.
394 fn do_call<F: FnOnce() -> R, R>(data: *mut u8) {
395 // SAFETY: this is the responsibilty of the caller, see above.
397 let data = data as *mut Data<F, R>;
398 let data = &mut (*data);
399 let f = ManuallyDrop::take(&mut data.f);
400 data.r = ManuallyDrop::new(f());
404 // We *do* want this part of the catch to be inlined: this allows the
405 // compiler to properly track accesses to the Data union and optimize it
406 // away most of the time.
409 // data must be non-NUL, correctly aligned, and a pointer to a `Data<F, R>`
410 // Since this uses `cleanup` it also hinges on a correct implementation of
411 // `__rustc_panic_cleanup`.
413 // This function cannot be marked as `unsafe` because `intrinsics::r#try`
414 // expects normal function pointers.
416 fn do_catch<F: FnOnce() -> R, R>(data: *mut u8, payload: *mut u8) {
417 // SAFETY: this is the responsibilty of the caller, see above.
419 // When `__rustc_panic_cleaner` is correctly implemented we can rely
420 // on `obj` being the correct thing to pass to `data.p` (after wrapping
421 // in `ManuallyDrop`).
423 let data = data as *mut Data<F, R>;
424 let data = &mut (*data);
425 let obj = cleanup(payload);
426 data.p = ManuallyDrop::new(obj);
431 /// Determines whether the current thread is unwinding because of panic.
433 pub fn panicking() -> bool {
434 !panic_count::is_zero()
437 /// The entry point for panicking with a formatted message.
439 /// This is designed to reduce the amount of code required at the call
440 /// site as much as possible (so that `panic!()` has as low an impact
441 /// on (e.g.) the inlining of other functions as possible), by moving
442 /// the actual formatting into this shared place.
443 #[unstable(feature = "libstd_sys_internals", reason = "used by the panic! macro", issue = "none")]
445 // If panic_immediate_abort, inline the abort call,
446 // otherwise avoid inlining because of it is cold path.
447 #[cfg_attr(not(feature = "panic_immediate_abort"), track_caller)]
448 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
449 #[cfg_attr(feature = "panic_immediate_abort", inline)]
450 pub fn begin_panic_fmt(msg: &fmt::Arguments<'_>) -> ! {
451 if cfg!(feature = "panic_immediate_abort") {
455 let info = PanicInfo::internal_constructor(Some(msg), Location::caller());
456 begin_panic_handler(&info)
459 /// Entry point of panics from the libcore crate (`panic_impl` lang item).
460 #[cfg_attr(not(test), panic_handler)]
462 pub fn begin_panic_handler(info: &PanicInfo<'_>) -> ! {
463 struct PanicPayload<'a> {
464 inner: &'a fmt::Arguments<'a>,
465 string: Option<String>,
468 impl<'a> PanicPayload<'a> {
469 fn new(inner: &'a fmt::Arguments<'a>) -> PanicPayload<'a> {
470 PanicPayload { inner, string: None }
473 fn fill(&mut self) -> &mut String {
474 use crate::fmt::Write;
476 let inner = self.inner;
477 // Lazily, the first time this gets called, run the actual string formatting.
478 self.string.get_or_insert_with(|| {
479 let mut s = String::new();
480 drop(s.write_fmt(*inner));
486 unsafe impl<'a> BoxMeUp for PanicPayload<'a> {
487 fn take_box(&mut self) -> *mut (dyn Any + Send) {
488 // We do two allocations here, unfortunately. But (a) they're required with the current
489 // scheme, and (b) we don't handle panic + OOM properly anyway (see comment in
490 // begin_panic below).
491 let contents = mem::take(self.fill());
492 Box::into_raw(Box::new(contents))
495 fn get(&mut self) -> &(dyn Any + Send) {
500 struct StrPanicPayload(&'static str);
502 unsafe impl BoxMeUp for StrPanicPayload {
503 fn take_box(&mut self) -> *mut (dyn Any + Send) {
504 Box::into_raw(Box::new(self.0))
507 fn get(&mut self) -> &(dyn Any + Send) {
512 let loc = info.location().unwrap(); // The current implementation always returns Some
513 let msg = info.message().unwrap(); // The current implementation always returns Some
514 crate::sys_common::backtrace::__rust_end_short_backtrace(move || {
515 if let Some(msg) = msg.as_str() {
516 rust_panic_with_hook(&mut StrPanicPayload(msg), info.message(), loc);
518 rust_panic_with_hook(&mut PanicPayload::new(msg), info.message(), loc);
523 /// This is the entry point of panicking for the non-format-string variants of
524 /// panic!() and assert!(). In particular, this is the only entry point that supports
525 /// arbitrary payloads, not just format strings.
526 #[unstable(feature = "libstd_sys_internals", reason = "used by the panic! macro", issue = "none")]
527 #[cfg_attr(not(test), lang = "begin_panic")]
528 // lang item for CTFE panic support
529 // never inline unless panic_immediate_abort to avoid code
530 // bloat at the call sites as much as possible
531 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
534 pub fn begin_panic<M: Any + Send>(msg: M) -> ! {
535 if cfg!(feature = "panic_immediate_abort") {
539 let loc = Location::caller();
540 return crate::sys_common::backtrace::__rust_end_short_backtrace(move || {
541 rust_panic_with_hook(&mut PanicPayload::new(msg), None, loc)
544 struct PanicPayload<A> {
548 impl<A: Send + 'static> PanicPayload<A> {
549 fn new(inner: A) -> PanicPayload<A> {
550 PanicPayload { inner: Some(inner) }
554 unsafe impl<A: Send + 'static> BoxMeUp for PanicPayload<A> {
555 fn take_box(&mut self) -> *mut (dyn Any + Send) {
556 // Note that this should be the only allocation performed in this code path. Currently
557 // this means that panic!() on OOM will invoke this code path, but then again we're not
558 // really ready for panic on OOM anyway. If we do start doing this, then we should
559 // propagate this allocation to be performed in the parent of this thread instead of the
560 // thread that's panicking.
561 let data = match self.inner.take() {
562 Some(a) => Box::new(a) as Box<dyn Any + Send>,
563 None => process::abort(),
568 fn get(&mut self) -> &(dyn Any + Send) {
571 None => process::abort(),
577 /// Central point for dispatching panics.
579 /// Executes the primary logic for a panic, including checking for recursive
580 /// panics, panic hooks, and finally dispatching to the panic runtime to either
582 fn rust_panic_with_hook(
583 payload: &mut dyn BoxMeUp,
584 message: Option<&fmt::Arguments<'_>>,
585 location: &Location<'_>,
587 let panics = panic_count::increase();
589 // If this is the third nested call (e.g., panics == 2, this is 0-indexed),
590 // the panic hook probably triggered the last panic, otherwise the
591 // double-panic check would have aborted the process. In this case abort the
592 // process real quickly as we don't want to try calling it again as it'll
593 // probably just panic again.
595 util::dumb_print(format_args!("thread panicked while processing panic. aborting.\n"));
600 let mut info = PanicInfo::internal_constructor(message, location);
603 // Some platforms (like wasm) know that printing to stderr won't ever actually
604 // print anything, and if that's the case we can skip the default
605 // hook. Since string formatting happens lazily when calling `payload`
606 // methods, this means we avoid formatting the string at all!
607 // (The panic runtime might still call `payload.take_box()` though and trigger
609 Hook::Default if panic_output().is_none() => {}
611 info.set_payload(payload.get());
614 Hook::Custom(ptr) => {
615 info.set_payload(payload.get());
619 HOOK_LOCK.read_unlock();
623 // If a thread panics while it's already unwinding then we
624 // have limited options. Currently our preference is to
625 // just abort. In the future we may consider resuming
626 // unwinding or otherwise exiting the thread cleanly.
627 util::dumb_print(format_args!("thread panicked while panicking. aborting.\n"));
634 /// This is the entry point for `resume_unwind`.
635 /// It just forwards the payload to the panic runtime.
636 pub fn rust_panic_without_hook(payload: Box<dyn Any + Send>) -> ! {
637 panic_count::increase();
639 struct RewrapBox(Box<dyn Any + Send>);
641 unsafe impl BoxMeUp for RewrapBox {
642 fn take_box(&mut self) -> *mut (dyn Any + Send) {
643 Box::into_raw(mem::replace(&mut self.0, Box::new(())))
646 fn get(&mut self) -> &(dyn Any + Send) {
651 rust_panic(&mut RewrapBox(payload))
654 /// An unmangled function (through `rustc_std_internal_symbol`) on which to slap
657 #[cfg_attr(not(test), rustc_std_internal_symbol)]
658 fn rust_panic(mut msg: &mut dyn BoxMeUp) -> ! {
660 let obj = &mut msg as *mut &mut dyn BoxMeUp;
661 __rust_start_panic(obj as usize)
663 rtabort!("failed to initiate panic, error {}", code)