Skip to content

Commit 56e88c4

Browse files
committed
Auto merge of rust-lang#120238 - joboet:always_confirm_lock_success, r=Mark-Simulacrum
Always check the result of `pthread_mutex_lock` Fixes rust-lang#120147. Instead of manually adding a list of "good" platforms, I've simply made the check unconditional. pthread's mutex is already quite slow on most platforms, so one single well-predictable branch shouldn't hurt performance too much.
2 parents fb4bca0 + 8d708e5 commit 56e88c4

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

library/std/src/sys/pal/unix/locks/pthread_mutex.rs

+18-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use crate::cell::UnsafeCell;
2+
use crate::io::Error;
23
use crate::mem::{forget, MaybeUninit};
34
use crate::sys::cvt_nz;
45
use crate::sys_common::lazy_box::{LazyBox, LazyInit};
@@ -103,8 +104,24 @@ impl Mutex {
103104

104105
#[inline]
105106
pub unsafe fn lock(&self) {
107+
#[cold]
108+
#[inline(never)]
109+
fn fail() -> ! {
110+
let error = Error::last_os_error();
111+
panic!("failed to lock mutex: {error}");
112+
}
113+
106114
let r = libc::pthread_mutex_lock(raw(self));
107-
debug_assert_eq!(r, 0);
115+
// As we set the mutex type to `PTHREAD_MUTEX_NORMAL` above, we expect
116+
// the lock call to never fail. Unfortunately however, some platforms
117+
// (Solaris) do not conform to the standard, and instead always provide
118+
// deadlock detection. How kind of them! Unfortunately that means that
119+
// we need to check the error code here. To save us from UB on other
120+
// less well-behaved platforms in the future, we do it even on "good"
121+
// platforms like macOS. See #120147 for more context.
122+
if r != 0 {
123+
fail()
124+
}
108125
}
109126

110127
#[inline]

0 commit comments

Comments
 (0)