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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#[cfg(target_os = "linux")]
pub mod eventfd {
    use super::check_err;
    use std::os::unix::io::RawFd;

    pub type EfdFlags = libc::c_int;

    pub fn eventfd(initval: libc::c_uint, flags: EfdFlags) -> Result<RawFd, std::io::Error> {
        let res = unsafe { libc::eventfd(initval, flags) };

        check_err(res).map(|r| r as RawFd)
    }
}

#[cfg(target_os = "linux")]
pub mod unistd {
    use super::check_err;
    use std::os::unix::io::RawFd;

    pub fn close(fd: RawFd) -> Result<(), std::io::Error> {
        let res = unsafe { libc::close(fd) };

        check_err(res).map(drop)
    }

    pub fn dup(oldfd: RawFd) -> Result<RawFd, std::io::Error> {
        let res = unsafe { libc::dup(oldfd) };
        check_err(res)
    }

    pub fn read(fd: RawFd, buf: &mut [u8]) -> Result<usize, std::io::Error> {
        let res = unsafe {
            libc::read(
                fd,
                buf.as_mut_ptr() as *mut libc::c_void,
                buf.len() as libc::size_t,
            )
        };

        check_err(res as _).map(|r| r as usize)
    }

    pub fn write(fd: RawFd, buf: &[u8]) -> Result<usize, std::io::Error> {
        let res = unsafe {
            libc::write(
                fd,
                buf.as_ptr() as *const libc::c_void,
                buf.len() as libc::size_t,
            )
        };

        check_err(res as _).map(|r| r as usize)
    }
}

#[cfg(unix)]
pub mod fcntl {
    use super::check_err;
    use std::os::unix::io::RawFd;

    pub type OFlag = libc::c_int;
    pub type FdFlag = libc::c_int;

    #[allow(non_camel_case_types)]
    #[allow(dead_code)]
    /// Arguments passed to `fcntl`.
    pub enum FcntlArg {
        F_GETFL,
        F_SETFL(OFlag),
        F_SETFD(FdFlag),
    }

    /// Thin wrapper around `libc::fcntl`.
    ///
    /// See [`fcntl(2)`](http://man7.org/linux/man-pages/man2/fcntl.2.html) for details.
    pub fn fcntl(fd: RawFd, arg: FcntlArg) -> Result<libc::c_int, std::io::Error> {
        let res = unsafe {
            match arg {
                FcntlArg::F_GETFL => libc::fcntl(fd, libc::F_GETFL),
                FcntlArg::F_SETFL(flag) => libc::fcntl(fd, libc::F_SETFL, flag),
                FcntlArg::F_SETFD(flag) => libc::fcntl(fd, libc::F_SETFD, flag),
            }
        };
        check_err(res)
    }
}

#[cfg(unix)]
fn check_err(res: libc::c_int) -> Result<libc::c_int, std::io::Error> {
    if res == -1 {
        return Err(std::io::Error::last_os_error());
    }

    Ok(res)
}

#[cfg(any(
    target_os = "macos",
    target_os = "ios",
    target_os = "freebsd",
    target_os = "netbsd",
    target_os = "openbsd",
    target_os = "dragonfly",
))]
/// Kqueue.
pub mod event {
    use super::check_err;
    use std::os::unix::io::RawFd;

