]> git.lizzy.rs Git - rust.git/blob - library/std/src/panic.rs
Auto merge of #78280 - bugadani:span, r=lcnr
[rust.git] / library / std / src / panic.rs
1 //! Panic support in the standard library.
2
3 #![stable(feature = "std_panic", since = "1.9.0")]
4
5 use crate::any::Any;
6 use crate::cell::UnsafeCell;
7 use crate::collections;
8 use crate::fmt;
9 use crate::future::Future;
10 use crate::ops::{Deref, DerefMut};
11 use crate::panicking;
12 use crate::pin::Pin;
13 use crate::ptr::{NonNull, Unique};
14 use crate::rc::Rc;
15 use crate::sync::atomic;
16 use crate::sync::{Arc, Mutex, RwLock};
17 use crate::task::{Context, Poll};
18 use crate::thread::Result;
19
20 #[stable(feature = "panic_hooks", since = "1.10.0")]
21 pub use crate::panicking::{set_hook, take_hook};
22
23 #[stable(feature = "panic_hooks", since = "1.10.0")]
24 pub use core::panic::{Location, PanicInfo};
25
26 /// Panic the current thread with the given message as the panic payload.
27 ///
28 /// The message can be of any (`Any + Send`) type, not just strings.
29 ///
30 /// The message is wrapped in a `Box<'static + Any + Send>`, which can be
31 /// accessed later using [`PanicInfo::payload`].
32 ///
33 /// See the [`panic!`] macro for more information about panicking.
34 #[unstable(feature = "panic_any", issue = "78500")]
35 #[inline]
36 pub fn panic_any<M: Any + Send>(msg: M) -> ! {
37     crate::panicking::begin_panic(msg);
38 }
39
40 /// A marker trait which represents "panic safe" types in Rust.
41 ///
42 /// This trait is implemented by default for many types and behaves similarly in
43 /// terms of inference of implementation to the [`Send`] and [`Sync`] traits. The
44 /// purpose of this trait is to encode what types are safe to cross a [`catch_unwind`]
45 /// boundary with no fear of unwind safety.
46 ///
47 /// ## What is unwind safety?
48 ///
49 /// In Rust a function can "return" early if it either panics or calls a
50 /// function which transitively panics. This sort of control flow is not always
51 /// anticipated, and has the possibility of causing subtle bugs through a
52 /// combination of two critical components:
53 ///
54 /// 1. A data structure is in a temporarily invalid state when the thread
55 ///    panics.
56 /// 2. This broken invariant is then later observed.
57 ///
58 /// Typically in Rust, it is difficult to perform step (2) because catching a
59 /// panic involves either spawning a thread (which in turns makes it difficult
60 /// to later witness broken invariants) or using the `catch_unwind` function in this
61 /// module. Additionally, even if an invariant is witnessed, it typically isn't a
62 /// problem in Rust because there are no uninitialized values (like in C or C++).
63 ///
64 /// It is possible, however, for **logical** invariants to be broken in Rust,
65 /// which can end up causing behavioral bugs. Another key aspect of unwind safety
66 /// in Rust is that, in the absence of `unsafe` code, a panic cannot lead to
67 /// memory unsafety.
68 ///
69 /// That was a bit of a whirlwind tour of unwind safety, but for more information
70 /// about unwind safety and how it applies to Rust, see an [associated RFC][rfc].
71 ///
72 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
73 ///
74 /// ## What is `UnwindSafe`?
75 ///
76 /// Now that we've got an idea of what unwind safety is in Rust, it's also
77 /// important to understand what this trait represents. As mentioned above, one
78 /// way to witness broken invariants is through the `catch_unwind` function in this
79 /// module as it allows catching a panic and then re-using the environment of
80 /// the closure.
81 ///
82 /// Simply put, a type `T` implements `UnwindSafe` if it cannot easily allow
83 /// witnessing a broken invariant through the use of `catch_unwind` (catching a
84 /// panic). This trait is an auto trait, so it is automatically implemented for
85 /// many types, and it is also structurally composed (e.g., a struct is unwind
86 /// safe if all of its components are unwind safe).
87 ///
88 /// Note, however, that this is not an unsafe trait, so there is not a succinct
89 /// contract that this trait is providing. Instead it is intended as more of a
90 /// "speed bump" to alert users of `catch_unwind` that broken invariants may be
91 /// witnessed and may need to be accounted for.
92 ///
93 /// ## Who implements `UnwindSafe`?
94 ///
95 /// Types such as `&mut T` and `&RefCell<T>` are examples which are **not**
96 /// unwind safe. The general idea is that any mutable state which can be shared
97 /// across `catch_unwind` is not unwind safe by default. This is because it is very
98 /// easy to witness a broken invariant outside of `catch_unwind` as the data is
99 /// simply accessed as usual.
100 ///
101 /// Types like `&Mutex<T>`, however, are unwind safe because they implement
102 /// poisoning by default. They still allow witnessing a broken invariant, but
103 /// they already provide their own "speed bumps" to do so.
104 ///
105 /// ## When should `UnwindSafe` be used?
106 ///
107 /// It is not intended that most types or functions need to worry about this trait.
108 /// It is only used as a bound on the `catch_unwind` function and as mentioned
109 /// above, the lack of `unsafe` means it is mostly an advisory. The
110 /// [`AssertUnwindSafe`] wrapper struct can be used to force this trait to be
111 /// implemented for any closed over variables passed to `catch_unwind`.
112 #[stable(feature = "catch_unwind", since = "1.9.0")]
113 #[rustc_on_unimplemented(
114     message = "the type `{Self}` may not be safely transferred across an unwind boundary",
115     label = "`{Self}` may not be safely transferred across an unwind boundary"
116 )]
117 pub auto trait UnwindSafe {}
118
119 /// A marker trait representing types where a shared reference is considered
120 /// unwind safe.
121 ///
122 /// This trait is namely not implemented by [`UnsafeCell`], the root of all
123 /// interior mutability.
124 ///
125 /// This is a "helper marker trait" used to provide impl blocks for the
126 /// [`UnwindSafe`] trait, for more information see that documentation.
127 #[stable(feature = "catch_unwind", since = "1.9.0")]
128 #[rustc_on_unimplemented(
129     message = "the type `{Self}` may contain interior mutability and a reference may not be safely \
130                transferrable across a catch_unwind boundary",
131     label = "`{Self}` may contain interior mutability and a reference may not be safely \
132              transferrable across a catch_unwind boundary"
133 )]
134 pub auto trait RefUnwindSafe {}
135
136 /// A simple wrapper around a type to assert that it is unwind safe.
137 ///
138 /// When using [`catch_unwind`] it may be the case that some of the closed over
139 /// variables are not unwind safe. For example if `&mut T` is captured the
140 /// compiler will generate a warning indicating that it is not unwind safe. It
141 /// may not be the case, however, that this is actually a problem due to the
142 /// specific usage of [`catch_unwind`] if unwind safety is specifically taken into
143 /// account. This wrapper struct is useful for a quick and lightweight
144 /// annotation that a variable is indeed unwind safe.
145 ///
146 /// # Examples
147 ///
148 /// One way to use `AssertUnwindSafe` is to assert that the entire closure
149 /// itself is unwind safe, bypassing all checks for all variables:
150 ///
151 /// ```
152 /// use std::panic::{self, AssertUnwindSafe};
153 ///
154 /// let mut variable = 4;
155 ///
156 /// // This code will not compile because the closure captures `&mut variable`
157 /// // which is not considered unwind safe by default.
158 ///
159 /// // panic::catch_unwind(|| {
160 /// //     variable += 3;
161 /// // });
162 ///
163 /// // This, however, will compile due to the `AssertUnwindSafe` wrapper
164 /// let result = panic::catch_unwind(AssertUnwindSafe(|| {
165 ///     variable += 3;
166 /// }));
167 /// // ...
168 /// ```
169 ///
170 /// Wrapping the entire closure amounts to a blanket assertion that all captured
171 /// variables are unwind safe. This has the downside that if new captures are
172 /// added in the future, they will also be considered unwind safe. Therefore,
173 /// you may prefer to just wrap individual captures, as shown below. This is
174 /// more annotation, but it ensures that if a new capture is added which is not
175 /// unwind safe, you will get a compilation error at that time, which will
176 /// allow you to consider whether that new capture in fact represent a bug or
177 /// not.
178 ///
179 /// ```
180 /// use std::panic::{self, AssertUnwindSafe};
181 ///
182 /// let mut variable = 4;
183 /// let other_capture = 3;
184 ///
185 /// let result = {
186 ///     let mut wrapper = AssertUnwindSafe(&mut variable);
187 ///     panic::catch_unwind(move || {
188 ///         **wrapper += other_capture;
189 ///     })
190 /// };
191 /// // ...
192 /// ```
193 #[stable(feature = "catch_unwind", since = "1.9.0")]
194 pub struct AssertUnwindSafe<T>(#[stable(feature = "catch_unwind", since = "1.9.0")] pub T);
195
196 // Implementations of the `UnwindSafe` trait:
197 //
198 // * By default everything is unwind safe
199 // * pointers T contains mutability of some form are not unwind safe
200 // * Unique, an owning pointer, lifts an implementation
201 // * Types like Mutex/RwLock which are explicitly poisoned are unwind safe
202 // * Our custom AssertUnwindSafe wrapper is indeed unwind safe
203
204 #[stable(feature = "catch_unwind", since = "1.9.0")]
205 impl<T: ?Sized> !UnwindSafe for &mut T {}
206 #[stable(feature = "catch_unwind", since = "1.9.0")]
207 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for &T {}
208 #[stable(feature = "catch_unwind", since = "1.9.0")]
209 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *const T {}
210 #[stable(feature = "catch_unwind", since = "1.9.0")]
211 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *mut T {}
212 #[unstable(feature = "ptr_internals", issue = "none")]
213 impl<T: UnwindSafe + ?Sized> UnwindSafe for Unique<T> {}
214 #[stable(feature = "nonnull", since = "1.25.0")]
215 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for NonNull<T> {}
216 #[stable(feature = "catch_unwind", since = "1.9.0")]
217 impl<T: ?Sized> UnwindSafe for Mutex<T> {}
218 #[stable(feature = "catch_unwind", since = "1.9.0")]
219 impl<T: ?Sized> UnwindSafe for RwLock<T> {}
220 #[stable(feature = "catch_unwind", since = "1.9.0")]
221 impl<T> UnwindSafe for AssertUnwindSafe<T> {}
222
223 // not covered via the Shared impl above b/c the inner contents use
224 // Cell/AtomicUsize, but the usage here is unwind safe so we can lift the
225 // impl up one level to Arc/Rc itself
226 #[stable(feature = "catch_unwind", since = "1.9.0")]
227 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Rc<T> {}
228 #[stable(feature = "catch_unwind", since = "1.9.0")]
229 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Arc<T> {}
230
231 // Pretty simple implementations for the `RefUnwindSafe` marker trait,
232 // basically just saying that `UnsafeCell` is the
233 // only thing which doesn't implement it (which then transitively applies to
234 // everything else).
235 #[stable(feature = "catch_unwind", since = "1.9.0")]
236 impl<T: ?Sized> !RefUnwindSafe for UnsafeCell<T> {}
237 #[stable(feature = "catch_unwind", since = "1.9.0")]
238 impl<T> RefUnwindSafe for AssertUnwindSafe<T> {}
239
240 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
241 impl<T: ?Sized> RefUnwindSafe for Mutex<T> {}
242 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
243 impl<T: ?Sized> RefUnwindSafe for RwLock<T> {}
244
245 #[cfg(target_has_atomic_load_store = "ptr")]
246 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
247 impl RefUnwindSafe for atomic::AtomicIsize {}
248 #[cfg(target_has_atomic_load_store = "8")]
249 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
250 impl RefUnwindSafe for atomic::AtomicI8 {}
251 #[cfg(target_has_atomic_load_store = "16")]
252 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
253 impl RefUnwindSafe for atomic::AtomicI16 {}
254 #[cfg(target_has_atomic_load_store = "32")]
255 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
256 impl RefUnwindSafe for atomic::AtomicI32 {}
257 #[cfg(target_has_atomic_load_store = "64")]
258 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
259 impl RefUnwindSafe for atomic::AtomicI64 {}
260 #[cfg(target_has_atomic_load_store = "128")]
261 #[unstable(feature = "integer_atomics", issue = "32976")]
262 impl RefUnwindSafe for atomic::AtomicI128 {}
263
264 #[cfg(target_has_atomic_load_store = "ptr")]
265 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
266 impl RefUnwindSafe for atomic::AtomicUsize {}
267 #[cfg(target_has_atomic_load_store = "8")]
268 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
269 impl RefUnwindSafe for atomic::AtomicU8 {}
270 #[cfg(target_has_atomic_load_store = "16")]
271 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
272 impl RefUnwindSafe for atomic::AtomicU16 {}
273 #[cfg(target_has_atomic_load_store = "32")]
274 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
275 impl RefUnwindSafe for atomic::AtomicU32 {}
276 #[cfg(target_has_atomic_load_store = "64")]
277 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
278 impl RefUnwindSafe for atomic::AtomicU64 {}
279 #[cfg(target_has_atomic_load_store = "128")]
280 #[unstable(feature = "integer_atomics", issue = "32976")]
281 impl RefUnwindSafe for atomic::AtomicU128 {}
282
283 #[cfg(target_has_atomic_load_store = "8")]
284 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
285 impl RefUnwindSafe for atomic::AtomicBool {}
286
287 #[cfg(target_has_atomic_load_store = "ptr")]
288 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
289 impl<T> RefUnwindSafe for atomic::AtomicPtr<T> {}
290
291 // https://github.com/rust-lang/rust/issues/62301
292 #[stable(feature = "hashbrown", since = "1.36.0")]
293 impl<K, V, S> UnwindSafe for collections::HashMap<K, V, S>
294 where
295     K: UnwindSafe,
296     V: UnwindSafe,
297     S: UnwindSafe,
298 {
299 }
300
301 #[stable(feature = "catch_unwind", since = "1.9.0")]
302 impl<T> Deref for AssertUnwindSafe<T> {
303     type Target = T;
304
305     fn deref(&self) -> &T {
306         &self.0
307     }
308 }
309
310 #[stable(feature = "catch_unwind", since = "1.9.0")]
311 impl<T> DerefMut for AssertUnwindSafe<T> {
312     fn deref_mut(&mut self) -> &mut T {
313         &mut self.0
314     }
315 }
316
317 #[stable(feature = "catch_unwind", since = "1.9.0")]
318 impl<R, F: FnOnce() -> R> FnOnce<()> for AssertUnwindSafe<F> {
319     type Output = R;
320
321     extern "rust-call" fn call_once(self, _args: ()) -> R {
322         (self.0)()
323     }
324 }
325
326 #[stable(feature = "std_debug", since = "1.16.0")]
327 impl<T: fmt::Debug> fmt::Debug for AssertUnwindSafe<T> {
328     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329         f.debug_tuple("AssertUnwindSafe").field(&self.0).finish()
330     }
331 }
332
333 #[stable(feature = "futures_api", since = "1.36.0")]
334 impl<F: Future> Future for AssertUnwindSafe<F> {
335     type Output = F::Output;
336
337     fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
338         let pinned_field = unsafe { Pin::map_unchecked_mut(self, |x| &mut x.0) };
339         F::poll(pinned_field, cx)
340     }
341 }
342
343 /// Invokes a closure, capturing the cause of an unwinding panic if one occurs.
344 ///
345 /// This function will return `Ok` with the closure's result if the closure
346 /// does not panic, and will return `Err(cause)` if the closure panics. The
347 /// `cause` returned is the object with which panic was originally invoked.
348 ///
349 /// It is currently undefined behavior to unwind from Rust code into foreign
350 /// code, so this function is particularly useful when Rust is called from
351 /// another language (normally C). This can run arbitrary Rust code, capturing a
352 /// panic and allowing a graceful handling of the error.
353 ///
354 /// It is **not** recommended to use this function for a general try/catch
355 /// mechanism. The [`Result`] type is more appropriate to use for functions that
356 /// can fail on a regular basis. Additionally, this function is not guaranteed
357 /// to catch all panics, see the "Notes" section below.
358 ///
359 /// The closure provided is required to adhere to the [`UnwindSafe`] trait to ensure
360 /// that all captured variables are safe to cross this boundary. The purpose of
361 /// this bound is to encode the concept of [exception safety][rfc] in the type
362 /// system. Most usage of this function should not need to worry about this
363 /// bound as programs are naturally unwind safe without `unsafe` code. If it
364 /// becomes a problem the [`AssertUnwindSafe`] wrapper struct can be used to quickly
365 /// assert that the usage here is indeed unwind safe.
366 ///
367 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
368 ///
369 /// # Notes
370 ///
371 /// Note that this function **may not catch all panics** in Rust. A panic in
372 /// Rust is not always implemented via unwinding, but can be implemented by
373 /// aborting the process as well. This function *only* catches unwinding panics,
374 /// not those that abort the process.
375 ///
376 /// Also note that unwinding into Rust code with a foreign exception (e.g. a
377 /// an exception thrown from C++ code) is undefined behavior.
378 ///
379 /// # Examples
380 ///
381 /// ```
382 /// use std::panic;
383 ///
384 /// let result = panic::catch_unwind(|| {
385 ///     println!("hello!");
386 /// });
387 /// assert!(result.is_ok());
388 ///
389 /// let result = panic::catch_unwind(|| {
390 ///     panic!("oh no!");
391 /// });
392 /// assert!(result.is_err());
393 /// ```
394 #[stable(feature = "catch_unwind", since = "1.9.0")]
395 pub fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R> {
396     unsafe { panicking::r#try(f) }
397 }
398
399 /// Triggers a panic without invoking the panic hook.
400 ///
401 /// This is designed to be used in conjunction with [`catch_unwind`] to, for
402 /// example, carry a panic across a layer of C code.
403 ///
404 /// # Notes
405 ///
406 /// Note that panics in Rust are not always implemented via unwinding, but they
407 /// may be implemented by aborting the process. If this function is called when
408 /// panics are implemented this way then this function will abort the process,
409 /// not trigger an unwind.
410 ///
411 /// # Examples
412 ///
413 /// ```should_panic
414 /// use std::panic;
415 ///
416 /// let result = panic::catch_unwind(|| {
417 ///     panic!("oh no!");
418 /// });
419 ///
420 /// if let Err(err) = result {
421 ///     panic::resume_unwind(err);
422 /// }
423 /// ```
424 #[stable(feature = "resume_unwind", since = "1.9.0")]
425 pub fn resume_unwind(payload: Box<dyn Any + Send>) -> ! {
426     panicking::rust_panic_without_hook(payload)
427 }
428
429 #[cfg(test)]
430 mod tests;