]> git.lizzy.rs Git - rust.git/blob - src/libstd/panicking.rs
add inline attributes to stage 0 methods
[rust.git] / src / libstd / panicking.rs
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.
4 //
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.
10
11 //! Implementation of various bits and pieces of the `panic!` macro and
12 //! associated runtime pieces.
13 //!
14 //! Specifically, this module contains the implementation of:
15 //!
16 //! * Panic hooks
17 //! * Executing a panic up to doing the actual implementation
18 //! * Shims around "try"
19
20 use io::prelude::*;
21
22 use any::Any;
23 use cell::RefCell;
24 use fmt;
25 use intrinsics;
26 use mem;
27 use ptr;
28 use raw;
29 use sys::stdio::Stderr;
30 use sys_common::rwlock::RWLock;
31 use sys_common::thread_info;
32 use sys_common::util;
33 use thread;
34
35 thread_local! {
36     pub static LOCAL_STDERR: RefCell<Option<Box<Write + Send>>> = {
37         RefCell::new(None)
38     }
39 }
40
41 // Binary interface to the panic runtime that the standard library depends on.
42 //
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
47 // to them.
48 //
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)]
52 extern {
53     fn __rust_maybe_catch_panic(f: fn(*mut u8),
54                                 data: *mut u8,
55                                 data_ptr: *mut usize,
56                                 vtable_ptr: *mut usize) -> u32;
57     #[unwind]
58     fn __rust_start_panic(data: usize, vtable: usize) -> u32;
59 }
60
61 #[derive(Copy, Clone)]
62 enum Hook {
63     Default,
64     Custom(*mut (Fn(&PanicInfo) + 'static + Sync + Send)),
65 }
66
67 static HOOK_LOCK: RWLock = RWLock::new();
68 static mut HOOK: Hook = Hook::Default;
69
70 /// Registers a custom panic hook, replacing any that was previously registered.
71 ///
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.
77 ///
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.
81 ///
82 /// The panic hook is a global resource.
83 ///
84 /// # Panics
85 ///
86 /// Panics if called from a panicking thread.
87 ///
88 /// # Examples
89 ///
90 /// The following will print "Custom panic hook":
91 ///
92 /// ```should_panic
93 /// use std::panic;
94 ///
95 /// panic::set_hook(Box::new(|_| {
96 ///     println!("Custom panic hook");
97 /// }));
98 ///
99 /// panic!("Normal panic");
100 /// ```
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");
105     }
106
107     unsafe {
108         HOOK_LOCK.write();
109         let old_hook = HOOK;
110         HOOK = Hook::Custom(Box::into_raw(hook));
111         HOOK_LOCK.write_unlock();
112
113         if let Hook::Custom(ptr) = old_hook {
114             Box::from_raw(ptr);
115         }
116     }
117 }
118
119 /// Unregisters the current panic hook, returning it.
120 ///
121 /// If no custom hook is registered, the default hook will be returned.
122 ///
123 /// # Panics
124 ///
125 /// Panics if called from a panicking thread.
126 ///
127 /// # Examples
128 ///
129 /// The following will print "Normal panic":
130 ///
131 /// ```should_panic
132 /// use std::panic;
133 ///
134 /// panic::set_hook(Box::new(|_| {
135 ///     println!("Custom panic hook");
136 /// }));
137 ///
138 /// let _ = panic::take_hook();
139 ///
140 /// panic!("Normal panic");
141 /// ```
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");
146     }
147
148     unsafe {
149         HOOK_LOCK.write();
150         let hook = HOOK;
151         HOOK = Hook::Default;
152         HOOK_LOCK.write_unlock();
153
154         match hook {
155             Hook::Default => Box::new(default_hook),
156             Hook::Custom(ptr) => Box::from_raw(ptr),
157         }
158     }
159 }
160
161 /// A struct providing information about a panic.
162 ///
163 /// `PanicInfo` structure is passed to a panic hook set by the [`set_hook()`]
164 /// function.
165 ///
166 /// [`set_hook()`]: ../../std/panic/fn.set_hook.html
167 ///
168 /// # Examples
169 ///
170 /// ```should_panic
171 /// use std::panic;
172 ///
173 /// panic::set_hook(Box::new(|panic_info| {
174 ///     println!("panic occured: {:?}", panic_info.payload().downcast_ref::<&str>().unwrap());
175 /// }));
176 ///
177 /// panic!("Normal panic");
178 /// ```
179 #[stable(feature = "panic_hooks", since = "1.10.0")]
180 #[derive(Debug)]
181 pub struct PanicInfo<'a> {
182     payload: &'a (Any + Send),
183     location: Location<'a>,
184 }
185
186 impl<'a> PanicInfo<'a> {
187     /// Returns the payload associated with the panic.
188     ///
189     /// This will commonly, but not always, be a `&'static str` or [`String`].
190     ///
191     /// [`String`]: ../../std/string/struct.String.html
192     ///
193     /// # Examples
194     ///
195     /// ```should_panic
196     /// use std::panic;
197     ///
198     /// panic::set_hook(Box::new(|panic_info| {
199     ///     println!("panic occured: {:?}", panic_info.payload().downcast_ref::<&str>().unwrap());
200     /// }));
201     ///
202     /// panic!("Normal panic");
203     /// ```
204     #[stable(feature = "panic_hooks", since = "1.10.0")]
205     pub fn payload(&self) -> &(Any + Send) {
206         self.payload
207     }
208
209     /// Returns information about the location from which the panic originated,
210     /// if available.
211     ///
212     /// This method will currently always return [`Some`], but this may change
213     /// in future versions.
214     ///
215     /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
216     ///
217     /// # Examples
218     ///
219     /// ```should_panic
220     /// use std::panic;
221     ///
222     /// panic::set_hook(Box::new(|panic_info| {
223     ///     if let Some(location) = panic_info.location() {
224     ///         println!("panic occured in file '{}' at line {}", location.file(), location.line());
225     ///     } else {
226     ///         println!("panic occured but can't get location information...");
227     ///     }
228     /// }));
229     ///
230     /// panic!("Normal panic");
231     /// ```
232     #[stable(feature = "panic_hooks", since = "1.10.0")]
233     pub fn location(&self) -> Option<&Location> {
234         Some(&self.location)
235     }
236 }
237
238 /// A struct containing information about the location of a panic.
239 ///
240 /// This structure is created by the [`location()`] method of [`PanicInfo`].
241 ///
242 /// [`location()`]: ../../std/panic/struct.PanicInfo.html#method.location
243 /// [`PanicInfo`]: ../../std/panic/struct.PanicInfo.html
244 ///
245 /// # Examples
246 ///
247 /// ```should_panic
248 /// use std::panic;
249 ///
250 /// panic::set_hook(Box::new(|panic_info| {
251 ///     if let Some(location) = panic_info.location() {
252 ///         println!("panic occured in file '{}' at line {}", location.file(), location.line());
253 ///     } else {
254 ///         println!("panic occured but can't get location information...");
255 ///     }
256 /// }));
257 ///
258 /// panic!("Normal panic");
259 /// ```
260 #[derive(Debug)]
261 #[stable(feature = "panic_hooks", since = "1.10.0")]
262 pub struct Location<'a> {
263     file: &'a str,
264     line: u32,
265 }
266
267 impl<'a> Location<'a> {
268     /// Returns the name of the source file from which the panic originated.
269     ///
270     /// # Examples
271     ///
272     /// ```should_panic
273     /// use std::panic;
274     ///
275     /// panic::set_hook(Box::new(|panic_info| {
276     ///     if let Some(location) = panic_info.location() {
277     ///         println!("panic occured in file '{}'", location.file());
278     ///     } else {
279     ///         println!("panic occured but can't get location information...");
280     ///     }
281     /// }));
282     ///
283     /// panic!("Normal panic");
284     /// ```
285     #[stable(feature = "panic_hooks", since = "1.10.0")]
286     pub fn file(&self) -> &str {
287         self.file
288     }
289
290     /// Returns the line number from which the panic originated.
291     ///
292     /// # Examples
293     ///
294     /// ```should_panic
295     /// use std::panic;
296     ///
297     /// panic::set_hook(Box::new(|panic_info| {
298     ///     if let Some(location) = panic_info.location() {
299     ///         println!("panic occured at line {}", location.line());
300     ///     } else {
301     ///         println!("panic occured but can't get location information...");
302     ///     }
303     /// }));
304     ///
305     /// panic!("Normal panic");
306     /// ```
307     #[stable(feature = "panic_hooks", since = "1.10.0")]
308     pub fn line(&self) -> u32 {
309         self.line
310     }
311 }
312
313 fn default_hook(info: &PanicInfo) {
314     #[cfg(feature = "backtrace")]
315     use sys_common::backtrace;
316
317     // If this is a double panic, make sure that we print a backtrace
318     // for this panic. Otherwise only print it if logging is enabled.
319     #[cfg(feature = "backtrace")]
320     let log_backtrace = {
321         let panics = update_panic_count(0);
322
323         if panics >= 2 {
324             Some(backtrace::PrintFormat::Full)
325         } else {
326             backtrace::log_enabled()
327         }
328     };
329
330     let file = info.location.file;
331     let line = info.location.line;
332
333     let msg = match info.payload.downcast_ref::<&'static str>() {
334         Some(s) => *s,
335         None => match info.payload.downcast_ref::<String>() {
336             Some(s) => &s[..],
337             None => "Box<Any>",
338         }
339     };
340     let mut err = Stderr::new().ok();
341     let thread = thread_info::current_thread();
342     let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");
343
344     let write = |err: &mut ::io::Write| {
345         let _ = writeln!(err, "thread '{}' panicked at '{}', {}:{}",
346                          name, msg, file, line);
347
348         #[cfg(feature = "backtrace")]
349         {
350             use sync::atomic::{AtomicBool, Ordering};
351
352             static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
353
354             if let Some(format) = log_backtrace {
355                 let _ = backtrace::print(err, format);
356             } else if FIRST_PANIC.compare_and_swap(true, false, Ordering::SeqCst) {
357                 let _ = writeln!(err, "note: Run with `RUST_BACKTRACE=1` for a backtrace.");
358             }
359         }
360     };
361
362     let prev = LOCAL_STDERR.with(|s| s.borrow_mut().take());
363     match (prev, err.as_mut()) {
364         (Some(mut stderr), _) => {
365             write(&mut *stderr);
366             let mut s = Some(stderr);
367             LOCAL_STDERR.with(|slot| {
368                 *slot.borrow_mut() = s.take();
369             });
370         }
371         (None, Some(ref mut err)) => { write(err) }
372         _ => {}
373     }
374 }
375
376
377 #[cfg(not(test))]
378 #[doc(hidden)]
379 #[unstable(feature = "update_panic_count", issue = "0")]
380 pub fn update_panic_count(amt: isize) -> usize {
381     use cell::Cell;
382     thread_local! { static PANIC_COUNT: Cell<usize> = Cell::new(0) }
383
384     PANIC_COUNT.with(|c| {
385         let next = (c.get() as isize + amt) as usize;
386         c.set(next);
387         return next
388     })
389 }
390
391 #[cfg(test)]
392 pub use realstd::rt::update_panic_count;
393
394 /// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
395 pub unsafe fn try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<Any + Send>> {
396     #[allow(unions_with_drop_fields)]
397     union Data<F, R> {
398         f: F,
399         r: R,
400     }
401
402     // We do some sketchy operations with ownership here for the sake of
403     // performance. We can only  pass pointers down to
404     // `__rust_maybe_catch_panic` (can't pass objects by value), so we do all
405     // the ownership tracking here manually using a union.
406     //
407     // We go through a transition where:
408     //
409     // * First, we set the data to be the closure that we're going to call.
410     // * When we make the function call, the `do_call` function below, we take
411     //   ownership of the function pointer. At this point the `Data` union is
412     //   entirely uninitialized.
413     // * If the closure successfully returns, we write the return value into the
414     //   data's return slot. Note that `ptr::write` is used as it's overwriting
415     //   uninitialized data.
416     // * Finally, when we come back out of the `__rust_maybe_catch_panic` we're
417     //   in one of two states:
418     //
419     //      1. The closure didn't panic, in which case the return value was
420     //         filled in. We move it out of `data` and return it.
421     //      2. The closure panicked, in which case the return value wasn't
422     //         filled in. In this case the entire `data` union is invalid, so
423     //         there is no need to drop anything.
424     //
425     // Once we stack all that together we should have the "most efficient'
426     // method of calling a catch panic whilst juggling ownership.
427     let mut any_data = 0;
428     let mut any_vtable = 0;
429     let mut data = Data {
430         f: f,
431     };
432
433     let r = __rust_maybe_catch_panic(do_call::<F, R>,
434                                      &mut data as *mut _ as *mut u8,
435                                      &mut any_data,
436                                      &mut any_vtable);
437
438     return if r == 0 {
439         debug_assert!(update_panic_count(0) == 0);
440         Ok(data.r)
441     } else {
442         update_panic_count(-1);
443         debug_assert!(update_panic_count(0) == 0);
444         Err(mem::transmute(raw::TraitObject {
445             data: any_data as *mut _,
446             vtable: any_vtable as *mut _,
447         }))
448     };
449
450     fn do_call<F: FnOnce() -> R, R>(data: *mut u8) {
451         unsafe {
452             let data = data as *mut Data<F, R>;
453             let f = ptr::read(&mut (*data).f);
454             ptr::write(&mut (*data).r, f());
455         }
456     }
457 }
458
459 /// Determines whether the current thread is unwinding because of panic.
460 pub fn panicking() -> bool {
461     update_panic_count(0) != 0
462 }
463
464 /// Entry point of panic from the libcore crate.
465 #[cfg(not(test))]
466 #[lang = "panic_fmt"]
467 #[unwind]
468 pub extern fn rust_begin_panic(msg: fmt::Arguments,
469                                file: &'static str,
470                                line: u32) -> ! {
471     begin_panic_fmt(&msg, &(file, line))
472 }
473
474 /// The entry point for panicking with a formatted message.
475 ///
476 /// This is designed to reduce the amount of code required at the call
477 /// site as much as possible (so that `panic!()` has as low an impact
478 /// on (e.g.) the inlining of other functions as possible), by moving
479 /// the actual formatting into this shared place.
480 #[unstable(feature = "libstd_sys_internals",
481            reason = "used by the panic! macro",
482            issue = "0")]
483 #[inline(never)] #[cold]
484 pub fn begin_panic_fmt(msg: &fmt::Arguments,
485                        file_line: &(&'static str, u32)) -> ! {
486     use fmt::Write;
487
488     // We do two allocations here, unfortunately. But (a) they're
489     // required with the current scheme, and (b) we don't handle
490     // panic + OOM properly anyway (see comment in begin_panic
491     // below).
492
493     let mut s = String::new();
494     let _ = s.write_fmt(*msg);
495     begin_panic(s, file_line)
496 }
497
498 /// This is the entry point of panicking for panic!() and assert!().
499 #[unstable(feature = "libstd_sys_internals",
500            reason = "used by the panic! macro",
501            issue = "0")]
502 #[inline(never)] #[cold] // avoid code bloat at the call sites as much as possible
503 pub fn begin_panic<M: Any + Send>(msg: M, file_line: &(&'static str, u32)) -> ! {
504     // Note that this should be the only allocation performed in this code path.
505     // Currently this means that panic!() on OOM will invoke this code path,
506     // but then again we're not really ready for panic on OOM anyway. If
507     // we do start doing this, then we should propagate this allocation to
508     // be performed in the parent of this thread instead of the thread that's
509     // panicking.
510
511     rust_panic_with_hook(Box::new(msg), file_line)
512 }
513
514 /// Executes the primary logic for a panic, including checking for recursive
515 /// panics and panic hooks.
516 ///
517 /// This is the entry point or panics from libcore, formatted panics, and
518 /// `Box<Any>` panics. Here we'll verify that we're not panicking recursively,
519 /// run panic hooks, and then delegate to the actual implementation of panics.
520 #[inline(never)]
521 #[cold]
522 fn rust_panic_with_hook(msg: Box<Any + Send>,
523                         file_line: &(&'static str, u32)) -> ! {
524     let (file, line) = *file_line;
525
526     let panics = update_panic_count(1);
527
528     // If this is the third nested call (e.g. panics == 2, this is 0-indexed),
529     // the panic hook probably triggered the last panic, otherwise the
530     // double-panic check would have aborted the process. In this case abort the
531     // process real quickly as we don't want to try calling it again as it'll
532     // probably just panic again.
533     if panics > 2 {
534         util::dumb_print(format_args!("thread panicked while processing \
535                                        panic. aborting.\n"));
536         unsafe { intrinsics::abort() }
537     }
538
539     unsafe {
540         let info = PanicInfo {
541             payload: &*msg,
542             location: Location {
543                 file: file,
544                 line: line,
545             },
546         };
547         HOOK_LOCK.read();
548         match HOOK {
549             Hook::Default => default_hook(&info),
550             Hook::Custom(ptr) => (*ptr)(&info),
551         }
552         HOOK_LOCK.read_unlock();
553     }
554
555     if panics > 1 {
556         // If a thread panics while it's already unwinding then we
557         // have limited options. Currently our preference is to
558         // just abort. In the future we may consider resuming
559         // unwinding or otherwise exiting the thread cleanly.
560         util::dumb_print(format_args!("thread panicked while panicking. \
561                                        aborting.\n"));
562         unsafe { intrinsics::abort() }
563     }
564
565     rust_panic(msg)
566 }
567
568 /// Shim around rust_panic. Called by resume_unwind.
569 pub fn update_count_then_panic(msg: Box<Any + Send>) -> ! {
570     update_panic_count(1);
571     rust_panic(msg)
572 }
573
574 /// A private no-mangle function on which to slap yer breakpoints.
575 #[no_mangle]
576 #[allow(private_no_mangle_fns)] // yes we get it, but we like breakpoints
577 pub fn rust_panic(msg: Box<Any + Send>) -> ! {
578     let code = unsafe {
579         let obj = mem::transmute::<_, raw::TraitObject>(msg);
580         __rust_start_panic(obj.data as usize, obj.vtable as usize)
581     };
582     rtabort!("failed to initiate panic, error {}", code)
583 }