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