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"
30 use sys_common::rwlock::RWLock;
31 use sys::stdio::Stderr;
32 use sys_common::thread_info;
37 pub static LOCAL_STDERR: RefCell<Option<Box<Write + Send>>> = {
42 thread_local! { pub static PANIC_COUNT: Cell<usize> = Cell::new(0) }
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(data: usize, vtable: 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 /// The hook is provided with a `PanicInfo` struct which contains information
82 /// about the origin of the panic, including the payload passed to `panic!` and
83 /// the source code location from which the panic originated.
85 /// The panic hook is a global resource.
89 /// Panics if called from a panicking thread.
90 #[stable(feature = "panic_hooks", since = "1.10.0")]
91 pub fn set_hook(hook: Box<Fn(&PanicInfo) + 'static + Sync + Send>) {
92 if thread::panicking() {
93 panic!("cannot modify the panic hook from a panicking thread");
99 HOOK = Hook::Custom(Box::into_raw(hook));
100 HOOK_LOCK.write_unlock();
102 if let Hook::Custom(ptr) = old_hook {
108 /// Unregisters the current panic hook, returning it.
110 /// If no custom hook is registered, the default hook will be returned.
114 /// Panics if called from a panicking thread.
115 #[stable(feature = "panic_hooks", since = "1.10.0")]
116 pub fn take_hook() -> Box<Fn(&PanicInfo) + 'static + Sync + Send> {
117 if thread::panicking() {
118 panic!("cannot modify the panic hook from a panicking thread");
124 HOOK = Hook::Default;
125 HOOK_LOCK.write_unlock();
128 Hook::Default => Box::new(default_hook),
129 Hook::Custom(ptr) => {Box::from_raw(ptr)} // FIXME #30530
134 /// A struct providing information about a panic.
135 #[stable(feature = "panic_hooks", since = "1.10.0")]
136 pub struct PanicInfo<'a> {
137 payload: &'a (Any + Send),
138 location: Location<'a>,
141 impl<'a> PanicInfo<'a> {
142 /// Returns the payload associated with the panic.
144 /// This will commonly, but not always, be a `&'static str` or `String`.
145 #[stable(feature = "panic_hooks", since = "1.10.0")]
146 pub fn payload(&self) -> &(Any + Send) {
150 /// Returns information about the location from which the panic originated,
153 /// This method will currently always return `Some`, but this may change
154 /// in future versions.
155 #[stable(feature = "panic_hooks", since = "1.10.0")]
156 pub fn location(&self) -> Option<&Location> {
161 /// A struct containing information about the location of a panic.
162 #[stable(feature = "panic_hooks", since = "1.10.0")]
163 pub struct Location<'a> {
168 impl<'a> Location<'a> {
169 /// Returns the name of the source file from which the panic originated.
170 #[stable(feature = "panic_hooks", since = "1.10.0")]
171 pub fn file(&self) -> &str {
175 /// Returns the line number from which the panic originated.
176 #[stable(feature = "panic_hooks", since = "1.10.0")]
177 pub fn line(&self) -> u32 {
182 fn default_hook(info: &PanicInfo) {
183 #[cfg(any(not(cargobuild), feature = "backtrace"))]
184 use sys_common::backtrace;
186 // If this is a double panic, make sure that we print a backtrace
187 // for this panic. Otherwise only print it if logging is enabled.
188 #[cfg(any(not(cargobuild), feature = "backtrace"))]
189 let log_backtrace = {
190 let panics = PANIC_COUNT.with(|c| c.get());
192 panics >= 2 || backtrace::log_enabled()
195 let file = info.location.file;
196 let line = info.location.line;
198 let msg = match info.payload.downcast_ref::<&'static str>() {
200 None => match info.payload.downcast_ref::<String>() {
205 let mut err = Stderr::new().ok();
206 let thread = thread_info::current_thread();
207 let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");
209 let write = |err: &mut ::io::Write| {
210 let _ = writeln!(err, "thread '{}' panicked at '{}', {}:{}",
211 name, msg, file, line);
213 #[cfg(any(not(cargobuild), feature = "backtrace"))]
215 use sync::atomic::{AtomicBool, Ordering};
217 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
220 let _ = backtrace::write(err);
221 } else if FIRST_PANIC.compare_and_swap(true, false, Ordering::SeqCst) {
222 let _ = writeln!(err, "note: Run with `RUST_BACKTRACE=1` for a backtrace.");
227 let prev = LOCAL_STDERR.with(|s| s.borrow_mut().take());
228 match (prev, err.as_mut()) {
229 (Some(mut stderr), _) => {
231 let mut s = Some(stderr);
232 LOCAL_STDERR.with(|slot| {
233 *slot.borrow_mut() = s.take();
236 (None, Some(ref mut err)) => { write(err) }
241 /// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
242 pub unsafe fn try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<Any + Send>> {
245 let ret = PANIC_COUNT.with(|s| {
249 let mut to_run = || {
250 slot = Some(f.take().unwrap()());
252 let fnptr = get_call(&mut to_run);
253 let dataptr = &mut to_run as *mut _ as *mut u8;
254 let mut any_data = 0;
255 let mut any_vtable = 0;
256 let fnptr = mem::transmute::<fn(&mut _), fn(*mut u8)>(fnptr);
257 let r = __rust_maybe_catch_panic(fnptr,
266 Err(mem::transmute(raw::TraitObject {
267 data: any_data as *mut _,
268 vtable: any_vtable as *mut _,
273 return ret.map(|()| {
277 fn get_call<F: FnMut()>(_: &mut F) -> fn(&mut F) {
281 fn call<F: FnMut()>(f: &mut F) {
286 /// Determines whether the current thread is unwinding because of panic.
287 pub fn panicking() -> bool {
288 PANIC_COUNT.with(|c| c.get() != 0)
291 /// Entry point of panic from the libcore crate.
293 #[lang = "panic_fmt"]
295 pub extern fn rust_begin_panic(msg: fmt::Arguments,
298 begin_panic_fmt(&msg, &(file, line))
301 /// The entry point for panicking with a formatted message.
303 /// This is designed to reduce the amount of code required at the call
304 /// site as much as possible (so that `panic!()` has as low an impact
305 /// on (e.g.) the inlining of other functions as possible), by moving
306 /// the actual formatting into this shared place.
307 #[unstable(feature = "libstd_sys_internals",
308 reason = "used by the panic! macro",
310 #[inline(never)] #[cold]
311 pub fn begin_panic_fmt(msg: &fmt::Arguments,
312 file_line: &(&'static str, u32)) -> ! {
315 // We do two allocations here, unfortunately. But (a) they're
316 // required with the current scheme, and (b) we don't handle
317 // panic + OOM properly anyway (see comment in begin_panic
320 let mut s = String::new();
321 let _ = s.write_fmt(*msg);
322 begin_panic(s, file_line)
325 /// This is the entry point of panicking for panic!() and assert!().
326 #[unstable(feature = "libstd_sys_internals",
327 reason = "used by the panic! macro",
329 #[inline(never)] #[cold] // avoid code bloat at the call sites as much as possible
330 pub fn begin_panic<M: Any + Send>(msg: M, file_line: &(&'static str, u32)) -> ! {
331 // Note that this should be the only allocation performed in this code path.
332 // Currently this means that panic!() on OOM will invoke this code path,
333 // but then again we're not really ready for panic on OOM anyway. If
334 // we do start doing this, then we should propagate this allocation to
335 // be performed in the parent of this thread instead of the thread that's
338 rust_panic_with_hook(Box::new(msg), file_line)
341 /// Executes the primary logic for a panic, including checking for recursive
342 /// panics and panic hooks.
344 /// This is the entry point or panics from libcore, formatted panics, and
345 /// `Box<Any>` panics. Here we'll verify that we're not panicking recursively,
346 /// run panic hooks, and then delegate to the actual implementation of panics.
349 fn rust_panic_with_hook(msg: Box<Any + Send>,
350 file_line: &(&'static str, u32)) -> ! {
351 let (file, line) = *file_line;
353 let panics = PANIC_COUNT.with(|c| {
359 // If this is the third nested call (e.g. panics == 2, this is 0-indexed),
360 // the panic hook probably triggered the last panic, otherwise the
361 // double-panic check would have aborted the process. In this case abort the
362 // process real quickly as we don't want to try calling it again as it'll
363 // probably just panic again.
365 util::dumb_print(format_args!("thread panicked while processing \
366 panic. aborting.\n"));
367 unsafe { intrinsics::abort() }
371 let info = PanicInfo {
380 Hook::Default => default_hook(&info),
381 Hook::Custom(ptr) => (*ptr)(&info),
383 HOOK_LOCK.read_unlock();
387 // If a thread panics while it's already unwinding then we
388 // have limited options. Currently our preference is to
389 // just abort. In the future we may consider resuming
390 // unwinding or otherwise exiting the thread cleanly.
391 util::dumb_print(format_args!("thread panicked while panicking. \
393 unsafe { intrinsics::abort() }
399 /// A private no-mangle function on which to slap yer breakpoints.
401 #[allow(private_no_mangle_fns)] // yes we get it, but we like breakpoints
402 pub fn rust_panic(msg: Box<Any + Send>) -> ! {
404 let obj = mem::transmute::<_, raw::TraitObject>(msg);
405 __rust_start_panic(obj.data as usize, obj.vtable as usize)
407 rtabort!("failed to initiate panic, error {}", code)