Add yanix crate and replace nix with yanix in wasi-common (#649)

* Add yanix crate

This commit adds `yanix` crate as a Unix dependency for `wasi-common`.
`yanix` stands for Yet Another Nix crate and is exactly what the name
suggests: a crate in the spirit of the `nix` crate, but which takes a different
approach, using lower-level interfaces with less abstraction, so that it fits
better with its main use case, implementation of WASI syscalls.

* Replace nix with yanix crate

Having introduced `yanix` crate as an in-house replacement for the
`nix` crate, this commit makes the necessary changes to `wasi-common`
to depend _only_ on `yanix` crate.

* Address review comments

* make `fd_dup` unsafe
* rename `get_fd` to `get_fd_flags`, etc.
* reuse `io::Error::last_os_error()` to get the last errno value

* Address more comments

* make all `fcntl` fns unsafe
* adjust `wasi-common` impl appropriately

* Make all fns operating on RawFd unsafe

* Fix linux build

* Address more comments
This commit is contained in:
Jakub Konka
2019-12-09 01:40:05 +01:00
committed by Dan Gohman
parent ec8144b87d
commit 51f880f625
54 changed files with 2383 additions and 2031 deletions

View File

@@ -0,0 +1,29 @@
use crate::{Errno, Result};
use std::mem::MaybeUninit;
#[derive(Debug, Copy, Clone)]
pub enum ClockId {
Realtime,
Monotonic,
ProcessCPUTime,
ThreadCPUTime,
}
impl ClockId {
pub fn as_raw(&self) -> libc::clockid_t {
match self {
Self::Realtime => libc::CLOCK_REALTIME,
Self::Monotonic => libc::CLOCK_MONOTONIC,
Self::ProcessCPUTime => libc::CLOCK_PROCESS_CPUTIME_ID,
Self::ThreadCPUTime => libc::CLOCK_THREAD_CPUTIME_ID,
}
}
}
pub fn clock_getres(clock_id: ClockId) -> Result<libc::timespec> {
let mut timespec = MaybeUninit::<libc::timespec>::uninit();
Errno::from_success_code(unsafe {
libc::clock_getres(clock_id.as_raw(), timespec.as_mut_ptr())
})?;
Ok(unsafe { timespec.assume_init() })
}

View File

@@ -0,0 +1,162 @@
use crate::{
sys::dir::{iter_impl, EntryImpl},
Errno, Result,
};
use std::os::unix::io::{AsRawFd, IntoRawFd, RawFd};
use std::{ffi::CStr, ops::Deref, ptr};
pub use crate::sys::EntryExt;
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Dir(pub(crate) ptr::NonNull<libc::DIR>);
impl Dir {
/// Takes the ownership of the passed-in descriptor-based object,
/// and creates a new instance of `Dir`.
#[inline]
pub fn from<F: IntoRawFd>(fd: F) -> Result<Self> {
let fd = fd.into_raw_fd();
unsafe { Self::from_fd(fd) }
}
unsafe fn from_fd(fd: RawFd) -> Result<Self> {
let d = libc::fdopendir(fd);
if let Some(d) = ptr::NonNull::new(d) {
Ok(Self(d))
} else {
let e = Errno::last();
libc::close(fd);
Err(e.into())
}
}
/// Set the position of the directory stream, see `seekdir(3)`.
#[cfg(not(target_os = "android"))]
pub fn seek(&mut self, loc: SeekLoc) {
unsafe { libc::seekdir(self.0.as_ptr(), loc.0) }
}
/// Reset directory stream, see `rewinddir(3)`.
pub fn rewind(&mut self) {
unsafe { libc::rewinddir(self.0.as_ptr()) }
}
/// Get the current position in the directory stream.
///
/// If this location is given to `Dir::seek`, the entries up to the previously returned
/// will be omitted and the iteration will start from the currently pending directory entry.
#[cfg(not(target_os = "android"))]
#[allow(dead_code)]
pub fn tell(&self) -> SeekLoc {
let loc = unsafe { libc::telldir(self.0.as_ptr()) };
SeekLoc(loc)
}
}
unsafe impl Send for Dir {}
impl AsRawFd for Dir {
fn as_raw_fd(&self) -> RawFd {
unsafe { libc::dirfd(self.0.as_ptr()) }
}
}
impl Drop for Dir {
fn drop(&mut self) {
unsafe { libc::closedir(self.0.as_ptr()) };
}
}
#[derive(Debug, Copy, Clone)]
pub struct Entry(pub(crate) EntryImpl);
impl Entry {
/// Returns the file name of this directory entry.
pub fn file_name(&self) -> &CStr {
unsafe { CStr::from_ptr(self.0.d_name.as_ptr()) }
}
/// Returns the type of this directory entry.
pub fn file_type(&self) -> FileType {
unsafe { FileType::from_raw(self.0.d_type) }
}
}
#[cfg(not(target_os = "android"))]
#[derive(Clone, Copy, Debug)]
pub struct SeekLoc(libc::c_long);
#[cfg(not(target_os = "android"))]
impl SeekLoc {
pub unsafe fn from_raw(loc: i64) -> Self {
Self(loc.into())
}
pub fn to_raw(&self) -> i64 {
self.0.into()
}
}
#[derive(Clone, Copy, Debug)]
#[repr(u8)]
pub enum FileType {
CharacterDevice = libc::DT_CHR,
Directory = libc::DT_DIR,
BlockDevice = libc::DT_BLK,
RegularFile = libc::DT_REG,
Symlink = libc::DT_LNK,
Fifo = libc::DT_FIFO,
Socket = libc::DT_SOCK,
Unknown = libc::DT_UNKNOWN,
}
impl FileType {
pub unsafe fn from_raw(file_type: u8) -> Self {
match file_type {
libc::DT_CHR => Self::CharacterDevice,
libc::DT_DIR => Self::Directory,
libc::DT_BLK => Self::BlockDevice,
libc::DT_REG => Self::RegularFile,
libc::DT_LNK => Self::Symlink,
libc::DT_SOCK => Self::Socket,
libc::DT_FIFO => Self::Fifo,
/* libc::DT_UNKNOWN */ _ => Self::Unknown,
}
}
pub fn to_raw(&self) -> u8 {
match self {
Self::CharacterDevice => libc::DT_CHR,
Self::Directory => libc::DT_DIR,
Self::BlockDevice => libc::DT_BLK,
Self::RegularFile => libc::DT_REG,
Self::Symlink => libc::DT_LNK,
Self::Socket => libc::DT_SOCK,
Self::Fifo => libc::DT_FIFO,
Self::Unknown => libc::DT_UNKNOWN,
}
}
}
#[derive(Debug)]
pub struct DirIter<T: Deref<Target = Dir>>(T);
impl<T> DirIter<T>
where
T: Deref<Target = Dir>,
{
pub fn new(dir: T) -> Self {
Self(dir)
}
}
impl<T> Iterator for DirIter<T>
where
T: Deref<Target = Dir>,
{
type Item = Result<Entry>;
fn next(&mut self) -> Option<Self::Item> {
unsafe { iter_impl(&self.0).map(|x| x.map(Entry)) }
}
}

View File

@@ -0,0 +1,227 @@
//! Errno-specific for different Unix platforms
use crate::Result;
use std::{fmt, io};
use thiserror::Error;
#[derive(Debug, Copy, Clone, Error, PartialEq, Eq, Hash)]
#[repr(i32)]
pub enum Errno {
EPERM = libc::EPERM,
ENOENT = libc::ENOENT,
ESRCH = libc::ESRCH,
EINTR = libc::EINTR,
EIO = libc::EIO,
ENXIO = libc::ENXIO,
E2BIG = libc::E2BIG,
ENOEXEC = libc::ENOEXEC,
EBADF = libc::EBADF,
ECHILD = libc::ECHILD,
EAGAIN = libc::EAGAIN,
ENOMEM = libc::ENOMEM,
EACCES = libc::EACCES,
EFAULT = libc::EFAULT,
EBUSY = libc::EBUSY,
EEXIST = libc::EEXIST,
EXDEV = libc::EXDEV,
ENODEV = libc::ENODEV,
ENOTDIR = libc::ENOTDIR,
EISDIR = libc::EISDIR,
EINVAL = libc::EINVAL,
ENFILE = libc::ENFILE,
EMFILE = libc::EMFILE,
ENOTTY = libc::ENOTTY,
ETXTBSY = libc::ETXTBSY,
EFBIG = libc::EFBIG,
ENOSPC = libc::ENOSPC,
ESPIPE = libc::ESPIPE,
EROFS = libc::EROFS,
EMLINK = libc::EMLINK,
EPIPE = libc::EPIPE,
EDOM = libc::EDOM,
ERANGE = libc::ERANGE,
EDEADLK = libc::EDEADLK,
ENAMETOOLONG = libc::ENAMETOOLONG,
ENOLCK = libc::ENOLCK,
ENOSYS = libc::ENOSYS,
ENOTEMPTY = libc::ENOTEMPTY,
ELOOP = libc::ELOOP,
ENOMSG = libc::ENOMSG,
EIDRM = libc::EIDRM,
ENOLINK = libc::ENOLINK,
EPROTO = libc::EPROTO,
EMULTIHOP = libc::EMULTIHOP,
EBADMSG = libc::EBADMSG,
EOVERFLOW = libc::EOVERFLOW,
EILSEQ = libc::EILSEQ,
ENOTSOCK = libc::ENOTSOCK,
EDESTADDRREQ = libc::EDESTADDRREQ,
EMSGSIZE = libc::EMSGSIZE,
EPROTOTYPE = libc::EPROTOTYPE,
ENOPROTOOPT = libc::ENOPROTOOPT,
EPROTONOSUPPORT = libc::EPROTONOSUPPORT,
EAFNOSUPPORT = libc::EAFNOSUPPORT,
EADDRINUSE = libc::EADDRINUSE,
EADDRNOTAVAIL = libc::EADDRNOTAVAIL,
ENETDOWN = libc::ENETDOWN,
ENETUNREACH = libc::ENETUNREACH,
ENETRESET = libc::ENETRESET,
ECONNABORTED = libc::ECONNABORTED,
ECONNRESET = libc::ECONNRESET,
ENOBUFS = libc::ENOBUFS,
EISCONN = libc::EISCONN,
ENOTCONN = libc::ENOTCONN,
ETIMEDOUT = libc::ETIMEDOUT,
ECONNREFUSED = libc::ECONNREFUSED,
EHOSTUNREACH = libc::EHOSTUNREACH,
EALREADY = libc::EALREADY,
EINPROGRESS = libc::EINPROGRESS,
ESTALE = libc::ESTALE,
EDQUOT = libc::EDQUOT,
ECANCELED = libc::ECANCELED,
EOWNERDEAD = libc::EOWNERDEAD,
ENOTRECOVERABLE = libc::ENOTRECOVERABLE,
}
impl Errno {
pub fn from_i32(err: i32) -> Self {
match err {
libc::EPERM => Self::EPERM,
libc::ENOENT => Self::ENOENT,
libc::ESRCH => Self::ESRCH,
libc::EINTR => Self::EINTR,
libc::EIO => Self::EIO,
libc::ENXIO => Self::ENXIO,
libc::E2BIG => Self::E2BIG,
libc::ENOEXEC => Self::ENOEXEC,
libc::EBADF => Self::EBADF,
libc::ECHILD => Self::ECHILD,
libc::EAGAIN => Self::EAGAIN,
libc::ENOMEM => Self::ENOMEM,
libc::EACCES => Self::EACCES,
libc::EFAULT => Self::EFAULT,
libc::EBUSY => Self::EBUSY,
libc::EEXIST => Self::EEXIST,
libc::EXDEV => Self::EXDEV,
libc::ENODEV => Self::ENODEV,
libc::ENOTDIR => Self::ENOTDIR,
libc::EISDIR => Self::EISDIR,
libc::EINVAL => Self::EINVAL,
libc::ENFILE => Self::ENFILE,
libc::EMFILE => Self::EMFILE,
libc::ENOTTY => Self::ENOTTY,
libc::ETXTBSY => Self::ETXTBSY,
libc::EFBIG => Self::EFBIG,
libc::ENOSPC => Self::ENOSPC,
libc::ESPIPE => Self::ESPIPE,
libc::EROFS => Self::EROFS,
libc::EMLINK => Self::EMLINK,
libc::EPIPE => Self::EPIPE,
libc::EDOM => Self::EDOM,
libc::ERANGE => Self::ERANGE,
libc::EDEADLK => Self::EDEADLK,
libc::ENAMETOOLONG => Self::ENAMETOOLONG,
libc::ENOLCK => Self::ENOLCK,
libc::ENOSYS => Self::ENOSYS,
libc::ENOTEMPTY => Self::ENOTEMPTY,
libc::ELOOP => Self::ELOOP,
libc::ENOMSG => Self::ENOMSG,
libc::EIDRM => Self::EIDRM,
libc::ENOLINK => Self::ENOLINK,
libc::EPROTO => Self::EPROTO,
libc::EMULTIHOP => Self::EMULTIHOP,
libc::EBADMSG => Self::EBADMSG,
libc::EOVERFLOW => Self::EOVERFLOW,
libc::EILSEQ => Self::EILSEQ,
libc::ENOTSOCK => Self::ENOTSOCK,
libc::EDESTADDRREQ => Self::EDESTADDRREQ,
libc::EMSGSIZE => Self::EMSGSIZE,
libc::EPROTOTYPE => Self::EPROTOTYPE,
libc::ENOPROTOOPT => Self::ENOPROTOOPT,
libc::EPROTONOSUPPORT => Self::EPROTONOSUPPORT,
libc::EAFNOSUPPORT => Self::EAFNOSUPPORT,
libc::EADDRINUSE => Self::EADDRINUSE,
libc::EADDRNOTAVAIL => Self::EADDRNOTAVAIL,
libc::ENETDOWN => Self::ENETDOWN,
libc::ENETUNREACH => Self::ENETUNREACH,
libc::ENETRESET => Self::ENETRESET,
libc::ECONNABORTED => Self::ECONNABORTED,
libc::ECONNRESET => Self::ECONNRESET,
libc::ENOBUFS => Self::ENOBUFS,
libc::EISCONN => Self::EISCONN,
libc::ENOTCONN => Self::ENOTCONN,
libc::ETIMEDOUT => Self::ETIMEDOUT,
libc::ECONNREFUSED => Self::ECONNREFUSED,
libc::EHOSTUNREACH => Self::EHOSTUNREACH,
libc::EALREADY => Self::EALREADY,
libc::EINPROGRESS => Self::EINPROGRESS,
libc::ESTALE => Self::ESTALE,
libc::EDQUOT => Self::EDQUOT,
libc::ECANCELED => Self::ECANCELED,
libc::EOWNERDEAD => Self::EOWNERDEAD,
libc::ENOTRECOVERABLE => Self::ENOTRECOVERABLE,
other => {
log::warn!("Unknown errno: {}", other);
Self::ENOSYS
}
}
}
pub fn last() -> Self {
let errno = io::Error::last_os_error()
.raw_os_error()
.unwrap_or(libc::ENOSYS);
Self::from_i32(errno)
}
pub fn from_success_code<T: IsZero>(t: T) -> Result<()> {
if t.is_zero() {
Ok(())
} else {
Err(Self::last().into())
}
}
pub fn from_result<T: IsMinusOne>(t: T) -> Result<T> {
if t.is_minus_one() {
Err(Self::last().into())
} else {
Ok(t)
}
}
}
impl fmt::Display for Errno {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Errno code: {}", self)
}
}
#[doc(hidden)]
pub trait IsZero {
fn is_zero(&self) -> bool;
}
macro_rules! impl_is_zero {
($($t:ident)*) => ($(impl IsZero for $t {
fn is_zero(&self) -> bool {
*self == 0
}
})*)
}
impl_is_zero! { i32 i64 isize }
#[doc(hidden)]
pub trait IsMinusOne {
fn is_minus_one(&self) -> bool;
}
macro_rules! impl_is_minus_one {
($($t:ident)*) => ($(impl IsMinusOne for $t {
fn is_minus_one(&self) -> bool {
*self == -1
}
})*)
}
impl_is_minus_one! { i32 i64 isize }

