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