]> git.lizzy.rs Git - rust.git/blob - src/libstd/panic.rs
Don't use ExpnKind::descr to get the name of a bang macro.
[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::ops::{Deref, DerefMut};
11 use crate::panicking;
12 use crate::pin::Pin;
13 use crate::ptr::{NonNull, Unique};
14 use crate::rc::Rc;
15 use crate::sync::atomic;
16 use crate::sync::{Arc, Mutex, RwLock};
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::{set_hook, take_hook};
22
23 #[stable(feature = "panic_hooks", since = "1.10.0")]
24 pub use core::panic::{Location, PanicInfo};
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>(#[stable(feature = "catch_unwind", since = "1.9.0")] pub T);
191
192 // Implementations of the `UnwindSafe` trait:
193 //
194 // * By default everything is unwind safe
195 // * pointers T contains mutability of some form are not unwind safe
196 // * Unique, an owning pointer, lifts an implementation
197 // * Types like Mutex/RwLock which are explicitly poisoned are unwind safe
198 // * Our custom AssertUnwindSafe wrapper is indeed unwind safe
199
200 #[stable(feature = "catch_unwind", since = "1.9.0")]
201 impl<T: ?Sized> !UnwindSafe for &mut T {}
202 #[stable(feature = "catch_unwind", since = "1.9.0")]
203 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for &T {}
204 #[stable(feature = "catch_unwind", since = "1.9.0")]
205 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *const T {}
206 #[stable(feature = "catch_unwind", since = "1.9.0")]
207 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *mut T {}
208 #[unstable(feature = "ptr_internals", issue = "none")]
209 impl<T: UnwindSafe + ?Sized> UnwindSafe for Unique<T> {}
210 #[stable(feature = "nonnull", since = "1.25.0")]
211 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for NonNull<T> {}
212 #[stable(feature = "catch_unwind", since = "1.9.0")]
213 impl<T: ?Sized> UnwindSafe for Mutex<T> {}
214 #[stable(feature = "catch_unwind", since = "1.9.0")]
215 impl<T: ?Sized> UnwindSafe for RwLock<T> {}
216 #[stable(feature = "catch_unwind", since = "1.9.0")]
217 impl<T> UnwindSafe for AssertUnwindSafe<T> {}
218
219 // not covered via the Shared impl above b/c the inner contents use
220 // Cell/AtomicUsize, but the usage here is unwind safe so we can lift the
221 // impl up one level to Arc/Rc itself
222 #[stable(feature = "catch_unwind", since = "1.9.0")]
223 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Rc<T> {}
224 #[stable(feature = "catch_unwind", since = "1.9.0")]
225 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Arc<T> {}
226
227 // Pretty simple implementations for the `RefUnwindSafe` marker trait,
228 // basically just saying that `UnsafeCell` is the
229 // only thing which doesn't implement it (which then transitively applies to
230 // everything else).
231 #[stable(feature = "catch_unwind", since = "1.9.0")]
232 impl<T: ?Sized> !RefUnwindSafe for UnsafeCell<T> {}
233 #[stable(feature = "catch_unwind", since = "1.9.0")]
234 impl<T> RefUnwindSafe for AssertUnwindSafe<T> {}
235
236 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
237 impl<T: ?Sized> RefUnwindSafe for Mutex<T> {}
238 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
239 impl<T: ?Sized> RefUnwindSafe for RwLock<T> {}
240
241 #[cfg(target_has_atomic_load_store = "ptr")]
242 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
243 impl RefUnwindSafe for atomic::AtomicIsize {}
244 #[cfg(target_has_atomic_load_store = "8")]
245 #[unstable(feature = "integer_atomics", issue = "32976")]
246 impl RefUnwindSafe for atomic::AtomicI8 {}
247 #[cfg(target_has_atomic_load_store = "16")]
248 #[unstable(feature = "integer_atomics", issue = "32976")]
249 impl RefUnwindSafe for atomic::AtomicI16 {}
250 #[cfg(target_has_atomic_load_store = "32")]
251 #[unstable(feature = "integer_atomics", issue = "32976")]
252 impl RefUnwindSafe for atomic::AtomicI32 {}
253 #[cfg(target_has_atomic_load_store = "64")]
254 #[unstable(feature = "integer_atomics", issue = "32976")]
255 impl RefUnwindSafe for atomic::AtomicI64 {}
256 #[cfg(target_has_atomic_load_store = "128")]
257 #[unstable(feature = "integer_atomics", issue = "32976")]
258 impl RefUnwindSafe for atomic::AtomicI128 {}
259
260 #[cfg(target_has_atomic_load_store = "ptr")]
261 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
262 impl RefUnwindSafe for atomic::AtomicUsize {}
263 #[cfg(target_has_atomic_load_store = "8")]
264 #[unstable(feature = "integer_atomics", issue = "32976")]
265 impl RefUnwindSafe for atomic::AtomicU8 {}
266 #[cfg(target_has_atomic_load_store = "16")]
267 #[unstable(feature = "integer_atomics", issue = "32976")]
268 impl RefUnwindSafe for atomic::AtomicU16 {}
269 #[cfg(target_has_atomic_load_store = "32")]
270 #[unstable(feature = "integer_atomics", issue = "32976")]
271 impl RefUnwindSafe for atomic::AtomicU32 {}
272 #[cfg(target_has_atomic_load_store = "64")]
273 #[unstable(feature = "integer_atomics", issue = "32976")]
274 impl RefUnwindSafe for atomic::AtomicU64 {}
275 #[cfg(target_has_atomic_load_store = "128")]
276 #[unstable(feature = "integer_atomics", issue = "32976")]
277 impl RefUnwindSafe for atomic::AtomicU128 {}
278
279 #[cfg(target_has_atomic_load_store = "8")]
280 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
281 impl RefUnwindSafe for atomic::AtomicBool {}
282
283 #[cfg(target_has_atomic_load_store = "ptr")]
284 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
285 impl<T> RefUnwindSafe for atomic::AtomicPtr<T> {}
286
287 // https://github.com/rust-lang/rust/issues/62301
288 #[stable(feature = "hashbrown", since = "1.36.0")]
289 impl<K, V, S> UnwindSafe for collections::HashMap<K, V, S>
290 where
291     K: UnwindSafe,
292     V: UnwindSafe,
293     S: UnwindSafe,
294 {
295 }
296
297 #[stable(feature = "catch_unwind", since = "1.9.0")]
298 impl<T> Deref for AssertUnwindSafe<T> {
299     type Target = T;
300
301     fn deref(&self) -> &T {
302         &self.0
303     }
304 }
305
306 #[stable(feature = "catch_unwind", since = "1.9.0")]
307 impl<T> DerefMut for AssertUnwindSafe<T> {
308     fn deref_mut(&mut self) -> &mut T {
309         &mut self.0
310     }
311 }
312
313 #[stable(feature = "catch_unwind", since = "1.9.0")]
314 impl<R, F: FnOnce() -> R> FnOnce<()> for AssertUnwindSafe<F> {
315     type Output = R;
316
317     extern "rust-call" fn call_once(self, _args: ()) -> R {
318         (self.0)()
319     }
320 }
321
322 #[stable(feature = "std_debug", since = "1.16.0")]
323 impl<T: fmt::Debug> fmt::Debug for AssertUnwindSafe<T> {
324     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
325         f.debug_tuple("AssertUnwindSafe").field(&self.0).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 { panicking::r#try(f) }
395 }
396
397 /// Triggers a panic without invoking the panic hook.
398 ///
399 /// This is designed to be used in conjunction with [`catch_unwind`] to, for
400 /// example, carry a panic across a layer of C code.
401 ///
402 /// [`catch_unwind`]: ./fn.catch_unwind.html
403 ///
404 /// # Notes
405 ///
406 /// Note that panics in Rust are not always implemented via unwinding, but they
407 /// may be implemented by aborting the process. If this function is called when
408 /// panics are implemented this way then this function will abort the process,
409 /// not trigger an unwind.
410 ///
411 /// # Examples
412 ///
413 /// ```should_panic
414 /// use std::panic;
415 ///
416 /// let result = panic::catch_unwind(|| {
417 ///     panic!("oh no!");
418 /// });
419 ///
420 /// if let Err(err) = result {
421 ///     panic::resume_unwind(err);
422 /// }
423 /// ```
424 #[stable(feature = "resume_unwind", since = "1.9.0")]
425 pub fn resume_unwind(payload: Box<dyn Any + Send>) -> ! {
426     panicking::rust_panic_without_hook(payload)
427 }