View File

@@ -0,0 +1,33 @@
use crate::{
file::{FdFlag, OFlag},
Errno, Result,
};
use std::os::unix::prelude::*;
pub unsafe fn dup_fd(fd: RawFd, close_on_exec: bool) -> Result<RawFd> {
// Both fcntl commands expect a RawFd arg which will specify
// the minimum duplicated RawFd number. In our case, I don't
// think we have to worry about this that much, so passing in
// the RawFd descriptor we want duplicated
Errno::from_result(if close_on_exec {
libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, fd)
} else {
libc::fcntl(fd, libc::F_DUPFD, fd)
})
}
pub unsafe fn get_fd_flags(fd: RawFd) -> Result<FdFlag> {
Errno::from_result(libc::fcntl(fd, libc::F_GETFD)).map(FdFlag::from_bits_truncate)
}
pub unsafe fn set_fd_flags(fd: RawFd, flags: FdFlag) -> Result<()> {
Errno::from_success_code(libc::fcntl(fd, libc::F_SETFD, flags.bits()))
}
pub unsafe fn get_status_flags(fd: RawFd) -> Result<OFlag> {
Errno::from_result(libc::fcntl(fd, libc::F_GETFL)).map(OFlag::from_bits_truncate)
}
pub unsafe fn set_status_flags(fd: RawFd, flags: OFlag) -> Result<()> {
Errno::from_success_code(libc::fcntl(fd, libc::F_SETFL, flags.bits()))
}

