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