1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#![cfg(unix)]

use crate::Event;
use std::os::unix::prelude::*;

pub type Inner = OwnedFd;

/// Runs f() until it stop failing with EINTR (as indicated by errno).
fn while_eintr<F, R>(mut f: F) -> std::io::Result<R>
where
    F: FnMut() -> std::io::Result<R>,
{
    loop {
        match f() {
            Err(err) if err.raw_os_error() == Some(libc::EINTR) => {}
            r => break r,
        }
    }
}

fn syscall_result<T: PartialOrd + Default>(result: T) -> std::io::Result<T> {
    if result >= T::default() {
        Ok(result)
    } else {
        Err(std::io::Error::last_os_error())
    }
}

#[cfg(target_os = "linux")]
mod eventfd {
    use super::syscall_result;
    use super::while_eintr;
    use crate::Event;

    use std::os::unix::prelude::*;

    impl Event {
        pub(crate) fn new_inner() -> std::io::Result<Self> {
            // Create an event fd.
            // SAFETY: calling C APIs as documented, with no special requirements, and validating its
            // return value before passing it to from_raw_fd.
            let fd = unsafe {
                let fd = syscall_result(libc::eventfd(0, libc::EFD_NONBLOCK | libc::EFD_CLOEXEC))?;
                OwnedFd::from_raw_fd(fd)
            };
            Ok(Self(fd))
        }

        pub(crate) fn try_wait_inner(&self) -> bool {
            let mut c: u64 = 0;
            // SAFETY: fd holds a valid and open file descriptor.
            let n = while_eintr(|| unsafe {
                syscall_result(libc::read(
                    self.0.as_raw_fd(),
                    std::ptr::from_mut(&mut c).cast::<std::ffi::c_void>(),
                    size_of_val(&c),
                ))
            });
            match n {
                Ok(n) => {
                    assert!(n == size_of_val(&c) as isize);
                    true
                }
                Err(err) => {
                    assert_eq!(err.raw_os_error(), Some(libc::EAGAIN));
                    false
                }
            }
        }
    }
}

#[cfg(not(target_os = "linux"))]
mod fifo {
    use super::syscall_result;
    use super::while_eintr;
    use crate::Event;
    use std::fs::File;

    use std::os::unix::prelude::*;

    impl Event {
        // Create an anonymous FIFO to emulate a Linux eventfd.
        pub(crate) fn new_inner() -> std::io::Result<Self> {
            // Create a random path.
            let mut path = std::env::temp_dir();
            let mut val = [0; 16];
            getrandom::getrandom(&mut val).unwrap();
            path.push(u128::from_ne_bytes(val).to_string());

            // Create the FIFO.
            let cpath = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap();
            // SAFETY: calling C APIs as documented, with no special requirements.
            syscall_result(unsafe { libc::mkfifo(cpath.as_ptr(), 0o600) })?;

            // Open the FIFO.
            let fifo = File::options()
                .read(true)
                .write(true)
                .custom_flags(libc::O_NONBLOCK)
                .open(&path)?;

            // Unlink it so that it can't be opened again.
            let _ = std::fs::remove_file(&path);
            Ok(Self(fifo.into()))
        }

        /// Consumes the ready state of an emulated eventfd on non-Linux platforms.
        ///
        /// Reads using a large buffer in case the underlying FIFO was signaled multiple
        /// times.
        pub(crate) fn try_wait_inner(&self) -> bool {
            let mut c = [0u8; 512];
            // SAFETY: fd holds a valid and open file descriptor.
            let n = while_eintr(|| unsafe {
                syscall_result(libc::read(
                    self.0.as_raw_fd(),
                    c.as_mut_ptr().cast::<std::ffi::c_void>(),
                    size_of_val(&c),
                ))
            });
            match n {
                Ok(_) => true,
                Err(err) => {
                    assert_eq!(err.raw_os_error(), Some(libc::EAGAIN));
                    false
                }
            }
        }
    }
}

impl Event {
    pub(crate) fn signal_inner(&self) {
        let c: u64 = 1;
        // SAFETY: fd holds a valid and open file descriptor.
        let r = unsafe {
            syscall_result(libc::write(
                self.0.as_raw_fd(),
                std::ptr::from_ref::<u64>(&c).cast::<libc::c_void>(),
                size_of_val(&c),
            ))
        };
        match r {
            Ok(n) if n == size_of_val(&c) as isize => {}
            Err(err) if err.raw_os_error() == Some(libc::EAGAIN) => {}
            r => {
                panic!("unexpected event write result: {:?}", r);
            }
        }
    }

    fn poll(&self) {
        let mut pollfds = [libc::pollfd {
            fd: self.0.as_raw_fd(),
            events: libc::POLLIN,
            revents: 0,
        }];
        // SAFETY: fd holds a valid and open file descriptor.
        while_eintr(|| unsafe { syscall_result(libc::poll(pollfds.as_mut_ptr(), 1, !0)) }).unwrap();
    }

    pub(crate) fn wait_inner(&self) {
        while !self.try_wait_inner() {
            self.poll();
        }
    }
}

impl Clone for Event {
    fn clone(&self) -> Self {
        Self(self.0.try_clone().expect("out of resources dup eventfd"))
    }
}

impl From<OwnedFd> for Event {
    fn from(fd: OwnedFd) -> Self {
        Self(fd)
    }
}

impl From<Event> for OwnedFd {
    fn from(event: Event) -> Self {
        event.0
    }
}

impl AsFd for Event {
    fn as_fd(&self) -> BorrowedFd<'_> {
        self.0.as_fd()
    }
}

#[cfg(feature = "mesh")]
mesh_protobuf::os_resource!(Event, OwnedFd);