]> git.lizzy.rs Git - rust.git/blob - src/libstd/panic.rs
Rollup merge of #31264 - est31:block_coment_parent, r=alexcrichton
[rust.git] / src / libstd / panic.rs
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.
4 //
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.
10
11 //! Panic support in the standard library
12
13 #![unstable(feature = "std_panic", reason = "awaiting feedback",
14             issue = "27719")]
15
16 use any::Any;
17 use boxed::Box;
18 use cell::UnsafeCell;
19 use ops::{Deref, DerefMut};
20 use ptr::{Unique, Shared};
21 use rc::Rc;
22 use sync::{Arc, Mutex, RwLock};
23 use sys_common::unwind;
24 use thread::Result;
25
26 pub use panicking::{take_handler, set_handler, PanicInfo, Location};
27
28 /// A marker trait which represents "panic safe" types in Rust.
29 ///
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 `recover`
33 /// boundary with no fear of panic safety.
34 ///
35 /// ## What is panic safety?
36 ///
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 cricial components:
41 ///
42 /// 1. A data structure is in a temporarily invalid state when the thread
43 ///    panics.
44 /// 2. This broken invariant is then later observed.
45 ///
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 `recover` function in this
49 /// module. Additionally, even if an invariant is witnessed, it typically isn't a
50 /// problem in Rust because there's no uninitialized values (like in C or C++).
51 ///
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 panic safety
54 /// in Rust is that, in the absence of `unsafe` code, a panic cannot lead to
55 /// memory unsafety.
56 ///
57 /// That was a bit of a whirlwind tour of panic safety, but for more information
58 /// about panic safety and how it applies to Rust, see an [associated RFC][rfc].
59 ///
60 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
61 ///
62 /// ## What is `RecoverSafe`?
63 ///
64 /// Now that we've got an idea of what panic 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 `recover` function in this
67 /// module as it allows catching a panic and then re-using the environment of
68 /// the closure.
69 ///
70 /// Simply put, a type `T` implements `RecoverSafe` if it cannot easily allow
71 /// witnessing a broken invariant through the use of `recover` (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 recover
74 /// safe if all of its components are recover safe).
75 ///
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 `recover` that broken invariants may be
79 /// witnessed and may need to be accounted for.
80 ///
81 /// ## Who implements `RecoverSafe`?
82 ///
83 /// Types such as `&mut T` and `&RefCell<T>` are examples which are **not**
84 /// recover safe. The general idea is that any mutable state which can be shared
85 /// across `recover` is not recover safe by default. This is because it is very
86 /// easy to witness a broken invariant outside of `recover` as the data is
87 /// simply accesed as usual.
88 ///
89 /// Types like `&Mutex<T>`, however, are recover 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.
92 ///
93 /// ## When should `RecoverSafe` be used?
94 ///
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 `recover` function and as mentioned above,
97 /// the lack of `unsafe` means it is mostly an advisory. The `AssertRecoverSafe`
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 `recover` function
100 /// (more on this below).
101 #[unstable(feature = "recover", reason = "awaiting feedback", issue = "27719")]
102 #[rustc_on_unimplemented = "the type {Self} may not be safely transferred \
103                             across a recover boundary"]
104 pub trait RecoverSafe {}
105
106 /// A marker trait representing types where a shared reference is considered
107 /// recover safe.
108 ///
109 /// This trait is namely not implemented by `UnsafeCell`, the root of all
110 /// interior mutability.
111 ///
112 /// This is a "helper marker trait" used to provide impl blocks for the
113 /// `RecoverSafe` trait, for more information see that documentation.
114 #[unstable(feature = "recover", reason = "awaiting feedback", issue = "27719")]
115 #[rustc_on_unimplemented = "the type {Self} contains interior mutability \
116                             and a reference may not be safely transferrable \
117                             across a recover boundary"]
118 pub trait RefRecoverSafe {}
119
120 /// A simple wrapper around a type to assert that it is panic safe.
121 ///
122 /// When using `recover` it may be the case that some of the closed over
123 /// variables are not panic safe. For example if `&mut T` is captured the
124 /// compiler will generate a warning indicating that it is not panic safe. It
125 /// may not be the case, however, that this is actually a problem due to the
126 /// specific usage of `recover` if panic safety is specifically taken into
127 /// account. This wrapper struct is useful for a quick and lightweight
128 /// annotation that a variable is indeed panic safe.
129 ///
130 /// # Examples
131 ///
132 /// ```
133 /// #![feature(recover, std_panic)]
134 ///
135 /// use std::panic::{self, AssertRecoverSafe};
136 ///
137 /// let mut variable = 4;
138 ///
139 /// // This code will not compile because the closure captures `&mut variable`
140 /// // which is not considered panic safe by default.
141 ///
142 /// // panic::recover(|| {
143 /// //     variable += 3;
144 /// // });
145 ///
146 /// // This, however, will compile due to the `AssertRecoverSafe` wrapper
147 /// let result = {
148 ///     let mut wrapper = AssertRecoverSafe::new(&mut variable);
149 ///     panic::recover(move || {
150 ///         **wrapper += 3;
151 ///     })
152 /// };
153 /// // ...
154 /// ```
155 #[unstable(feature = "recover", reason = "awaiting feedback", issue = "27719")]
156 pub struct AssertRecoverSafe<T>(T);
157
158 // Implementations of the `RecoverSafe` trait:
159 //
160 // * By default everything is recover safe
161 // * pointers T contains mutability of some form are not recover safe
162 // * Unique, an owning pointer, lifts an implementation
163 // * Types like Mutex/RwLock which are explicilty poisoned are recover safe
164 // * Our custom AssertRecoverSafe wrapper is indeed recover safe
165 impl RecoverSafe for .. {}
166 impl<'a, T: ?Sized> !RecoverSafe for &'a mut T {}
167 impl<'a, T: RefRecoverSafe + ?Sized> RecoverSafe for &'a T {}
168 impl<T: RefRecoverSafe + ?Sized> RecoverSafe for *const T {}
169 impl<T: RefRecoverSafe + ?Sized> RecoverSafe for *mut T {}
170 impl<T: RecoverSafe> RecoverSafe for Unique<T> {}
171 impl<T: RefRecoverSafe + ?Sized> RecoverSafe for Shared<T> {}
172 impl<T: ?Sized> RecoverSafe for Mutex<T> {}
173 impl<T: ?Sized> RecoverSafe for RwLock<T> {}
174 impl<T> RecoverSafe for AssertRecoverSafe<T> {}
175
176 // not covered via the Shared impl above b/c the inner contents use
177 // Cell/AtomicUsize, but the usage here is recover safe so we can lift the
178 // impl up one level to Arc/Rc itself
179 impl<T: RefRecoverSafe + ?Sized> RecoverSafe for Rc<T> {}
180 impl<T: RefRecoverSafe + ?Sized> RecoverSafe for Arc<T> {}
181
182 // Pretty simple implementations for the `RefRecoverSafe` marker trait,
183 // basically just saying that this is a marker trait and `UnsafeCell` is the
184 // only thing which doesn't implement it (which then transitively applies to
185 // everything else).
186 impl RefRecoverSafe for .. {}
187 impl<T: ?Sized> !RefRecoverSafe for UnsafeCell<T> {}
188 impl<T> RefRecoverSafe for AssertRecoverSafe<T> {}
189
190 impl<T> AssertRecoverSafe<T> {
191     /// Creates a new `AssertRecoverSafe` wrapper around the provided type.
192     #[unstable(feature = "recover", reason = "awaiting feedback", issue = "27719")]
193     pub fn new(t: T) -> AssertRecoverSafe<T> {
194         AssertRecoverSafe(t)
195     }
196 }
197
198 impl<T> Deref for AssertRecoverSafe<T> {
199     type Target = T;
200
201     fn deref(&self) -> &T {
202         &self.0
203     }
204 }
205
206 impl<T> DerefMut for AssertRecoverSafe<T> {
207     fn deref_mut(&mut self) -> &mut T {
208         &mut self.0
209     }
210 }
211
212 /// Invokes a closure, capturing the cause of panic if one occurs.
213 ///
214 /// This function will return `Ok` with the closure's result if the closure
215 /// does not panic, and will return `Err(cause)` if the closure panics. The
216 /// `cause` returned is the object with which panic was originally invoked.
217 ///
218 /// It is currently undefined behavior to unwind from Rust code into foreign
219 /// code, so this function is particularly useful when Rust is called from
220 /// another language (normally C). This can run arbitrary Rust code, capturing a
221 /// panic and allowing a graceful handling of the error.
222 ///
223 /// It is **not** recommended to use this function for a general try/catch
224 /// mechanism. The `Result` type is more appropriate to use for functions that
225 /// can fail on a regular basis.
226 ///
227 /// The closure provided is required to adhere to the `RecoverSafe` to ensure
228 /// that all captured variables are safe to cross this recover boundary. The
229 /// purpose of this bound is to encode the concept of [exception safety][rfc] in
230 /// the type system. Most usage of this function should not need to worry about
231 /// this bound as programs are naturally panic safe without `unsafe` code. If it
232 /// becomes a problem the associated `AssertRecoverSafe` wrapper type in this
233 /// module can be used to quickly assert that the usage here is indeed exception
234 /// safe.
235 ///
236 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
237 ///
238 /// # Examples
239 ///
240 /// ```
241 /// #![feature(recover, std_panic)]
242 ///
243 /// use std::panic;
244 ///
245 /// let result = panic::recover(|| {
246 ///     println!("hello!");
247 /// });
248 /// assert!(result.is_ok());
249 ///
250 /// let result = panic::recover(|| {
251 ///     panic!("oh no!");
252 /// });
253 /// assert!(result.is_err());
254 /// ```
255 #[unstable(feature = "recover", reason = "awaiting feedback", issue = "27719")]
256 pub fn recover<F: FnOnce() -> R + RecoverSafe, R>(f: F) -> Result<R> {
257     let mut result = None;
258     unsafe {
259         let result = &mut result;
260         try!(unwind::try(move || *result = Some(f())))
261     }
262     Ok(result.unwrap())
263 }
264
265 /// Triggers a panic without invoking the panic handler.
266 ///
267 /// This is designed to be used in conjunction with `recover` to, for example,
268 /// carry a panic across a layer of C code.
269 ///
270 /// # Examples
271 ///
272 /// ```should_panic
273 /// #![feature(std_panic, recover, panic_propagate)]
274 ///
275 /// use std::panic;
276 ///
277 /// let result = panic::recover(|| {
278 ///     panic!("oh no!");
279 /// });
280 ///
281 /// if let Err(err) = result {
282 ///     panic::propagate(err);
283 /// }
284 /// ```
285 #[unstable(feature = "panic_propagate", reason = "awaiting feedback", issue = "30752")]
286 pub fn propagate(payload: Box<Any + Send>) -> ! {
287     unwind::rust_panic(payload)
288 }