View File

@@ -0,0 +1,198 @@
use crate::{Errno, Result};
use bitflags::bitflags;
use std::{
convert::TryInto,
ffi::{CString, OsStr, OsString},
os::unix::prelude::*,
};
pub use crate::sys::file::*;
bitflags! {
pub struct FdFlag: libc::c_int {
const CLOEXEC = libc::FD_CLOEXEC;
}
}
bitflags! {
pub struct AtFlag: libc::c_int {
const REMOVEDIR = libc::AT_REMOVEDIR;
const SYMLINK_FOLLOW = libc::AT_SYMLINK_FOLLOW;
const SYMLINK_NOFOLLOW = libc::AT_SYMLINK_NOFOLLOW;
}
}
bitflags! {
pub struct Mode: libc::mode_t {
const IRWXU = libc::S_IRWXU;
const IRUSR = libc::S_IRUSR;
const IWUSR = libc::S_IWUSR;
const IXUSR = libc::S_IXUSR;
const IRWXG = libc::S_IRWXG;
const IRGRP = libc::S_IRGRP;
const IWGRP = libc::S_IWGRP;
const IXGRP = libc::S_IXGRP;
const IRWXO = libc::S_IRWXO;
const IROTH = libc::S_IROTH;
const IWOTH = libc::S_IWOTH;
const IXOTH = libc::S_IXOTH;
const ISUID = libc::S_ISUID as libc::mode_t;
const ISGID = libc::S_ISGID as libc::mode_t;
const ISVTX = libc::S_ISVTX as libc::mode_t;
}
}
bitflags! {
pub struct OFlag: libc::c_int {
const ACCMODE = libc::O_ACCMODE;
const APPEND = libc::O_APPEND;
const CREAT = libc::O_CREAT;
const DIRECTORY = libc::O_DIRECTORY;
#[cfg(any(target_os = "android",
target_os = "ios",
target_os = "linux",
target_os = "macos",
target_os = "netbsd",
target_os = "openbsd",
target_os = "emscripten"))]
const DSYNC = libc::O_DSYNC;
const EXCL = libc::O_EXCL;
#[cfg(any(target_os = "dragonfly",
target_os = "freebsd",
target_os = "ios",
all(target_os = "linux", not(target_env = "musl")),
target_os = "macos",
target_os = "netbsd",
target_os = "openbsd"))]
const FSYNC = libc::O_FSYNC;
const NOFOLLOW = libc::O_NOFOLLOW;
const NONBLOCK = libc::O_NONBLOCK;
const RDONLY = libc::O_RDONLY;
const WRONLY = libc::O_WRONLY;
const RDWR = libc::O_RDWR;
#[cfg(any(target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
target_os = "emscripten"))]
const RSYNC = libc::O_RSYNC;
const SYNC = libc::O_SYNC;
const TRUNC = libc::O_TRUNC;
}
}
bitflags! {
pub struct SFlag: libc::mode_t {
const IFIFO = libc::S_IFIFO;
const IFCHR = libc::S_IFCHR;
const IFDIR = libc::S_IFDIR;
const IFBLK = libc::S_IFBLK;
const IFREG = libc::S_IFREG;
const IFLNK = libc::S_IFLNK;
const IFSOCK = libc::S_IFSOCK;
const IFMT = libc::S_IFMT;
}
}
pub unsafe fn openat<P: AsRef<OsStr>>(
dirfd: RawFd,
path: P,
oflag: OFlag,
mode: Mode,
) -> Result<RawFd> {
let path = CString::new(path.as_ref().as_bytes())?;
Errno::from_result(libc::openat(
dirfd,
path.as_ptr(),
oflag.bits(),
libc::c_uint::from(mode.bits()),
))
}
pub unsafe fn readlinkat<P: AsRef<OsStr>>(dirfd: RawFd, path: P) -> Result<OsString> {
let path = CString::new(path.as_ref().as_bytes())?;
let buffer = &mut [0u8; libc::PATH_MAX as usize + 1];
Errno::from_result(libc::readlinkat(
dirfd,
path.as_ptr(),
buffer.as_mut_ptr() as *mut _,
buffer.len(),
))
.and_then(|nread| {
let link = OsStr::from_bytes(&buffer[0..nread.try_into()?]);
Ok(link.into())
})
}
pub unsafe fn mkdirat<P: AsRef<OsStr>>(dirfd: RawFd, path: P, mode: Mode) -> Result<()> {
let path = CString::new(path.as_ref().as_bytes())?;
Errno::from_success_code(libc::mkdirat(dirfd, path.as_ptr(), mode.bits()))
}
pub unsafe fn linkat<P: AsRef<OsStr>>(
old_dirfd: RawFd,
old_path: P,
new_dirfd: RawFd,
new_path: P,
flags: AtFlag,
) -> Result<()> {
let old_path = CString::new(old_path.as_ref().as_bytes())?;
let new_path = CString::new(new_path.as_ref().as_bytes())?;
Errno::from_success_code(libc::linkat(
old_dirfd,
old_path.as_ptr(),
new_dirfd,
new_path.as_ptr(),
flags.bits(),
))
}
pub unsafe fn unlinkat<P: AsRef<OsStr>>(dirfd: RawFd, path: P, flags: AtFlag) -> Result<()> {
let path = CString::new(path.as_ref().as_bytes())?;
Errno::from_success_code(libc::unlinkat(dirfd, path.as_ptr(), flags.bits()))
}
pub unsafe fn renameat<P: AsRef<OsStr>>(
old_dirfd: RawFd,
old_path: P,
new_dirfd: RawFd,
new_path: P,
) -> Result<()> {
let old_path = CString::new(old_path.as_ref().as_bytes())?;
let new_path = CString::new(new_path.as_ref().as_bytes())?;
Errno::from_success_code(libc::renameat(
old_dirfd,
old_path.as_ptr(),
new_dirfd,
new_path.as_ptr(),
))
}
pub unsafe fn symlinkat<P: AsRef<OsStr>>(old_path: P, new_dirfd: RawFd, new_path: P) -> Result<()> {
let old_path = CString::new(old_path.as_ref().as_bytes())?;
let new_path = CString::new(new_path.as_ref().as_bytes())?;
Errno::from_success_code(libc::symlinkat(
old_path.as_ptr(),
new_dirfd,
new_path.as_ptr(),
))
}
pub unsafe fn fstatat<P: AsRef<OsStr>>(dirfd: RawFd, path: P, flags: AtFlag) -> Result<libc::stat> {
use std::mem::MaybeUninit;
let path = CString::new(path.as_ref().as_bytes())?;
let mut filestat = MaybeUninit::<libc::stat>::uninit();
Errno::from_result(libc::fstatat(
dirfd,
path.as_ptr(),
filestat.as_mut_ptr(),
flags.bits(),
))?;
Ok(filestat.assume_init())
}
/// `fionread()` function, equivalent to `ioctl(fd, FIONREAD, *bytes)`.
pub unsafe fn fionread(fd: RawFd) -> Result<usize> {
let mut nread: libc::c_int = 0;
Errno::from_result(libc::ioctl(fd, libc::FIONREAD, &mut nread as *mut _))?;
Ok(nread.try_into()?)
}

