miri/shims/unix/linux_like/
eventfd.rs

1//! Linux `eventfd` implementation.
2use std::cell::{Cell, RefCell};
3use std::io;
4use std::io::ErrorKind;
5
6use crate::concurrency::VClock;
7use crate::shims::files::{FdId, FileDescription, FileDescriptionRef, WeakFileDescriptionRef};
8use crate::shims::unix::UnixFileDescription;
9use crate::shims::unix::linux_like::epoll::{EpollEvents, EvalContextExt as _};
10use crate::*;
11
12/// Maximum value that the eventfd counter can hold.
13const MAX_COUNTER: u64 = u64::MAX - 1;
14
15/// A kind of file descriptor created by `eventfd`.
16/// The `Event` type isn't currently written to by `eventfd`.
17/// The interface is meant to keep track of objects associated
18/// with a file descriptor. For more information see the man
19/// page below:
20///
21/// <https://man.netbsd.org/eventfd.2>
22#[derive(Debug)]
23struct EventFd {
24    /// The object contains an unsigned 64-bit integer (uint64_t) counter that is maintained by the
25    /// kernel. This counter is initialized with the value specified in the argument initval.
26    counter: Cell<u64>,
27    is_nonblock: bool,
28    clock: RefCell<VClock>,
29    /// A list of thread ids blocked on eventfd::read.
30    blocked_read_tid: RefCell<Vec<ThreadId>>,
31    /// A list of thread ids blocked on eventfd::write.
32    blocked_write_tid: RefCell<Vec<ThreadId>>,
33}
34
35impl FileDescription for EventFd {
36    fn name(&self) -> &'static str {
37        "event"
38    }
39
40    fn destroy<'tcx>(
41        self,
42        _self_id: FdId,
43        _communicate_allowed: bool,
44        _ecx: &mut MiriInterpCx<'tcx>,
45    ) -> InterpResult<'tcx, io::Result<()>> {
46        interp_ok(Ok(()))
47    }
48
49    /// Read the counter in the buffer and return the counter if succeeded.
50    fn read<'tcx>(
51        self: FileDescriptionRef<Self>,
52        _communicate_allowed: bool,
53        ptr: Pointer,
54        len: usize,
55        ecx: &mut MiriInterpCx<'tcx>,
56        finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
57    ) -> InterpResult<'tcx> {
58        // We're treating the buffer as a `u64`.
59        let ty = ecx.machine.layouts.u64;
60        // Check the size of slice, and return error only if the size of the slice < 8.
61        if len < ty.size.bytes_usize() {
62            return finish.call(ecx, Err(ErrorKind::InvalidInput.into()));
63        }
64
65        // Turn the pointer into a place at the right type.
66        let buf_place = ecx.ptr_to_mplace_unaligned(ptr, ty);
67
68        eventfd_read(buf_place, self, ecx, finish)
69    }
70
71    /// A write call adds the 8-byte integer value supplied in
72    /// its buffer (in native endianness) to the counter.  The maximum value that may be
73    /// stored in the counter is the largest unsigned 64-bit value
74    /// minus 1 (i.e., 0xfffffffffffffffe).  If the addition would
75    /// cause the counter's value to exceed the maximum, then the
76    /// write either blocks until a read is performed on the
77    /// file descriptor, or fails with the error EAGAIN if the
78    /// file descriptor has been made nonblocking.
79    ///
80    /// A write fails with the error EINVAL if the size of the
81    /// supplied buffer is less than 8 bytes, or if an attempt is
82    /// made to write the value 0xffffffffffffffff.
83    fn write<'tcx>(
84        self: FileDescriptionRef<Self>,
85        _communicate_allowed: bool,
86        ptr: Pointer,
87        len: usize,
88        ecx: &mut MiriInterpCx<'tcx>,
89        finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
90    ) -> InterpResult<'tcx> {
91        // We're treating the buffer as a `u64`.
92        let ty = ecx.machine.layouts.u64;
93        // Check the size of slice, and return error only if the size of the slice < 8.
94        if len < ty.layout.size.bytes_usize() {
95            return finish.call(ecx, Err(ErrorKind::InvalidInput.into()));
96        }
97
98        // Turn the pointer into a place at the right type.
99        let buf_place = ecx.ptr_to_mplace_unaligned(ptr, ty);
100
101        eventfd_write(buf_place, self, ecx, finish)
102    }
103
104    fn as_unix<'tcx>(&self, _ecx: &MiriInterpCx<'tcx>) -> &dyn UnixFileDescription {
105        self
106    }
107}
108
109impl UnixFileDescription for EventFd {
110    fn epoll_active_events<'tcx>(&self) -> InterpResult<'tcx, EpollEvents> {
111        // We only check the status of EPOLLIN and EPOLLOUT flags for eventfd. If other event flags
112        // need to be supported in the future, the check should be added here.
113
114        interp_ok(EpollEvents {
115            epollin: self.counter.get() != 0,
116            epollout: self.counter.get() != MAX_COUNTER,
117            ..EpollEvents::new()
118        })
119    }
120}
121
122impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
123pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
124    /// This function creates an `Event` that is used as an event wait/notify mechanism by
125    /// user-space applications, and by the kernel to notify user-space applications of events.
126    /// The `Event` contains an `u64` counter maintained by the kernel. The counter is initialized
127    /// with the value specified in the `initval` argument.
128    ///
129    /// A new file descriptor referring to the `Event` is returned. The `read`, `write`, `poll`,
130    /// `select`, and `close` operations can be performed on the file descriptor. For more
131    /// information on these operations, see the man page linked below.
132    ///
133    /// The `flags` are not currently implemented for eventfd.
134    /// The `flags` may be bitwise ORed to change the behavior of `eventfd`:
135    /// `EFD_CLOEXEC` - Set the close-on-exec (`FD_CLOEXEC`) flag on the new file descriptor.
136    /// `EFD_NONBLOCK` - Set the `O_NONBLOCK` file status flag on the new open file description.
137    /// `EFD_SEMAPHORE` - miri does not support semaphore-like semantics.
138    ///
139    /// <https://linux.die.net/man/2/eventfd>
140    fn eventfd(&mut self, val: &OpTy<'tcx>, flags: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
141        let this = self.eval_context_mut();
142
143        let val = this.read_scalar(val)?.to_u32()?;
144        let mut flags = this.read_scalar(flags)?.to_i32()?;
145
146        let efd_cloexec = this.eval_libc_i32("EFD_CLOEXEC");
147        let efd_nonblock = this.eval_libc_i32("EFD_NONBLOCK");
148        let efd_semaphore = this.eval_libc_i32("EFD_SEMAPHORE");
149
150        if flags & efd_semaphore == efd_semaphore {
151            throw_unsup_format!("eventfd: EFD_SEMAPHORE is unsupported");
152        }
153
154        let mut is_nonblock = false;
155        // Unset the flag that we support.
156        // After unloading, flags != 0 means other flags are used.
157        if flags & efd_cloexec == efd_cloexec {
158            // cloexec is ignored because Miri does not support exec.
159            flags &= !efd_cloexec;
160        }
161        if flags & efd_nonblock == efd_nonblock {
162            flags &= !efd_nonblock;
163            is_nonblock = true;
164        }
165        if flags != 0 {
166            throw_unsup_format!("eventfd: encountered unknown unsupported flags {:#x}", flags);
167        }
168
169        let fds = &mut this.machine.fds;
170
171        let fd_value = fds.insert_new(EventFd {
172            counter: Cell::new(val.into()),
173            is_nonblock,
174            clock: RefCell::new(VClock::default()),
175            blocked_read_tid: RefCell::new(Vec::new()),
176            blocked_write_tid: RefCell::new(Vec::new()),
177        });
178
179        interp_ok(Scalar::from_i32(fd_value))
180    }
181}
182
183/// Block thread if the value addition will exceed u64::MAX -1,
184/// else just add the user-supplied value to current counter.
185fn eventfd_write<'tcx>(
186    buf_place: MPlaceTy<'tcx>,
187    eventfd: FileDescriptionRef<EventFd>,
188    ecx: &mut MiriInterpCx<'tcx>,
189    finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
190) -> InterpResult<'tcx> {
191    // Figure out which value we should add.
192    let num = ecx.read_scalar(&buf_place)?.to_u64()?;
193    // u64::MAX as input is invalid because the maximum value of counter is u64::MAX - 1.
194    if num == u64::MAX {
195        return finish.call(ecx, Err(ErrorKind::InvalidInput.into()));
196    }
197
198    match eventfd.counter.get().checked_add(num) {
199        Some(new_count @ 0..=MAX_COUNTER) => {
200            // Future `read` calls will synchronize with this write, so update the FD clock.
201            ecx.release_clock(|clock| {
202                eventfd.clock.borrow_mut().join(clock);
203            })?;
204
205            // Store new counter value.
206            eventfd.counter.set(new_count);
207
208            // Unblock *all* threads previously blocked on `read`.
209            // We need to take out the blocked thread ids and unblock them together,
210            // because `unblock_threads` may block them again and end up re-adding the
211            // thread to the blocked list.
212            let waiting_threads = std::mem::take(&mut *eventfd.blocked_read_tid.borrow_mut());
213            // FIXME: We can randomize the order of unblocking.
214            for thread_id in waiting_threads {
215                ecx.unblock_thread(thread_id, BlockReason::Eventfd)?;
216            }
217
218            // The state changed; we check and update the status of all supported event
219            // types for current file description.
220            // Linux seems to cause spurious wakeups here, and Tokio seems to rely on that
221            // (see <https://github.com/rust-lang/miri/pull/4676#discussion_r2510528994>
222            // and also <https://www.illumos.org/issues/16700>).
223            ecx.update_epoll_active_events(eventfd, /* force_edge */ true)?;
224
225            // Return how many bytes we consumed from the user-provided buffer.
226            return finish.call(ecx, Ok(buf_place.layout.size.bytes_usize()));
227        }
228        None | Some(u64::MAX) => {
229            // We can't update the state, so we have to block.
230            if eventfd.is_nonblock {
231                return finish.call(ecx, Err(ErrorKind::WouldBlock.into()));
232            }
233
234            eventfd.blocked_write_tid.borrow_mut().push(ecx.active_thread());
235
236            let weak_eventfd = FileDescriptionRef::downgrade(&eventfd);
237            ecx.block_thread(
238                BlockReason::Eventfd,
239                None,
240                callback!(
241                    @capture<'tcx> {
242                        num: u64,
243                        buf_place: MPlaceTy<'tcx>,
244                        finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
245                        weak_eventfd: WeakFileDescriptionRef<EventFd>,
246                    }
247                    |this, unblock: UnblockKind| {
248                        assert_eq!(unblock, UnblockKind::Ready);
249                        // When we get unblocked, try again. We know the ref is still valid,
250                        // otherwise there couldn't be a `write` that unblocks us.
251                        let eventfd_ref = weak_eventfd.upgrade().unwrap();
252                        eventfd_write(buf_place, eventfd_ref, this, finish)
253                    }
254                ),
255            );
256        }
257    };
258    interp_ok(())
259}
260
261/// Block thread if the current counter is 0,
262/// else just return the current counter value to the caller and set the counter to 0.
263fn eventfd_read<'tcx>(
264    buf_place: MPlaceTy<'tcx>,
265    eventfd: FileDescriptionRef<EventFd>,
266    ecx: &mut MiriInterpCx<'tcx>,
267    finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
268) -> InterpResult<'tcx> {
269    // Set counter to 0, get old value.
270    let counter = eventfd.counter.replace(0);
271
272    // Block when counter == 0.
273    if counter == 0 {
274        if eventfd.is_nonblock {
275            return finish.call(ecx, Err(ErrorKind::WouldBlock.into()));
276        }
277
278        eventfd.blocked_read_tid.borrow_mut().push(ecx.active_thread());
279
280        let weak_eventfd = FileDescriptionRef::downgrade(&eventfd);
281        ecx.block_thread(
282            BlockReason::Eventfd,
283            None,
284            callback!(
285                @capture<'tcx> {
286                    buf_place: MPlaceTy<'tcx>,
287                    finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
288                    weak_eventfd: WeakFileDescriptionRef<EventFd>,
289                }
290                |this, unblock: UnblockKind| {
291                    assert_eq!(unblock, UnblockKind::Ready);
292                    // When we get unblocked, try again. We know the ref is still valid,
293                    // otherwise there couldn't be a `write` that unblocks us.
294                    let eventfd_ref = weak_eventfd.upgrade().unwrap();
295                    eventfd_read(buf_place, eventfd_ref, this, finish)
296                }
297            ),
298        );
299    } else {
300        // Synchronize with all prior `write` calls to this FD.
301        ecx.acquire_clock(&eventfd.clock.borrow())?;
302
303        // Return old counter value into user-space buffer.
304        ecx.write_int(counter, &buf_place)?;
305
306        // Unblock *all* threads previously blocked on `write`.
307        // We need to take out the blocked thread ids and unblock them together,
308        // because `unblock_threads` may block them again and end up re-adding the
309        // thread to the blocked list.
310        let waiting_threads = std::mem::take(&mut *eventfd.blocked_write_tid.borrow_mut());
311        // FIXME: We can randomize the order of unblocking.
312        for thread_id in waiting_threads {
313            ecx.unblock_thread(thread_id, BlockReason::Eventfd)?;
314        }
315
316        // The state changed; we check and update the status of all supported event
317        // types for current file description.
318        // Linux seems to always emit do notifications here, even if we were already writable.
319        ecx.update_epoll_active_events(eventfd, /* force_edge */ true)?;
320
321        // Tell userspace how many bytes we put into the buffer.
322        return finish.call(ecx, Ok(buf_place.layout.size.bytes_usize()));
323    }
324    interp_ok(())
325}