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