View File

@@ -0,0 +1,40 @@
//! `yanix` stands for Yet Another Nix crate, and, well, it is simply
//! a yet another crate in the spirit of the [nix] crate. As such,
//! this crate is inspired by the original `nix` crate, however,
//! it takes a different approach, using lower-level interfaces with
//! less abstraction, so that it fits better with its main use case
//! which is our WASI implementation, [wasi-common].
//!
//! [nix]: https://github.com/nix-rust/nix
//! [wasi-common]: https://github.com/bytecodealliance/wasmtime/tree/master/crates/wasi-common
#![cfg(unix)]
pub mod clock;
pub mod dir;
pub mod fcntl;
pub mod file;
pub mod poll;
pub mod socket;
mod errno;
mod sys;
pub mod fadvise {
pub use super::sys::fadvise::*;
}
pub use errno::Errno;
use std::{ffi, num};
use thiserror::Error;
pub type Result<T> = std::result::Result<T, YanixError>;
#[derive(Debug, Error)]
pub enum YanixError {
#[error("raw os error {0}")]
Errno(#[from] Errno),
#[error("a nul byte was not found in the expected position")]
NulError(#[from] ffi::NulError),
#[error("integral type conversion failed")]
TryFromIntError(#[from] num::TryFromIntError),
}

View File

@@ -0,0 +1,47 @@
use crate::{Errno, Result};
use bitflags::bitflags;
use std::{convert::TryInto, os::unix::prelude::*};
bitflags! {
pub struct PollFlags: libc::c_short {
const POLLIN = libc::POLLIN;
const POLLPRI = libc::POLLPRI;
const POLLOUT = libc::POLLOUT;
const POLLRDNORM = libc::POLLRDNORM;
const POLLWRNORM = libc::POLLWRNORM;
const POLLRDBAND = libc::POLLRDBAND;
const POLLWRBAND = libc::POLLWRBAND;
const POLLERR = libc::POLLERR;
const POLLHUP = libc::POLLHUP;
const POLLNVAL = libc::POLLNVAL;
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[repr(C)]
pub struct PollFd(libc::pollfd);
impl PollFd {
pub unsafe fn new(fd: RawFd, events: PollFlags) -> Self {
Self(libc::pollfd {
fd,
events: events.bits(),
revents: PollFlags::empty().bits(),
})
}
pub fn revents(self) -> Option<PollFlags> {
PollFlags::from_bits(self.0.revents)
}
}
pub fn poll(fds: &mut [PollFd], timeout: i32) -> Result<usize> {
Errno::from_result(unsafe {
libc::poll(
fds.as_mut_ptr() as *mut libc::pollfd,
fds.len() as libc::nfds_t,
timeout,
)
})
.and_then(|nready| nready.try_into().map_err(Into::into))
}

View File

@@ -0,0 +1,31 @@
use crate::{Errno, Result};
use std::os::unix::prelude::*;
#[derive(Debug, Clone, Copy)]
#[repr(i32)]
pub enum SockType {
Stream = libc::SOCK_STREAM,
Datagram = libc::SOCK_DGRAM,
SeqPacket = libc::SOCK_SEQPACKET,
Raw = libc::SOCK_RAW,
Rdm = libc::SOCK_RDM,
}
pub unsafe fn get_socket_type(fd: RawFd) -> Result<SockType> {
use std::mem::{self, MaybeUninit};
let mut buffer = MaybeUninit::<SockType>::zeroed().assume_init();
let mut out_len = mem::size_of::<SockType>() as libc::socklen_t;
Errno::from_success_code(libc::getsockopt(
fd,
libc::SOL_SOCKET,
libc::SO_TYPE,
&mut buffer as *mut SockType as *mut _,
&mut out_len,
))?;
assert_eq!(
out_len as usize,
mem::size_of::<SockType>(),
"invalid SockType value"
);
Ok(buffer)
}

View File

@@ -0,0 +1,52 @@
use crate::{
dir::{Dir, Entry, EntryExt, SeekLoc},
Errno, Result,
};
use std::ops::Deref;
#[derive(Copy, Clone, Debug)]
pub(crate) struct EntryImpl {
dirent: libc::dirent,
loc: SeekLoc,
}
impl Deref for EntryImpl {
type Target = libc::dirent;
fn deref(&self) -> &Self::Target {
&self.dirent
}
}
pub(crate) unsafe fn iter_impl(dir: &Dir) -> Option<Result<EntryImpl>> {
let errno = Errno::last();
let dirent = libc::readdir(dir.0.as_ptr());
if dirent.is_null() {
if errno != Errno::last() {
// TODO This should be verified on different BSD-flavours.
//
// According to 4.3BSD/POSIX.1-2001 man pages, there was an error
// if the errno value has changed at some point during the sequence
// of readdir calls.
Some(Err(Errno::last().into()))
} else {
// Not an error. We've simply reached the end of the stream.
None
}
} else {
Some(Ok(EntryImpl {
dirent: *dirent,
loc: dir.tell(),
}))
}
}
impl EntryExt for Entry {
fn ino(&self) -> u64 {
self.0.d_ino.into()
}
fn seek_loc(&self) -> SeekLoc {
self.0.loc
}
}

View File

@@ -0,0 +1,51 @@
use crate::{Errno, Result};
use std::{convert::TryInto, os::unix::prelude::*};
#[derive(Debug, Copy, Clone)]
#[repr(i32)]
pub enum PosixFadviseAdvice {
Normal,
Sequential,
Random,
NoReuse,
WillNeed,
DontNeed,
}
// There's no posix_fadvise on macOS but we can use fcntl with F_RDADVISE
// command instead to achieve the same
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub unsafe fn posix_fadvise(
fd: RawFd,
offset: libc::off_t,
len: libc::off_t,
_advice: PosixFadviseAdvice,
) -> Result<()> {
// From macOS man pages:
// F_RDADVISE Issue an advisory read async with no copy to user.
//
// The F_RDADVISE command operates on the following structure which holds information passed from
// the user to the system:
//
// struct radvisory {
// off_t ra_offset; /* offset into the file */
// int ra_count; /* size of the read */
// };
let advisory = libc::radvisory {
ra_offset: offset,
ra_count: len.try_into()?,
};
Errno::from_success_code(libc::fcntl(fd, libc::F_RDADVISE, &advisory))
}
// TODO
// On non-macOS BSD's we leave it as no-op for now
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
pub unsafe fn posix_fadvise(
_fd: RawFd,
_offset: libc::off_t,
_len: libc::off_t,
_advice: PosixFadviseAdvice,
) -> Result<()> {
Ok(())
}

View File

@@ -0,0 +1,18 @@
use crate::{Errno, Result};
use std::os::unix::prelude::*;
pub unsafe fn isatty(fd: RawFd) -> Result<bool> {
let res = libc::isatty(fd);
if res == 1 {
// isatty() returns 1 if fd is an open file descriptor referring to a terminal...
Ok(true)
} else {
// ... otherwise 0 is returned, and errno is set to indicate the error.
let errno = Errno::last();
if errno == Errno::ENOTTY {
Ok(false)
} else {
Err(errno.into())
}
}
}

View File

@@ -0,0 +1,3 @@
pub(crate) mod dir;
pub(crate) mod fadvise;
pub(crate) mod file;

View File

@@ -0,0 +1,46 @@
use crate::{
dir::{Dir, Entry, EntryExt, SeekLoc},
Errno, Result,
};
use std::ops::Deref;
#[derive(Copy, Clone, Debug)]
pub(crate) struct EntryImpl(libc::dirent64);
impl Deref for EntryImpl {
type Target = libc::dirent64;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl EntryExt for Entry {
fn ino(&self) -> u64 {
self.0.d_ino.into()
}
fn seek_loc(&self) -> SeekLoc {
unsafe { SeekLoc::from_raw(self.0.d_off) }
}
}
pub(crate) unsafe fn iter_impl(dir: &Dir) -> Option<Result<EntryImpl>> {
let errno = Errno::last();
let dirent = libc::readdir64(dir.0.as_ptr());
if dirent.is_null() {
if errno != Errno::last() {
// TODO This should be verified on different BSD-flavours.
//
// According to 4.3BSD/POSIX.1-2001 man pages, there was an error
// if the errno value has changed at some point during the sequence
// of readdir calls.
Some(Err(Errno::last().into()))
} else {
// Not an error. We've simply reached the end of the stream.
None
}
} else {
Some(Ok(EntryImpl(*dirent)))
}
}

View File

@@ -0,0 +1,22 @@
use crate::{Errno, Result};
use std::os::unix::prelude::*;
#[derive(Debug, Copy, Clone)]
#[repr(i32)]
pub enum PosixFadviseAdvice {
Normal = libc::POSIX_FADV_NORMAL,
Sequential = libc::POSIX_FADV_SEQUENTIAL,
Random = libc::POSIX_FADV_RANDOM,
NoReuse = libc::POSIX_FADV_NOREUSE,
WillNeed = libc::POSIX_FADV_WILLNEED,
DontNeed = libc::POSIX_FADV_DONTNEED,
}
pub unsafe fn posix_fadvise(
fd: RawFd,
offset: libc::off_t,
len: libc::off_t,
advice: PosixFadviseAdvice,
) -> Result<()> {
Errno::from_success_code(libc::posix_fadvise(fd, offset, len, advice as libc::c_int))
}

View File

@@ -0,0 +1,23 @@
use crate::{Errno, Result};
use std::os::unix::prelude::*;
pub unsafe fn isatty(fd: RawFd) -> Result<bool> {
let res = libc::isatty(fd);
if res == 1 {
// isatty() returns 1 if fd is an open file descriptor referring to a terminal...
Ok(true)
} else {
// ... otherwise 0 is returned, and errno is set to indicate the error.
let errno = Errno::last();
// While POSIX specifies ENOTTY if the passed
// fd is *not* a tty, on Linux, some implementations
// may return EINVAL instead.
//
// https://linux.die.net/man/3/isatty
if errno == Errno::ENOTTY || errno == Errno::EINVAL {
Ok(false)
} else {
Err(errno.into())
}
}
}

View File

@@ -0,0 +1,3 @@
pub(crate) mod dir;
pub(crate) mod fadvise;
pub(crate) mod file;

View File

@@ -0,0 +1,27 @@
use crate::dir::SeekLoc;
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(any(target_os = "linux",
target_os = "android",
target_os = "emscripten"))] {
mod linux;
pub(crate) use self::linux::*;
}
else if #[cfg(any(target_os = "macos",
target_os = "ios",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "dragonfly"))] {
mod bsd;
pub(crate) use self::bsd::*;
} else {
compile_error!("yanix doesn't compile for this platform yet");
}
}
pub trait EntryExt {
fn ino(&self) -> u64;
fn seek_loc(&self) -> SeekLoc;
}