1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Implementation of various bits and pieces of the `panic!` macro and
12 //! associated runtime pieces.
14 //! Specifically, this module contains the implementation of:
17 //! * Executing a panic up to doing the actual implementation
18 //! * Shims around "try"
29 use sys::stdio::Stderr;
30 use sys_common::rwlock::RWLock;
31 use sys_common::thread_info;
36 pub static LOCAL_STDERR: RefCell<Option<Box<Write + Send>>> = {
41 // Binary interface to the panic runtime that the standard library depends on.
43 // The standard library is tagged with `#![needs_panic_runtime]` (introduced in
44 // RFC 1513) to indicate that it requires some other crate tagged with
45 // `#![panic_runtime]` to exist somewhere. Each panic runtime is intended to
46 // implement these symbols (with the same signatures) so we can get matched up
49 // One day this may look a little less ad-hoc with the compiler helping out to
50 // hook up these functions, but it is not this day!
51 #[allow(improper_ctypes)]
53 fn __rust_maybe_catch_panic(f: fn(*mut u8),
56 vtable_ptr: *mut usize) -> u32;
58 fn __rust_start_panic(data: usize, vtable: usize) -> u32;
61 #[derive(Copy, Clone)]
64 Custom(*mut (Fn(&PanicInfo) + 'static + Sync + Send)),
67 static HOOK_LOCK: RWLock = RWLock::new();
68 static mut HOOK: Hook = Hook::Default;
70 /// Registers a custom panic hook, replacing any that was previously registered.
72 /// The panic hook is invoked when a thread panics, but before the panic runtime
73 /// is invoked. As such, the hook will run with both the aborting and unwinding
74 /// runtimes. The default hook prints a message to standard error and generates
75 /// a backtrace if requested, but this behavior can be customized with the
76 /// `set_hook` and `take_hook` functions.
78 /// The hook is provided with a `PanicInfo` struct which contains information
79 /// about the origin of the panic, including the payload passed to `panic!` and
80 /// the source code location from which the panic originated.
82 /// The panic hook is a global resource.
86 /// Panics if called from a panicking thread.
90 /// The following will print "Custom panic hook":
95 /// panic::set_hook(Box::new(|_| {
96 /// println!("Custom panic hook");
99 /// panic!("Normal panic");
101 #[stable(feature = "panic_hooks", since = "1.10.0")]
102 pub fn set_hook(hook: Box<Fn(&PanicInfo) + 'static + Sync + Send>) {
103 if thread::panicking() {
104 panic!("cannot modify the panic hook from a panicking thread");
110 HOOK = Hook::Custom(Box::into_raw(hook));
111 HOOK_LOCK.write_unlock();
113 if let Hook::Custom(ptr) = old_hook {
119 /// Unregisters the current panic hook, returning it.
121 /// If no custom hook is registered, the default hook will be returned.
125 /// Panics if called from a panicking thread.
129 /// The following will print "Normal panic":
134 /// panic::set_hook(Box::new(|_| {
135 /// println!("Custom panic hook");
138 /// let _ = panic::take_hook();
140 /// panic!("Normal panic");
142 #[stable(feature = "panic_hooks", since = "1.10.0")]
143 pub fn take_hook() -> Box<Fn(&PanicInfo) + 'static + Sync + Send> {
144 if thread::panicking() {
145 panic!("cannot modify the panic hook from a panicking thread");
151 HOOK = Hook::Default;
152 HOOK_LOCK.write_unlock();
155 Hook::Default => Box::new(default_hook),
156 Hook::Custom(ptr) => Box::from_raw(ptr),
161 /// A struct providing information about a panic.
163 /// `PanicInfo` structure is passed to a panic hook set by the [`set_hook`]
166 /// [`set_hook`]: ../../std/panic/fn.set_hook.html
173 /// panic::set_hook(Box::new(|panic_info| {
174 /// println!("panic occurred: {:?}", panic_info.payload().downcast_ref::<&str>().unwrap());
177 /// panic!("Normal panic");
179 #[stable(feature = "panic_hooks", since = "1.10.0")]
181 pub struct PanicInfo<'a> {
182 payload: &'a (Any + Send),
183 location: Location<'a>,
186 impl<'a> PanicInfo<'a> {
187 /// Returns the payload associated with the panic.
189 /// This will commonly, but not always, be a `&'static str` or [`String`].
191 /// [`String`]: ../../std/string/struct.String.html
198 /// panic::set_hook(Box::new(|panic_info| {
199 /// println!("panic occurred: {:?}", panic_info.payload().downcast_ref::<&str>().unwrap());
202 /// panic!("Normal panic");
204 #[stable(feature = "panic_hooks", since = "1.10.0")]
205 pub fn payload(&self) -> &(Any + Send) {
209 /// Returns information about the location from which the panic originated,
212 /// This method will currently always return [`Some`], but this may change
213 /// in future versions.
215 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
222 /// panic::set_hook(Box::new(|panic_info| {
223 /// if let Some(location) = panic_info.location() {
224 /// println!("panic occurred in file '{}' at line {}", location.file(),
225 /// location.line());
227 /// println!("panic occurred but can't get location information...");
231 /// panic!("Normal panic");
233 #[stable(feature = "panic_hooks", since = "1.10.0")]
234 pub fn location(&self) -> Option<&Location> {
239 /// A struct containing information about the location of a panic.
241 /// This structure is created by the [`location`] method of [`PanicInfo`].
243 /// [`location`]: ../../std/panic/struct.PanicInfo.html#method.location
244 /// [`PanicInfo`]: ../../std/panic/struct.PanicInfo.html
251 /// panic::set_hook(Box::new(|panic_info| {
252 /// if let Some(location) = panic_info.location() {
253 /// println!("panic occurred in file '{}' at line {}", location.file(), location.line());
255 /// println!("panic occurred but can't get location information...");
259 /// panic!("Normal panic");
262 #[stable(feature = "panic_hooks", since = "1.10.0")]
263 pub struct Location<'a> {
269 impl<'a> Location<'a> {
270 /// Returns the name of the source file from which the panic originated.
277 /// panic::set_hook(Box::new(|panic_info| {
278 /// if let Some(location) = panic_info.location() {
279 /// println!("panic occurred in file '{}'", location.file());
281 /// println!("panic occurred but can't get location information...");
285 /// panic!("Normal panic");
287 #[stable(feature = "panic_hooks", since = "1.10.0")]
288 pub fn file(&self) -> &str {
292 /// Returns the line number from which the panic originated.
299 /// panic::set_hook(Box::new(|panic_info| {
300 /// if let Some(location) = panic_info.location() {
301 /// println!("panic occurred at line {}", location.line());
303 /// println!("panic occurred but can't get location information...");
307 /// panic!("Normal panic");
309 #[stable(feature = "panic_hooks", since = "1.10.0")]
310 pub fn line(&self) -> u32 {
314 /// Returns the column from which the panic originated.
319 /// #![feature(panic_col)]
322 /// panic::set_hook(Box::new(|panic_info| {
323 /// if let Some(location) = panic_info.location() {
324 /// println!("panic occurred at column {}", location.column());
326 /// println!("panic occurred but can't get location information...");
330 /// panic!("Normal panic");
332 #[unstable(feature = "panic_col", reason = "recently added", issue = "42939")]
333 pub fn column(&self) -> u32 {
338 fn default_hook(info: &PanicInfo) {
339 #[cfg(feature = "backtrace")]
340 use sys_common::backtrace;
342 // If this is a double panic, make sure that we print a backtrace
343 // for this panic. Otherwise only print it if logging is enabled.
344 #[cfg(feature = "backtrace")]
345 let log_backtrace = {
346 let panics = update_panic_count(0);
349 Some(backtrace::PrintFormat::Full)
351 backtrace::log_enabled()
355 let file = info.location.file;
356 let line = info.location.line;
357 let col = info.location.col;
359 let msg = match info.payload.downcast_ref::<&'static str>() {
361 None => match info.payload.downcast_ref::<String>() {
366 let mut err = Stderr::new().ok();
367 let thread = thread_info::current_thread();
368 let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");
370 let write = |err: &mut ::io::Write| {
371 let _ = writeln!(err, "thread '{}' panicked at '{}', {}:{}:{}",
372 name, msg, file, line, col);
374 #[cfg(feature = "backtrace")]
376 use sync::atomic::{AtomicBool, Ordering};
378 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
380 if let Some(format) = log_backtrace {
381 let _ = backtrace::print(err, format);
382 } else if FIRST_PANIC.compare_and_swap(true, false, Ordering::SeqCst) {
383 let _ = writeln!(err, "note: Run with `RUST_BACKTRACE=1` for a backtrace.");
388 let prev = LOCAL_STDERR.with(|s| s.borrow_mut().take());
389 match (prev, err.as_mut()) {
390 (Some(mut stderr), _) => {
392 let mut s = Some(stderr);
393 LOCAL_STDERR.with(|slot| {
394 *slot.borrow_mut() = s.take();
397 (None, Some(ref mut err)) => { write(err) }
405 #[unstable(feature = "update_panic_count", issue = "0")]
406 pub fn update_panic_count(amt: isize) -> usize {
408 thread_local! { static PANIC_COUNT: Cell<usize> = Cell::new(0) }
410 PANIC_COUNT.with(|c| {
411 let next = (c.get() as isize + amt) as usize;
418 pub use realstd::rt::update_panic_count;
420 /// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
421 pub unsafe fn try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<Any + Send>> {
422 #[allow(unions_with_drop_fields)]
428 // We do some sketchy operations with ownership here for the sake of
429 // performance. We can only pass pointers down to
430 // `__rust_maybe_catch_panic` (can't pass objects by value), so we do all
431 // the ownership tracking here manually using a union.
433 // We go through a transition where:
435 // * First, we set the data to be the closure that we're going to call.
436 // * When we make the function call, the `do_call` function below, we take
437 // ownership of the function pointer. At this point the `Data` union is
438 // entirely uninitialized.
439 // * If the closure successfully returns, we write the return value into the
440 // data's return slot. Note that `ptr::write` is used as it's overwriting
441 // uninitialized data.
442 // * Finally, when we come back out of the `__rust_maybe_catch_panic` we're
443 // in one of two states:
445 // 1. The closure didn't panic, in which case the return value was
446 // filled in. We move it out of `data` and return it.
447 // 2. The closure panicked, in which case the return value wasn't
448 // filled in. In this case the entire `data` union is invalid, so
449 // there is no need to drop anything.
451 // Once we stack all that together we should have the "most efficient'
452 // method of calling a catch panic whilst juggling ownership.
453 let mut any_data = 0;
454 let mut any_vtable = 0;
455 let mut data = Data {
459 let r = __rust_maybe_catch_panic(do_call::<F, R>,
460 &mut data as *mut _ as *mut u8,
465 debug_assert!(update_panic_count(0) == 0);
468 update_panic_count(-1);
469 debug_assert!(update_panic_count(0) == 0);
470 Err(mem::transmute(raw::TraitObject {
471 data: any_data as *mut _,
472 vtable: any_vtable as *mut _,
476 fn do_call<F: FnOnce() -> R, R>(data: *mut u8) {
478 let data = data as *mut Data<F, R>;
479 let f = ptr::read(&mut (*data).f);
480 ptr::write(&mut (*data).r, f());
485 /// Determines whether the current thread is unwinding because of panic.
486 pub fn panicking() -> bool {
487 update_panic_count(0) != 0
490 /// Entry point of panic from the libcore crate.
492 #[lang = "panic_fmt"]
494 pub extern fn rust_begin_panic(msg: fmt::Arguments,
498 begin_panic_fmt(&msg, &(file, line, col))
501 /// The entry point for panicking with a formatted message.
503 /// This is designed to reduce the amount of code required at the call
504 /// site as much as possible (so that `panic!()` has as low an impact
505 /// on (e.g.) the inlining of other functions as possible), by moving
506 /// the actual formatting into this shared place.
507 #[unstable(feature = "libstd_sys_internals",
508 reason = "used by the panic! macro",
510 #[inline(never)] #[cold]
511 pub fn begin_panic_fmt(msg: &fmt::Arguments,
512 file_line_col: &(&'static str, u32, u32)) -> ! {
515 // We do two allocations here, unfortunately. But (a) they're
516 // required with the current scheme, and (b) we don't handle
517 // panic + OOM properly anyway (see comment in begin_panic
520 let mut s = String::new();
521 let _ = s.write_fmt(*msg);
522 begin_panic(s, file_line_col)
525 /// This is the entry point of panicking for panic!() and assert!().
526 #[unstable(feature = "libstd_sys_internals",
527 reason = "used by the panic! macro",
529 #[inline(never)] #[cold] // avoid code bloat at the call sites as much as possible
530 pub fn begin_panic<M: Any + Send>(msg: M, file_line_col: &(&'static str, u32, u32)) -> ! {
531 // Note that this should be the only allocation performed in this code path.
532 // Currently this means that panic!() on OOM will invoke this code path,
533 // but then again we're not really ready for panic on OOM anyway. If
534 // we do start doing this, then we should propagate this allocation to
535 // be performed in the parent of this thread instead of the thread that's
538 rust_panic_with_hook(Box::new(msg), file_line_col)
541 /// Executes the primary logic for a panic, including checking for recursive
542 /// panics and panic hooks.
544 /// This is the entry point or panics from libcore, formatted panics, and
545 /// `Box<Any>` panics. Here we'll verify that we're not panicking recursively,
546 /// run panic hooks, and then delegate to the actual implementation of panics.
549 fn rust_panic_with_hook(msg: Box<Any + Send>,
550 file_line_col: &(&'static str, u32, u32)) -> ! {
551 let (file, line, col) = *file_line_col;
553 let panics = update_panic_count(1);
555 // If this is the third nested call (e.g. panics == 2, this is 0-indexed),
556 // the panic hook probably triggered the last panic, otherwise the
557 // double-panic check would have aborted the process. In this case abort the
558 // process real quickly as we don't want to try calling it again as it'll
559 // probably just panic again.
561 util::dumb_print(format_args!("thread panicked while processing \
562 panic. aborting.\n"));
563 unsafe { intrinsics::abort() }
567 let info = PanicInfo {
577 Hook::Default => default_hook(&info),
578 Hook::Custom(ptr) => (*ptr)(&info),
580 HOOK_LOCK.read_unlock();
584 // If a thread panics while it's already unwinding then we
585 // have limited options. Currently our preference is to
586 // just abort. In the future we may consider resuming
587 // unwinding or otherwise exiting the thread cleanly.
588 util::dumb_print(format_args!("thread panicked while panicking. \
590 unsafe { intrinsics::abort() }
596 /// Shim around rust_panic. Called by resume_unwind.
597 pub fn update_count_then_panic(msg: Box<Any + Send>) -> ! {
598 update_panic_count(1);
602 /// A private no-mangle function on which to slap yer breakpoints.
604 #[allow(private_no_mangle_fns)] // yes we get it, but we like breakpoints
605 pub fn rust_panic(msg: Box<Any + Send>) -> ! {
607 let obj = mem::transmute::<_, raw::TraitObject>(msg);
608 __rust_start_panic(obj.data as usize, obj.vtable as usize)
610 rtabort!("failed to initiate panic, error {}", code)