]> git.lizzy.rs Git - rust.git/blob - src/libstd/panicking.rs
Auto merge of #35856 - phimuemue:master, r=brson
[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 #[stable(feature = "panic_hooks", since = "1.10.0")]
88 pub fn set_hook(hook: Box<Fn(&PanicInfo) + 'static + Sync + Send>) {
89     if thread::panicking() {
90         panic!("cannot modify the panic hook from a panicking thread");
91     }
92
93     unsafe {
94         HOOK_LOCK.write();
95         let old_hook = HOOK;
96         HOOK = Hook::Custom(Box::into_raw(hook));
97         HOOK_LOCK.write_unlock();
98
99         if let Hook::Custom(ptr) = old_hook {
100             Box::from_raw(ptr);
101         }
102     }
103 }
104
105 /// Unregisters the current panic hook, returning it.
106 ///
107 /// If no custom hook is registered, the default hook will be returned.
108 ///
109 /// # Panics
110 ///
111 /// Panics if called from a panicking thread.
112 #[stable(feature = "panic_hooks", since = "1.10.0")]
113 pub fn take_hook() -> Box<Fn(&PanicInfo) + 'static + Sync + Send> {
114     if thread::panicking() {
115         panic!("cannot modify the panic hook from a panicking thread");
116     }
117
118     unsafe {
119         HOOK_LOCK.write();
120         let hook = HOOK;
121         HOOK = Hook::Default;
122         HOOK_LOCK.write_unlock();
123
124         match hook {
125             Hook::Default => Box::new(default_hook),
126             Hook::Custom(ptr) => {Box::from_raw(ptr)} // FIXME #30530
127         }
128     }
129 }
130
131 /// A struct providing information about a panic.
132 #[stable(feature = "panic_hooks", since = "1.10.0")]
133 pub struct PanicInfo<'a> {
134     payload: &'a (Any + Send),
135     location: Location<'a>,
136 }
137
138 impl<'a> PanicInfo<'a> {
139     /// Returns the payload associated with the panic.
140     ///
141     /// This will commonly, but not always, be a `&'static str` or `String`.
142     #[stable(feature = "panic_hooks", since = "1.10.0")]
143     pub fn payload(&self) -> &(Any + Send) {
144         self.payload
145     }
146
147     /// Returns information about the location from which the panic originated,
148     /// if available.
149     ///
150     /// This method will currently always return `Some`, but this may change
151     /// in future versions.
152     #[stable(feature = "panic_hooks", since = "1.10.0")]
153     pub fn location(&self) -> Option<&Location> {
154         Some(&self.location)
155     }
156 }
157
158 /// A struct containing information about the location of a panic.
159 #[stable(feature = "panic_hooks", since = "1.10.0")]
160 pub struct Location<'a> {
161     file: &'a str,
162     line: u32,
163 }
164
165 impl<'a> Location<'a> {
166     /// Returns the name of the source file from which the panic originated.
167     #[stable(feature = "panic_hooks", since = "1.10.0")]
168     pub fn file(&self) -> &str {
169         self.file
170     }
171
172     /// Returns the line number from which the panic originated.
173     #[stable(feature = "panic_hooks", since = "1.10.0")]
174     pub fn line(&self) -> u32 {
175         self.line
176     }
177 }
178
179 fn default_hook(info: &PanicInfo) {
180     #[cfg(any(not(cargobuild), feature = "backtrace"))]
181     use sys_common::backtrace;
182
183     // If this is a double panic, make sure that we print a backtrace
184     // for this panic. Otherwise only print it if logging is enabled.
185     #[cfg(any(not(cargobuild), feature = "backtrace"))]
186     let log_backtrace = {
187         let panics = update_panic_count(0);
188
189         panics >= 2 || backtrace::log_enabled()
190     };
191
192     let file = info.location.file;
193     let line = info.location.line;
194
195     let msg = match info.payload.downcast_ref::<&'static str>() {
196         Some(s) => *s,
197         None => match info.payload.downcast_ref::<String>() {
198             Some(s) => &s[..],
199             None => "Box<Any>",
200         }
201     };
202     let mut err = Stderr::new().ok();
203     let thread = thread_info::current_thread();
204     let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");
205
206     let write = |err: &mut ::io::Write| {
207         let _ = writeln!(err, "thread '{}' panicked at '{}', {}:{}",
208                          name, msg, file, line);
209
210         #[cfg(any(not(cargobuild), feature = "backtrace"))]
211         {
212             use sync::atomic::{AtomicBool, Ordering};
213
214             static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
215
216             if log_backtrace {
217                 let _ = backtrace::write(err);
218             } else if FIRST_PANIC.compare_and_swap(true, false, Ordering::SeqCst) {
219                 let _ = writeln!(err, "note: Run with `RUST_BACKTRACE=1` for a backtrace.");
220             }
221         }
222     };
223
224     let prev = LOCAL_STDERR.with(|s| s.borrow_mut().take());
225     match (prev, err.as_mut()) {
226         (Some(mut stderr), _) => {
227             write(&mut *stderr);
228             let mut s = Some(stderr);
229             LOCAL_STDERR.with(|slot| {
230                 *slot.borrow_mut() = s.take();
231             });
232         }
233         (None, Some(ref mut err)) => { write(err) }
234         _ => {}
235     }
236 }
237
238
239 #[cfg(not(test))]
240 #[doc(hidden)]
241 #[unstable(feature = "update_panic_count", issue = "0")]
242 pub fn update_panic_count(amt: isize) -> usize {
243     use cell::Cell;
244     thread_local! { static PANIC_COUNT: Cell<usize> = Cell::new(0) }
245
246     PANIC_COUNT.with(|c| {
247         let next = (c.get() as isize + amt) as usize;
248         c.set(next);
249         return next
250     })
251 }
252
253 #[cfg(test)]
254 pub use realstd::rt::update_panic_count;
255
256 /// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
257 pub unsafe fn try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<Any + Send>> {
258     struct Data<F, R> {
259         f: F,
260         r: R,
261     }
262
263     // We do some sketchy operations with ownership here for the sake of
264     // performance. The `Data` structure is never actually fully valid, but
265     // instead it always contains at least one uninitialized field. We can only
266     // pass pointers down to `__rust_maybe_catch_panic` (can't pass objects by
267     // value), so we do all the ownership tracking here manully.
268     //
269     // Note that this is all invalid if any of these functions unwind, but the
270     // whole point of this function is to prevent that! As a result we go
271     // through a transition where:
272     //
273     // * First, only the closure we're going to call is initialized. The return
274     //   value is uninitialized.
275     // * When we make the function call, the `do_call` function below, we take
276     //   ownership of the function pointer, replacing it with uninitialized
277     //   data. At this point the `Data` structure is entirely uninitialized, but
278     //   it won't drop due to an unwind because it's owned on the other side of
279     //   the catch panic.
280     // * If the closure successfully returns, we write the return value into the
281     //   data's return slot. Note that `ptr::write` is used as it's overwriting
282     //   uninitialized data.
283     // * Finally, when we come back out of the `__rust_maybe_catch_panic` we're
284     //   in one of two states:
285     //
286     //      1. The closure didn't panic, in which case the return value was
287     //         filled in. We have to be careful to `forget` the closure,
288     //         however, as ownership was passed to the `do_call` function.
289     //      2. The closure panicked, in which case the return value wasn't
290     //         filled in. In this case the entire `data` structure is invalid,
291     //         so we forget the entire thing.
292     //
293     // Once we stack all that together we should have the "most efficient'
294     // method of calling a catch panic whilst juggling ownership.
295     let mut any_data = 0;
296     let mut any_vtable = 0;
297     let mut data = Data {
298         f: f,
299         r: mem::uninitialized(),
300     };
301
302     let r = __rust_maybe_catch_panic(do_call::<F, R>,
303                                      &mut data as *mut _ as *mut u8,
304                                      &mut any_data,
305                                      &mut any_vtable);
306
307     return if r == 0 {
308         let Data { f, r } = data;
309         mem::forget(f);
310         debug_assert!(update_panic_count(0) == 0);
311         Ok(r)
312     } else {
313         mem::forget(data);
314         update_panic_count(-1);
315         debug_assert!(update_panic_count(0) == 0);
316         Err(mem::transmute(raw::TraitObject {
317             data: any_data as *mut _,
318             vtable: any_vtable as *mut _,
319         }))
320     };
321
322     fn do_call<F: FnOnce() -> R, R>(data: *mut u8) {
323         unsafe {
324             let data = data as *mut Data<F, R>;
325             let f = ptr::read(&mut (*data).f);
326             ptr::write(&mut (*data).r, f());
327         }
328     }
329 }
330
331 /// Determines whether the current thread is unwinding because of panic.
332 pub fn panicking() -> bool {
333     update_panic_count(0) != 0
334 }
335
336 /// Entry point of panic from the libcore crate.
337 #[cfg(not(test))]
338 #[lang = "panic_fmt"]
339 #[unwind]
340 pub extern fn rust_begin_panic(msg: fmt::Arguments,
341                                file: &'static str,
342                                line: u32) -> ! {
343     begin_panic_fmt(&msg, &(file, line))
344 }
345
346 /// The entry point for panicking with a formatted message.
347 ///
348 /// This is designed to reduce the amount of code required at the call
349 /// site as much as possible (so that `panic!()` has as low an impact
350 /// on (e.g.) the inlining of other functions as possible), by moving
351 /// the actual formatting into this shared place.
352 #[unstable(feature = "libstd_sys_internals",
353            reason = "used by the panic! macro",
354            issue = "0")]
355 #[inline(never)] #[cold]
356 pub fn begin_panic_fmt(msg: &fmt::Arguments,
357                        file_line: &(&'static str, u32)) -> ! {
358     use fmt::Write;
359
360     // We do two allocations here, unfortunately. But (a) they're
361     // required with the current scheme, and (b) we don't handle
362     // panic + OOM properly anyway (see comment in begin_panic
363     // below).
364
365     let mut s = String::new();
366     let _ = s.write_fmt(*msg);
367     begin_panic(s, file_line)
368 }
369
370 /// This is the entry point of panicking for panic!() and assert!().
371 #[unstable(feature = "libstd_sys_internals",
372            reason = "used by the panic! macro",
373            issue = "0")]
374 #[inline(never)] #[cold] // avoid code bloat at the call sites as much as possible
375 pub fn begin_panic<M: Any + Send>(msg: M, file_line: &(&'static str, u32)) -> ! {
376     // Note that this should be the only allocation performed in this code path.
377     // Currently this means that panic!() on OOM will invoke this code path,
378     // but then again we're not really ready for panic on OOM anyway. If
379     // we do start doing this, then we should propagate this allocation to
380     // be performed in the parent of this thread instead of the thread that's
381     // panicking.
382
383     rust_panic_with_hook(Box::new(msg), file_line)
384 }
385
386 /// Executes the primary logic for a panic, including checking for recursive
387 /// panics and panic hooks.
388 ///
389 /// This is the entry point or panics from libcore, formatted panics, and
390 /// `Box<Any>` panics. Here we'll verify that we're not panicking recursively,
391 /// run panic hooks, and then delegate to the actual implementation of panics.
392 #[inline(never)]
393 #[cold]
394 fn rust_panic_with_hook(msg: Box<Any + Send>,
395                         file_line: &(&'static str, u32)) -> ! {
396     let (file, line) = *file_line;
397
398     let panics = update_panic_count(1);
399
400     // If this is the third nested call (e.g. panics == 2, this is 0-indexed),
401     // the panic hook probably triggered the last panic, otherwise the
402     // double-panic check would have aborted the process. In this case abort the
403     // process real quickly as we don't want to try calling it again as it'll
404     // probably just panic again.
405     if panics > 2 {
406         util::dumb_print(format_args!("thread panicked while processing \
407                                        panic. aborting.\n"));
408         unsafe { intrinsics::abort() }
409     }
410
411     unsafe {
412         let info = PanicInfo {
413             payload: &*msg,
414             location: Location {
415                 file: file,
416                 line: line,
417             },
418         };
419         HOOK_LOCK.read();
420         match HOOK {
421             Hook::Default => default_hook(&info),
422             Hook::Custom(ptr) => (*ptr)(&info),
423         }
424         HOOK_LOCK.read_unlock();
425     }
426
427     if panics > 1 {
428         // If a thread panics while it's already unwinding then we
429         // have limited options. Currently our preference is to
430         // just abort. In the future we may consider resuming
431         // unwinding or otherwise exiting the thread cleanly.
432         util::dumb_print(format_args!("thread panicked while panicking. \
433                                        aborting.\n"));
434         unsafe { intrinsics::abort() }
435     }
436
437     rust_panic(msg)
438 }
439
440 /// Shim around rust_panic. Called by resume_unwind.
441 pub fn update_count_then_panic(msg: Box<Any + Send>) -> ! {
442     update_panic_count(1);
443     rust_panic(msg)
444 }
445
446 /// A private no-mangle function on which to slap yer breakpoints.
447 #[no_mangle]
448 #[allow(private_no_mangle_fns)] // yes we get it, but we like breakpoints
449 pub fn rust_panic(msg: Box<Any + Send>) -> ! {
450     let code = unsafe {
451         let obj = mem::transmute::<_, raw::TraitObject>(msg);
452         __rust_start_panic(obj.data as usize, obj.vtable as usize)
453     };
454     rtabort!("failed to initiate panic, error {}", code)
455 }