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 use core::panic::{BoxMeUp, PanicInfo, Location};
14 use crate::intrinsics;
18 use crate::sys::stdio::panic_output;
19 use crate::sys_common::rwlock::RWLock;
20 use crate::sys_common::thread_info;
21 use crate::sys_common::util;
25 use crate::io::set_panic;
26 // make sure to use the stderr output configured
27 // by libtest in the real copy of std
29 use realstd::io::set_panic;
31 // Binary interface to the panic runtime that the standard library depends on.
33 // The standard library is tagged with `#![needs_panic_runtime]` (introduced in
34 // RFC 1513) to indicate that it requires some other crate tagged with
35 // `#![panic_runtime]` to exist somewhere. Each panic runtime is intended to
36 // implement these symbols (with the same signatures) so we can get matched up
39 // One day this may look a little less ad-hoc with the compiler helping out to
40 // hook up these functions, but it is not this day!
41 #[allow(improper_ctypes)]
43 fn __rust_maybe_catch_panic(f: fn(*mut u8),
46 vtable_ptr: *mut usize) -> u32;
48 fn __rust_start_panic(payload: usize) -> u32;
51 #[derive(Copy, Clone)]
54 Custom(*mut (dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send)),
57 static HOOK_LOCK: RWLock = RWLock::new();
58 static mut HOOK: Hook = Hook::Default;
60 /// Registers a custom panic hook, replacing any that was previously registered.
62 /// The panic hook is invoked when a thread panics, but before the panic runtime
63 /// is invoked. As such, the hook will run with both the aborting and unwinding
64 /// runtimes. The default hook prints a message to standard error and generates
65 /// a backtrace if requested, but this behavior can be customized with the
66 /// `set_hook` and [`take_hook`] functions.
68 /// [`take_hook`]: ./fn.take_hook.html
70 /// The hook is provided with a `PanicInfo` struct which contains information
71 /// about the origin of the panic, including the payload passed to `panic!` and
72 /// the source code location from which the panic originated.
74 /// The panic hook is a global resource.
78 /// Panics if called from a panicking thread.
82 /// The following will print "Custom panic hook":
87 /// panic::set_hook(Box::new(|_| {
88 /// println!("Custom panic hook");
91 /// panic!("Normal panic");
93 #[stable(feature = "panic_hooks", since = "1.10.0")]
94 pub fn set_hook(hook: Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send>) {
95 if thread::panicking() {
96 panic!("cannot modify the panic hook from a panicking thread");
102 HOOK = Hook::Custom(Box::into_raw(hook));
103 HOOK_LOCK.write_unlock();
105 if let Hook::Custom(ptr) = old_hook {
106 #[allow(unused_must_use)] {
113 /// Unregisters the current panic hook, returning it.
115 /// *See also the function [`set_hook`].*
117 /// [`set_hook`]: ./fn.set_hook.html
119 /// If no custom hook is registered, the default hook will be returned.
123 /// Panics if called from a panicking thread.
127 /// The following will print "Normal panic":
132 /// panic::set_hook(Box::new(|_| {
133 /// println!("Custom panic hook");
136 /// let _ = panic::take_hook();
138 /// panic!("Normal panic");
140 #[stable(feature = "panic_hooks", since = "1.10.0")]
141 pub fn take_hook() -> Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send> {
142 if thread::panicking() {
143 panic!("cannot modify the panic hook from a panicking thread");
149 HOOK = Hook::Default;
150 HOOK_LOCK.write_unlock();
153 Hook::Default => Box::new(default_hook),
154 Hook::Custom(ptr) => Box::from_raw(ptr),
159 fn default_hook(info: &PanicInfo<'_>) {
160 #[cfg(feature = "backtrace")]
161 use crate::sys_common::backtrace;
163 // If this is a double panic, make sure that we print a backtrace
164 // for this panic. Otherwise only print it if logging is enabled.
165 #[cfg(feature = "backtrace")]
166 let log_backtrace = {
167 let panics = update_panic_count(0);
170 Some(backtrace::PrintFormat::Full)
172 backtrace::log_enabled()
176 // The current implementation always returns `Some`.
177 let location = info.location().unwrap();
179 let msg = match info.payload().downcast_ref::<&'static str>() {
181 None => match info.payload().downcast_ref::<String>() {
186 let thread = thread_info::current_thread();
187 let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");
189 let write = |err: &mut dyn crate::io::Write| {
190 let _ = writeln!(err, "thread '{}' panicked at '{}', {}",
191 name, msg, location);
193 #[cfg(feature = "backtrace")]
195 use crate::sync::atomic::{AtomicBool, Ordering};
197 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
199 if let Some(format) = log_backtrace {
200 let _ = backtrace::print(err, format);
201 } else if FIRST_PANIC.compare_and_swap(true, false, Ordering::SeqCst) {
202 let _ = writeln!(err, "note: run with `RUST_BACKTRACE=1` \
203 environment variable to display a backtrace.");
208 if let Some(mut local) = set_panic(None) {
209 // NB. In `cfg(test)` this uses the forwarding impl
210 // for `Box<dyn (::realstd::io::Write) + Send>`.
212 set_panic(Some(local));
213 } else if let Some(mut out) = panic_output() {
221 #[unstable(feature = "update_panic_count", issue = "0")]
222 pub fn update_panic_count(amt: isize) -> usize {
223 use crate::cell::Cell;
224 thread_local! { static PANIC_COUNT: Cell<usize> = Cell::new(0) }
226 PANIC_COUNT.with(|c| {
227 let next = (c.get() as isize + amt) as usize;
234 pub use realstd::rt::update_panic_count;
236 /// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
237 pub unsafe fn r#try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>> {
238 #[allow(unions_with_drop_fields)]
244 // We do some sketchy operations with ownership here for the sake of
245 // performance. We can only pass pointers down to
246 // `__rust_maybe_catch_panic` (can't pass objects by value), so we do all
247 // the ownership tracking here manually using a union.
249 // We go through a transition where:
251 // * First, we set the data to be the closure that we're going to call.
252 // * When we make the function call, the `do_call` function below, we take
253 // ownership of the function pointer. At this point the `Data` union is
254 // entirely uninitialized.
255 // * If the closure successfully returns, we write the return value into the
256 // data's return slot. Note that `ptr::write` is used as it's overwriting
257 // uninitialized data.
258 // * Finally, when we come back out of the `__rust_maybe_catch_panic` we're
259 // in one of two states:
261 // 1. The closure didn't panic, in which case the return value was
262 // filled in. We move it out of `data` and return it.
263 // 2. The closure panicked, in which case the return value wasn't
264 // filled in. In this case the entire `data` union is invalid, so
265 // there is no need to drop anything.
267 // Once we stack all that together we should have the "most efficient'
268 // method of calling a catch panic whilst juggling ownership.
269 let mut any_data = 0;
270 let mut any_vtable = 0;
271 let mut data = Data {
275 let r = __rust_maybe_catch_panic(do_call::<F, R>,
276 &mut data as *mut _ as *mut u8,
281 debug_assert!(update_panic_count(0) == 0);
284 update_panic_count(-1);
285 debug_assert!(update_panic_count(0) == 0);
286 Err(mem::transmute(raw::TraitObject {
287 data: any_data as *mut _,
288 vtable: any_vtable as *mut _,
292 fn do_call<F: FnOnce() -> R, R>(data: *mut u8) {
294 let data = data as *mut Data<F, R>;
295 let f = ptr::read(&mut (*data).f);
296 ptr::write(&mut (*data).r, f());
301 /// Determines whether the current thread is unwinding because of panic.
302 pub fn panicking() -> bool {
303 update_panic_count(0) != 0
306 /// Entry point of panic from the libcore crate.
310 pub fn rust_begin_panic(info: &PanicInfo<'_>) -> ! {
311 continue_panic_fmt(&info)
314 /// The entry point for panicking with a formatted message.
316 /// This is designed to reduce the amount of code required at the call
317 /// site as much as possible (so that `panic!()` has as low an impact
318 /// on (e.g.) the inlining of other functions as possible), by moving
319 /// the actual formatting into this shared place.
320 #[unstable(feature = "libstd_sys_internals",
321 reason = "used by the panic! macro",
324 // If panic_immediate_abort, inline the abort call,
325 // otherwise avoid inlining because of it is cold path.
326 #[cfg_attr(not(feature="panic_immediate_abort"),inline(never))]
327 #[cfg_attr( feature="panic_immediate_abort" ,inline)]
328 pub fn begin_panic_fmt(msg: &fmt::Arguments<'_>,
329 file_line_col: &(&'static str, u32, u32)) -> ! {
330 if cfg!(feature = "panic_immediate_abort") {
331 unsafe { intrinsics::abort() }
334 let (file, line, col) = *file_line_col;
335 let info = PanicInfo::internal_constructor(
337 Location::internal_constructor(file, line, col),
339 continue_panic_fmt(&info)
342 fn continue_panic_fmt(info: &PanicInfo<'_>) -> ! {
343 struct PanicPayload<'a> {
344 inner: &'a fmt::Arguments<'a>,
345 string: Option<String>,
348 impl<'a> PanicPayload<'a> {
349 fn new(inner: &'a fmt::Arguments<'a>) -> PanicPayload<'a> {
350 PanicPayload { inner, string: None }
353 fn fill(&mut self) -> &mut String {
354 use crate::fmt::Write;
356 let inner = self.inner;
357 self.string.get_or_insert_with(|| {
358 let mut s = String::new();
359 drop(s.write_fmt(*inner));
365 unsafe impl<'a> BoxMeUp for PanicPayload<'a> {
366 fn box_me_up(&mut self) -> *mut (dyn Any + Send) {
367 let contents = mem::take(self.fill());
368 Box::into_raw(Box::new(contents))
371 fn get(&mut self) -> &(dyn Any + Send) {
376 // We do two allocations here, unfortunately. But (a) they're
377 // required with the current scheme, and (b) we don't handle
378 // panic + OOM properly anyway (see comment in begin_panic
381 let loc = info.location().unwrap(); // The current implementation always returns Some
382 let msg = info.message().unwrap(); // The current implementation always returns Some
383 let file_line_col = (loc.file(), loc.line(), loc.column());
384 rust_panic_with_hook(
385 &mut PanicPayload::new(msg),
390 /// This is the entry point of panicking for panic!() and assert!().
391 #[unstable(feature = "libstd_sys_internals",
392 reason = "used by the panic! macro",
394 #[cfg_attr(not(test), lang = "begin_panic")]
395 // never inline unless panic_immediate_abort to avoid code
396 // bloat at the call sites as much as possible
397 #[cfg_attr(not(feature="panic_immediate_abort"),inline(never))]
399 pub fn begin_panic<M: Any + Send>(msg: M, file_line_col: &(&'static str, u32, u32)) -> ! {
400 if cfg!(feature = "panic_immediate_abort") {
401 unsafe { intrinsics::abort() }
404 // Note that this should be the only allocation performed in this code path.
405 // Currently this means that panic!() on OOM will invoke this code path,
406 // but then again we're not really ready for panic on OOM anyway. If
407 // we do start doing this, then we should propagate this allocation to
408 // be performed in the parent of this thread instead of the thread that's
411 rust_panic_with_hook(&mut PanicPayload::new(msg), None, file_line_col);
413 struct PanicPayload<A> {
417 impl<A: Send + 'static> PanicPayload<A> {
418 fn new(inner: A) -> PanicPayload<A> {
419 PanicPayload { inner: Some(inner) }
423 unsafe impl<A: Send + 'static> BoxMeUp for PanicPayload<A> {
424 fn box_me_up(&mut self) -> *mut (dyn Any + Send) {
425 let data = match self.inner.take() {
426 Some(a) => Box::new(a) as Box<dyn Any + Send>,
427 None => Box::new(()),
432 fn get(&mut self) -> &(dyn Any + Send) {
441 /// Central point for dispatching panics.
443 /// Executes the primary logic for a panic, including checking for recursive
444 /// panics, panic hooks, and finally dispatching to the panic runtime to either
446 fn rust_panic_with_hook(payload: &mut dyn BoxMeUp,
447 message: Option<&fmt::Arguments<'_>>,
448 file_line_col: &(&str, u32, u32)) -> ! {
449 let (file, line, col) = *file_line_col;
451 let panics = update_panic_count(1);
453 // If this is the third nested call (e.g., panics == 2, this is 0-indexed),
454 // the panic hook probably triggered the last panic, otherwise the
455 // double-panic check would have aborted the process. In this case abort the
456 // process real quickly as we don't want to try calling it again as it'll
457 // probably just panic again.
459 util::dumb_print(format_args!("thread panicked while processing \
460 panic. aborting.\n"));
461 unsafe { intrinsics::abort() }
465 let mut info = PanicInfo::internal_constructor(
467 Location::internal_constructor(file, line, col),
471 // Some platforms know that printing to stderr won't ever actually
472 // print anything, and if that's the case we can skip the default
474 Hook::Default if panic_output().is_none() => {}
476 info.set_payload(payload.get());
479 Hook::Custom(ptr) => {
480 info.set_payload(payload.get());
484 HOOK_LOCK.read_unlock();
488 // If a thread panics while it's already unwinding then we
489 // have limited options. Currently our preference is to
490 // just abort. In the future we may consider resuming
491 // unwinding or otherwise exiting the thread cleanly.
492 util::dumb_print(format_args!("thread panicked while panicking. \
494 unsafe { intrinsics::abort() }
500 /// Shim around rust_panic. Called by resume_unwind.
501 pub fn update_count_then_panic(msg: Box<dyn Any + Send>) -> ! {
502 update_panic_count(1);
504 struct RewrapBox(Box<dyn Any + Send>);
506 unsafe impl BoxMeUp for RewrapBox {
507 fn box_me_up(&mut self) -> *mut (dyn Any + Send) {
508 Box::into_raw(mem::replace(&mut self.0, Box::new(())))
511 fn get(&mut self) -> &(dyn Any + Send) {
516 rust_panic(&mut RewrapBox(msg))
519 /// An unmangled function (through `rustc_std_internal_symbol`) on which to slap
522 #[cfg_attr(not(test), rustc_std_internal_symbol)]
523 fn rust_panic(mut msg: &mut dyn BoxMeUp) -> ! {
525 let obj = &mut msg as *mut &mut dyn BoxMeUp;
526 __rust_start_panic(obj as usize)
528 rtabort!("failed to initiate panic, error {}", code)