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"
24 use core::panic::{PanicInfo, Location};
30 use sys::stdio::Stderr;
31 use sys_common::rwlock::RWLock;
32 use sys_common::thread_info;
37 pub static LOCAL_STDERR: RefCell<Option<Box<Write + Send>>> = {
42 // Binary interface to the panic runtime that the standard library depends on.
44 // The standard library is tagged with `#![needs_panic_runtime]` (introduced in
45 // RFC 1513) to indicate that it requires some other crate tagged with
46 // `#![panic_runtime]` to exist somewhere. Each panic runtime is intended to
47 // implement these symbols (with the same signatures) so we can get matched up
50 // One day this may look a little less ad-hoc with the compiler helping out to
51 // hook up these functions, but it is not this day!
52 #[allow(improper_ctypes)]
54 fn __rust_maybe_catch_panic(f: fn(*mut u8),
57 vtable_ptr: *mut usize) -> u32;
59 fn __rust_start_panic(data: usize, vtable: usize) -> u32;
62 #[derive(Copy, Clone)]
65 Custom(*mut (Fn(&PanicInfo) + 'static + Sync + Send)),
68 static HOOK_LOCK: RWLock = RWLock::new();
69 static mut HOOK: Hook = Hook::Default;
71 /// Registers a custom panic hook, replacing any that was previously registered.
73 /// The panic hook is invoked when a thread panics, but before the panic runtime
74 /// is invoked. As such, the hook will run with both the aborting and unwinding
75 /// runtimes. The default hook prints a message to standard error and generates
76 /// a backtrace if requested, but this behavior can be customized with the
77 /// `set_hook` and `take_hook` functions.
79 /// The hook is provided with a `PanicInfo` struct which contains information
80 /// about the origin of the panic, including the payload passed to `panic!` and
81 /// the source code location from which the panic originated.
83 /// The panic hook is a global resource.
87 /// Panics if called from a panicking thread.
91 /// The following will print "Custom panic hook":
96 /// panic::set_hook(Box::new(|_| {
97 /// println!("Custom panic hook");
100 /// panic!("Normal panic");
102 #[stable(feature = "panic_hooks", since = "1.10.0")]
103 pub fn set_hook(hook: Box<Fn(&PanicInfo) + 'static + Sync + Send>) {
104 if thread::panicking() {
105 panic!("cannot modify the panic hook from a panicking thread");
111 HOOK = Hook::Custom(Box::into_raw(hook));
112 HOOK_LOCK.write_unlock();
114 if let Hook::Custom(ptr) = old_hook {
120 /// Unregisters the current panic hook, returning it.
122 /// If no custom hook is registered, the default hook will be returned.
126 /// Panics if called from a panicking thread.
130 /// The following will print "Normal panic":
135 /// panic::set_hook(Box::new(|_| {
136 /// println!("Custom panic hook");
139 /// let _ = panic::take_hook();
141 /// panic!("Normal panic");
143 #[stable(feature = "panic_hooks", since = "1.10.0")]
144 pub fn take_hook() -> Box<Fn(&PanicInfo) + 'static + Sync + Send> {
145 if thread::panicking() {
146 panic!("cannot modify the panic hook from a panicking thread");
152 HOOK = Hook::Default;
153 HOOK_LOCK.write_unlock();
156 Hook::Default => Box::new(default_hook),
157 Hook::Custom(ptr) => Box::from_raw(ptr),
162 fn default_hook(info: &PanicInfo) {
163 #[cfg(feature = "backtrace")]
164 use sys_common::backtrace;
166 // If this is a double panic, make sure that we print a backtrace
167 // for this panic. Otherwise only print it if logging is enabled.
168 #[cfg(feature = "backtrace")]
169 let log_backtrace = {
170 let panics = update_panic_count(0);
173 Some(backtrace::PrintFormat::Full)
175 backtrace::log_enabled()
179 let location = info.location().unwrap(); // The current implementation always returns Some
180 let file = location.file();
181 let line = location.line();
182 let col = location.column();
184 let msg = match info.payload().downcast_ref::<&'static str>() {
186 None => match info.payload().downcast_ref::<String>() {
191 let mut err = Stderr::new().ok();
192 let thread = thread_info::current_thread();
193 let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");
195 let write = |err: &mut ::io::Write| {
196 let _ = writeln!(err, "thread '{}' panicked at '{}', {}:{}:{}",
197 name, msg, file, line, col);
199 #[cfg(feature = "backtrace")]
201 use sync::atomic::{AtomicBool, Ordering};
203 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
205 if let Some(format) = log_backtrace {
206 let _ = backtrace::print(err, format);
207 } else if FIRST_PANIC.compare_and_swap(true, false, Ordering::SeqCst) {
208 let _ = writeln!(err, "note: Run with `RUST_BACKTRACE=1` for a backtrace.");
213 let prev = LOCAL_STDERR.with(|s| s.borrow_mut().take());
214 match (prev, err.as_mut()) {
215 (Some(mut stderr), _) => {
217 let mut s = Some(stderr);
218 LOCAL_STDERR.with(|slot| {
219 *slot.borrow_mut() = s.take();
222 (None, Some(ref mut err)) => { write(err) }
230 #[unstable(feature = "update_panic_count", issue = "0")]
231 pub fn update_panic_count(amt: isize) -> usize {
233 thread_local! { static PANIC_COUNT: Cell<usize> = Cell::new(0) }
235 PANIC_COUNT.with(|c| {
236 let next = (c.get() as isize + amt) as usize;
243 pub use realstd::rt::update_panic_count;
245 /// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
246 pub unsafe fn try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<Any + Send>> {
247 #[allow(unions_with_drop_fields)]
253 // We do some sketchy operations with ownership here for the sake of
254 // performance. We can only pass pointers down to
255 // `__rust_maybe_catch_panic` (can't pass objects by value), so we do all
256 // the ownership tracking here manually using a union.
258 // We go through a transition where:
260 // * First, we set the data to be the closure that we're going to call.
261 // * When we make the function call, the `do_call` function below, we take
262 // ownership of the function pointer. At this point the `Data` union is
263 // entirely uninitialized.
264 // * If the closure successfully returns, we write the return value into the
265 // data's return slot. Note that `ptr::write` is used as it's overwriting
266 // uninitialized data.
267 // * Finally, when we come back out of the `__rust_maybe_catch_panic` we're
268 // in one of two states:
270 // 1. The closure didn't panic, in which case the return value was
271 // filled in. We move it out of `data` and return it.
272 // 2. The closure panicked, in which case the return value wasn't
273 // filled in. In this case the entire `data` union is invalid, so
274 // there is no need to drop anything.
276 // Once we stack all that together we should have the "most efficient'
277 // method of calling a catch panic whilst juggling ownership.
278 let mut any_data = 0;
279 let mut any_vtable = 0;
280 let mut data = Data {
284 let r = __rust_maybe_catch_panic(do_call::<F, R>,
285 &mut data as *mut _ as *mut u8,
290 debug_assert!(update_panic_count(0) == 0);
293 update_panic_count(-1);
294 debug_assert!(update_panic_count(0) == 0);
295 Err(mem::transmute(raw::TraitObject {
296 data: any_data as *mut _,
297 vtable: any_vtable as *mut _,
301 fn do_call<F: FnOnce() -> R, R>(data: *mut u8) {
303 let data = data as *mut Data<F, R>;
304 let f = ptr::read(&mut (*data).f);
305 ptr::write(&mut (*data).r, f());
310 /// Determines whether the current thread is unwinding because of panic.
311 pub fn panicking() -> bool {
312 update_panic_count(0) != 0
315 /// Entry point of panic from the libcore crate.
317 #[lang = "panic_fmt"]
319 pub extern fn rust_begin_panic(msg: fmt::Arguments,
323 begin_panic_fmt(&msg, &(file, line, col))
326 /// The entry point for panicking with a formatted message.
328 /// This is designed to reduce the amount of code required at the call
329 /// site as much as possible (so that `panic!()` has as low an impact
330 /// on (e.g.) the inlining of other functions as possible), by moving
331 /// the actual formatting into this shared place.
332 #[unstable(feature = "libstd_sys_internals",
333 reason = "used by the panic! macro",
335 #[inline(never)] #[cold]
336 pub fn begin_panic_fmt(msg: &fmt::Arguments,
337 file_line_col: &(&'static str, u32, u32)) -> ! {
340 // We do two allocations here, unfortunately. But (a) they're
341 // required with the current scheme, and (b) we don't handle
342 // panic + OOM properly anyway (see comment in begin_panic
345 let mut s = String::new();
346 let _ = s.write_fmt(*msg);
347 rust_panic_with_hook(Box::new(s), Some(msg), file_line_col)
350 /// This is the entry point of panicking for panic!() and assert!().
351 #[unstable(feature = "libstd_sys_internals",
352 reason = "used by the panic! macro",
354 #[inline(never)] #[cold] // avoid code bloat at the call sites as much as possible
355 pub fn begin_panic<M: Any + Send>(msg: M, file_line_col: &(&'static str, u32, u32)) -> ! {
356 // Note that this should be the only allocation performed in this code path.
357 // Currently this means that panic!() on OOM will invoke this code path,
358 // but then again we're not really ready for panic on OOM anyway. If
359 // we do start doing this, then we should propagate this allocation to
360 // be performed in the parent of this thread instead of the thread that's
363 rust_panic_with_hook(Box::new(msg), None, file_line_col)
366 /// Executes the primary logic for a panic, including checking for recursive
367 /// panics and panic hooks.
369 /// This is the entry point or panics from libcore, formatted panics, and
370 /// `Box<Any>` panics. Here we'll verify that we're not panicking recursively,
371 /// run panic hooks, and then delegate to the actual implementation of panics.
374 fn rust_panic_with_hook(payload: Box<Any + Send>,
375 message: Option<&fmt::Arguments>,
376 file_line_col: &(&'static str, u32, u32)) -> ! {
377 let (file, line, col) = *file_line_col;
379 let panics = update_panic_count(1);
381 // If this is the third nested call (e.g. panics == 2, this is 0-indexed),
382 // the panic hook probably triggered the last panic, otherwise the
383 // double-panic check would have aborted the process. In this case abort the
384 // process real quickly as we don't want to try calling it again as it'll
385 // probably just panic again.
387 util::dumb_print(format_args!("thread panicked while processing \
388 panic. aborting.\n"));
389 unsafe { intrinsics::abort() }
393 let info = PanicInfo::internal_constructor(
396 Location::internal_constructor(file, line, col),
400 Hook::Default => default_hook(&info),
401 Hook::Custom(ptr) => (*ptr)(&info),
403 HOOK_LOCK.read_unlock();
407 // If a thread panics while it's already unwinding then we
408 // have limited options. Currently our preference is to
409 // just abort. In the future we may consider resuming
410 // unwinding or otherwise exiting the thread cleanly.
411 util::dumb_print(format_args!("thread panicked while panicking. \
413 unsafe { intrinsics::abort() }
419 /// Shim around rust_panic. Called by resume_unwind.
420 pub fn update_count_then_panic(msg: Box<Any + Send>) -> ! {
421 update_panic_count(1);
425 /// A private no-mangle function on which to slap yer breakpoints.
427 #[allow(private_no_mangle_fns)] // yes we get it, but we like breakpoints
428 pub fn rust_panic(msg: Box<Any + Send>) -> ! {
430 let obj = mem::transmute::<_, raw::TraitObject>(msg);
431 __rust_start_panic(obj.data as usize, obj.vtable as usize)
433 rtabort!("failed to initiate panic, error {}", code)