std/sys/pal/unix/sync/mutex.rs
1use super::super::cvt_nz;
2use crate::io::Error;
3use crate::pin::{Pin, pin};
4use crate::sys::helpers::COpaque;
5
6pub struct Mutex {
7 inner: COpaque<libc::pthread_mutex_t>,
8}
9
10impl Mutex {
11 pub fn new() -> Mutex {
12 Mutex { inner: COpaque::new(libc::PTHREAD_MUTEX_INITIALIZER) }
13 }
14
15 pub(super) fn raw(self: Pin<&Self>) -> *mut libc::pthread_mutex_t {
16 let inner = unsafe { self.map_unchecked(|m| &m.inner) };
17 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/9799919799/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 attr = pin!(COpaque::<libc::pthread_mutexattr_t>::uninit());
49 // FIXME(pin-ergonomics): remove the next line.
50 let attr = attr.into_ref();
51 cvt_nz(libc::pthread_mutexattr_init(attr.get())).unwrap();
52 let attr = AttrGuard(attr);
53 cvt_nz(libc::pthread_mutexattr_settype(attr.0.get(), libc::PTHREAD_MUTEX_NORMAL))
54 .unwrap();
55 cvt_nz(libc::pthread_mutex_init(self.as_ref().raw(), attr.0.get())).unwrap();
56 }
57 }
58
59 /// # Safety
60 /// * If `init` was not called on this instance, reentrant locking causes
61 /// undefined behaviour.
62 /// * Destroying a locked mutex causes undefined behaviour.
63 pub unsafe fn lock(self: Pin<&Self>) {
64 #[cold]
65 #[inline(never)]
66 fn fail(r: i32) -> ! {
67 let error = Error::from_raw_os_error(r);
68 panic!("failed to lock mutex: {error}");
69 }
70
71 let r = unsafe { libc::pthread_mutex_lock(self.raw()) };
72 // As we set the mutex type to `PTHREAD_MUTEX_NORMAL` above, we expect
73 // the lock call to never fail. Unfortunately however, some platforms
74 // (Solaris) do not conform to the standard, and instead always provide
75 // deadlock detection. How kind of them! Unfortunately that means that
76 // we need to check the error code here. To save us from UB on other
77 // less well-behaved platforms in the future, we do it even on "good"
78 // platforms like macOS. See #120147 for more context.
79 if r != 0 {
80 fail(r)
81 }
82 }
83
84 /// # Safety
85 /// * If `init` was not called on this instance, reentrant locking causes
86 /// undefined behaviour.
87 /// * Destroying a locked mutex causes undefined behaviour.
88 pub unsafe fn try_lock(self: Pin<&Self>) -> bool {
89 unsafe { libc::pthread_mutex_trylock(self.raw()) == 0 }
90 }
91
92 /// # Safety
93 /// The mutex must be locked by the current thread.
94 pub unsafe fn unlock(self: Pin<&Self>) {
95 let r = unsafe { libc::pthread_mutex_unlock(self.raw()) };
96 debug_assert_eq!(r, 0);
97 }
98}
99
100impl !Unpin for Mutex {}
101
102unsafe impl Send for Mutex {}
103unsafe impl Sync for Mutex {}
104
105impl Drop for Mutex {
106 fn drop(&mut self) {
107 let inner = unsafe { Pin::new_unchecked(&self.inner) };
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(inner.get()) };
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 Pin<&'a COpaque<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.get());
132 assert_eq!(result, 0);
133 }
134 }
135}