std/sys/pal/unix/sync/
mutex.rs

1use super::super::cvt_nz;
2use crate::cell::UnsafeCell;
3use crate::io::Error;
4use crate::mem::MaybeUninit;
5use crate::pin::Pin;
6
7pub struct Mutex {
8    inner: UnsafeCell<libc::pthread_mutex_t>,
9}
10
11impl Mutex {
12    pub fn new() -> Mutex {
13        Mutex { inner: UnsafeCell::new(libc::PTHREAD_MUTEX_INITIALIZER) }
14    }
15
16    pub(super) fn raw(&self) -> *mut libc::pthread_mutex_t {
17        self.inner.get()
18    }
19
20    /// # Safety
21    /// May only be called once per instance of `Self`.
22    pub unsafe fn init(self: Pin<&mut Self>) {
23        // Issue #33770
24        //
25        // A pthread mutex initialized with PTHREAD_MUTEX_INITIALIZER will have
26        // a type of PTHREAD_MUTEX_DEFAULT, which has undefined behavior if you
27        // try to re-lock it from the same thread when you already hold a lock
28        // (https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_init.html).
29        // This is the case even if PTHREAD_MUTEX_DEFAULT == PTHREAD_MUTEX_NORMAL
30        // (https://github.com/rust-lang/rust/issues/33770#issuecomment-220847521) -- in that
31        // case, `pthread_mutexattr_settype(PTHREAD_MUTEX_DEFAULT)` will of course be the same
32        // as setting it to `PTHREAD_MUTEX_NORMAL`, but not setting any mode will result in
33        // a Mutex where re-locking is UB.
34        //
35        // In practice, glibc takes advantage of this undefined behavior to
36        // implement hardware lock elision, which uses hardware transactional
37        // memory to avoid acquiring the lock. While a transaction is in
38        // progress, the lock appears to be unlocked. This isn't a problem for
39        // other threads since the transactional memory will abort if a conflict
40        // is detected, however no abort is generated when re-locking from the
41        // same thread.
42        //
43        // Since locking the same mutex twice will result in two aliasing &mut
44        // references, we instead create the mutex with type
45        // PTHREAD_MUTEX_NORMAL which is guaranteed to deadlock if we try to
46        // re-lock it from the same thread, thus avoiding undefined behavior.
47        unsafe {
48            let mut attr = MaybeUninit::<libc::pthread_mutexattr_t>::uninit();
49            cvt_nz(libc::pthread_mutexattr_init(attr.as_mut_ptr())).unwrap();
50            let attr = AttrGuard(&mut attr);
51            cvt_nz(libc::pthread_mutexattr_settype(
52                attr.0.as_mut_ptr(),
53                libc::PTHREAD_MUTEX_NORMAL,
54            ))
55            .unwrap();
56            cvt_nz(libc::pthread_mutex_init(self.raw(), attr.0.as_ptr())).unwrap();
57        }
58    }
59
60    /// # Safety
61    /// * If `init` was not called on this instance, reentrant locking causes
62    ///   undefined behaviour.
63    /// * Destroying a locked mutex causes undefined behaviour.
64    pub unsafe fn lock(self: Pin<&Self>) {
65        #[cold]
66        #[inline(never)]
67        fn fail(r: i32) -> ! {
68            let error = Error::from_raw_os_error(r);
69            panic!("failed to lock mutex: {error}");
70        }
71
72        let r = unsafe { libc::pthread_mutex_lock(self.raw()) };
73        // As we set the mutex type to `PTHREAD_MUTEX_NORMAL` above, we expect
74        // the lock call to never fail. Unfortunately however, some platforms
75        // (Solaris) do not conform to the standard, and instead always provide
76        // deadlock detection. How kind of them! Unfortunately that means that
77        // we need to check the error code here. To save us from UB on other
78        // less well-behaved platforms in the future, we do it even on "good"
79        // platforms like macOS. See #120147 for more context.
80        if r != 0 {
81            fail(r)
82        }
83    }
84
85    /// # Safety
86    /// * If `init` was not called on this instance, reentrant locking causes
87    ///   undefined behaviour.
88    /// * Destroying a locked mutex causes undefined behaviour.
89    pub unsafe fn try_lock(self: Pin<&Self>) -> bool {
90        unsafe { libc::pthread_mutex_trylock(self.raw()) == 0 }
91    }
92
93    /// # Safety
94    /// The mutex must be locked by the current thread.
95    pub unsafe fn unlock(self: Pin<&Self>) {
96        let r = unsafe { libc::pthread_mutex_unlock(self.raw()) };
97        debug_assert_eq!(r, 0);
98    }
99}
100
101impl !Unpin for Mutex {}
102
103unsafe impl Send for Mutex {}
104unsafe impl Sync for Mutex {}
105
106impl Drop for Mutex {
107    fn drop(&mut self) {
108        // SAFETY:
109        // If `lock` or `init` was called, the mutex must have been pinned, so
110        // it is still at the same location. Otherwise, `inner` must contain
111        // `PTHREAD_MUTEX_INITIALIZER`, which is valid at all locations. Thus,
112        // this call always destroys a valid mutex.
113        let r = unsafe { libc::pthread_mutex_destroy(self.raw()) };
114        if cfg!(any(target_os = "aix", target_os = "dragonfly")) {
115            // On AIX and DragonFly pthread_mutex_destroy() returns EINVAL if called
116            // on a mutex that was just initialized with libc::PTHREAD_MUTEX_INITIALIZER.
117            // Once it is used (locked/unlocked) or pthread_mutex_init() is called,
118            // this behaviour no longer occurs.
119            debug_assert!(r == 0 || r == libc::EINVAL);
120        } else {
121            debug_assert_eq!(r, 0);
122        }
123    }
124}
125
126struct AttrGuard<'a>(pub &'a mut MaybeUninit<libc::pthread_mutexattr_t>);
127
128impl Drop for AttrGuard<'_> {
129    fn drop(&mut self) {
130        unsafe {
131            let result = libc::pthread_mutexattr_destroy(self.0.as_mut_ptr());
132            assert_eq!(result, 0);
133        }
134    }
135}