]> git.lizzy.rs Git - rust.git/blob - src/libstd/panic.rs
Rollup merge of #58802 - nnethercote:inline-record_layout, r=oli-obk
[rust.git] / src / libstd / panic.rs
1 //! Panic support in the standard library.
2
3 #![stable(feature = "std_panic", since = "1.9.0")]
4
5 use crate::any::Any;
6 use crate::cell::UnsafeCell;
7 use crate::fmt;
8 use crate::future::Future;
9 use crate::pin::Pin;
10 use crate::ops::{Deref, DerefMut};
11 use crate::panicking;
12 use crate::ptr::{Unique, NonNull};
13 use crate::rc::Rc;
14 use crate::sync::{Arc, Mutex, RwLock, atomic};
15 use crate::task::{Waker, Poll};
16 use crate::thread::Result;
17
18 #[stable(feature = "panic_hooks", since = "1.10.0")]
19 pub use crate::panicking::{take_hook, set_hook};
20
21 #[stable(feature = "panic_hooks", since = "1.10.0")]
22 pub use core::panic::{PanicInfo, Location};
23
24 /// A marker trait which represents "panic safe" types in Rust.
25 ///
26 /// This trait is implemented by default for many types and behaves similarly in
27 /// terms of inference of implementation to the [`Send`] and [`Sync`] traits. The
28 /// purpose of this trait is to encode what types are safe to cross a [`catch_unwind`]
29 /// boundary with no fear of unwind safety.
30 ///
31 /// [`Send`]: ../marker/trait.Send.html
32 /// [`Sync`]: ../marker/trait.Sync.html
33 /// [`catch_unwind`]: ./fn.catch_unwind.html
34 ///
35 /// ## What is unwind safety?
36 ///
37 /// In Rust a function can "return" early if it either panics or calls a
38 /// function which transitively panics. This sort of control flow is not always
39 /// anticipated, and has the possibility of causing subtle bugs through a
40 /// combination of two critical components:
41 ///
42 /// 1. A data structure is in a temporarily invalid state when the thread
43 ///    panics.
44 /// 2. This broken invariant is then later observed.
45 ///
46 /// Typically in Rust, it is difficult to perform step (2) because catching a
47 /// panic involves either spawning a thread (which in turns makes it difficult
48 /// to later witness broken invariants) or using the `catch_unwind` function in this
49 /// module. Additionally, even if an invariant is witnessed, it typically isn't a
50 /// problem in Rust because there are no uninitialized values (like in C or C++).
51 ///
52 /// It is possible, however, for **logical** invariants to be broken in Rust,
53 /// which can end up causing behavioral bugs. Another key aspect of unwind safety
54 /// in Rust is that, in the absence of `unsafe` code, a panic cannot lead to
55 /// memory unsafety.
56 ///
57 /// That was a bit of a whirlwind tour of unwind safety, but for more information
58 /// about unwind safety and how it applies to Rust, see an [associated RFC][rfc].
59 ///
60 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
61 ///
62 /// ## What is `UnwindSafe`?
63 ///
64 /// Now that we've got an idea of what unwind safety is in Rust, it's also
65 /// important to understand what this trait represents. As mentioned above, one
66 /// way to witness broken invariants is through the `catch_unwind` function in this
67 /// module as it allows catching a panic and then re-using the environment of
68 /// the closure.
69 ///
70 /// Simply put, a type `T` implements `UnwindSafe` if it cannot easily allow
71 /// witnessing a broken invariant through the use of `catch_unwind` (catching a
72 /// panic). This trait is an auto trait, so it is automatically implemented for
73 /// many types, and it is also structurally composed (e.g., a struct is unwind
74 /// safe if all of its components are unwind safe).
75 ///
76 /// Note, however, that this is not an unsafe trait, so there is not a succinct
77 /// contract that this trait is providing. Instead it is intended as more of a
78 /// "speed bump" to alert users of `catch_unwind` that broken invariants may be
79 /// witnessed and may need to be accounted for.
80 ///
81 /// ## Who implements `UnwindSafe`?
82 ///
83 /// Types such as `&mut T` and `&RefCell<T>` are examples which are **not**
84 /// unwind safe. The general idea is that any mutable state which can be shared
85 /// across `catch_unwind` is not unwind safe by default. This is because it is very
86 /// easy to witness a broken invariant outside of `catch_unwind` as the data is
87 /// simply accessed as usual.
88 ///
89 /// Types like `&Mutex<T>`, however, are unwind safe because they implement
90 /// poisoning by default. They still allow witnessing a broken invariant, but
91 /// they already provide their own "speed bumps" to do so.
92 ///
93 /// ## When should `UnwindSafe` be used?
94 ///
95 /// It is not intended that most types or functions need to worry about this trait.
96 /// It is only used as a bound on the `catch_unwind` function and as mentioned
97 /// above, the lack of `unsafe` means it is mostly an advisory. The
98 /// [`AssertUnwindSafe`] wrapper struct can be used to force this trait to be
99 /// implemented for any closed over variables passed to `catch_unwind`.
100 ///
101 /// [`AssertUnwindSafe`]: ./struct.AssertUnwindSafe.html
102 #[stable(feature = "catch_unwind", since = "1.9.0")]
103 #[rustc_on_unimplemented(
104     message="the type `{Self}` may not be safely transferred across an unwind boundary",
105     label="`{Self}` may not be safely transferred across an unwind boundary",
106 )]
107 pub auto trait UnwindSafe {}
108
109 /// A marker trait representing types where a shared reference is considered
110 /// unwind safe.
111 ///
112 /// This trait is namely not implemented by [`UnsafeCell`], the root of all
113 /// interior mutability.
114 ///
115 /// This is a "helper marker trait" used to provide impl blocks for the
116 /// [`UnwindSafe`] trait, for more information see that documentation.
117 ///
118 /// [`UnsafeCell`]: ../cell/struct.UnsafeCell.html
119 /// [`UnwindSafe`]: ./trait.UnwindSafe.html
120 #[stable(feature = "catch_unwind", since = "1.9.0")]
121 #[rustc_on_unimplemented(
122     message="the type `{Self}` may contain interior mutability and a reference may not be safely \
123              transferrable across a catch_unwind boundary",
124     label="`{Self}` may contain interior mutability and a reference may not be safely \
125            transferrable across a catch_unwind boundary",
126 )]
127 pub auto trait RefUnwindSafe {}
128
129 /// A simple wrapper around a type to assert that it is unwind safe.
130 ///
131 /// When using [`catch_unwind`] it may be the case that some of the closed over
132 /// variables are not unwind safe. For example if `&mut T` is captured the
133 /// compiler will generate a warning indicating that it is not unwind safe. It
134 /// may not be the case, however, that this is actually a problem due to the
135 /// specific usage of [`catch_unwind`] if unwind safety is specifically taken into
136 /// account. This wrapper struct is useful for a quick and lightweight
137 /// annotation that a variable is indeed unwind safe.
138 ///
139 /// [`catch_unwind`]: ./fn.catch_unwind.html
140 /// # Examples
141 ///
142 /// One way to use `AssertUnwindSafe` is to assert that the entire closure
143 /// itself is unwind safe, bypassing all checks for all variables:
144 ///
145 /// ```
146 /// use std::panic::{self, AssertUnwindSafe};
147 ///
148 /// let mut variable = 4;
149 ///
150 /// // This code will not compile because the closure captures `&mut variable`
151 /// // which is not considered unwind safe by default.
152 ///
153 /// // panic::catch_unwind(|| {
154 /// //     variable += 3;
155 /// // });
156 ///
157 /// // This, however, will compile due to the `AssertUnwindSafe` wrapper
158 /// let result = panic::catch_unwind(AssertUnwindSafe(|| {
159 ///     variable += 3;
160 /// }));
161 /// // ...
162 /// ```
163 ///
164 /// Wrapping the entire closure amounts to a blanket assertion that all captured
165 /// variables are unwind safe. This has the downside that if new captures are
166 /// added in the future, they will also be considered unwind safe. Therefore,
167 /// you may prefer to just wrap individual captures, as shown below. This is
168 /// more annotation, but it ensures that if a new capture is added which is not
169 /// unwind safe, you will get a compilation error at that time, which will
170 /// allow you to consider whether that new capture in fact represent a bug or
171 /// not.
172 ///
173 /// ```
174 /// use std::panic::{self, AssertUnwindSafe};
175 ///
176 /// let mut variable = 4;
177 /// let other_capture = 3;
178 ///
179 /// let result = {
180 ///     let mut wrapper = AssertUnwindSafe(&mut variable);
181 ///     panic::catch_unwind(move || {
182 ///         **wrapper += other_capture;
183 ///     })
184 /// };
185 /// // ...
186 /// ```
187 #[stable(feature = "catch_unwind", since = "1.9.0")]
188 pub struct AssertUnwindSafe<T>(
189     #[stable(feature = "catch_unwind", since = "1.9.0")]
190     pub T
191 );
192
193 // Implementations of the `UnwindSafe` trait:
194 //
195 // * By default everything is unwind safe
196 // * pointers T contains mutability of some form are not unwind safe
197 // * Unique, an owning pointer, lifts an implementation
198 // * Types like Mutex/RwLock which are explicitly poisoned are unwind safe
199 // * Our custom AssertUnwindSafe wrapper is indeed unwind safe
200
201 #[stable(feature = "catch_unwind", since = "1.9.0")]
202 impl<T: ?Sized> !UnwindSafe for &mut T {}
203 #[stable(feature = "catch_unwind", since = "1.9.0")]
204 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for &T {}
205 #[stable(feature = "catch_unwind", since = "1.9.0")]
206 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *const T {}
207 #[stable(feature = "catch_unwind", since = "1.9.0")]
208 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *mut T {}
209 #[unstable(feature = "ptr_internals", issue = "0")]
210 impl<T: UnwindSafe + ?Sized> UnwindSafe for Unique<T> {}
211 #[stable(feature = "nonnull", since = "1.25.0")]
212 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for NonNull<T> {}
213 #[stable(feature = "catch_unwind", since = "1.9.0")]
214 impl<T: ?Sized> UnwindSafe for Mutex<T> {}
215 #[stable(feature = "catch_unwind", since = "1.9.0")]
216 impl<T: ?Sized> UnwindSafe for RwLock<T> {}
217 #[stable(feature = "catch_unwind", since = "1.9.0")]
218 impl<T> UnwindSafe for AssertUnwindSafe<T> {}
219
220 // not covered via the Shared impl above b/c the inner contents use
221 // Cell/AtomicUsize, but the usage here is unwind safe so we can lift the
222 // impl up one level to Arc/Rc itself
223 #[stable(feature = "catch_unwind", since = "1.9.0")]
224 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Rc<T> {}
225 #[stable(feature = "catch_unwind", since = "1.9.0")]
226 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Arc<T> {}
227
228 // Pretty simple implementations for the `RefUnwindSafe` marker trait,
229 // basically just saying that `UnsafeCell` is the
230 // only thing which doesn't implement it (which then transitively applies to
231 // everything else).
232 #[stable(feature = "catch_unwind", since = "1.9.0")]
233 impl<T: ?Sized> !RefUnwindSafe for UnsafeCell<T> {}
234 #[stable(feature = "catch_unwind", since = "1.9.0")]
235 impl<T> RefUnwindSafe for AssertUnwindSafe<T> {}
236
237 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
238 impl<T: ?Sized> RefUnwindSafe for Mutex<T> {}
239 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
240 impl<T: ?Sized> RefUnwindSafe for RwLock<T> {}
241
242 #[cfg(target_has_atomic = "ptr")]
243 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
244 impl RefUnwindSafe for atomic::AtomicIsize {}
245 #[cfg(target_has_atomic = "8")]
246 #[unstable(feature = "integer_atomics", issue = "32976")]
247 impl RefUnwindSafe for atomic::AtomicI8 {}
248 #[cfg(target_has_atomic = "16")]
249 #[unstable(feature = "integer_atomics", issue = "32976")]
250 impl RefUnwindSafe for atomic::AtomicI16 {}
251 #[cfg(target_has_atomic = "32")]
252 #[unstable(feature = "integer_atomics", issue = "32976")]
253 impl RefUnwindSafe for atomic::AtomicI32 {}
254 #[cfg(target_has_atomic = "64")]
255 #[unstable(feature = "integer_atomics", issue = "32976")]
256 impl RefUnwindSafe for atomic::AtomicI64 {}
257 #[cfg(target_has_atomic = "128")]
258 #[unstable(feature = "integer_atomics", issue = "32976")]
259 impl RefUnwindSafe for atomic::AtomicI128 {}
260
261 #[cfg(target_has_atomic = "ptr")]
262 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
263 impl RefUnwindSafe for atomic::AtomicUsize {}
264 #[cfg(target_has_atomic = "8")]
265 #[unstable(feature = "integer_atomics", issue = "32976")]
266 impl RefUnwindSafe for atomic::AtomicU8 {}
267 #[cfg(target_has_atomic = "16")]
268 #[unstable(feature = "integer_atomics", issue = "32976")]
269 impl RefUnwindSafe for atomic::AtomicU16 {}
270 #[cfg(target_has_atomic = "32")]
271 #[unstable(feature = "integer_atomics", issue = "32976")]
272 impl RefUnwindSafe for atomic::AtomicU32 {}
273 #[cfg(target_has_atomic = "64")]
274 #[unstable(feature = "integer_atomics", issue = "32976")]
275 impl RefUnwindSafe for atomic::AtomicU64 {}
276 #[cfg(target_has_atomic = "128")]
277 #[unstable(feature = "integer_atomics", issue = "32976")]
278 impl RefUnwindSafe for atomic::AtomicU128 {}
279
280 #[cfg(target_has_atomic = "8")]
281 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
282 impl RefUnwindSafe for atomic::AtomicBool {}
283
284 #[cfg(target_has_atomic = "ptr")]
285 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
286 impl<T> RefUnwindSafe for atomic::AtomicPtr<T> {}
287
288 #[stable(feature = "catch_unwind", since = "1.9.0")]
289 impl<T> Deref for AssertUnwindSafe<T> {
290     type Target = T;
291
292     fn deref(&self) -> &T {
293         &self.0
294     }
295 }
296
297 #[stable(feature = "catch_unwind", since = "1.9.0")]
298 impl<T> DerefMut for AssertUnwindSafe<T> {
299     fn deref_mut(&mut self) -> &mut T {
300         &mut self.0
301     }
302 }
303
304 #[stable(feature = "catch_unwind", since = "1.9.0")]
305 impl<R, F: FnOnce() -> R> FnOnce<()> for AssertUnwindSafe<F> {
306     type Output = R;
307
308     extern "rust-call" fn call_once(self, _args: ()) -> R {
309         (self.0)()
310     }
311 }
312
313 #[stable(feature = "std_debug", since = "1.16.0")]
314 impl<T: fmt::Debug> fmt::Debug for AssertUnwindSafe<T> {
315     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
316         f.debug_tuple("AssertUnwindSafe")
317             .field(&self.0)
318             .finish()
319     }
320 }
321
322 #[unstable(feature = "futures_api", issue = "50547")]
323 impl<F: Future> Future for AssertUnwindSafe<F> {
324     type Output = F::Output;
325
326     fn poll(self: Pin<&mut Self>, waker: &Waker) -> Poll<Self::Output> {
327         let pinned_field = unsafe { Pin::map_unchecked_mut(self, |x| &mut x.0) };
328         F::poll(pinned_field, waker)
329     }
330 }
331
332 /// Invokes a closure, capturing the cause of an unwinding panic if one occurs.
333 ///
334 /// This function will return `Ok` with the closure's result if the closure
335 /// does not panic, and will return `Err(cause)` if the closure panics. The
336 /// `cause` returned is the object with which panic was originally invoked.
337 ///
338 /// It is currently undefined behavior to unwind from Rust code into foreign
339 /// code, so this function is particularly useful when Rust is called from
340 /// another language (normally C). This can run arbitrary Rust code, capturing a
341 /// panic and allowing a graceful handling of the error.
342 ///
343 /// It is **not** recommended to use this function for a general try/catch
344 /// mechanism. The [`Result`] type is more appropriate to use for functions that
345 /// can fail on a regular basis. Additionally, this function is not guaranteed
346 /// to catch all panics, see the "Notes" section below.
347 ///
348 /// [`Result`]: ../result/enum.Result.html
349 ///
350 /// The closure provided is required to adhere to the [`UnwindSafe`] trait to ensure
351 /// that all captured variables are safe to cross this boundary. The purpose of
352 /// this bound is to encode the concept of [exception safety][rfc] in the type
353 /// system. Most usage of this function should not need to worry about this
354 /// bound as programs are naturally unwind safe without `unsafe` code. If it
355 /// becomes a problem the [`AssertUnwindSafe`] wrapper struct can be used to quickly
356 /// assert that the usage here is indeed unwind safe.
357 ///
358 /// [`AssertUnwindSafe`]: ./struct.AssertUnwindSafe.html
359 /// [`UnwindSafe`]: ./trait.UnwindSafe.html
360 ///
361 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
362 ///
363 /// # Notes
364 ///
365 /// Note that this function **may not catch all panics** in Rust. A panic in
366 /// Rust is not always implemented via unwinding, but can be implemented by
367 /// aborting the process as well. This function *only* catches unwinding panics,
368 /// not those that abort the process.
369 ///
370 /// # Examples
371 ///
372 /// ```
373 /// use std::panic;
374 ///
375 /// let result = panic::catch_unwind(|| {
376 ///     println!("hello!");
377 /// });
378 /// assert!(result.is_ok());
379 ///
380 /// let result = panic::catch_unwind(|| {
381 ///     panic!("oh no!");
382 /// });
383 /// assert!(result.is_err());
384 /// ```
385 #[stable(feature = "catch_unwind", since = "1.9.0")]
386 pub fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R> {
387     unsafe {
388         panicking::r#try(f)
389     }
390 }
391
392 /// Triggers a panic without invoking the panic hook.
393 ///
394 /// This is designed to be used in conjunction with [`catch_unwind`] to, for
395 /// example, carry a panic across a layer of C code.
396 ///
397 /// [`catch_unwind`]: ./fn.catch_unwind.html
398 ///
399 /// # Notes
400 ///
401 /// Note that panics in Rust are not always implemented via unwinding, but they
402 /// may be implemented by aborting the process. If this function is called when
403 /// panics are implemented this way then this function will abort the process,
404 /// not trigger an unwind.
405 ///
406 /// # Examples
407 ///
408 /// ```should_panic
409 /// use std::panic;
410 ///
411 /// let result = panic::catch_unwind(|| {
412 ///     panic!("oh no!");
413 /// });
414 ///
415 /// if let Err(err) = result {
416 ///     panic::resume_unwind(err);
417 /// }
418 /// ```
419 #[stable(feature = "resume_unwind", since = "1.9.0")]
420 pub fn resume_unwind(payload: Box<dyn Any + Send>) -> ! {
421     panicking::update_count_then_panic(payload)
422 }