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"
20 use core::panic::BoxMeUp;
26 use core::panic::{PanicInfo, Location};
32 use sys::stdio::{Stderr, stderr_prints_nothing};
33 use sys_common::rwlock::RWLock;
34 use sys_common::thread_info;
39 pub static LOCAL_STDERR: RefCell<Option<Box<Write + Send>>> = {
44 // Binary interface to the panic runtime that the standard library depends on.
46 // The standard library is tagged with `#![needs_panic_runtime]` (introduced in
47 // RFC 1513) to indicate that it requires some other crate tagged with
48 // `#![panic_runtime]` to exist somewhere. Each panic runtime is intended to
49 // implement these symbols (with the same signatures) so we can get matched up
52 // One day this may look a little less ad-hoc with the compiler helping out to
53 // hook up these functions, but it is not this day!
54 #[allow(improper_ctypes)]
56 fn __rust_maybe_catch_panic(f: fn(*mut u8),
59 vtable_ptr: *mut usize) -> u32;
61 fn __rust_start_panic(payload: usize) -> u32;
64 #[derive(Copy, Clone)]
67 Custom(*mut (Fn(&PanicInfo) + 'static + Sync + Send)),
70 static HOOK_LOCK: RWLock = RWLock::new();
71 static mut HOOK: Hook = Hook::Default;
73 /// Registers a custom panic hook, replacing any that was previously registered.
75 /// The panic hook is invoked when a thread panics, but before the panic runtime
76 /// is invoked. As such, the hook will run with both the aborting and unwinding
77 /// runtimes. The default hook prints a message to standard error and generates
78 /// a backtrace if requested, but this behavior can be customized with the
79 /// `set_hook` and [`take_hook`] functions.
81 /// [`take_hook`]: ./fn.take_hook.html
83 /// The hook is provided with a `PanicInfo` struct which contains information
84 /// about the origin of the panic, including the payload passed to `panic!` and
85 /// the source code location from which the panic originated.
87 /// The panic hook is a global resource.
91 /// Panics if called from a panicking thread.
95 /// The following will print "Custom panic hook":
100 /// panic::set_hook(Box::new(|_| {
101 /// println!("Custom panic hook");
104 /// panic!("Normal panic");
106 #[stable(feature = "panic_hooks", since = "1.10.0")]
107 pub fn set_hook(hook: Box<Fn(&PanicInfo) + 'static + Sync + Send>) {
108 if thread::panicking() {
109 panic!("cannot modify the panic hook from a panicking thread");
115 HOOK = Hook::Custom(Box::into_raw(hook));
116 HOOK_LOCK.write_unlock();
118 if let Hook::Custom(ptr) = old_hook {
124 /// Unregisters the current panic hook, returning it.
126 /// *See also the function [`set_hook`].*
128 /// [`set_hook`]: ./fn.set_hook.html
130 /// If no custom hook is registered, the default hook will be returned.
134 /// Panics if called from a panicking thread.
138 /// The following will print "Normal panic":
143 /// panic::set_hook(Box::new(|_| {
144 /// println!("Custom panic hook");
147 /// let _ = panic::take_hook();
149 /// panic!("Normal panic");
151 #[stable(feature = "panic_hooks", since = "1.10.0")]
152 pub fn take_hook() -> Box<Fn(&PanicInfo) + 'static + Sync + Send> {
153 if thread::panicking() {
154 panic!("cannot modify the panic hook from a panicking thread");
160 HOOK = Hook::Default;
161 HOOK_LOCK.write_unlock();
164 Hook::Default => Box::new(default_hook),
165 Hook::Custom(ptr) => Box::from_raw(ptr),
170 fn default_hook(info: &PanicInfo) {
171 #[cfg(feature = "backtrace")]
172 use sys_common::backtrace;
174 // If this is a double panic, make sure that we print a backtrace
175 // for this panic. Otherwise only print it if logging is enabled.
176 #[cfg(feature = "backtrace")]
177 let log_backtrace = {
178 let panics = update_panic_count(0);
181 Some(backtrace::PrintFormat::Full)
183 backtrace::log_enabled()
187 let location = info.location().unwrap(); // The current implementation always returns Some
189 let msg = match info.payload().downcast_ref::<&'static str>() {
191 None => match info.payload().downcast_ref::<String>() {
196 let mut err = Stderr::new().ok();
197 let thread = thread_info::current_thread();
198 let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");
200 let write = |err: &mut ::io::Write| {
201 let _ = writeln!(err, "thread '{}' panicked at '{}', {}",
202 name, msg, location);
204 #[cfg(feature = "backtrace")]
206 use sync::atomic::{AtomicBool, Ordering};
208 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
210 if let Some(format) = log_backtrace {
211 let _ = backtrace::print(err, format);
212 } else if FIRST_PANIC.compare_and_swap(true, false, Ordering::SeqCst) {
213 let _ = writeln!(err, "note: Run with `RUST_BACKTRACE=1` for a backtrace.");
218 let prev = LOCAL_STDERR.with(|s| s.borrow_mut().take());
219 match (prev, err.as_mut()) {
220 (Some(mut stderr), _) => {
222 let mut s = Some(stderr);
223 LOCAL_STDERR.with(|slot| {
224 *slot.borrow_mut() = s.take();
227 (None, Some(ref mut err)) => { write(err) }
235 #[unstable(feature = "update_panic_count", issue = "0")]
236 pub fn update_panic_count(amt: isize) -> usize {
238 thread_local! { static PANIC_COUNT: Cell<usize> = Cell::new(0) }
240 PANIC_COUNT.with(|c| {
241 let next = (c.get() as isize + amt) as usize;
248 pub use realstd::rt::update_panic_count;
250 /// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
251 pub unsafe fn try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<Any + Send>> {
252 #[allow(unions_with_drop_fields)]
258 // We do some sketchy operations with ownership here for the sake of
259 // performance. We can only pass pointers down to
260 // `__rust_maybe_catch_panic` (can't pass objects by value), so we do all
261 // the ownership tracking here manually using a union.
263 // We go through a transition where:
265 // * First, we set the data to be the closure that we're going to call.
266 // * When we make the function call, the `do_call` function below, we take
267 // ownership of the function pointer. At this point the `Data` union is
268 // entirely uninitialized.
269 // * If the closure successfully returns, we write the return value into the
270 // data's return slot. Note that `ptr::write` is used as it's overwriting
271 // uninitialized data.
272 // * Finally, when we come back out of the `__rust_maybe_catch_panic` we're
273 // in one of two states:
275 // 1. The closure didn't panic, in which case the return value was
276 // filled in. We move it out of `data` and return it.
277 // 2. The closure panicked, in which case the return value wasn't
278 // filled in. In this case the entire `data` union is invalid, so
279 // there is no need to drop anything.
281 // Once we stack all that together we should have the "most efficient'
282 // method of calling a catch panic whilst juggling ownership.
283 let mut any_data = 0;
284 let mut any_vtable = 0;
285 let mut data = Data {
289 let r = __rust_maybe_catch_panic(do_call::<F, R>,
290 &mut data as *mut _ as *mut u8,
295 debug_assert!(update_panic_count(0) == 0);
298 update_panic_count(-1);
299 debug_assert!(update_panic_count(0) == 0);
300 Err(mem::transmute(raw::TraitObject {
301 data: any_data as *mut _,
302 vtable: any_vtable as *mut _,
306 fn do_call<F: FnOnce() -> R, R>(data: *mut u8) {
308 let data = data as *mut Data<F, R>;
309 let f = ptr::read(&mut (*data).f);
310 ptr::write(&mut (*data).r, f());
315 /// Determines whether the current thread is unwinding because of panic.
316 pub fn panicking() -> bool {
317 update_panic_count(0) != 0
320 /// Entry point of panic from the libcore crate.
322 #[panic_implementation]
324 pub fn rust_begin_panic(info: &PanicInfo) -> ! {
325 continue_panic_fmt(&info)
328 /// The entry point for panicking with a formatted message.
330 /// This is designed to reduce the amount of code required at the call
331 /// site as much as possible (so that `panic!()` has as low an impact
332 /// on (e.g.) the inlining of other functions as possible), by moving
333 /// the actual formatting into this shared place.
334 #[unstable(feature = "libstd_sys_internals",
335 reason = "used by the panic! macro",
337 #[inline(never)] #[cold]
338 pub fn begin_panic_fmt(msg: &fmt::Arguments,
339 file_line_col: &(&'static str, u32, u32)) -> ! {
340 let (file, line, col) = *file_line_col;
341 let info = PanicInfo::internal_constructor(
343 Location::internal_constructor(file, line, col),
345 continue_panic_fmt(&info)
348 fn continue_panic_fmt(info: &PanicInfo) -> ! {
349 struct PanicPayload<'a> {
350 inner: &'a fmt::Arguments<'a>,
351 string: Option<String>,
354 impl<'a> PanicPayload<'a> {
355 fn new(inner: &'a fmt::Arguments<'a>) -> PanicPayload<'a> {
356 PanicPayload { inner, string: None }
359 fn fill(&mut self) -> &mut String {
362 let inner = self.inner;
363 self.string.get_or_insert_with(|| {
364 let mut s = String::new();
365 drop(s.write_fmt(*inner));
371 unsafe impl<'a> BoxMeUp for PanicPayload<'a> {
372 fn box_me_up(&mut self) -> *mut (Any + Send) {
373 let contents = mem::replace(self.fill(), String::new());
374 Box::into_raw(Box::new(contents))
377 fn get(&mut self) -> &(Any + Send) {
382 // We do two allocations here, unfortunately. But (a) they're
383 // required with the current scheme, and (b) we don't handle
384 // panic + OOM properly anyway (see comment in begin_panic
387 let loc = info.location().unwrap(); // The current implementation always returns Some
388 let msg = info.message().unwrap(); // The current implementation always returns Some
389 let file_line_col = (loc.file(), loc.line(), loc.column());
390 rust_panic_with_hook(
391 &mut PanicPayload::new(msg),
396 /// This is the entry point of panicking for panic!() and assert!().
397 #[unstable(feature = "libstd_sys_internals",
398 reason = "used by the panic! macro",
400 #[inline(never)] #[cold] // avoid code bloat at the call sites as much as possible
401 pub fn begin_panic<M: Any + Send>(msg: M, file_line_col: &(&'static str, u32, u32)) -> ! {
402 // Note that this should be the only allocation performed in this code path.
403 // Currently this means that panic!() on OOM will invoke this code path,
404 // but then again we're not really ready for panic on OOM anyway. If
405 // we do start doing this, then we should propagate this allocation to
406 // be performed in the parent of this thread instead of the thread that's
409 rust_panic_with_hook(&mut PanicPayload::new(msg), None, file_line_col);
411 struct PanicPayload<A> {
415 impl<A: Send + 'static> PanicPayload<A> {
416 fn new(inner: A) -> PanicPayload<A> {
417 PanicPayload { inner: Some(inner) }
421 unsafe impl<A: Send + 'static> BoxMeUp for PanicPayload<A> {
422 fn box_me_up(&mut self) -> *mut (Any + Send) {
423 let data = match self.inner.take() {
424 Some(a) => Box::new(a) as Box<Any + Send>,
425 None => Box::new(()),
430 fn get(&mut self) -> &(Any + Send) {
439 /// Central point for dispatching panics.
441 /// Executes the primary logic for a panic, including checking for recursive
442 /// panics, panic hooks, and finally dispatching to the panic runtime to either
444 fn rust_panic_with_hook(payload: &mut BoxMeUp,
445 message: Option<&fmt::Arguments>,
446 file_line_col: &(&str, u32, u32)) -> ! {
447 let (file, line, col) = *file_line_col;
449 let panics = update_panic_count(1);
451 // If this is the third nested call (e.g. panics == 2, this is 0-indexed),
452 // the panic hook probably triggered the last panic, otherwise the
453 // double-panic check would have aborted the process. In this case abort the
454 // process real quickly as we don't want to try calling it again as it'll
455 // probably just panic again.
457 util::dumb_print(format_args!("thread panicked while processing \
458 panic. aborting.\n"));
459 unsafe { intrinsics::abort() }
463 let mut info = PanicInfo::internal_constructor(
465 Location::internal_constructor(file, line, col),
469 // Some platforms know that printing to stderr won't ever actually
470 // print anything, and if that's the case we can skip the default
472 Hook::Default if stderr_prints_nothing() => {}
474 info.set_payload(payload.get());
477 Hook::Custom(ptr) => {
478 info.set_payload(payload.get());
482 HOOK_LOCK.read_unlock();
486 // If a thread panics while it's already unwinding then we
487 // have limited options. Currently our preference is to
488 // just abort. In the future we may consider resuming
489 // unwinding or otherwise exiting the thread cleanly.
490 util::dumb_print(format_args!("thread panicked while panicking. \
492 unsafe { intrinsics::abort() }
498 /// Shim around rust_panic. Called by resume_unwind.
499 pub fn update_count_then_panic(msg: Box<Any + Send>) -> ! {
500 update_panic_count(1);
502 struct RewrapBox(Box<Any + Send>);
504 unsafe impl BoxMeUp for RewrapBox {
505 fn box_me_up(&mut self) -> *mut (Any + Send) {
506 Box::into_raw(mem::replace(&mut self.0, Box::new(())))
509 fn get(&mut self) -> &(Any + Send) {
514 rust_panic(&mut RewrapBox(msg))
517 /// A private no-mangle function on which to slap yer breakpoints.
519 #[allow(private_no_mangle_fns)] // yes we get it, but we like breakpoints
520 pub fn rust_panic(mut msg: &mut BoxMeUp) -> ! {
522 let obj = &mut msg as *mut &mut BoxMeUp;
523 __rust_start_panic(obj as usize)
525 rtabort!("failed to initiate panic, error {}", code)