1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Panic support in the standard library.
13 #![stable(feature = "std_panic", since = "1.9.0")]
20 use ops::{Deref, DerefMut};
22 use ptr::{Unique, NonNull};
24 use sync::{Arc, Mutex, RwLock, atomic};
25 use task::{self, Poll};
28 #[stable(feature = "panic_hooks", since = "1.10.0")]
29 pub use panicking::{take_hook, set_hook};
31 #[stable(feature = "panic_hooks", since = "1.10.0")]
32 pub use core::panic::{PanicInfo, Location};
34 /// A marker trait which represents "panic safe" types in Rust.
36 /// This trait is implemented by default for many types and behaves similarly in
37 /// terms of inference of implementation to the [`Send`] and [`Sync`] traits. The
38 /// purpose of this trait is to encode what types are safe to cross a [`catch_unwind`]
39 /// boundary with no fear of unwind safety.
41 /// [`Send`]: ../marker/trait.Send.html
42 /// [`Sync`]: ../marker/trait.Sync.html
43 /// [`catch_unwind`]: ./fn.catch_unwind.html
45 /// ## What is unwind safety?
47 /// In Rust a function can "return" early if it either panics or calls a
48 /// function which transitively panics. This sort of control flow is not always
49 /// anticipated, and has the possibility of causing subtle bugs through a
50 /// combination of two critical components:
52 /// 1. A data structure is in a temporarily invalid state when the thread
54 /// 2. This broken invariant is then later observed.
56 /// Typically in Rust, it is difficult to perform step (2) because catching a
57 /// panic involves either spawning a thread (which in turns makes it difficult
58 /// to later witness broken invariants) or using the `catch_unwind` function in this
59 /// module. Additionally, even if an invariant is witnessed, it typically isn't a
60 /// problem in Rust because there are no uninitialized values (like in C or C++).
62 /// It is possible, however, for **logical** invariants to be broken in Rust,
63 /// which can end up causing behavioral bugs. Another key aspect of unwind safety
64 /// in Rust is that, in the absence of `unsafe` code, a panic cannot lead to
67 /// That was a bit of a whirlwind tour of unwind safety, but for more information
68 /// about unwind safety and how it applies to Rust, see an [associated RFC][rfc].
70 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
72 /// ## What is `UnwindSafe`?
74 /// Now that we've got an idea of what unwind safety is in Rust, it's also
75 /// important to understand what this trait represents. As mentioned above, one
76 /// way to witness broken invariants is through the `catch_unwind` function in this
77 /// module as it allows catching a panic and then re-using the environment of
80 /// Simply put, a type `T` implements `UnwindSafe` if it cannot easily allow
81 /// witnessing a broken invariant through the use of `catch_unwind` (catching a
82 /// panic). This trait is a marker trait, so it is automatically implemented for
83 /// many types, and it is also structurally composed (e.g. a struct is unwind
84 /// safe if all of its components are unwind safe).
86 /// Note, however, that this is not an unsafe trait, so there is not a succinct
87 /// contract that this trait is providing. Instead it is intended as more of a
88 /// "speed bump" to alert users of `catch_unwind` that broken invariants may be
89 /// witnessed and may need to be accounted for.
91 /// ## Who implements `UnwindSafe`?
93 /// Types such as `&mut T` and `&RefCell<T>` are examples which are **not**
94 /// unwind safe. The general idea is that any mutable state which can be shared
95 /// across `catch_unwind` is not unwind safe by default. This is because it is very
96 /// easy to witness a broken invariant outside of `catch_unwind` as the data is
97 /// simply accessed as usual.
99 /// Types like `&Mutex<T>`, however, are unwind safe because they implement
100 /// poisoning by default. They still allow witnessing a broken invariant, but
101 /// they already provide their own "speed bumps" to do so.
103 /// ## When should `UnwindSafe` be used?
105 /// It is not intended that most types or functions need to worry about this trait.
106 /// It is only used as a bound on the `catch_unwind` function and as mentioned
107 /// above, the lack of `unsafe` means it is mostly an advisory. The
108 /// [`AssertUnwindSafe`] wrapper struct can be used to force this trait to be
109 /// implemented for any closed over variables passed to `catch_unwind`.
111 /// [`AssertUnwindSafe`]: ./struct.AssertUnwindSafe.html
112 #[stable(feature = "catch_unwind", since = "1.9.0")]
113 #[rustc_on_unimplemented(
114 message="the type `{Self}` may not be safely transferred across an unwind boundary",
115 label="`{Self}` may not be safely transferred across an unwind boundary",
117 pub auto trait UnwindSafe {}
119 /// A marker trait representing types where a shared reference is considered
122 /// This trait is namely not implemented by [`UnsafeCell`], the root of all
123 /// interior mutability.
125 /// This is a "helper marker trait" used to provide impl blocks for the
126 /// [`UnwindSafe`] trait, for more information see that documentation.
128 /// [`UnsafeCell`]: ../cell/struct.UnsafeCell.html
129 /// [`UnwindSafe`]: ./trait.UnwindSafe.html
130 #[stable(feature = "catch_unwind", since = "1.9.0")]
131 #[rustc_on_unimplemented(
132 message="the type `{Self}` may contain interior mutability and a reference may not be safely \
133 transferrable across a catch_unwind boundary",
134 label="`{Self}` may contain interior mutability and a reference may not be safely \
135 transferrable across a catch_unwind boundary",
137 pub auto trait RefUnwindSafe {}
139 /// A simple wrapper around a type to assert that it is unwind safe.
141 /// When using [`catch_unwind`] it may be the case that some of the closed over
142 /// variables are not unwind safe. For example if `&mut T` is captured the
143 /// compiler will generate a warning indicating that it is not unwind safe. It
144 /// may not be the case, however, that this is actually a problem due to the
145 /// specific usage of [`catch_unwind`] if unwind safety is specifically taken into
146 /// account. This wrapper struct is useful for a quick and lightweight
147 /// annotation that a variable is indeed unwind safe.
149 /// [`catch_unwind`]: ./fn.catch_unwind.html
152 /// One way to use `AssertUnwindSafe` is to assert that the entire closure
153 /// itself is unwind safe, bypassing all checks for all variables:
156 /// use std::panic::{self, AssertUnwindSafe};
158 /// let mut variable = 4;
160 /// // This code will not compile because the closure captures `&mut variable`
161 /// // which is not considered unwind safe by default.
163 /// // panic::catch_unwind(|| {
164 /// // variable += 3;
167 /// // This, however, will compile due to the `AssertUnwindSafe` wrapper
168 /// let result = panic::catch_unwind(AssertUnwindSafe(|| {
174 /// Wrapping the entire closure amounts to a blanket assertion that all captured
175 /// variables are unwind safe. This has the downside that if new captures are
176 /// added in the future, they will also be considered unwind safe. Therefore,
177 /// you may prefer to just wrap individual captures, as shown below. This is
178 /// more annotation, but it ensures that if a new capture is added which is not
179 /// unwind safe, you will get a compilation error at that time, which will
180 /// allow you to consider whether that new capture in fact represent a bug or
184 /// use std::panic::{self, AssertUnwindSafe};
186 /// let mut variable = 4;
187 /// let other_capture = 3;
190 /// let mut wrapper = AssertUnwindSafe(&mut variable);
191 /// panic::catch_unwind(move || {
192 /// **wrapper += other_capture;
197 #[stable(feature = "catch_unwind", since = "1.9.0")]
198 pub struct AssertUnwindSafe<T>(
199 #[stable(feature = "catch_unwind", since = "1.9.0")]
203 // Implementations of the `UnwindSafe` trait:
205 // * By default everything is unwind safe
206 // * pointers T contains mutability of some form are not unwind safe
207 // * Unique, an owning pointer, lifts an implementation
208 // * Types like Mutex/RwLock which are explicitly poisoned are unwind safe
209 // * Our custom AssertUnwindSafe wrapper is indeed unwind safe
211 #[stable(feature = "catch_unwind", since = "1.9.0")]
212 impl<'a, T: ?Sized> !UnwindSafe for &'a mut T {}
213 #[stable(feature = "catch_unwind", since = "1.9.0")]
214 impl<'a, T: RefUnwindSafe + ?Sized> UnwindSafe for &'a T {}
215 #[stable(feature = "catch_unwind", since = "1.9.0")]
216 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *const T {}
217 #[stable(feature = "catch_unwind", since = "1.9.0")]
218 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *mut T {}
219 #[unstable(feature = "ptr_internals", issue = "0")]
220 impl<T: UnwindSafe + ?Sized> UnwindSafe for Unique<T> {}
221 #[stable(feature = "nonnull", since = "1.25.0")]
222 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for NonNull<T> {}
223 #[stable(feature = "catch_unwind", since = "1.9.0")]
224 impl<T: ?Sized> UnwindSafe for Mutex<T> {}
225 #[stable(feature = "catch_unwind", since = "1.9.0")]
226 impl<T: ?Sized> UnwindSafe for RwLock<T> {}
227 #[stable(feature = "catch_unwind", since = "1.9.0")]
228 impl<T> UnwindSafe for AssertUnwindSafe<T> {}
230 // not covered via the Shared impl above b/c the inner contents use
231 // Cell/AtomicUsize, but the usage here is unwind safe so we can lift the
232 // impl up one level to Arc/Rc itself
233 #[stable(feature = "catch_unwind", since = "1.9.0")]
234 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Rc<T> {}
235 #[stable(feature = "catch_unwind", since = "1.9.0")]
236 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Arc<T> {}
238 // Pretty simple implementations for the `RefUnwindSafe` marker trait,
239 // basically just saying that `UnsafeCell` is the
240 // only thing which doesn't implement it (which then transitively applies to
242 #[stable(feature = "catch_unwind", since = "1.9.0")]
243 impl<T: ?Sized> !RefUnwindSafe for UnsafeCell<T> {}
244 #[stable(feature = "catch_unwind", since = "1.9.0")]
245 impl<T> RefUnwindSafe for AssertUnwindSafe<T> {}
247 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
248 impl<T: ?Sized> RefUnwindSafe for Mutex<T> {}
249 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
250 impl<T: ?Sized> RefUnwindSafe for RwLock<T> {}
252 #[cfg(target_has_atomic = "ptr")]
253 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
254 impl RefUnwindSafe for atomic::AtomicIsize {}
255 #[cfg(target_has_atomic = "8")]
256 #[unstable(feature = "integer_atomics", issue = "32976")]
257 impl RefUnwindSafe for atomic::AtomicI8 {}
258 #[cfg(target_has_atomic = "16")]
259 #[unstable(feature = "integer_atomics", issue = "32976")]
260 impl RefUnwindSafe for atomic::AtomicI16 {}
261 #[cfg(target_has_atomic = "32")]
262 #[unstable(feature = "integer_atomics", issue = "32976")]
263 impl RefUnwindSafe for atomic::AtomicI32 {}
264 #[cfg(target_has_atomic = "64")]
265 #[unstable(feature = "integer_atomics", issue = "32976")]
266 impl RefUnwindSafe for atomic::AtomicI64 {}
268 #[cfg(target_has_atomic = "ptr")]
269 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
270 impl RefUnwindSafe for atomic::AtomicUsize {}
271 #[cfg(target_has_atomic = "8")]
272 #[unstable(feature = "integer_atomics", issue = "32976")]
273 impl RefUnwindSafe for atomic::AtomicU8 {}
274 #[cfg(target_has_atomic = "16")]
275 #[unstable(feature = "integer_atomics", issue = "32976")]
276 impl RefUnwindSafe for atomic::AtomicU16 {}
277 #[cfg(target_has_atomic = "32")]
278 #[unstable(feature = "integer_atomics", issue = "32976")]
279 impl RefUnwindSafe for atomic::AtomicU32 {}
280 #[cfg(target_has_atomic = "64")]
281 #[unstable(feature = "integer_atomics", issue = "32976")]
282 impl RefUnwindSafe for atomic::AtomicU64 {}
284 #[cfg(target_has_atomic = "8")]
285 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
286 impl RefUnwindSafe for atomic::AtomicBool {}
288 #[cfg(target_has_atomic = "ptr")]
289 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
290 impl<T> RefUnwindSafe for atomic::AtomicPtr<T> {}
292 #[stable(feature = "catch_unwind", since = "1.9.0")]
293 impl<T> Deref for AssertUnwindSafe<T> {
296 fn deref(&self) -> &T {
301 #[stable(feature = "catch_unwind", since = "1.9.0")]
302 impl<T> DerefMut for AssertUnwindSafe<T> {
303 fn deref_mut(&mut self) -> &mut T {
308 #[stable(feature = "catch_unwind", since = "1.9.0")]
309 impl<R, F: FnOnce() -> R> FnOnce<()> for AssertUnwindSafe<F> {
312 extern "rust-call" fn call_once(self, _args: ()) -> R {
317 #[stable(feature = "std_debug", since = "1.16.0")]
318 impl<T: fmt::Debug> fmt::Debug for AssertUnwindSafe<T> {
319 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
320 f.debug_tuple("AssertUnwindSafe")
326 #[unstable(feature = "futures_api", issue = "50547")]
327 impl<'a, F: Future> Future for AssertUnwindSafe<F> {
328 type Output = F::Output;
330 fn poll(self: PinMut<Self>, cx: &mut task::Context) -> Poll<Self::Output> {
331 let pinned_field = unsafe { PinMut::map_unchecked(self, |x| &mut x.0) };
332 pinned_field.poll(cx)
336 /// Invokes a closure, capturing the cause of an unwinding panic if one occurs.
338 /// This function will return `Ok` with the closure's result if the closure
339 /// does not panic, and will return `Err(cause)` if the closure panics. The
340 /// `cause` returned is the object with which panic was originally invoked.
342 /// It is currently undefined behavior to unwind from Rust code into foreign
343 /// code, so this function is particularly useful when Rust is called from
344 /// another language (normally C). This can run arbitrary Rust code, capturing a
345 /// panic and allowing a graceful handling of the error.
347 /// It is **not** recommended to use this function for a general try/catch
348 /// mechanism. The [`Result`] type is more appropriate to use for functions that
349 /// can fail on a regular basis. Additionally, this function is not guaranteed
350 /// to catch all panics, see the "Notes" section below.
352 /// [`Result`]: ../result/enum.Result.html
354 /// The closure provided is required to adhere to the [`UnwindSafe`] trait to ensure
355 /// that all captured variables are safe to cross this boundary. The purpose of
356 /// this bound is to encode the concept of [exception safety][rfc] in the type
357 /// system. Most usage of this function should not need to worry about this
358 /// bound as programs are naturally unwind safe without `unsafe` code. If it
359 /// becomes a problem the [`AssertUnwindSafe`] wrapper struct can be used to quickly
360 /// assert that the usage here is indeed unwind safe.
362 /// [`AssertUnwindSafe`]: ./struct.AssertUnwindSafe.html
363 /// [`UnwindSafe`]: ./trait.UnwindSafe.html
365 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
369 /// Note that this function **may not catch all panics** in Rust. A panic in
370 /// Rust is not always implemented via unwinding, but can be implemented by
371 /// aborting the process as well. This function *only* catches unwinding panics,
372 /// not those that abort the process.
379 /// let result = panic::catch_unwind(|| {
380 /// println!("hello!");
382 /// assert!(result.is_ok());
384 /// let result = panic::catch_unwind(|| {
385 /// panic!("oh no!");
387 /// assert!(result.is_err());
389 #[stable(feature = "catch_unwind", since = "1.9.0")]
390 pub fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R> {
396 /// Triggers a panic without invoking the panic hook.
398 /// This is designed to be used in conjunction with [`catch_unwind`] to, for
399 /// example, carry a panic across a layer of C code.
401 /// [`catch_unwind`]: ./fn.catch_unwind.html
405 /// Note that panics in Rust are not always implemented via unwinding, but they
406 /// may be implemented by aborting the process. If this function is called when
407 /// panics are implemented this way then this function will abort the process,
408 /// not trigger an unwind.
415 /// let result = panic::catch_unwind(|| {
416 /// panic!("oh no!");
419 /// if let Err(err) = result {
420 /// panic::resume_unwind(err);
423 #[stable(feature = "resume_unwind", since = "1.9.0")]
424 pub fn resume_unwind(payload: Box<dyn Any + Send>) -> ! {
425 panicking::update_count_then_panic(payload)