From f3d201a26b81ef1a84856d95d7efe36eff79bd69 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Tue, 18 Jun 2019 07:39:24 -0700 Subject: [PATCH] pull in the poll implementation from wezterm+termwiz --- filedescriptor/src/lib.rs | 30 +++++++ filedescriptor/src/unix.rs | 142 ++++++++++++++++++++++++++++++++++ filedescriptor/src/windows.rs | 19 +++++ 3 files changed, 191 insertions(+) diff --git a/filedescriptor/src/lib.rs b/filedescriptor/src/lib.rs index ea82deaad..2c0436ce8 100644 --- a/filedescriptor/src/lib.rs +++ b/filedescriptor/src/lib.rs @@ -211,3 +211,33 @@ pub struct Pipe { /// The writable end of the pipe pub write: FileDescriptor, } + +use std::time::Duration; + +/// Examines a set of FileDescriptors to see if some of them are ready for I/O, +/// or if certain events have occurred on them. +/// +/// This uses the system native readiness checking mechanism, which on Windows +/// means that it does NOT use IOCP and that this only works with sockets on +/// Windows. If you need IOCP then the `mio` crate is recommended for a much +/// more scalable solution. +/// +/// On macOS, the `poll(2)` implementation has problems when used with eg: pty +/// descriptors, so this implementation of poll uses the `select(2)` interface +/// under the covers. That places a limit on the maximum file descriptor value +/// that can be passed to poll. If a file descriptor is out of range then an +/// error will returned. This limitation could potentially be lifted in the +/// future. +/// +/// If `duration` is `None`, then `poll` will block until any of the requested +/// events are ready. Otherwise, `duration` specifies how long to wait for +/// readiness before giving up. +/// +/// The return value is the number of entries that were satisfied; `0` means +/// that none were ready after waiting for the specified duration. +/// +/// The `pfd` array is mutated and the `revents` field is updated to indicate +/// which of the events were received. +pub fn poll(pfd: &mut [pollfd], duration: Option) -> Fallible { + poll_impl(pfd, duration) +} diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index 1a4a56d20..7eb55ea01 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -208,3 +208,145 @@ impl Pipe { } } } + +pub use libc::{pollfd, POLLERR, POLLHUP, POLLIN, POLLOUT}; +use std::time::Duration; + +#[cfg(not(target_os = "macos"))] +#[doc(hidden)] +pub fn poll_impl(pfd: &mut [pollfd], duration: Option) -> Fallible { + let poll_result = unsafe { + libc::poll( + pfd.as_mut_ptr(), + pfd.len() as _, + duration + .map(|wait| wait.as_millis() as libc::c_int) + .unwrap_or(-1), + ) + }; + if poll_result < 0 { + Err(std::io::Error::last_os_error()) + } else { + Ok(poll_result as usize) + } +} + +// macOS has a broken poll(2) implementation, so we introduce a layer to deal with that here +#[cfg(target_os = "macos")] +mod macos { + use super::*; + use libc::{fd_set, timeval, FD_ISSET, FD_SET, FD_SETSIZE, FD_ZERO, POLLERR, POLLIN, POLLOUT}; + use std::os::unix::io::RawFd; + + struct FdSet { + set: fd_set, + } + + #[inline] + fn check_fd(fd: RawFd) -> Fallible<()> { + failure::ensure!(fd >= 0, "illegal fd value"); + failure::ensure!( + (fd as usize) < FD_SETSIZE, + "fd value is too large to use with select(2) on macos" + ); + Ok(()) + } + + impl FdSet { + pub fn new() -> Self { + unsafe { + let mut set = std::mem::uninitialized(); + FD_ZERO(&mut set); + Self { set } + } + } + + pub fn add(&mut self, fd: RawFd) -> Fallible<()> { + check_fd(fd)?; + unsafe { + FD_SET(fd, &mut self.set); + } + Ok(()) + } + + pub fn contains(&mut self, fd: RawFd) -> bool { + check_fd(fd).unwrap(); + unsafe { FD_ISSET(fd, &mut self.set) } + } + } + + fn materialize(set: &mut Option) -> &mut FdSet { + set.get_or_insert_with(FdSet::new) + } + + fn set_ptr(set: &mut Option) -> *mut fd_set { + set.as_mut() + .map(|s| &mut s.set as *mut _) + .unwrap_or_else(std::ptr::null_mut) + } + + fn is_set(set: &mut Option, fd: RawFd) -> bool { + set.as_mut().map(|s| s.contains(fd)).unwrap_or(false) + } + + pub fn poll_impl(pfd: &mut [pollfd], duration: Option) -> Fallible { + let mut read_set = None; + let mut write_set = None; + let mut exception_set = None; + let mut nfds = 0; + + for item in pfd.iter_mut() { + item.revents = 0; + + nfds = nfds.max(item.fd); + + if item.events & POLLIN != 0 { + materialize(&mut read_set).add(item.fd)?; + } + if item.events & POLLOUT != 0 { + materialize(&mut write_set).add(item.fd)?; + } + materialize(&mut exception_set).add(item.fd)?; + } + + let mut timeout = duration.map(|d| timeval { + tv_sec: d.as_secs() as _, + tv_usec: d.as_micros() as _, + }); + + let res = unsafe { + libc::select( + nfds + 1, + set_ptr(&mut read_set), + set_ptr(&mut write_set), + set_ptr(&mut exception_set), + timeout + .as_mut() + .map(|t| t as *mut _) + .unwrap_or_else(std::ptr::null_mut), + ) + }; + + if res < 0 { + Err(std::io::Error::last_os_error().into()) + } else { + for item in pfd.iter_mut() { + if is_set(&mut read_set, item.fd) { + item.revents |= POLLIN; + } + if is_set(&mut write_set, item.fd) { + item.revents |= POLLOUT; + } + if is_set(&mut exception_set, item.fd) { + item.revents |= POLLERR; + } + } + + Ok(res as usize) + } + } +} + +#[cfg(target_os = "macos")] +#[doc(hidden)] +pub use macos::poll_impl; diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index 61a577e6c..56f17268c 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -12,6 +12,7 @@ use winapi::um::minwinbase::SECURITY_ATTRIBUTES; use winapi::um::namedpipeapi::CreatePipe; use winapi::um::processthreadsapi::*; use winapi::um::winnt::HANDLE; +pub use winapi::um::winsock2::{POLLERR, POLLHUP, POLLIN, POLLOUT, WSAPOLLFD as pollfd}; /// `RawFileDescriptor` is a platform independent type alias for the /// underlying platform file descriptor type. It is primarily useful @@ -192,3 +193,21 @@ impl Pipe { }) } } + +#[doc(hidden)] +pub fn poll_impl(pfd: &mut [pollfd], duration: Option) -> Fallible { + let poll_result = unsafe { + WSAPoll( + pfd.as_mut_ptr(), + pfd.len() as _, + duration + .map(|wait| wait.as_millis() as libc::c_int) + .unwrap_or(-1), + ) + }; + if poll_result < 0 { + Err(std::io::Error::last_os_error()) + } else { + Ok(poll_result as usize) + } +}