mc_sgx_sync/
poison.rs

1// Copyright (c) The Rust Foundation
2// Copyright (c) 2023 The MobileCoin Foundation
3
4//! Poison implementation more or less copied from
5//! [rust source](https://github.com/rust-lang/rust.git) at
6//! [606c3907](https://github.com/rust-lang/rust/commit/606c3907251397a42e23d3e60de31be9d32525d5)
7//!
8//! Differences:
9//! - The imports were changed to work with the `mc-sgx` crates.
10//! - The stable attributes have been removed
11//! - Items that are crate only were converted from `pub` to `pub(crate)`
12//! - Examples that were not possible in an SGX enclave have been omitted
13//! - Ran `cargo fmt`
14
15use core::error::Error;
16use core::fmt;
17use core::sync::atomic::{AtomicBool, Ordering};
18use mc_sgx_panic_sys::thread;
19
20pub(crate) struct Flag {
21    failed: AtomicBool,
22}
23
24// Note that the Ordering uses to access the `failed` field of `Flag` below is
25// always `Relaxed`, and that's because this isn't actually protecting any data,
26// it's just a flag whether we've panicked or not.
27//
28// The actual location that this matters is when a mutex is **locked** which is
29// where we have external synchronization ensuring that we see memory
30// reads/writes to this flag.
31//
32// As a result, if it matters, we should see the correct value for `failed` in
33// all cases.
34
35impl Flag {
36    #[inline]
37    pub const fn new() -> Flag {
38        Flag {
39            failed: AtomicBool::new(false),
40        }
41    }
42
43    /// Check the flag for an unguarded borrow, where we only care about existing poison.
44    #[inline]
45    pub fn borrow(&self) -> LockResult<()> {
46        if self.get() {
47            Err(PoisonError::new(()))
48        } else {
49            Ok(())
50        }
51    }
52
53    /// Check the flag for a guarded borrow, where we may also set poison when `done`.
54    #[inline]
55    pub fn guard(&self) -> LockResult<Guard> {
56        let ret = Guard {
57            panicking: thread::panicking(),
58        };
59        if self.get() {
60            Err(PoisonError::new(ret))
61        } else {
62            Ok(ret)
63        }
64    }
65
66    #[inline]
67    pub fn done(&self, guard: &Guard) {
68        if !guard.panicking && thread::panicking() {
69            self.failed.store(true, Ordering::Relaxed);
70        }
71    }
72
73    #[inline]
74    pub fn get(&self) -> bool {
75        self.failed.load(Ordering::Relaxed)
76    }
77
78    #[inline]
79    pub fn clear(&self) {
80        self.failed.store(false, Ordering::Relaxed)
81    }
82}
83
84pub(crate) struct Guard {
85    panicking: bool,
86}
87
88/// A type of error which can be returned whenever a lock is acquired.
89///
90/// Both [`Mutex`]es and [`RwLock`]s are poisoned whenever a thread fails while the lock
91/// is held. The precise semantics for when a lock is poisoned is documented on
92/// each lock, but once a lock is poisoned then all future acquisitions will
93/// return this error.
94///
95/// [`Mutex`]: crate::Mutex
96/// [`RwLock`]: crate::RwLock
97pub struct PoisonError<T> {
98    guard: T,
99}
100
101/// An enumeration of possible errors associated with a [`TryLockResult`] which
102/// can occur while trying to acquire a lock, from the [`try_lock`] method on a
103/// [`Mutex`] or the [`try_read`] and [`try_write`] methods on an [`RwLock`].
104///
105/// [`try_lock`]: crate::Mutex::try_lock
106/// [`try_read`]: crate::RwLock::try_read
107/// [`try_write`]: crate::RwLock::try_write
108/// [`Mutex`]: crate::Mutex
109/// [`RwLock`]: crate::RwLock
110pub enum TryLockError<T> {
111    /// The lock could not be acquired because another thread failed while holding
112    /// the lock.
113    Poisoned(PoisonError<T>),
114    /// The lock could not be acquired at this time because the operation would
115    /// otherwise block.
116    WouldBlock,
117}
118
119/// A type alias for the result of a lock method which can be poisoned.
120///
121/// The [`Ok`] variant of this result indicates that the primitive was not
122/// poisoned, and the `Guard` is contained within. The [`Err`] variant indicates
123/// that the primitive was poisoned. Note that the [`Err`] variant *also* carries
124/// the associated guard, and it can be acquired through the [`into_inner`]
125/// method.
126///
127/// [`into_inner`]: PoisonError::into_inner
128pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
129
130/// A type alias for the result of a nonblocking locking method.
131///
132/// For more information, see [`LockResult`]. A `TryLockResult` doesn't
133/// necessarily hold the associated guard in the [`Err`] type as the lock might not
134/// have been acquired for other reasons.
135pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
136
137impl<T> fmt::Debug for PoisonError<T> {
138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139        f.debug_struct("PoisonError").finish_non_exhaustive()
140    }
141}
142
143impl<T> fmt::Display for PoisonError<T> {
144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145        "poisoned lock: another task failed inside".fmt(f)
146    }
147}
148
149impl<T> Error for PoisonError<T> {
150    #[allow(deprecated)]
151    fn description(&self) -> &str {
152        "poisoned lock: another task failed inside"
153    }
154}
155
156impl<T> PoisonError<T> {
157    /// Creates a `PoisonError`.
158    ///
159    /// This is generally created by methods like [`Mutex::lock`](crate::Mutex::lock)
160    /// or [`RwLock::read`](crate::RwLock::read).
161    pub fn new(guard: T) -> PoisonError<T> {
162        PoisonError { guard }
163    }
164
165    /// Consumes this error indicating that a lock is poisoned, returning the
166    /// underlying guard to allow access regardless.
167    pub fn into_inner(self) -> T {
168        self.guard
169    }
170
171    /// Reaches into this error indicating that a lock is poisoned, returning a
172    /// reference to the underlying guard to allow access regardless.
173    pub fn get_ref(&self) -> &T {
174        &self.guard
175    }
176
177    /// Reaches into this error indicating that a lock is poisoned, returning a
178    /// mutable reference to the underlying guard to allow access regardless.
179    pub fn get_mut(&mut self) -> &mut T {
180        &mut self.guard
181    }
182}
183
184impl<T> From<PoisonError<T>> for TryLockError<T> {
185    fn from(err: PoisonError<T>) -> TryLockError<T> {
186        TryLockError::Poisoned(err)
187    }
188}
189
190impl<T> fmt::Debug for TryLockError<T> {
191    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192        match *self {
193            TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
194            TryLockError::WouldBlock => "WouldBlock".fmt(f),
195        }
196    }
197}
198
199impl<T> fmt::Display for TryLockError<T> {
200    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201        match *self {
202            TryLockError::Poisoned(..) => "poisoned lock: another task failed inside",
203            TryLockError::WouldBlock => "try_lock failed because the operation would block",
204        }
205        .fmt(f)
206    }
207}
208
209impl<T> Error for TryLockError<T> {
210    #[allow(deprecated, deprecated_in_future)]
211    fn description(&self) -> &str {
212        match *self {
213            TryLockError::Poisoned(ref p) => p.description(),
214            TryLockError::WouldBlock => "try_lock failed because the operation would block",
215        }
216    }
217
218    #[allow(deprecated)]
219    fn cause(&self) -> Option<&dyn Error> {
220        match *self {
221            TryLockError::Poisoned(ref p) => Some(p),
222            _ => None,
223        }
224    }
225}
226
227pub(crate) fn map_result<T, U, F>(result: LockResult<T>, f: F) -> LockResult<U>
228where
229    F: FnOnce(T) -> U,
230{
231    match result {
232        Ok(t) => Ok(f(t)),
233        Err(PoisonError { guard }) => Err(PoisonError::new(f(guard))),
234    }
235}