    #[cfg(any(
        target_os = "macos",
        target_os = "ios",
        target_os = "freebsd",
        target_os = "dragonfly",
        target_os = "openbsd"
    ))]
    #[allow(non_camel_case_types)]
    type type_of_nchanges = libc::c_int;
    #[cfg(target_os = "netbsd")]
    #[allow(non_camel_case_types)]
    type type_of_nchanges = libc::size_t;

    #[cfg(target_os = "netbsd")]
    #[allow(non_camel_case_types)]
    type type_of_event_filter = u32;
    #[cfg(not(target_os = "netbsd"))]
    #[allow(non_camel_case_types)]
    type type_of_event_filter = i16;

    #[cfg(any(
        target_os = "dragonfly",
        target_os = "freebsd",
        target_os = "ios",
        target_os = "macos",
        target_os = "openbsd"
    ))]
    #[allow(non_camel_case_types)]
    type type_of_udata = *mut libc::c_void;
    #[cfg(any(
        target_os = "dragonfly",
        target_os = "freebsd",
        target_os = "ios",
        target_os = "macos"
    ))]
    #[allow(non_camel_case_types)]
    type type_of_data = libc::intptr_t;
    #[cfg(any(target_os = "netbsd"))]
    #[allow(non_camel_case_types)]
    type type_of_udata = libc::intptr_t;
    #[cfg(any(target_os = "netbsd", target_os = "openbsd"))]
    #[allow(non_camel_case_types)]
    type type_of_data = libc::int64_t;

    #[derive(Clone, Copy)]
    #[repr(C)]
    pub struct KEvent(libc::kevent);

    unsafe impl Send for KEvent {}

    impl KEvent {
        pub fn new(
            ident: libc::uintptr_t,
            filter: EventFilter,
            flags: EventFlag,
            fflags: FilterFlag,
            data: libc::intptr_t,
            udata: libc::intptr_t,
        ) -> KEvent {
            KEvent(libc::kevent {
                ident,
                filter: filter as type_of_event_filter,
                flags,
                fflags,
                data: data as type_of_data,
                udata: udata as type_of_udata,
            })
        }

        pub fn filter(&self) -> EventFilter {
            unsafe { std::mem::transmute(self.0.filter as type_of_event_filter) }
        }

        pub fn flags(&self) -> EventFlag {
            self.0.flags
        }

        pub fn data(&self) -> libc::intptr_t {
            self.0.data as libc::intptr_t
        }

        pub fn udata(&self) -> libc::intptr_t {
            self.0.udata as libc::intptr_t
        }
    }

    #[cfg(any(
        target_os = "dragonfly",
        target_os = "freebsd",
        target_os = "ios",
        target_os = "macos",
        target_os = "openbsd"
    ))]
    pub type EventFlag = u16;
    #[cfg(any(target_os = "netbsd"))]
    pub type EventFlag = u32;

    pub type FilterFlag = u32;

    #[cfg(target_os = "netbsd")]
    pub type EventFilter = u32;
    #[cfg(not(target_os = "netbsd"))]
    pub type EventFilter = i16;

    pub fn kqueue() -> Result<RawFd, std::io::Error> {
        let res = unsafe { libc::kqueue() };

        check_err(res)
    }

    pub fn kevent_ts(
        kq: RawFd,
        changelist: &[KEvent],
        eventlist: &mut [KEvent],
        timeout_opt: Option<libc::timespec>,
    ) -> Result<usize, std::io::Error> {
        let res = unsafe {
            libc::kevent(
                kq,
                changelist.as_ptr() as *const libc::kevent,
                changelist.len() as type_of_nchanges,
                eventlist.as_mut_ptr() as *mut libc::kevent,
                eventlist.len() as type_of_nchanges,
                if let Some(ref timeout) = timeout_opt {
                    timeout as *const libc::timespec
                } else {
                    std::ptr::null()
                },
            )
        };

        check_err(res).map(|r| r as usize)
    }
}

#[cfg(any(target_os = "linux", target_os = "android", target_os = "illumos"))]
/// Epoll.
pub mod epoll {
    use super::check_err;
    use std::os::unix::io::RawFd;

    #[macro_use]
    mod dlsym {
        // Based on https://github.com/tokio-rs/mio/blob/v0.6.x/src/sys/unix/dlsym.rs
        // I feel very sad including this code, but I have not found a better way
        // to check for the existence of a symbol in Rust.

        use std::marker;
        use std::mem;
        use std::sync::atomic::{AtomicUsize, Ordering};

        macro_rules! dlsym {
            (fn $name:ident($($t:ty),*) -> $ret:ty) => (
                #[allow(bad_style)]
                static $name: $crate::sys::epoll::dlsym::DlSym<unsafe extern fn($($t),*) -> $ret> =
                    $crate::sys::epoll::dlsym::DlSym {
                        name: concat!(stringify!($name), "\0"),
                        addr: std::sync::atomic::AtomicUsize::new(0),
                        _marker: std::marker::PhantomData,
                    };
            )
        }

        pub struct DlSym<F> {
            pub name: &'static str,
            pub addr: AtomicUsize,
            pub _marker: marker::PhantomData<F>,
        }

