miri/shims/unix/linux_like/sync.rs
1use crate::concurrency::sync::FutexRef;
2use crate::helpers::check_min_vararg_count;
3use crate::*;
4
5struct LinuxFutex {
6 futex: FutexRef,
7}
8
9/// Implementation of the SYS_futex syscall.
10/// `args` is the arguments *including* the syscall number.
11pub fn futex<'tcx>(
12 ecx: &mut MiriInterpCx<'tcx>,
13 varargs: &[OpTy<'tcx>],
14 dest: &MPlaceTy<'tcx>,
15) -> InterpResult<'tcx> {
16 let [addr, op, val] = check_min_vararg_count("`syscall(SYS_futex, ...)`", varargs)?;
17
18 // See <https://man7.org/linux/man-pages/man2/futex.2.html> for docs.
19 // The first three arguments (after the syscall number itself) are the same to all futex operations:
20 // (uint32_t *addr, int op, uint32_t val).
21 // We checked above that these definitely exist.
22 let addr = ecx.read_pointer(addr)?;
23 let op = ecx.read_scalar(op)?.to_i32()?;
24 let val = ecx.read_scalar(val)?.to_u32()?;
25
26 // This is a vararg function so we have to bring our own type for this pointer.
27 let addr = ecx.ptr_to_mplace(addr, ecx.machine.layouts.i32);
28
29 let futex_private = ecx.eval_libc_i32("FUTEX_PRIVATE_FLAG");
30 let futex_wait = ecx.eval_libc_i32("FUTEX_WAIT");
31 let futex_wait_bitset = ecx.eval_libc_i32("FUTEX_WAIT_BITSET");
32 let futex_wake = ecx.eval_libc_i32("FUTEX_WAKE");
33 let futex_wake_bitset = ecx.eval_libc_i32("FUTEX_WAKE_BITSET");
34 let futex_realtime = ecx.eval_libc_i32("FUTEX_CLOCK_REALTIME");
35
36 // FUTEX_PRIVATE enables an optimization that stops it from working across processes.
37 // Miri doesn't support that anyway, so we ignore that flag.
38 match op & !futex_private {
39 // FUTEX_WAIT: (int *addr, int op = FUTEX_WAIT, int val, const timespec *timeout)
40 // Blocks the thread if *addr still equals val. Wakes up when FUTEX_WAKE is called on the same address,
41 // or *timeout expires. `timeout == null` for an infinite timeout.
42 //
43 // FUTEX_WAIT_BITSET: (int *addr, int op = FUTEX_WAIT_BITSET, int val, const timespec *timeout, int *_ignored, unsigned int bitset)
44 // This is identical to FUTEX_WAIT, except:
45 // - The timeout is absolute rather than relative.
46 // - You can specify the bitset to selecting what WAKE operations to respond to.
47 op if op & !futex_realtime == futex_wait || op & !futex_realtime == futex_wait_bitset => {
48 let wait_bitset = op & !futex_realtime == futex_wait_bitset;
49
50 let (timeout, bitset) = if wait_bitset {
51 let [_, _, _, timeout, uaddr2, bitset] = check_min_vararg_count(
52 "`syscall(SYS_futex, FUTEX_WAIT_BITSET, ...)`",
53 varargs,
54 )?;
55 let _timeout = ecx.read_pointer(timeout)?;
56 let _uaddr2 = ecx.read_pointer(uaddr2)?;
57 (timeout, ecx.read_scalar(bitset)?.to_u32()?)
58 } else {
59 let [_, _, _, timeout] =
60 check_min_vararg_count("`syscall(SYS_futex, FUTEX_WAIT, ...)`", varargs)?;
61 (timeout, u32::MAX)
62 };
63
64 if bitset == 0 {
65 return ecx.set_last_error_and_return(LibcError("EINVAL"), dest);
66 }
67
68 let timeout = ecx.deref_pointer_as(timeout, ecx.libc_ty_layout("timespec"))?;
69 let timeout = if ecx.ptr_is_null(timeout.ptr())? {
70 None
71 } else {
72 let duration = match ecx.read_timespec(&timeout)? {
73 Some(duration) => duration,
74 None => {
75 return ecx.set_last_error_and_return(LibcError("EINVAL"), dest);
76 }
77 };
78 let timeout_clock = if op & futex_realtime == futex_realtime {
79 ecx.check_no_isolation(
80 "`futex` syscall with `op=FUTEX_WAIT` and non-null timeout with `FUTEX_CLOCK_REALTIME`",
81 )?;
82 TimeoutClock::RealTime
83 } else {
84 TimeoutClock::Monotonic
85 };
86 let timeout_anchor = if wait_bitset {
87 // FUTEX_WAIT_BITSET uses an absolute timestamp.
88 TimeoutAnchor::Absolute
89 } else {
90 // FUTEX_WAIT uses a relative timestamp.
91 TimeoutAnchor::Relative
92 };
93 Some((timeout_clock, timeout_anchor, duration))
94 };
95 // There may be a concurrent thread changing the value of addr
96 // and then invoking the FUTEX_WAKE syscall. It is critical that the
97 // effects of this and the other thread are correctly observed,
98 // otherwise we will deadlock.
99 //
100 // There are two scenarios to consider, depending on whether WAIT or WAKE goes first:
101 // 1. If we (FUTEX_WAIT) execute first, we'll push ourselves into the waiters queue and
102 // go to sleep. They (FUTEX_WAKE) will see us in the queue and wake us up. It doesn't
103 // matter how the addr write is ordered.
104 // 2. If they (FUTEX_WAKE) execute first, that means the addr write is also before us
105 // (FUTEX_WAIT). It is crucial that we observe addr's new value. If we see an
106 // outdated value that happens to equal the expected val, then we'll put ourselves to
107 // sleep with no one to wake us up, so we end up with a deadlock. This is prevented
108 // by having a SeqCst fence inside FUTEX_WAKE syscall, and another SeqCst fence here
109 // in FUTEX_WAIT. The atomic read on addr after the SeqCst fence is guaranteed not to
110 // see any value older than the addr write immediately before calling FUTEX_WAKE.
111 // We'll see futex_val != val and return without sleeping.
112 //
113 // Note that the fences do not create any happens-before relationship.
114 // The read sees the write immediately before the fence not because
115 // one happens after the other, but is instead due to a guarantee unique
116 // to SeqCst fences that restricts what an atomic read placed AFTER the
117 // fence can see. The read still has to be atomic, otherwise it's a data
118 // race. This guarantee cannot be achieved with acquire-release fences
119 // since they only talk about reads placed BEFORE a fence - and places
120 // no restrictions on what the read itself can see, only that there is
121 // a happens-before between the fences IF the read happens to see the
122 // right value. This is useless to us, since we need the read itself
123 // to see an up-to-date value.
124 //
125 // The above case distinction is valid since both FUTEX_WAIT and FUTEX_WAKE
126 // contain a SeqCst fence, therefore inducing a total order between the operations.
127 // It is also critical that the fence, the atomic load, and the comparison in FUTEX_WAIT
128 // altogether happen atomically. If the other thread's fence in FUTEX_WAKE
129 // gets interleaved after our fence, then we lose the guarantee on the
130 // atomic load being up-to-date; if the other thread's write on addr and FUTEX_WAKE
131 // call are interleaved after the load but before the comparison, then we get a TOCTOU
132 // race condition, and go to sleep thinking the other thread will wake us up,
133 // even though they have already finished.
134 //
135 // Thankfully, preemptions cannot happen inside a Miri shim, so we do not need to
136 // do anything special to guarantee fence-load-comparison atomicity.
137 ecx.atomic_fence(AtomicFenceOrd::SeqCst)?;
138 // Read an `i32` through the pointer, regardless of any wrapper types.
139 // It's not uncommon for `addr` to be passed as another type than `*mut i32`, such as `*const AtomicI32`.
140 // We do an acquire read -- it only seems reasonable that if we observe a value here, we
141 // actually establish an ordering with that value.
142 let futex_val = ecx.read_scalar_atomic(&addr, AtomicReadOrd::Acquire)?.to_u32()?;
143 if val == futex_val {
144 // The value still matches, so we block the thread and make it wait for FUTEX_WAKE.
145
146 // This cannot fail since we already did an atomic acquire read on that pointer.
147 // Acquire reads are only allowed on mutable memory.
148 let futex_ref = ecx
149 .get_sync_or_init(addr.ptr(), |_| LinuxFutex { futex: Default::default() })
150 .unwrap()
151 .futex
152 .clone();
153
154 let dest = dest.clone();
155 ecx.futex_wait(
156 futex_ref,
157 bitset,
158 timeout,
159 callback!(
160 @capture<'tcx> {
161 dest: MPlaceTy<'tcx>,
162 }
163 |ecx, unblock: UnblockKind| match unblock {
164 UnblockKind::Ready => {
165 ecx.write_int(0, &dest)
166 }
167 UnblockKind::TimedOut => {
168 ecx.set_last_error_and_return(LibcError("ETIMEDOUT"), &dest)
169 }
170 }
171 ),
172 );
173 } else {
174 // The futex value doesn't match the expected value, so we return failure
175 // right away without sleeping: -1 and errno set to EAGAIN.
176 return ecx.set_last_error_and_return(LibcError("EAGAIN"), dest);
177 }
178 }
179 // FUTEX_WAKE: (int *addr, int op = FUTEX_WAKE, int val)
180 // Wakes at most `val` threads waiting on the futex at `addr`.
181 // Returns the amount of threads woken up.
182 // Does not access the futex value at *addr.
183 // FUTEX_WAKE_BITSET: (int *addr, int op = FUTEX_WAKE, int val, const timespect *_unused, int *_unused, unsigned int bitset)
184 // Same as FUTEX_WAKE, but allows you to specify a bitset to select which threads to wake up.
185 op if op == futex_wake || op == futex_wake_bitset => {
186 let Some(futex_ref) =
187 ecx.get_sync_or_init(addr.ptr(), |_| LinuxFutex { futex: Default::default() })
188 else {
189 // No AllocId, or no live allocation at that AllocId.
190 // Return an error code. (That seems nicer than silently doing something non-intuitive.)
191 // This means that if an address gets reused by a new allocation,
192 // we'll use an independent futex queue for this... that seems acceptable.
193 return ecx.set_last_error_and_return(LibcError("EFAULT"), dest);
194 };
195 let futex_ref = futex_ref.futex.clone();
196
197 let bitset = if op == futex_wake_bitset {
198 let [_, _, _, timeout, uaddr2, bitset] = check_min_vararg_count(
199 "`syscall(SYS_futex, FUTEX_WAKE_BITSET, ...)`",
200 varargs,
201 )?;
202 let _timeout = ecx.read_pointer(timeout)?;
203 let _uaddr2 = ecx.read_pointer(uaddr2)?;
204 ecx.read_scalar(bitset)?.to_u32()?
205 } else {
206 u32::MAX
207 };
208 if bitset == 0 {
209 return ecx.set_last_error_and_return(LibcError("EINVAL"), dest);
210 }
211 // Together with the SeqCst fence in futex_wait, this makes sure that futex_wait
212 // will see the latest value on addr which could be changed by our caller
213 // before doing the syscall.
214 ecx.atomic_fence(AtomicFenceOrd::SeqCst)?;
215 let woken = ecx.futex_wake(&futex_ref, bitset, val.try_into().unwrap())?;
216 ecx.write_scalar(Scalar::from_target_isize(woken.try_into().unwrap(), ecx), dest)?;
217 }
218 op => throw_unsup_format!("Miri does not support `futex` syscall with op={}", op),
219 }
220
221 interp_ok(())
222}