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