        impl<F> DlSym<F> {
            pub fn get(&self) -> Option<&F> {
                assert_eq!(mem::size_of::<F>(), mem::size_of::<usize>());
                unsafe {
                    if self.addr.load(Ordering::SeqCst) == 0 {
                        self.addr.store(fetch(self.name), Ordering::SeqCst);
                    }
                    if self.addr.load(Ordering::SeqCst) == 1 {
                        None
                    } else {
                        mem::transmute::<&AtomicUsize, Option<&F>>(&self.addr)
                    }
                }
            }
        }

        unsafe fn fetch(name: &str) -> usize {
            assert_eq!(name.as_bytes()[name.len() - 1], 0);
            match libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr() as *const _) as usize {
                0 => 1,
                n => n,
            }
        }
    }

    #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
    #[repr(i32)]
    pub enum EpollOp {
        EpollCtlAdd = libc::EPOLL_CTL_ADD,
        EpollCtlDel = libc::EPOLL_CTL_DEL,
        EpollCtlMod = libc::EPOLL_CTL_MOD,
    }

    pub type EpollFlags = libc::c_int;

    pub fn epoll_create1() -> Result<RawFd, std::io::Error> {
        // According to libuv, `EPOLL_CLOEXEC` is not defined on Android API <
        // 21. But `EPOLL_CLOEXEC` is an alias for `O_CLOEXEC` on that platform,
        // so we use it instead.
        #[cfg(target_os = "android")]
        const CLOEXEC: libc::c_int = libc::O_CLOEXEC;
        #[cfg(not(target_os = "android"))]
        const CLOEXEC: libc::c_int = libc::EPOLL_CLOEXEC;

        let fd = unsafe {
            // Emulate epoll_create1 if not available.

            dlsym!(fn epoll_create1(libc::c_int) -> libc::c_int);
            match epoll_create1.get() {
                Some(epoll_create1_fn) => check_err(epoll_create1_fn(CLOEXEC))?,
                None => {
                    let fd = check_err(libc::epoll_create(1024))?;
                    drop(set_cloexec(fd));
                    fd
                }
            }
        };

        Ok(fd)
    }

    unsafe fn set_cloexec(fd: libc::c_int) -> Result<(), std::io::Error> {
        let flags = libc::fcntl(fd, libc::F_GETFD);
        check_err(libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC)).map(|_| ())
    }

    pub fn epoll_ctl<'a, T>(
        epfd: RawFd,
        op: EpollOp,
        fd: RawFd,
        event: T,
    ) -> Result<(), std::io::Error>
    where
        T: Into<Option<&'a mut EpollEvent>>,
    {
        let mut event: Option<&mut EpollEvent> = event.into();
        if event.is_none() && op != EpollOp::EpollCtlDel {
            Err(std::io::Error::from_raw_os_error(libc::EINVAL))
        } else {
            let res = unsafe {
                if let Some(ref mut event) = event {
                    libc::epoll_ctl(epfd, op as libc::c_int, fd, &mut event.event)
                } else {
                    libc::epoll_ctl(epfd, op as libc::c_int, fd, std::ptr::null_mut())
                }
            };
            check_err(res).map(drop)
        }
    }

    pub fn epoll_wait(
        epfd: RawFd,
        events: &mut [EpollEvent],
        timeout_ms: isize,
    ) -> Result<usize, std::io::Error> {
        let res = unsafe {
            libc::epoll_wait(
                epfd,
                events.as_mut_ptr() as *mut libc::epoll_event,
                events.len() as libc::c_int,
                timeout_ms as libc::c_int,
            )
        };

        check_err(res).map(|r| r as usize)
    }

    #[derive(Clone, Copy)]
    #[repr(transparent)]
    pub struct EpollEvent {
        event: libc::epoll_event,
    }

    impl EpollEvent {
        pub fn new(events: EpollFlags, data: u64) -> Self {
            EpollEvent {
                event: libc::epoll_event {
                    events: events as u32,
                    u64: data,
                },
            }
        }

        pub fn empty() -> Self {
            unsafe { std::mem::zeroed::<EpollEvent>() }
        }

        pub fn events(&self) -> EpollFlags {
            self.event.events as libc::c_int
        }

        pub fn data(&self) -> u64 {
            self.event.u64
        }
    }
}