]> git.proxmox.com Git - rustc.git/blob - src/libstd/panic.rs
New upstream version 1.17.0+dfsg1
[rustc.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 cell::UnsafeCell;
17 use fmt;
18 use ops::{Deref, DerefMut};
19 use panicking;
20 use ptr::{Unique, Shared};
21 use rc::Rc;
22 use sync::{Arc, Mutex, RwLock, atomic};
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 #[unstable(feature = "unique", issue = "27730")]
201 impl<T: UnwindSafe + ?Sized> UnwindSafe for Unique<T> {}
202 #[unstable(feature = "shared", issue = "27730")]
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 #[cfg(target_has_atomic = "ptr")]
236 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
237 impl RefUnwindSafe for atomic::AtomicIsize {}
238 #[cfg(target_has_atomic = "8")]
239 #[unstable(feature = "integer_atomics", issue = "32976")]
240 impl RefUnwindSafe for atomic::AtomicI8 {}
241 #[cfg(target_has_atomic = "16")]
242 #[unstable(feature = "integer_atomics", issue = "32976")]
243 impl RefUnwindSafe for atomic::AtomicI16 {}
244 #[cfg(target_has_atomic = "32")]
245 #[unstable(feature = "integer_atomics", issue = "32976")]
246 impl RefUnwindSafe for atomic::AtomicI32 {}
247 #[cfg(target_has_atomic = "64")]
248 #[unstable(feature = "integer_atomics", issue = "32976")]
249 impl RefUnwindSafe for atomic::AtomicI64 {}
250
251 #[cfg(target_has_atomic = "ptr")]
252 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
253 impl RefUnwindSafe for atomic::AtomicUsize {}
254 #[cfg(target_has_atomic = "8")]
255 #[unstable(feature = "integer_atomics", issue = "32976")]
256 impl RefUnwindSafe for atomic::AtomicU8 {}
257 #[cfg(target_has_atomic = "16")]
258 #[unstable(feature = "integer_atomics", issue = "32976")]
259 impl RefUnwindSafe for atomic::AtomicU16 {}
260 #[cfg(target_has_atomic = "32")]
261 #[unstable(feature = "integer_atomics", issue = "32976")]
262 impl RefUnwindSafe for atomic::AtomicU32 {}
263 #[cfg(target_has_atomic = "64")]
264 #[unstable(feature = "integer_atomics", issue = "32976")]
265 impl RefUnwindSafe for atomic::AtomicU64 {}
266
267 #[cfg(target_has_atomic = "8")]
268 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
269 impl RefUnwindSafe for atomic::AtomicBool {}
270
271 #[cfg(target_has_atomic = "ptr")]
272 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
273 impl<T> RefUnwindSafe for atomic::AtomicPtr<T> {}
274
275 #[stable(feature = "catch_unwind", since = "1.9.0")]
276 impl<T> Deref for AssertUnwindSafe<T> {
277 type Target = T;
278
279 fn deref(&self) -> &T {
280 &self.0
281 }
282 }
283
284 #[stable(feature = "catch_unwind", since = "1.9.0")]
285 impl<T> DerefMut for AssertUnwindSafe<T> {
286 fn deref_mut(&mut self) -> &mut T {
287 &mut self.0
288 }
289 }
290
291 #[stable(feature = "catch_unwind", since = "1.9.0")]
292 impl<R, F: FnOnce() -> R> FnOnce<()> for AssertUnwindSafe<F> {
293 type Output = R;
294
295 extern "rust-call" fn call_once(self, _args: ()) -> R {
296 (self.0)()
297 }
298 }
299
300 #[stable(feature = "std_debug", since = "1.16.0")]
301 impl<T: fmt::Debug> fmt::Debug for AssertUnwindSafe<T> {
302 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
303 f.debug_tuple("AssertUnwindSafe")
304 .field(&self.0)
305 .finish()
306 }
307 }
308
309 /// Invokes a closure, capturing the cause of an unwinding panic if one occurs.
310 ///
311 /// This function will return `Ok` with the closure's result if the closure
312 /// does not panic, and will return `Err(cause)` if the closure panics. The
313 /// `cause` returned is the object with which panic was originally invoked.
314 ///
315 /// It is currently undefined behavior to unwind from Rust code into foreign
316 /// code, so this function is particularly useful when Rust is called from
317 /// another language (normally C). This can run arbitrary Rust code, capturing a
318 /// panic and allowing a graceful handling of the error.
319 ///
320 /// It is **not** recommended to use this function for a general try/catch
321 /// mechanism. The `Result` type is more appropriate to use for functions that
322 /// can fail on a regular basis. Additionally, this function is not guaranteed
323 /// to catch all panics, see the "Notes" section below.
324 ///
325 /// The closure provided is required to adhere to the `UnwindSafe` trait to ensure
326 /// that all captured variables are safe to cross this boundary. The purpose of
327 /// this bound is to encode the concept of [exception safety][rfc] in the type
328 /// system. Most usage of this function should not need to worry about this
329 /// bound as programs are naturally unwind safe without `unsafe` code. If it
330 /// becomes a problem the associated `AssertUnwindSafe` wrapper type in this
331 /// module can be used to quickly assert that the usage here is indeed unwind
332 /// safe.
333 ///
334 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
335 ///
336 /// # Notes
337 ///
338 /// Note that this function **may not catch all panics** in Rust. A panic in
339 /// Rust is not always implemented via unwinding, but can be implemented by
340 /// aborting the process as well. This function *only* catches unwinding panics,
341 /// not those that abort the process.
342 ///
343 /// # Examples
344 ///
345 /// ```
346 /// use std::panic;
347 ///
348 /// let result = panic::catch_unwind(|| {
349 /// println!("hello!");
350 /// });
351 /// assert!(result.is_ok());
352 ///
353 /// let result = panic::catch_unwind(|| {
354 /// panic!("oh no!");
355 /// });
356 /// assert!(result.is_err());
357 /// ```
358 #[stable(feature = "catch_unwind", since = "1.9.0")]
359 pub fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R> {
360 unsafe {
361 panicking::try(f)
362 }
363 }
364
365 /// Triggers a panic without invoking the panic hook.
366 ///
367 /// This is designed to be used in conjunction with `catch_unwind` to, for
368 /// example, carry a panic across a layer of C code.
369 ///
370 /// # Notes
371 ///
372 /// Note that panics in Rust are not always implemented via unwinding, but they
373 /// may be implemented by aborting the process. If this function is called when
374 /// panics are implemented this way then this function will abort the process,
375 /// not trigger an unwind.
376 ///
377 /// # Examples
378 ///
379 /// ```should_panic
380 /// use std::panic;
381 ///
382 /// let result = panic::catch_unwind(|| {
383 /// panic!("oh no!");
384 /// });
385 ///
386 /// if let Err(err) = result {
387 /// panic::resume_unwind(err);
388 /// }
389 /// ```
390 #[stable(feature = "resume_unwind", since = "1.9.0")]
391 pub fn resume_unwind(payload: Box<Any + Send>) -> ! {
392 panicking::update_count_then_panic(payload)
393 }