]> git.lizzy.rs Git - rust.git/blob - src/shims/posix/linux/sync.rs
Use read_scalar_at_offset in futex_wait instead of memory.get_raw.
[rust.git] / src / shims / posix / linux / sync.rs
1 use crate::thread::Time;
2 use crate::*;
3 use rustc_target::abi::{Align, Size};
4 use std::time::{Instant, SystemTime};
5
6 /// Implementation of the SYS_futex syscall.
7 pub fn futex<'tcx>(
8     this: &mut MiriEvalContext<'_, 'tcx>,
9     args: &[OpTy<'tcx, Tag>],
10     dest: PlaceTy<'tcx, Tag>,
11 ) -> InterpResult<'tcx> {
12     // The amount of arguments used depends on the type of futex operation.
13     // The full futex syscall takes six arguments (excluding the syscall
14     // number), which is also the maximum amount of arguments a linux syscall
15     // can take on most architectures.
16     // However, not all futex operations use all six arguments. The unused ones
17     // may or may not be left out from the `syscall()` call.
18     // Therefore we don't use `check_arg_count` here, but only check for the
19     // number of arguments to fall within a range.
20     if !(4..=7).contains(&args.len()) {
21         throw_ub_format!("incorrect number of arguments for futex syscall: got {}, expected between 4 and 7 (inclusive)", args.len());
22     }
23
24     // The first three arguments (after the syscall number itself) are the same to all futex operations:
25     //     (int *addr, int op, int val).
26     // We checked above that these definitely exist.
27     let addr = this.read_immediate(args[1])?;
28     let op = this.read_scalar(args[2])?.to_i32()?;
29     let val = this.read_scalar(args[3])?.to_i32()?;
30
31     // The raw pointer value is used to identify the mutex.
32     // Not all mutex operations actually read from this address or even require this address to exist.
33     let futex_ptr = this.force_ptr(addr.to_scalar()?)?;
34
35     let thread = this.get_active_thread();
36
37     let futex_private = this.eval_libc_i32("FUTEX_PRIVATE_FLAG")?;
38     let futex_wait = this.eval_libc_i32("FUTEX_WAIT")?;
39     let futex_wake = this.eval_libc_i32("FUTEX_WAKE")?;
40     let futex_realtime = this.eval_libc_i32("FUTEX_CLOCK_REALTIME")?;
41
42     // FUTEX_PRIVATE enables an optimization that stops it from working across processes.
43     // Miri doesn't support that anyway, so we ignore that flag.
44     match op & !futex_private {
45         // FUTEX_WAIT: (int *addr, int op = FUTEX_WAIT, int val, const timespec *timeout)
46         // Blocks the thread if *addr still equals val. Wakes up when FUTEX_WAKE is called on the same address,
47         // or *timeout expires. `timeout == null` for an infinite timeout.
48         op if op & !futex_realtime == futex_wait => {
49             if args.len() < 5 {
50                 throw_ub_format!("incorrect number of arguments for FUTEX_WAIT syscall: got {}, expected at least 5", args.len());
51             }
52             let timeout = args[4];
53             let timeout_time = if this.is_null(this.read_scalar(timeout)?.check_init()?)? {
54                 None
55             } else {
56                 let duration = match this.read_timespec(timeout)? {
57                     Some(duration) => duration,
58                     None => {
59                         let einval = this.eval_libc("EINVAL")?;
60                         this.set_last_error(einval)?;
61                         this.write_scalar(Scalar::from_machine_isize(-1, this), dest)?;
62                         return Ok(());
63                     }
64                 };
65                 this.check_no_isolation("FUTEX_WAIT with timeout")?;
66                 Some(if op & futex_realtime != 0 {
67                     Time::RealTime(SystemTime::now().checked_add(duration).unwrap())
68                 } else {
69                     Time::Monotonic(Instant::now().checked_add(duration).unwrap())
70                 })
71             };
72             // Check the pointer for alignment and validity.
73             // The API requires `addr` to be a 4-byte aligned pointer, and will
74             // use the 4 bytes at the given address as an (atomic) i32.
75             this.memory.check_ptr_access(addr.to_scalar()?, Size::from_bytes(4), Align::from_bytes(4).unwrap())?;
76             // Read an `i32` through the pointer, regardless of any wrapper types.
77             // It's not uncommon for `addr` to be passed as another type than `*mut i32`, such as `*const AtomicI32`.
78             let futex_val = this.read_scalar_at_offset(addr.into(), 0, this.machine.layouts.i32)?.to_i32()?;
79             if val == futex_val {
80                 // The value still matches, so we block the trait make it wait for FUTEX_WAKE.
81                 this.block_thread(thread);
82                 this.futex_wait(futex_ptr, thread);
83                 // Succesfully waking up from FUTEX_WAIT always returns zero.
84                 this.write_scalar(Scalar::from_machine_isize(0, this), dest)?;
85                 // Register a timeout callback if a timeout was specified.
86                 // This callback will override the return value when the timeout triggers.
87                 if let Some(timeout_time) = timeout_time {
88                     this.register_timeout_callback(
89                         thread,
90                         timeout_time,
91                         Box::new(move |this| {
92                             this.unblock_thread(thread);
93                             this.futex_remove_waiter(futex_ptr, thread);
94                             let etimedout = this.eval_libc("ETIMEDOUT")?;
95                             this.set_last_error(etimedout)?;
96                             this.write_scalar(Scalar::from_machine_isize(-1, this), dest)?;
97                             Ok(())
98                         }),
99                     );
100                 }
101             } else {
102                 // The futex value doesn't match the expected value, so we return failure
103                 // right away without sleeping: -1 and errno set to EAGAIN.
104                 let eagain = this.eval_libc("EAGAIN")?;
105                 this.set_last_error(eagain)?;
106                 this.write_scalar(Scalar::from_machine_isize(-1, this), dest)?;
107             }
108         }
109         // FUTEX_WAKE: (int *addr, int op = FUTEX_WAKE, int val)
110         // Wakes at most `val` threads waiting on the futex at `addr`.
111         // Returns the amount of threads woken up.
112         // Does not access the futex value at *addr.
113         op if op == futex_wake => {
114             let mut n = 0;
115             for _ in 0..val {
116                 if let Some(thread) = this.futex_wake(futex_ptr) {
117                     this.unblock_thread(thread);
118                     this.unregister_timeout_callback_if_exists(thread);
119                     n += 1;
120                 } else {
121                     break;
122                 }
123             }
124             this.write_scalar(Scalar::from_machine_isize(n, this), dest)?;
125         }
126         op => throw_unsup_format!("miri does not support SYS_futex operation {}", op),
127     }
128
129     Ok(())
130 }