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")]
18 use ops::{Deref, DerefMut};
20 use ptr::{Unique, NonNull};
22 use sync::{Arc, Mutex, RwLock, atomic};
25 #[stable(feature = "panic_hooks", since = "1.10.0")]
26 pub use panicking::{take_hook, set_hook, PanicInfo, Location};
28 /// A marker trait which represents "panic safe" types in Rust.
30 /// This trait is implemented by default for many types and behaves similarly in
31 /// terms of inference of implementation to the `Send` and `Sync` traits. The
32 /// purpose of this trait is to encode what types are safe to cross a `catch_unwind`
33 /// boundary with no fear of unwind safety.
35 /// ## What is unwind safety?
37 /// In Rust a function can "return" early if it either panics or calls a
38 /// function which transitively panics. This sort of control flow is not always
39 /// anticipated, and has the possibility of causing subtle bugs through a
40 /// combination of two critical components:
42 /// 1. A data structure is in a temporarily invalid state when the thread
44 /// 2. This broken invariant is then later observed.
46 /// Typically in Rust, it is difficult to perform step (2) because catching a
47 /// panic involves either spawning a thread (which in turns makes it difficult
48 /// to later witness broken invariants) or using the `catch_unwind` function in this
49 /// module. Additionally, even if an invariant is witnessed, it typically isn't a
50 /// problem in Rust because there are no uninitialized values (like in C or C++).
52 /// It is possible, however, for **logical** invariants to be broken in Rust,
53 /// which can end up causing behavioral bugs. Another key aspect of unwind safety
54 /// in Rust is that, in the absence of `unsafe` code, a panic cannot lead to
57 /// That was a bit of a whirlwind tour of unwind safety, but for more information
58 /// about unwind safety and how it applies to Rust, see an [associated RFC][rfc].
60 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
62 /// ## What is `UnwindSafe`?
64 /// Now that we've got an idea of what unwind safety is in Rust, it's also
65 /// important to understand what this trait represents. As mentioned above, one
66 /// way to witness broken invariants is through the `catch_unwind` function in this
67 /// module as it allows catching a panic and then re-using the environment of
70 /// Simply put, a type `T` implements `UnwindSafe` if it cannot easily allow
71 /// witnessing a broken invariant through the use of `catch_unwind` (catching a
72 /// panic). This trait is a marker trait, so it is automatically implemented for
73 /// many types, and it is also structurally composed (e.g. a struct is unwind
74 /// safe if all of its components are unwind safe).
76 /// Note, however, that this is not an unsafe trait, so there is not a succinct
77 /// contract that this trait is providing. Instead it is intended as more of a
78 /// "speed bump" to alert users of `catch_unwind` that broken invariants may be
79 /// witnessed and may need to be accounted for.
81 /// ## Who implements `UnwindSafe`?
83 /// Types such as `&mut T` and `&RefCell<T>` are examples which are **not**
84 /// unwind safe. The general idea is that any mutable state which can be shared
85 /// across `catch_unwind` is not unwind safe by default. This is because it is very
86 /// easy to witness a broken invariant outside of `catch_unwind` as the data is
87 /// simply accessed as usual.
89 /// Types like `&Mutex<T>`, however, are unwind safe because they implement
90 /// poisoning by default. They still allow witnessing a broken invariant, but
91 /// they already provide their own "speed bumps" to do so.
93 /// ## When should `UnwindSafe` be used?
95 /// Is not intended that most types or functions need to worry about this trait.
96 /// It is only used as a bound on the `catch_unwind` function and as mentioned above,
97 /// the lack of `unsafe` means it is mostly an advisory. The `AssertUnwindSafe`
98 /// wrapper struct in this module can be used to force this trait to be
99 /// implemented for any closed over variables passed to the `catch_unwind` function
100 /// (more on this below).
101 #[stable(feature = "catch_unwind", since = "1.9.0")]
102 #[rustc_on_unimplemented = "the type {Self} may not be safely transferred \
103 across an unwind boundary"]
104 pub auto trait UnwindSafe {}
106 /// A marker trait representing types where a shared reference is considered
109 /// This trait is namely not implemented by `UnsafeCell`, the root of all
110 /// interior mutability.
112 /// This is a "helper marker trait" used to provide impl blocks for the
113 /// `UnwindSafe` trait, for more information see that documentation.
114 #[stable(feature = "catch_unwind", since = "1.9.0")]
115 #[rustc_on_unimplemented = "the type {Self} may contain interior mutability \
116 and a reference may not be safely transferrable \
117 across a catch_unwind boundary"]
118 pub auto trait RefUnwindSafe {}
120 /// A simple wrapper around a type to assert that it is unwind safe.
122 /// When using `catch_unwind` it may be the case that some of the closed over
123 /// variables are not unwind safe. For example if `&mut T` is captured the
124 /// compiler will generate a warning indicating that it is not unwind safe. It
125 /// may not be the case, however, that this is actually a problem due to the
126 /// specific usage of `catch_unwind` if unwind safety is specifically taken into
127 /// account. This wrapper struct is useful for a quick and lightweight
128 /// annotation that a variable is indeed unwind safe.
132 /// One way to use `AssertUnwindSafe` is to assert that the entire closure
133 /// itself is unwind safe, bypassing all checks for all variables:
136 /// use std::panic::{self, AssertUnwindSafe};
138 /// let mut variable = 4;
140 /// // This code will not compile because the closure captures `&mut variable`
141 /// // which is not considered unwind safe by default.
143 /// // panic::catch_unwind(|| {
144 /// // variable += 3;
147 /// // This, however, will compile due to the `AssertUnwindSafe` wrapper
148 /// let result = panic::catch_unwind(AssertUnwindSafe(|| {
154 /// Wrapping the entire closure amounts to a blanket assertion that all captured
155 /// variables are unwind safe. This has the downside that if new captures are
156 /// added in the future, they will also be considered unwind safe. Therefore,
157 /// you may prefer to just wrap individual captures, as shown below. This is
158 /// more annotation, but it ensures that if a new capture is added which is not
159 /// unwind safe, you will get a compilation error at that time, which will
160 /// allow you to consider whether that new capture in fact represent a bug or
164 /// use std::panic::{self, AssertUnwindSafe};
166 /// let mut variable = 4;
167 /// let other_capture = 3;
170 /// let mut wrapper = AssertUnwindSafe(&mut variable);
171 /// panic::catch_unwind(move || {
172 /// **wrapper += other_capture;
177 #[stable(feature = "catch_unwind", since = "1.9.0")]
178 pub struct AssertUnwindSafe<T>(
179 #[stable(feature = "catch_unwind", since = "1.9.0")]
183 // Implementations of the `UnwindSafe` trait:
185 // * By default everything is unwind safe
186 // * pointers T contains mutability of some form are not unwind safe
187 // * Unique, an owning pointer, lifts an implementation
188 // * Types like Mutex/RwLock which are explicilty poisoned are unwind safe
189 // * Our custom AssertUnwindSafe wrapper is indeed unwind safe
191 #[stable(feature = "catch_unwind", since = "1.9.0")]
192 impl<'a, T: ?Sized> !UnwindSafe for &'a mut T {}
193 #[stable(feature = "catch_unwind", since = "1.9.0")]
194 impl<'a, T: RefUnwindSafe + ?Sized> UnwindSafe for &'a T {}
195 #[stable(feature = "catch_unwind", since = "1.9.0")]
196 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *const T {}
197 #[stable(feature = "catch_unwind", since = "1.9.0")]
198 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *mut T {}
199 #[unstable(feature = "ptr_internals", issue = "0")]
200 impl<T: UnwindSafe + ?Sized> UnwindSafe for Unique<T> {}
201 #[stable(feature = "nonnull", since = "1.25.0")]
202 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for NonNull<T> {}
203 #[stable(feature = "catch_unwind", since = "1.9.0")]
204 impl<T: ?Sized> UnwindSafe for Mutex<T> {}
205 #[stable(feature = "catch_unwind", since = "1.9.0")]
206 impl<T: ?Sized> UnwindSafe for RwLock<T> {}
207 #[stable(feature = "catch_unwind", since = "1.9.0")]
208 impl<T> UnwindSafe for AssertUnwindSafe<T> {}
210 // not covered via the Shared impl above b/c the inner contents use
211 // Cell/AtomicUsize, but the usage here is unwind safe so we can lift the
212 // impl up one level to Arc/Rc itself
213 #[stable(feature = "catch_unwind", since = "1.9.0")]
214 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Rc<T> {}
215 #[stable(feature = "catch_unwind", since = "1.9.0")]
216 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Arc<T> {}
218 // Pretty simple implementations for the `RefUnwindSafe` marker trait,
219 // basically just saying that `UnsafeCell` is the
220 // only thing which doesn't implement it (which then transitively applies to
222 #[stable(feature = "catch_unwind", since = "1.9.0")]
223 impl<T: ?Sized> !RefUnwindSafe for UnsafeCell<T> {}
224 #[stable(feature = "catch_unwind", since = "1.9.0")]
225 impl<T> RefUnwindSafe for AssertUnwindSafe<T> {}
227 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
228 impl<T: ?Sized> RefUnwindSafe for Mutex<T> {}
229 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
230 impl<T: ?Sized> RefUnwindSafe for RwLock<T> {}
232 #[cfg(target_has_atomic = "ptr")]
233 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
234 impl RefUnwindSafe for atomic::AtomicIsize {}
235 #[cfg(target_has_atomic = "8")]
236 #[unstable(feature = "integer_atomics", issue = "32976")]
237 impl RefUnwindSafe for atomic::AtomicI8 {}
238 #[cfg(target_has_atomic = "16")]
239 #[unstable(feature = "integer_atomics", issue = "32976")]
240 impl RefUnwindSafe for atomic::AtomicI16 {}
241 #[cfg(target_has_atomic = "32")]
242 #[unstable(feature = "integer_atomics", issue = "32976")]
243 impl RefUnwindSafe for atomic::AtomicI32 {}
244 #[cfg(target_has_atomic = "64")]
245 #[unstable(feature = "integer_atomics", issue = "32976")]
246 impl RefUnwindSafe for atomic::AtomicI64 {}
248 #[cfg(target_has_atomic = "ptr")]
249 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
250 impl RefUnwindSafe for atomic::AtomicUsize {}
251 #[cfg(target_has_atomic = "8")]
252 #[unstable(feature = "integer_atomics", issue = "32976")]
253 impl RefUnwindSafe for atomic::AtomicU8 {}
254 #[cfg(target_has_atomic = "16")]
255 #[unstable(feature = "integer_atomics", issue = "32976")]
256 impl RefUnwindSafe for atomic::AtomicU16 {}
257 #[cfg(target_has_atomic = "32")]
258 #[unstable(feature = "integer_atomics", issue = "32976")]
259 impl RefUnwindSafe for atomic::AtomicU32 {}
260 #[cfg(target_has_atomic = "64")]
261 #[unstable(feature = "integer_atomics", issue = "32976")]
262 impl RefUnwindSafe for atomic::AtomicU64 {}
264 #[cfg(target_has_atomic = "8")]
265 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
266 impl RefUnwindSafe for atomic::AtomicBool {}
268 #[cfg(target_has_atomic = "ptr")]
269 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
270 impl<T> RefUnwindSafe for atomic::AtomicPtr<T> {}
272 #[stable(feature = "catch_unwind", since = "1.9.0")]
273 impl<T> Deref for AssertUnwindSafe<T> {
276 fn deref(&self) -> &T {
281 #[stable(feature = "catch_unwind", since = "1.9.0")]
282 impl<T> DerefMut for AssertUnwindSafe<T> {
283 fn deref_mut(&mut self) -> &mut T {
288 #[stable(feature = "catch_unwind", since = "1.9.0")]
289 impl<R, F: FnOnce() -> R> FnOnce<()> for AssertUnwindSafe<F> {
292 extern "rust-call" fn call_once(self, _args: ()) -> R {
297 #[stable(feature = "std_debug", since = "1.16.0")]
298 impl<T: fmt::Debug> fmt::Debug for AssertUnwindSafe<T> {
299 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
300 f.debug_tuple("AssertUnwindSafe")
306 /// Invokes a closure, capturing the cause of an unwinding panic if one occurs.
308 /// This function will return `Ok` with the closure's result if the closure
309 /// does not panic, and will return `Err(cause)` if the closure panics. The
310 /// `cause` returned is the object with which panic was originally invoked.
312 /// It is currently undefined behavior to unwind from Rust code into foreign
313 /// code, so this function is particularly useful when Rust is called from
314 /// another language (normally C). This can run arbitrary Rust code, capturing a
315 /// panic and allowing a graceful handling of the error.
317 /// It is **not** recommended to use this function for a general try/catch
318 /// mechanism. The `Result` type is more appropriate to use for functions that
319 /// can fail on a regular basis. Additionally, this function is not guaranteed
320 /// to catch all panics, see the "Notes" section below.
322 /// The closure provided is required to adhere to the `UnwindSafe` trait to ensure
323 /// that all captured variables are safe to cross this boundary. The purpose of
324 /// this bound is to encode the concept of [exception safety][rfc] in the type
325 /// system. Most usage of this function should not need to worry about this
326 /// bound as programs are naturally unwind safe without `unsafe` code. If it
327 /// becomes a problem the associated `AssertUnwindSafe` wrapper type in this
328 /// module can be used to quickly assert that the usage here is indeed unwind
331 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
335 /// Note that this function **may not catch all panics** in Rust. A panic in
336 /// Rust is not always implemented via unwinding, but can be implemented by
337 /// aborting the process as well. This function *only* catches unwinding panics,
338 /// not those that abort the process.
345 /// let result = panic::catch_unwind(|| {
346 /// println!("hello!");
348 /// assert!(result.is_ok());
350 /// let result = panic::catch_unwind(|| {
351 /// panic!("oh no!");
353 /// assert!(result.is_err());
355 #[stable(feature = "catch_unwind", since = "1.9.0")]
356 pub fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R> {
362 /// Triggers a panic without invoking the panic hook.
364 /// This is designed to be used in conjunction with `catch_unwind` to, for
365 /// example, carry a panic across a layer of C code.
369 /// Note that panics in Rust are not always implemented via unwinding, but they
370 /// may be implemented by aborting the process. If this function is called when
371 /// panics are implemented this way then this function will abort the process,
372 /// not trigger an unwind.
379 /// let result = panic::catch_unwind(|| {
380 /// panic!("oh no!");
383 /// if let Err(err) = result {
384 /// panic::resume_unwind(err);
387 #[stable(feature = "resume_unwind", since = "1.9.0")]
388 pub fn resume_unwind(payload: Box<Any + Send>) -> ! {
389 panicking::update_count_then_panic(payload)