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 {
111 /// Unregisters the current panic hook, returning it.
113 /// *See also the function [`set_hook`].*
115 /// [`set_hook`]: ./fn.set_hook.html
117 /// If no custom hook is registered, the default hook will be returned.
121 /// Panics if called from a panicking thread.
125 /// The following will print "Normal panic":
130 /// panic::set_hook(Box::new(|_| {
131 /// println!("Custom panic hook");
134 /// let _ = panic::take_hook();
136 /// panic!("Normal panic");
138 #[stable(feature = "panic_hooks", since = "1.10.0")]
139 pub fn take_hook() -> Box<dyn Fn(&PanicInfo) + 'static + Sync + Send> {
140 if thread::panicking() {
141 panic!("cannot modify the panic hook from a panicking thread");
147 HOOK = Hook::Default;
148 HOOK_LOCK.write_unlock();
151 Hook::Default => Box::new(default_hook),
152 Hook::Custom(ptr) => Box::from_raw(ptr),
157 fn default_hook(info: &PanicInfo) {
158 #[cfg(feature = "backtrace")]
159 use crate::sys_common::backtrace;
161 // If this is a double panic, make sure that we print a backtrace
162 // for this panic. Otherwise only print it if logging is enabled.
163 #[cfg(feature = "backtrace")]
164 let log_backtrace = {
165 let panics = update_panic_count(0);
168 Some(backtrace::PrintFormat::Full)
170 backtrace::log_enabled()
174 let location = info.location().unwrap(); // The current implementation always returns Some
176 let msg = match info.payload().downcast_ref::<&'static str>() {
178 None => match info.payload().downcast_ref::<String>() {
183 let thread = thread_info::current_thread();
184 let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");
186 let write = |err: &mut dyn crate::io::Write| {
187 let _ = writeln!(err, "thread '{}' panicked at '{}', {}",
188 name, msg, location);
190 #[cfg(feature = "backtrace")]
192 use crate::sync::atomic::{AtomicBool, Ordering};
194 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
196 if let Some(format) = log_backtrace {
197 let _ = backtrace::print(err, format);
198 } else if FIRST_PANIC.compare_and_swap(true, false, Ordering::SeqCst) {
199 let _ = writeln!(err, "note: Run with `RUST_BACKTRACE=1` \
200 environment variable to display a backtrace.");
205 if let Some(mut local) = set_panic(None) {
206 // NB. In `cfg(test)` this uses the forwarding impl
207 // for `Box<dyn (::realstd::io::Write) + Send>`.
209 set_panic(Some(local));
210 } else if let Some(mut out) = panic_output() {
218 #[unstable(feature = "update_panic_count", issue = "0")]
219 pub fn update_panic_count(amt: isize) -> usize {
220 use crate::cell::Cell;
221 thread_local! { static PANIC_COUNT: Cell<usize> = Cell::new(0) }
223 PANIC_COUNT.with(|c| {
224 let next = (c.get() as isize + amt) as usize;
231 pub use realstd::rt::update_panic_count;
233 /// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
234 pub unsafe fn r#try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>> {
235 #[allow(unions_with_drop_fields)]
241 // We do some sketchy operations with ownership here for the sake of
242 // performance. We can only pass pointers down to
243 // `__rust_maybe_catch_panic` (can't pass objects by value), so we do all
244 // the ownership tracking here manually using a union.
246 // We go through a transition where:
248 // * First, we set the data to be the closure that we're going to call.
249 // * When we make the function call, the `do_call` function below, we take
250 // ownership of the function pointer. At this point the `Data` union is
251 // entirely uninitialized.
252 // * If the closure successfully returns, we write the return value into the
253 // data's return slot. Note that `ptr::write` is used as it's overwriting
254 // uninitialized data.
255 // * Finally, when we come back out of the `__rust_maybe_catch_panic` we're
256 // in one of two states:
258 // 1. The closure didn't panic, in which case the return value was
259 // filled in. We move it out of `data` and return it.
260 // 2. The closure panicked, in which case the return value wasn't
261 // filled in. In this case the entire `data` union is invalid, so
262 // there is no need to drop anything.
264 // Once we stack all that together we should have the "most efficient'
265 // method of calling a catch panic whilst juggling ownership.
266 let mut any_data = 0;
267 let mut any_vtable = 0;
268 let mut data = Data {
272 let r = __rust_maybe_catch_panic(do_call::<F, R>,
273 &mut data as *mut _ as *mut u8,
278 debug_assert!(update_panic_count(0) == 0);
281 update_panic_count(-1);
282 debug_assert!(update_panic_count(0) == 0);
283 Err(mem::transmute(raw::TraitObject {
284 data: any_data as *mut _,
285 vtable: any_vtable as *mut _,
289 fn do_call<F: FnOnce() -> R, R>(data: *mut u8) {
291 let data = data as *mut Data<F, R>;
292 let f = ptr::read(&mut (*data).f);
293 ptr::write(&mut (*data).r, f());
298 /// Determines whether the current thread is unwinding because of panic.
299 pub fn panicking() -> bool {
300 update_panic_count(0) != 0
303 /// Entry point of panic from the libcore crate.
307 pub fn rust_begin_panic(info: &PanicInfo) -> ! {
308 continue_panic_fmt(&info)
311 /// The entry point for panicking with a formatted message.
313 /// This is designed to reduce the amount of code required at the call
314 /// site as much as possible (so that `panic!()` has as low an impact
315 /// on (e.g.) the inlining of other functions as possible), by moving
316 /// the actual formatting into this shared place.
317 #[unstable(feature = "libstd_sys_internals",
318 reason = "used by the panic! macro",
321 // If panic_immediate_abort, inline the abort call,
322 // otherwise avoid inlining because of it is cold path.
323 #[cfg_attr(not(feature="panic_immediate_abort"),inline(never))]
324 #[cfg_attr( feature="panic_immediate_abort" ,inline)]
325 pub fn begin_panic_fmt(msg: &fmt::Arguments,
326 file_line_col: &(&'static str, u32, u32)) -> ! {
327 if cfg!(feature = "panic_immediate_abort") {
328 unsafe { intrinsics::abort() }
331 let (file, line, col) = *file_line_col;
332 let info = PanicInfo::internal_constructor(
334 Location::internal_constructor(file, line, col),
336 continue_panic_fmt(&info)
339 fn continue_panic_fmt(info: &PanicInfo) -> ! {
340 struct PanicPayload<'a> {
341 inner: &'a fmt::Arguments<'a>,
342 string: Option<String>,
345 impl<'a> PanicPayload<'a> {
346 fn new(inner: &'a fmt::Arguments<'a>) -> PanicPayload<'a> {
347 PanicPayload { inner, string: None }
350 fn fill(&mut self) -> &mut String {
351 use crate::fmt::Write;
353 let inner = self.inner;
354 self.string.get_or_insert_with(|| {
355 let mut s = String::new();
356 drop(s.write_fmt(*inner));
362 unsafe impl<'a> BoxMeUp for PanicPayload<'a> {
363 fn box_me_up(&mut self) -> *mut (dyn Any + Send) {
364 let contents = mem::replace(self.fill(), String::new());
365 Box::into_raw(Box::new(contents))
368 fn get(&mut self) -> &(dyn Any + Send) {
373 // We do two allocations here, unfortunately. But (a) they're
374 // required with the current scheme, and (b) we don't handle
375 // panic + OOM properly anyway (see comment in begin_panic
378 let loc = info.location().unwrap(); // The current implementation always returns Some
379 let msg = info.message().unwrap(); // The current implementation always returns Some
380 let file_line_col = (loc.file(), loc.line(), loc.column());
381 rust_panic_with_hook(
382 &mut PanicPayload::new(msg),
387 /// This is the entry point of panicking for panic!() and assert!().
388 #[unstable(feature = "libstd_sys_internals",
389 reason = "used by the panic! macro",
391 #[cfg_attr(not(test), lang = "begin_panic")]
392 // never inline unless panic_immediate_abort to avoid code
393 // bloat at the call sites as much as possible
394 #[cfg_attr(not(feature="panic_immediate_abort"),inline(never))]
396 pub fn begin_panic<M: Any + Send>(msg: M, file_line_col: &(&'static str, u32, u32)) -> ! {
397 if cfg!(feature = "panic_immediate_abort") {
398 unsafe { intrinsics::abort() }
401 // Note that this should be the only allocation performed in this code path.
402 // Currently this means that panic!() on OOM will invoke this code path,
403 // but then again we're not really ready for panic on OOM anyway. If
404 // we do start doing this, then we should propagate this allocation to
405 // be performed in the parent of this thread instead of the thread that's
408 rust_panic_with_hook(&mut PanicPayload::new(msg), None, file_line_col);
410 struct PanicPayload<A> {
414 impl<A: Send + 'static> PanicPayload<A> {
415 fn new(inner: A) -> PanicPayload<A> {
416 PanicPayload { inner: Some(inner) }
420 unsafe impl<A: Send + 'static> BoxMeUp for PanicPayload<A> {
421 fn box_me_up(&mut self) -> *mut (dyn Any + Send) {
422 let data = match self.inner.take() {
423 Some(a) => Box::new(a) as Box<dyn Any + Send>,
424 None => Box::new(()),
429 fn get(&mut self) -> &(dyn Any + Send) {
438 /// Central point for dispatching panics.
440 /// Executes the primary logic for a panic, including checking for recursive
441 /// panics, panic hooks, and finally dispatching to the panic runtime to either
443 fn rust_panic_with_hook(payload: &mut dyn BoxMeUp,
444 message: Option<&fmt::Arguments>,
445 file_line_col: &(&str, u32, u32)) -> ! {
446 let (file, line, col) = *file_line_col;
448 let panics = update_panic_count(1);
450 // If this is the third nested call (e.g., panics == 2, this is 0-indexed),
451 // the panic hook probably triggered the last panic, otherwise the
452 // double-panic check would have aborted the process. In this case abort the
453 // process real quickly as we don't want to try calling it again as it'll
454 // probably just panic again.
456 util::dumb_print(format_args!("thread panicked while processing \
457 panic. aborting.\n"));
458 unsafe { intrinsics::abort() }
462 let mut info = PanicInfo::internal_constructor(
464 Location::internal_constructor(file, line, col),
468 // Some platforms know that printing to stderr won't ever actually
469 // print anything, and if that's the case we can skip the default
471 Hook::Default if panic_output().is_none() => {}
473 info.set_payload(payload.get());
476 Hook::Custom(ptr) => {
477 info.set_payload(payload.get());
481 HOOK_LOCK.read_unlock();
485 // If a thread panics while it's already unwinding then we
486 // have limited options. Currently our preference is to
487 // just abort. In the future we may consider resuming
488 // unwinding or otherwise exiting the thread cleanly.
489 util::dumb_print(format_args!("thread panicked while panicking. \
491 unsafe { intrinsics::abort() }
497 /// Shim around rust_panic. Called by resume_unwind.
498 pub fn update_count_then_panic(msg: Box<dyn Any + Send>) -> ! {
499 update_panic_count(1);
501 struct RewrapBox(Box<dyn Any + Send>);
503 unsafe impl BoxMeUp for RewrapBox {
504 fn box_me_up(&mut self) -> *mut (dyn Any + Send) {
505 Box::into_raw(mem::replace(&mut self.0, Box::new(())))
508 fn get(&mut self) -> &(dyn Any + Send) {
513 rust_panic(&mut RewrapBox(msg))
516 /// An unmangled function (through `rustc_std_internal_symbol`) on which to slap
519 #[cfg_attr(not(test), rustc_std_internal_symbol)]
520 fn rust_panic(mut msg: &mut dyn BoxMeUp) -> ! {
522 let obj = &mut msg as *mut &mut dyn BoxMeUp;
523 __rust_start_panic(obj as usize)
525 rtabort!("failed to initiate panic, error {}", code)