Skip to main content

miri/shims/windows/
sync.rs

1use std::time::Duration;
2
3use rustc_abi::{FieldIdx, Size};
4
5use crate::concurrency::init_once::{EvalContextExt as _, InitOnceStatus};
6use crate::concurrency::sync::FutexRef;
7use crate::*;
8
9#[derive(Clone)]
10struct WindowsInitOnce {
11    init_once: InitOnceRef,
12}
13
14impl MetaObj for WindowsInitOnce {
15    fn on_access<'tcx>(&self) -> InterpResult<'tcx> {
16        if !self.init_once.queue_is_empty() {
17            throw_ub_format!(
18                "accessing the memory backing a `INIT_ONCE` is forbidden while the queue is non-empty"
19            );
20        }
21        interp_ok(())
22    }
23}
24
25struct WindowsFutex {
26    futex: FutexRef,
27}
28
29impl MetaObj for WindowsFutex {
30    fn opaque(&self) -> bool {
31        false
32    }
33}
34
35impl<'tcx> EvalContextExtPriv<'tcx> for crate::MiriInterpCx<'tcx> {}
36trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
37    // Windows sync primitives are pointer sized.
38    // We only use the first byte for the "init" flag.
39
40    fn init_once_get_data<'a>(
41        &'a mut self,
42        init_once_ptr: &OpTy<'tcx>,
43    ) -> InterpResult<'tcx, &'a mut WindowsInitOnce>
44    where
45        'tcx: 'a,
46    {
47        let ecx = self.eval_context_mut();
48
49        let init_once = ecx.deref_pointer(init_once_ptr)?;
50
51        ecx.get_or_insert_meta(
52            &init_once,
53            |ecx| {
54                let ptr_field = ecx.project_field(&init_once, FieldIdx::from_u32(0))?;
55                let val = ecx.read_target_usize(&ptr_field)?;
56                if val == 0 {
57                    interp_ok(WindowsInitOnce { init_once: InitOnceRef::new() })
58                } else {
59                    throw_ub_format!("`INIT_ONCE` was not properly initialized at this location, or it got overwritten");
60                }
61            },
62        )
63    }
64
65    /// Returns `true` if we were successful, `false` if we would block.
66    fn init_once_try_begin(
67        &mut self,
68        init_once_ref: &InitOnceRef,
69        pending_place: &MPlaceTy<'tcx>,
70        dest: &MPlaceTy<'tcx>,
71    ) -> InterpResult<'tcx, bool> {
72        let ecx = self.eval_context_mut();
73        interp_ok(match init_once_ref.status() {
74            InitOnceStatus::Uninitialized => {
75                init_once_ref.begin();
76                ecx.write_scalar(ecx.eval_windows("c", "TRUE"), pending_place)?;
77                ecx.write_scalar(ecx.eval_windows("c", "TRUE"), dest)?;
78                true
79            }
80            InitOnceStatus::Complete => {
81                ecx.init_once_observe_completed(init_once_ref)?;
82                ecx.write_scalar(ecx.eval_windows("c", "FALSE"), pending_place)?;
83                ecx.write_scalar(ecx.eval_windows("c", "TRUE"), dest)?;
84                true
85            }
86            InitOnceStatus::Begun => false,
87        })
88    }
89}
90
91impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
92#[allow(non_snake_case)]
93pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
94    fn InitOnceBeginInitialize(
95        &mut self,
96        init_once_op: &OpTy<'tcx>,
97        flags_op: &OpTy<'tcx>,
98        pending_op: &OpTy<'tcx>,
99        context_op: &OpTy<'tcx>,
100        dest: &MPlaceTy<'tcx>,
101    ) -> InterpResult<'tcx> {
102        let ecx = self.eval_context_mut();
103
104        let init_once = ecx.init_once_get_data(init_once_op)?.init_once.clone();
105        let flags = ecx.read_scalar(flags_op)?.to_u32()?;
106        // PBOOL is int*
107        let pending_place = ecx.deref_pointer(pending_op)?;
108        let context = ecx.read_pointer(context_op)?;
109
110        if flags != 0 {
111            throw_unsup_format!("unsupported `dwFlags` {flags} in `InitOnceBeginInitialize`");
112        }
113
114        if !ecx.ptr_is_null(context)? {
115            throw_unsup_format!("non-null `lpContext` in `InitOnceBeginInitialize`");
116        }
117
118        if ecx.init_once_try_begin(&init_once, &pending_place, dest)? {
119            // Done!
120            return interp_ok(());
121        }
122
123        // We have to block, and then try again when we are woken up.
124        let dest = dest.clone();
125        ecx.init_once_enqueue_and_block(
126            init_once.clone(),
127            callback!(
128                @capture<'tcx> {
129                    init_once: InitOnceRef,
130                    pending_place: MPlaceTy<'tcx>,
131                    dest: MPlaceTy<'tcx>,
132                }
133                |ecx, unblock: UnblockKind| {
134                    assert_eq!(unblock, UnblockKind::Ready);
135                    let ret = ecx.init_once_try_begin(&init_once, &pending_place, &dest)?;
136                    assert!(ret, "we were woken up but init_once_try_begin still failed");
137                    interp_ok(())
138                }
139            ),
140        );
141        interp_ok(())
142    }
143
144    fn InitOnceComplete(
145        &mut self,
146        init_once_op: &OpTy<'tcx>,
147        flags_op: &OpTy<'tcx>,
148        context_op: &OpTy<'tcx>,
149    ) -> InterpResult<'tcx, Scalar> {
150        let ecx = self.eval_context_mut();
151
152        let init_once = ecx.init_once_get_data(init_once_op)?.init_once.clone();
153        let flags = ecx.read_scalar(flags_op)?.to_u32()?;
154        let context = ecx.read_pointer(context_op)?;
155
156        let success = if flags == 0 {
157            true
158        } else if flags == ecx.eval_windows_u32("c", "INIT_ONCE_INIT_FAILED") {
159            false
160        } else {
161            throw_unsup_format!("unsupported `dwFlags` {flags} in `InitOnceBeginInitialize`");
162        };
163
164        if !ecx.ptr_is_null(context)? {
165            throw_unsup_format!("non-null `lpContext` in `InitOnceBeginInitialize`");
166        }
167
168        if init_once.status() != InitOnceStatus::Begun {
169            // The docs do not say anything about this case, but it seems better to not allow it.
170            throw_ub_format!(
171                "calling InitOnceComplete on a one time initialization that has not begun or is already completed"
172            );
173        }
174
175        if success {
176            ecx.init_once_complete(&init_once)?;
177        } else {
178            ecx.init_once_fail(&init_once)?;
179        }
180
181        interp_ok(ecx.eval_windows("c", "TRUE"))
182    }
183
184    fn WaitOnAddress(
185        &mut self,
186        ptr_op: &OpTy<'tcx>,
187        compare_op: &OpTy<'tcx>,
188        size_op: &OpTy<'tcx>,
189        timeout_op: &OpTy<'tcx>,
190        dest: &MPlaceTy<'tcx>,
191    ) -> InterpResult<'tcx> {
192        let ecx = self.eval_context_mut();
193
194        let ptr = ecx.read_pointer(ptr_op)?;
195        let compare = ecx.read_pointer(compare_op)?;
196        let size = ecx.read_target_usize(size_op)?;
197        let timeout_ms = ecx.read_scalar(timeout_op)?.to_u32()?;
198
199        if size > 8 || !size.is_power_of_two() {
200            let invalid_param = ecx.eval_windows("c", "ERROR_INVALID_PARAMETER");
201            ecx.set_last_error(invalid_param)?;
202            ecx.write_scalar(Scalar::from_i32(0), dest)?;
203            return interp_ok(());
204        };
205        let size = Size::from_bytes(size);
206
207        let deadline = if timeout_ms == ecx.eval_windows_u32("c", "INFINITE") {
208            None
209        } else {
210            let duration = Duration::from_millis(timeout_ms.into());
211            Some(ecx.machine.monotonic_clock.now().add_lossy(duration).into())
212        };
213
214        // See the Linux futex implementation for why this fence exists.
215        ecx.atomic_fence(AtomicFenceOrd::SeqCst)?;
216
217        let layout = ecx.machine.layouts.uint(size).unwrap();
218        let futex_place = ecx.ptr_to_mplace(ptr, layout);
219        let futex_val = ecx.read_scalar_atomic(&futex_place, AtomicReadOrd::Acquire)?;
220        let compare_val = ecx.read_scalar(&ecx.ptr_to_mplace(compare, layout))?;
221
222        if futex_val == compare_val {
223            // If the values are the same, we have to block.
224
225            let futex_ref = ecx
226                .get_or_insert_meta(&futex_place, |_| {
227                    interp_ok(WindowsFutex { futex: Default::default() })
228                })?
229                .futex
230                .clone();
231
232            let dest = dest.clone();
233            ecx.futex_wait(
234                futex_ref,
235                u32::MAX, // bitset
236                deadline,
237                callback!(
238                    @capture<'tcx> {
239                        dest: MPlaceTy<'tcx>
240                    }
241                    |ecx, unblock: UnblockKind| {
242                        match unblock {
243                            UnblockKind::Ready => {
244                                ecx.write_int(1, &dest)
245                            }
246                            UnblockKind::TimedOut => {
247                                ecx.set_last_error(IoError::WindowsError("ERROR_TIMEOUT"))?;
248                                ecx.write_int(0, &dest)
249                            }
250                        }
251                    }
252                ),
253            );
254        }
255
256        ecx.write_scalar(Scalar::from_i32(1), dest)?;
257
258        interp_ok(())
259    }
260
261    fn WakeByAddressSingle(&mut self, ptr_op: &OpTy<'tcx>) -> InterpResult<'tcx> {
262        let ecx = self.eval_context_mut();
263
264        let ptr = ecx.read_pointer(ptr_op)?;
265
266        // See the Linux futex implementation for why this fence exists.
267        ecx.atomic_fence(AtomicFenceOrd::SeqCst)?;
268
269        let Ok(futex) = ecx.try_get_meta::<WindowsFutex>(ptr) else {
270            // Seems like this cannot return an error, so we just wake nobody.
271            return interp_ok(());
272        };
273        ecx.futex_wake(&futex.futex.clone(), u32::MAX, 1)?;
274
275        interp_ok(())
276    }
277    fn WakeByAddressAll(&mut self, ptr_op: &OpTy<'tcx>) -> InterpResult<'tcx> {
278        let ecx = self.eval_context_mut();
279
280        let ptr = ecx.read_pointer(ptr_op)?;
281
282        // See the Linux futex implementation for why this fence exists.
283        ecx.atomic_fence(AtomicFenceOrd::SeqCst)?;
284
285        let Ok(futex) = ecx.try_get_meta::<WindowsFutex>(ptr) else {
286            // Seems like this cannot return an error, so we just wake nobody.
287            return interp_ok(());
288        };
289        ecx.futex_wake(&futex.futex.clone(), u32::MAX, usize::MAX)?;
290
291        interp_ok(())
292    }
293}