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 #![unstable(feature = "std_panic", reason = "awaiting feedback",
17 use ops::{Deref, DerefMut};
18 use ptr::{Unique, Shared};
20 use sync::{Arc, Mutex, RwLock};
21 use sys_common::unwind;
24 pub use panicking::{take_handler, set_handler, PanicInfo, Location};
26 /// A marker trait which represents "panic safe" types in Rust.
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 `recover`
31 /// boundary with no fear of panic safety.
33 /// ## What is panic safety?
35 /// In Rust a function can "return" early if it either panics or calls a
36 /// function which transitively panics. This sort of control flow is not always
37 /// anticipated, and has the possibility of causing subtle bugs through a
38 /// combination of two cricial components:
40 /// 1. A data structure is in a temporarily invalid state when the thread
42 /// 2. This broken invariant is then later observed.
44 /// Typically in Rust it is difficult to perform step (2) because catching a
45 /// panic involves either spawning a thread (which in turns makes it difficult
46 /// to later witness broken invariants) or using the `recover` function in this
47 /// module. Additionally, even if an invariant is witness, it typically isn't a
48 /// problem in Rust because there's no uninitialized values (like in C or C++).
50 /// It is possible, however, for **logical** invariants to be broken in Rust,
51 /// which can end up causing behavioral bugs. Another key aspect of panic safety
52 /// in Rust is that in the absence of `unsafe` code, a panic cannot lead to
55 /// That was a bit of a whirlwind tour of panic safety, but for more information
56 /// about panic safety and how it applies to Rust, see an [associated RFC][rfc].
58 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
60 /// ## What is `RecoverSafe`?
62 /// Now that we've got an idea of what panic safety is in Rust, it's also
63 /// important to understand that this trait represents. As mentioned above, one
64 /// way to witness broken invariants is through the `recover` function in this
65 /// module as it allows catching a panic and then re-using the environment of
68 /// Simply but, a type `T` implements `RecoverSafe` if it cannot easily allow
69 /// witnessing a broken invariant through the use of `recover` (catching a
70 /// panic). This trait is a marker trait, so it is automatically implemented for
71 /// many types, and it is also structurally composed (e.g. a struct is recover
72 /// safe if all of its components are recover safe).
74 /// Note, however, that this is not an unsafe trait, so there is not a succinct
75 /// contract that this trait is providing. Instead it is intended as more of a
76 /// "speed bump" to alert users of `recover` that broken invariants may be
77 /// witnessed and may need to be accounted for.
79 /// ## Who implements `RecoverSafe`?
81 /// Types such as `&mut T` and `&RefCell<T>` are examples which are **not**
82 /// recover safe. The general idea is that any mutable state which can be shared
83 /// across `recover` is not recover safe by default. This is because it is very
84 /// easy to witness a broken invariant outside of `recover` as the data is
85 /// simply accesed as usual.
87 /// Types like `&Mutex<T>`, however, are recover safe because they implement
88 /// poisoning by default. They still allow witnessing a broken invariant, but
89 /// they already provide their own "speed bumps" to do so.
91 /// ## When should `RecoverSafe` be used?
93 /// Is not intended that most types or functions need to worry about this trait.
94 /// It is only used as a bound on the `recover` function and as mentioned above,
95 /// the lack of `unsafe` means it is mostly an advisory. The `AssertRecoverSafe`
96 /// wrapper struct in this module can be used to force this trait to be
97 /// implemented for any closed over variables passed to the `recover` function
98 /// (more on this below).
99 #[unstable(feature = "recover", reason = "awaiting feedback", issue = "27719")]
100 #[rustc_on_unimplemented = "the type {Self} may not be safely transferred \
101 across a recover boundary"]
102 pub trait RecoverSafe {}
104 /// A marker trait representing types where a shared reference is considered
107 /// This trait is namely not implemented by `UnsafeCell`, the root of all
108 /// interior mutability.
110 /// This is a "helper marker trait" used to provide impl blocks for the
111 /// `RecoverSafe` trait, for more information see that documentation.
112 #[unstable(feature = "recover", reason = "awaiting feedback", issue = "27719")]
113 #[rustc_on_unimplemented = "the type {Self} contains interior mutability \
114 and a reference may not be safely transferrable \
115 across a recover boundary"]
116 pub trait RefRecoverSafe {}
118 /// A simple wrapper around a type to assert that it is panic safe.
120 /// When using `recover` it may be the case that some of the closed over
121 /// variables are not panic safe. For example if `&mut T` is captured the
122 /// compiler will generate a warning indicating that it is not panic safe. It
123 /// may not be the case, however, that this is actually a problem due to the
124 /// specific usage of `recover` if panic safety is specifically taken into
125 /// account. This wrapper struct is useful for a quick and lightweight
126 /// annotation that a variable is indeed panic safe.
131 /// #![feature(recover, std_panic)]
133 /// use std::panic::{self, AssertRecoverSafe};
135 /// let mut variable = 4;
137 /// // This code will not compile becuause the closure captures `&mut variable`
138 /// // which is not considered panic safe by default.
140 /// // panic::recover(|| {
141 /// // variable += 3;
144 /// // This, however, will compile due to the `AssertRecoverSafe` wrapper
146 /// let mut wrapper = AssertRecoverSafe::new(&mut variable);
147 /// panic::recover(move || {
153 #[unstable(feature = "recover", reason = "awaiting feedback", issue = "27719")]
154 pub struct AssertRecoverSafe<T>(T);
156 // Implementations of the `RecoverSafe` trait:
158 // * By default everything is recover safe
159 // * pointers T contains mutability of some form are not recover safe
160 // * Unique, an owning pointer, lifts an implementation
161 // * Types like Mutex/RwLock which are explicilty poisoned are recover safe
162 // * Our custom AssertRecoverSafe wrapper is indeed recover safe
163 impl RecoverSafe for .. {}
164 impl<'a, T: ?Sized> !RecoverSafe for &'a mut T {}
165 impl<'a, T: RefRecoverSafe + ?Sized> RecoverSafe for &'a T {}
166 impl<T: RefRecoverSafe + ?Sized> RecoverSafe for *const T {}
167 impl<T: RefRecoverSafe + ?Sized> RecoverSafe for *mut T {}
168 impl<T: RecoverSafe> RecoverSafe for Unique<T> {}
169 impl<T: RefRecoverSafe + ?Sized> RecoverSafe for Shared<T> {}
170 impl<T: ?Sized> RecoverSafe for Mutex<T> {}
171 impl<T: ?Sized> RecoverSafe for RwLock<T> {}
172 impl<T> RecoverSafe for AssertRecoverSafe<T> {}
174 // not covered via the Shared impl above b/c the inner contents use
175 // Cell/AtomicUsize, but the usage here is recover safe so we can lift the
176 // impl up one level to Arc/Rc itself
177 impl<T: RefRecoverSafe + ?Sized> RecoverSafe for Rc<T> {}
178 impl<T: RefRecoverSafe + ?Sized> RecoverSafe for Arc<T> {}
180 // Pretty simple implementations for the `RefRecoverSafe` marker trait,
181 // basically just saying that this is a marker trait and `UnsafeCell` is the
182 // only thing which doesn't implement it (which then transitively applies to
184 impl RefRecoverSafe for .. {}
185 impl<T: ?Sized> !RefRecoverSafe for UnsafeCell<T> {}
186 impl<T> RefRecoverSafe for AssertRecoverSafe<T> {}
188 impl<T> AssertRecoverSafe<T> {
189 /// Creates a new `AssertRecoverSafe` wrapper around the provided type.
190 #[unstable(feature = "recover", reason = "awaiting feedback", issue = "27719")]
191 pub fn new(t: T) -> AssertRecoverSafe<T> {
196 impl<T> Deref for AssertRecoverSafe<T> {
199 fn deref(&self) -> &T {
204 impl<T> DerefMut for AssertRecoverSafe<T> {
205 fn deref_mut(&mut self) -> &mut T {
210 /// Invokes a closure, capturing the cause of panic if one occurs.
212 /// This function will return `Ok` with the closure's result if the closure
213 /// does not panic, and will return `Err(cause)` if the closure panics. The
214 /// `cause` returned is the object with which panic was originally invoked.
216 /// It is currently undefined behavior to unwind from Rust code into foreign
217 /// code, so this function is particularly useful when Rust is called from
218 /// another language (normally C). This can run arbitrary Rust code, capturing a
219 /// panic and allowing a graceful handling of the error.
221 /// It is **not** recommended to use this function for a general try/catch
222 /// mechanism. The `Result` type is more appropriate to use for functions that
223 /// can fail on a regular basis.
225 /// The closure provided is required to adhere to the `RecoverSafe` to ensure
226 /// that all captured variables are safe to cross this recover boundary. The
227 /// purpose of this bound is to encode the concept of [exception safety][rfc] in
228 /// the type system. Most usage of this function should not need to worry about
229 /// this bound as programs are naturally panic safe without `unsafe` code. If it
230 /// becomes a problem the associated `AssertRecoverSafe` wrapper type in this
231 /// module can be used to quickly assert that the usage here is indeed exception
234 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
239 /// #![feature(recover, std_panic)]
243 /// let result = panic::recover(|| {
244 /// println!("hello!");
246 /// assert!(result.is_ok());
248 /// let result = panic::recover(|| {
249 /// panic!("oh no!");
251 /// assert!(result.is_err());
253 #[unstable(feature = "recover", reason = "awaiting feedback", issue = "27719")]
254 pub fn recover<F: FnOnce() -> R + RecoverSafe, R>(f: F) -> Result<R> {
255 let mut result = None;
257 let result = &mut result;
258 try!(unwind::try(move || *result = Some(f())))