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