]> git.lizzy.rs Git - rust.git/blob - src/libstd/panic.rs
Changed issue number to 36105
[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 #![stable(feature = "std_panic", since = "1.9.0")]
14
15 use any::Any;
16 use boxed::Box;
17 use cell::UnsafeCell;
18 use ops::{Deref, DerefMut};
19 use panicking;
20 use ptr::{Unique, Shared};
21 use rc::Rc;
22 use sync::{Arc, Mutex, RwLock};
23 use thread::Result;
24
25 #[stable(feature = "panic_hooks", since = "1.10.0")]
26 pub use panicking::{take_hook, set_hook, 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 `catch_unwind`
33 /// boundary with no fear of unwind safety.
34 ///
35 /// ## What is unwind 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 `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++).
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 unwind 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 unwind safety, but for more information
58 /// about unwind 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 `UnwindSafe`?
63 ///
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
68 /// the closure.
69 ///
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).
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 `catch_unwind` that broken invariants may be
79 /// witnessed and may need to be accounted for.
80 ///
81 /// ## Who implements `UnwindSafe`?
82 ///
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.
88 ///
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.
92 ///
93 /// ## When should `UnwindSafe` 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 `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 trait UnwindSafe {}
105
106 /// A marker trait representing types where a shared reference is considered
107 /// unwind 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 /// `UnwindSafe` trait, for more information see that documentation.
114 #[stable(feature = "catch_unwind", since = "1.9.0")]
115 #[rustc_on_unimplemented = "the type {Self} contains interior mutability \
116                             and a reference may not be safely transferrable \
117                             across a catch_unwind boundary"]
118 pub trait RefUnwindSafe {}
119
120 /// A simple wrapper around a type to assert that it is unwind safe.
121 ///
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.
129 ///
130 /// # Examples
131 ///
132 /// One way to use `AssertUnwindSafe` is to assert that the entire closure
133 /// itself is unwind safe, bypassing all checks for all variables:
134 ///
135 /// ```
136 /// use std::panic::{self, AssertUnwindSafe};
137 ///
138 /// let mut variable = 4;
139 ///
140 /// // This code will not compile because the closure captures `&mut variable`
141 /// // which is not considered unwind safe by default.
142 ///
143 /// // panic::catch_unwind(|| {
144 /// //     variable += 3;
145 /// // });
146 ///
147 /// // This, however, will compile due to the `AssertUnwindSafe` wrapper
148 /// let result = panic::catch_unwind(AssertUnwindSafe(|| {
149 ///     variable += 3;
150 /// }));
151 /// // ...
152 /// ```
153 ///
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
161 /// not.
162 ///
163 /// ```
164 /// use std::panic::{self, AssertUnwindSafe};
165 ///
166 /// let mut variable = 4;
167 /// let other_capture = 3;
168 ///
169 /// let result = {
170 ///     let mut wrapper = AssertUnwindSafe(&mut variable);
171 ///     panic::catch_unwind(move || {
172 ///         **wrapper += other_capture;
173 ///     })
174 /// };
175 /// // ...
176 /// ```
177 #[stable(feature = "catch_unwind", since = "1.9.0")]
178 pub struct AssertUnwindSafe<T>(
179     #[stable(feature = "catch_unwind", since = "1.9.0")]
180     pub T
181 );
182
183 // Implementations of the `UnwindSafe` trait:
184 //
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
190 #[stable(feature = "catch_unwind", since = "1.9.0")]
191 impl UnwindSafe for .. {}
192 #[stable(feature = "catch_unwind", since = "1.9.0")]
193 impl<'a, T: ?Sized> !UnwindSafe for &'a mut T {}
194 #[stable(feature = "catch_unwind", since = "1.9.0")]
195 impl<'a, T: RefUnwindSafe + ?Sized> UnwindSafe for &'a T {}
196 #[stable(feature = "catch_unwind", since = "1.9.0")]
197 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *const T {}
198 #[stable(feature = "catch_unwind", since = "1.9.0")]
199 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *mut T {}
200 #[stable(feature = "catch_unwind", since = "1.9.0")]
201 impl<T: UnwindSafe> UnwindSafe for Unique<T> {}
202 #[stable(feature = "catch_unwind", since = "1.9.0")]
203 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Shared<T> {}
204 #[stable(feature = "catch_unwind", since = "1.9.0")]
205 impl<T: ?Sized> UnwindSafe for Mutex<T> {}
206 #[stable(feature = "catch_unwind", since = "1.9.0")]
207 impl<T: ?Sized> UnwindSafe for RwLock<T> {}
208 #[stable(feature = "catch_unwind", since = "1.9.0")]
209 impl<T> UnwindSafe for AssertUnwindSafe<T> {}
210
211 // not covered via the Shared impl above b/c the inner contents use
212 // Cell/AtomicUsize, but the usage here is unwind safe so we can lift the
213 // impl up one level to Arc/Rc itself
214 #[stable(feature = "catch_unwind", since = "1.9.0")]
215 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Rc<T> {}
216 #[stable(feature = "catch_unwind", since = "1.9.0")]
217 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Arc<T> {}
218
219 // Pretty simple implementations for the `RefUnwindSafe` marker trait,
220 // basically just saying that this is a marker trait and `UnsafeCell` is the
221 // only thing which doesn't implement it (which then transitively applies to
222 // everything else).
223 #[stable(feature = "catch_unwind", since = "1.9.0")]
224 impl RefUnwindSafe for .. {}
225 #[stable(feature = "catch_unwind", since = "1.9.0")]
226 impl<T: ?Sized> !RefUnwindSafe for UnsafeCell<T> {}
227 #[stable(feature = "catch_unwind", since = "1.9.0")]
228 impl<T> RefUnwindSafe for AssertUnwindSafe<T> {}
229
230 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
231 impl<T: ?Sized> RefUnwindSafe for Mutex<T> {}
232 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
233 impl<T: ?Sized> RefUnwindSafe for RwLock<T> {}
234
235 #[stable(feature = "catch_unwind", since = "1.9.0")]
236 impl<T> Deref for AssertUnwindSafe<T> {
237     type Target = T;
238
239     fn deref(&self) -> &T {
240         &self.0
241     }
242 }
243
244 #[stable(feature = "catch_unwind", since = "1.9.0")]
245 impl<T> DerefMut for AssertUnwindSafe<T> {
246     fn deref_mut(&mut self) -> &mut T {
247         &mut self.0
248     }
249 }
250
251 #[stable(feature = "catch_unwind", since = "1.9.0")]
252 impl<R, F: FnOnce() -> R> FnOnce<()> for AssertUnwindSafe<F> {
253     type Output = R;
254
255     extern "rust-call" fn call_once(self, _args: ()) -> R {
256         (self.0)()
257     }
258 }
259
260 /// Invokes a closure, capturing the cause of an unwinding panic if one occurs.
261 ///
262 /// This function will return `Ok` with the closure's result if the closure
263 /// does not panic, and will return `Err(cause)` if the closure panics. The
264 /// `cause` returned is the object with which panic was originally invoked.
265 ///
266 /// It is currently undefined behavior to unwind from Rust code into foreign
267 /// code, so this function is particularly useful when Rust is called from
268 /// another language (normally C). This can run arbitrary Rust code, capturing a
269 /// panic and allowing a graceful handling of the error.
270 ///
271 /// It is **not** recommended to use this function for a general try/catch
272 /// mechanism. The `Result` type is more appropriate to use for functions that
273 /// can fail on a regular basis. Additionally, this function is not guaranteed
274 /// to catch all panics, see the "Notes" section below.
275 ///
276 /// The closure provided is required to adhere to the `UnwindSafe` trait to ensure
277 /// that all captured variables are safe to cross this boundary. The purpose of
278 /// this bound is to encode the concept of [exception safety][rfc] in the type
279 /// system. Most usage of this function should not need to worry about this
280 /// bound as programs are naturally unwind safe without `unsafe` code. If it
281 /// becomes a problem the associated `AssertUnwindSafe` wrapper type in this
282 /// module can be used to quickly assert that the usage here is indeed unwind
283 /// safe.
284 ///
285 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
286 ///
287 /// # Notes
288 ///
289 /// Note that this function **may not catch all panics** in Rust. A panic in
290 /// Rust is not always implemented via unwinding, but can be implemented by
291 /// aborting the process as well. This function *only* catches unwinding panics,
292 /// not those that abort the process.
293 ///
294 /// # Examples
295 ///
296 /// ```
297 /// use std::panic;
298 ///
299 /// let result = panic::catch_unwind(|| {
300 ///     println!("hello!");
301 /// });
302 /// assert!(result.is_ok());
303 ///
304 /// let result = panic::catch_unwind(|| {
305 ///     panic!("oh no!");
306 /// });
307 /// assert!(result.is_err());
308 /// ```
309 #[stable(feature = "catch_unwind", since = "1.9.0")]
310 pub fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R> {
311     unsafe {
312         panicking::try(f)
313     }
314 }
315
316 /// Triggers a panic without invoking the panic hook.
317 ///
318 /// This is designed to be used in conjunction with `catch_unwind` to, for
319 /// example, carry a panic across a layer of C code.
320 ///
321 /// # Notes
322 ///
323 /// Note that panics in Rust are not always implemented via unwinding, but they
324 /// may be implemented by aborting the process. If this function is called when
325 /// panics are implemented this way then this function will abort the process,
326 /// not trigger an unwind.
327 ///
328 /// # Examples
329 ///
330 /// ```should_panic
331 /// use std::panic;
332 ///
333 /// let result = panic::catch_unwind(|| {
334 ///     panic!("oh no!");
335 /// });
336 ///
337 /// if let Err(err) = result {
338 ///     panic::resume_unwind(err);
339 /// }
340 /// ```
341 #[stable(feature = "resume_unwind", since = "1.9.0")]
342 pub fn resume_unwind(payload: Box<Any + Send>) -> ! {
343     panicking::update_count_then_panic(payload)
344 }