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