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

@@ -8,7 +8,7 @@ cfg_if! {
pub use self::unix::preopen_dir;
pub(crate) fn errno_from_host(err: i32) -> wasi::__wasi_errno_t {
host_impl::errno_from_nix(nix::errno::from_i32(err)).as_wasi_errno()
host_impl::errno_from_nix(yanix::Errno::from_i32(err)).as_wasi_errno()
}
} else if #[cfg(windows)] {
mod windows;

View File

@@ -1,27 +1,22 @@
use super::super::dir::{Dir, Entry, SeekLoc};
use super::oshandle::OsHandle;
use crate::hostcalls_impl::{Dirent, PathGet};
use crate::hostcalls_impl::PathGet;
use crate::sys::host_impl;
use crate::sys::unix::str_to_cstring;
use crate::{wasi, Error, Result};
use nix::libc;
use std::convert::TryInto;
use std::fs::File;
use crate::{Error, Result};
use std::os::unix::prelude::AsRawFd;
use std::sync::MutexGuard;
pub(crate) fn path_unlink_file(resolved: PathGet) -> Result<()> {
use nix::errno;
use nix::libc::unlinkat;
let path_cstr = str_to_cstring(resolved.path())?;
// nix doesn't expose unlinkat() yet
match unsafe { unlinkat(resolved.dirfd().as_raw_fd(), path_cstr.as_ptr(), 0) } {
0 => Ok(()),
_ => {
let mut e = errno::Errno::last();
use yanix::{
file::{unlinkat, AtFlag},
Errno, YanixError,
};
unsafe {
unlinkat(
resolved.dirfd().as_raw_fd(),
resolved.path(),
AtFlag::empty(),
)
}
.map_err(|err| {
if let YanixError::Errno(mut errno) = err {
// Non-Linux implementations may return EPERM when attempting to remove a
// directory without REMOVEDIR. While that's what POSIX specifies, it's
// less useful. Adjust this to EISDIR. It doesn't matter that this is not
@@ -29,84 +24,84 @@ pub(crate) fn path_unlink_file(resolved: PathGet) -> Result<()> {
// is created before fstatat sees it, we're racing with that change anyway
// and unlinkat could have legitimately seen the directory if the race had
// turned out differently.
use nix::fcntl::AtFlags;
use nix::sys::stat::{fstatat, SFlag};
use yanix::file::{fstatat, SFlag};
if e == errno::Errno::EPERM {
if let Ok(stat) = fstatat(
resolved.dirfd().as_raw_fd(),
resolved.path(),
AtFlags::AT_SYMLINK_NOFOLLOW,
) {
if SFlag::from_bits_truncate(stat.st_mode).contains(SFlag::S_IFDIR) {
e = errno::Errno::EISDIR;
if errno == Errno::EPERM {
if let Ok(stat) = unsafe {
fstatat(
resolved.dirfd().as_raw_fd(),
resolved.path(),
AtFlag::SYMLINK_NOFOLLOW,
)
} {
if SFlag::from_bits_truncate(stat.st_mode).contains(SFlag::IFDIR) {
errno = Errno::EISDIR;
}
} else {
e = errno::Errno::last();
errno = Errno::last();
}
}
Err(host_impl::errno_from_nix(e))
errno.into()
} else {
err
}
}
})
.map_err(Into::into)
}
pub(crate) fn path_symlink(old_path: &str, resolved: PathGet) -> Result<()> {
use nix::{errno::Errno, fcntl::AtFlags, libc::symlinkat, sys::stat::fstatat};
let old_path_cstr = str_to_cstring(old_path)?;
let new_path_cstr = str_to_cstring(resolved.path())?;
use yanix::{
file::{fstatat, symlinkat, AtFlag},
Errno, YanixError,
};
log::debug!("path_symlink old_path = {:?}", old_path);
log::debug!("path_symlink resolved = {:?}", resolved);
let res = unsafe {
symlinkat(
old_path_cstr.as_ptr(),
resolved.dirfd().as_raw_fd(),
new_path_cstr.as_ptr(),
)
};
if res != 0 {
match Errno::last() {
Errno::ENOTDIR => {
// On BSD, symlinkat returns ENOTDIR when it should in fact
// return a EEXIST. It seems that it gets confused with by
// the trailing slash in the target path. Thus, we strip
// the trailing slash and check if the path exists, and
// adjust the error code appropriately.
let new_path = resolved.path().trim_end_matches('/');
if let Ok(_) = fstatat(
resolved.dirfd().as_raw_fd(),
new_path,
AtFlags::AT_SYMLINK_NOFOLLOW,
) {
Err(Error::EEXIST)
} else {
Err(Error::ENOTDIR)
unsafe { symlinkat(old_path, resolved.dirfd().as_raw_fd(), resolved.path()) }.or_else(|err| {
if let YanixError::Errno(errno) = err {
match errno {
Errno::ENOTDIR => {
// On BSD, symlinkat returns ENOTDIR when it should in fact
// return a EEXIST. It seems that it gets confused with by
// the trailing slash in the target path. Thus, we strip
// the trailing slash and check if the path exists, and
// adjust the error code appropriately.
let new_path = resolved.path().trim_end_matches('/');
if let Ok(_) = unsafe {
fstatat(
resolved.dirfd().as_raw_fd(),
new_path,
AtFlag::SYMLINK_NOFOLLOW,
)
} {
Err(Error::EEXIST)
} else {
Err(Error::ENOTDIR)
}
}
x => Err(host_impl::errno_from_nix(x)),
}
x => Err(host_impl::errno_from_nix(x)),
} else {
Err(err.into())
}
} else {
Ok(())
}
})
}
pub(crate) fn path_rename(resolved_old: PathGet, resolved_new: PathGet) -> Result<()> {
use nix::{errno::Errno, fcntl::AtFlags, libc::renameat, sys::stat::fstatat};
let old_path_cstr = str_to_cstring(resolved_old.path())?;
let new_path_cstr = str_to_cstring(resolved_new.path())?;
let res = unsafe {
use yanix::{
file::{fstatat, renameat, AtFlag},
Errno, YanixError,
};
unsafe {
renameat(
resolved_old.dirfd().as_raw_fd(),
old_path_cstr.as_ptr(),
resolved_old.path(),
resolved_new.dirfd().as_raw_fd(),
new_path_cstr.as_ptr(),
resolved_new.path(),
)
};
if res != 0 {
}
.or_else(|err| {
// Currently, this is verified to be correct on macOS, where
// ENOENT can be returned in case when we try to rename a file
// into a name with a trailing slash. On macOS, if the latter does
@@ -116,175 +111,60 @@ pub(crate) fn path_rename(resolved_old: PathGet, resolved_new: PathGet) -> Resul
//
// TODO
// Verify on other BSD-based OSes.
match Errno::last() {
Errno::ENOENT => {
// check if the source path exists
if let Ok(_) = fstatat(
resolved_old.dirfd().as_raw_fd(),
resolved_old.path(),
AtFlags::AT_SYMLINK_NOFOLLOW,
) {
// check if destination contains a trailing slash
if resolved_new.path().contains('/') {
Err(Error::ENOTDIR)
if let YanixError::Errno(errno) = err {
match errno {
Errno::ENOENT => {
// check if the source path exists
if let Ok(_) = unsafe {
fstatat(
resolved_old.dirfd().as_raw_fd(),
resolved_old.path(),
AtFlag::SYMLINK_NOFOLLOW,
)
} {
// check if destination contains a trailing slash
if resolved_new.path().contains('/') {
Err(Error::ENOTDIR)
} else {
Err(Error::ENOENT)
}
} else {
Err(Error::ENOENT)
}
} else {
Err(Error::ENOENT)
}
x => Err(host_impl::errno_from_nix(x)),
}
x => Err(host_impl::errno_from_nix(x)),
} else {
Err(err.into())
}
} else {
Ok(())
}
})
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) fn fd_advise(
file: &File,
advice: wasi::__wasi_advice_t,
offset: wasi::__wasi_filesize_t,
len: wasi::__wasi_filesize_t,
) -> Result<()> {
use nix::errno::Errno;
pub(crate) mod fd_readdir_impl {
use crate::sys::fdentry_impl::OsHandle;
use crate::Result;
use std::sync::{Mutex, MutexGuard};
use yanix::dir::Dir;
match advice {
wasi::__WASI_ADVICE_DONTNEED => return Ok(()),
// unfortunately, the advisory syscall in macOS doesn't take any flags of this
// sort (unlike on Linux), hence, they are left here as a noop
wasi::__WASI_ADVICE_SEQUENTIAL
| wasi::__WASI_ADVICE_WILLNEED
| wasi::__WASI_ADVICE_NOREUSE
| wasi::__WASI_ADVICE_RANDOM
| wasi::__WASI_ADVICE_NORMAL => {}
_ => return Err(Error::EINVAL),
}
// 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.try_into()?,
ra_count: len.try_into()?,
};
let res = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_RDADVISE, &advisory) };
Errno::result(res).map(|_| ()).map_err(Error::from)
}
// TODO
// It seems that at least some BSDs do support `posix_fadvise`,
// so we should investigate further.
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
pub(crate) fn fd_advise(
_file: &File,
advice: wasi::__wasi_advice_t,
_offset: wasi::__wasi_filesize_t,
_len: wasi::__wasi_filesize_t,
) -> Result<()> {
match advice {
wasi::__WASI_ADVICE_DONTNEED
| wasi::__WASI_ADVICE_SEQUENTIAL
| wasi::__WASI_ADVICE_WILLNEED
| wasi::__WASI_ADVICE_NOREUSE
| wasi::__WASI_ADVICE_RANDOM
| wasi::__WASI_ADVICE_NORMAL => {}
_ => return Err(Error::EINVAL),
}
Ok(())
}
pub(crate) fn fd_readdir<'a>(
os_handle: &'a mut OsHandle,
cookie: wasi::__wasi_dircookie_t,
) -> Result<impl Iterator<Item = Result<Dirent>> + 'a> {
use std::sync::Mutex;
let dir = match os_handle.dir {
Some(ref mut dir) => dir,
None => {
// We need to duplicate the fd, because `opendir(3)`:
// Upon successful return from fdopendir(), the file descriptor is under
// control of the system, and if any attempt is made to close the file
// descriptor, or to modify the state of the associated description other
// than by means of closedir(), readdir(), readdir_r(), or rewinddir(),
// the behaviour is undefined.
let fd = (*os_handle).try_clone()?;
let dir = Dir::from(fd)?;
os_handle.dir.get_or_insert(Mutex::new(dir))
}
};
let mut dir = dir.lock().unwrap();
// Seek if needed. Unless cookie is wasi::__WASI_DIRCOOKIE_START,
// new items may not be returned to the caller.
if cookie == wasi::__WASI_DIRCOOKIE_START {
log::trace!(" | fd_readdir: doing rewinddir");
dir.rewind();
} else {
log::trace!(" | fd_readdir: doing seekdir to {}", cookie);
let loc = unsafe { SeekLoc::from_raw(cookie as i64) };
dir.seek(loc);
}
Ok(DirIter(dir).map(|entry| {
let (entry, loc): (Entry, SeekLoc) = entry?;
Ok(Dirent {
name: entry
// TODO can we reuse path_from_host for CStr?
.file_name()
.to_str()?
.to_owned(),
ino: entry.ino(),
ftype: entry.file_type().into(),
// Set cookie manually:
// * on macOS d_seekoff is not set for some reason
// * on FreeBSD d_seekoff doesn't exist; there is d_off but it is
// not equivalent to the value read from telldir call
cookie: loc.to_raw().try_into()?,
})
}))
}
struct DirIter<'a>(MutexGuard<'a, Dir>);
impl<'a> Iterator for DirIter<'a> {
type Item = nix::Result<(Entry, SeekLoc)>;
fn next(&mut self) -> Option<Self::Item> {
use libc::readdir;
use nix::{errno::Errno, Error};
unsafe {
let errno = Errno::last();
let ent = readdir((self.0).0.as_ptr());
if ent.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(Error::last()))
} else {
// Not an error. We've simply reached the end of the stream.
None
}
} else {
let entry = Entry(*ent);
let loc = self.0.tell();
Some(Ok((entry, loc)))
pub(crate) fn get_dir_from_os_handle<'a>(
os_handle: &'a mut OsHandle,
) -> Result<MutexGuard<'a, Dir>> {
let dir = match os_handle.dir {
Some(ref mut dir) => dir,
None => {
// We need to duplicate the fd, because `opendir(3)`:
// Upon successful return from fdopendir(), the file descriptor is under
// control of the system, and if any attempt is made to close the file
// descriptor, or to modify the state of the associated description other
// than by means of closedir(), readdir(), readdir_r(), or rewinddir(),
// the behaviour is undefined.
let fd = (*os_handle).try_clone()?;
let dir = Dir::from(fd)?;
os_handle.dir.get_or_insert(Mutex::new(dir))
}
}
};
// Note that from this point on, until the end of the parent scope (i.e., enclosing this
// function), we're locking the `Dir` member of this `OsHandle`.
Ok(dir.lock().unwrap())
}
}

View File

@@ -2,36 +2,17 @@ pub(crate) mod filetime;
pub(crate) mod hostcalls_impl;
pub(crate) mod oshandle;
pub(crate) mod fdentry_impl {
use crate::{sys::host_impl, Result};
use std::os::unix::prelude::AsRawFd;
pub(crate) unsafe fn isatty(fd: &impl AsRawFd) -> Result<bool> {
let res = libc::isatty(fd.as_raw_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.
match nix::errno::Errno::last() {
nix::errno::Errno::ENOTTY => Ok(false),
x => Err(host_impl::errno_from_nix(x)),
}
}
}
}
pub(crate) mod host_impl {
use crate::{wasi, Result};
use std::convert::TryFrom;
pub(crate) const O_RSYNC: nix::fcntl::OFlag = nix::fcntl::OFlag::O_SYNC;
pub(crate) const O_RSYNC: yanix::file::OFlag = yanix::file::OFlag::SYNC;
pub(crate) fn stdev_from_nix(dev: nix::libc::dev_t) -> Result<wasi::__wasi_device_t> {
pub(crate) fn stdev_from_nix(dev: libc::dev_t) -> Result<wasi::__wasi_device_t> {
wasi::__wasi_device_t::try_from(dev).map_err(Into::into)
}
pub(crate) fn stino_from_nix(ino: nix::libc::ino_t) -> Result<wasi::__wasi_inode_t> {
pub(crate) fn stino_from_nix(ino: libc::ino_t) -> Result<wasi::__wasi_inode_t> {
wasi::__wasi_device_t::try_from(ino).map_err(Into::into)
}
}

View File

@@ -1,8 +1,8 @@
use super::super::dir::Dir;
use std::fs;
use std::ops::{Deref, DerefMut};
use std::os::unix::prelude::{AsRawFd, RawFd};
use std::sync::Mutex;
use yanix::dir::Dir;
#[derive(Debug)]
pub(crate) struct OsHandle {

View File

@@ -1,174 +0,0 @@
// Based on src/dir.rs from nix
use crate::hostcalls_impl::FileType;
use libc;
use nix::{Error, Result};
use std::os::unix::io::{AsRawFd, IntoRawFd, RawFd};
use std::{ffi, ptr};
#[cfg(target_os = "linux")]
use libc::dirent64 as dirent;
#[cfg(not(target_os = "linux",))]
use libc::dirent;
/// An open directory.
///
/// This is a lower-level interface than `std::fs::ReadDir`. Notable differences:
/// * can be opened from a file descriptor (as returned by `openat`, perhaps before knowing
/// if the path represents a file or directory).
/// * implements `AsRawFd`, so it can be passed to `fstat`, `openat`, etc.
/// The file descriptor continues to be owned by the `Dir`, so callers must not keep a `RawFd`
/// after the `Dir` is dropped.
/// * can be iterated through multiple times without closing and reopening the file
/// descriptor. Each iteration rewinds when finished.
/// * returns entries for `.` (current directory) and `..` (parent directory).
/// * returns entries' names as a `CStr` (no allocation or conversion beyond whatever libc
/// does).
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub(crate) struct Dir(pub(crate) ptr::NonNull<libc::DIR>);
impl Dir {
/// Converts from a descriptor-based object, closing the descriptor on success or failure.
#[inline]
pub(crate) fn from<F: IntoRawFd>(fd: F) -> Result<Self> {
unsafe { Self::from_fd(fd.into_raw_fd()) }
}
/// Converts from a file descriptor, closing it on success or failure.
unsafe fn from_fd(fd: RawFd) -> Result<Self> {
let d = libc::fdopendir(fd);
if d.is_null() {
let e = Error::last();
libc::close(fd);
return Err(e);
};
// Always guaranteed to be non-null by the previous check
Ok(Self(ptr::NonNull::new(d).unwrap()))
}
/// Set the position of the directory stream, see `seekdir(3)`.
#[cfg(not(target_os = "android"))]
pub(crate) fn seek(&mut self, loc: SeekLoc) {
unsafe { libc::seekdir(self.0.as_ptr(), loc.0) }
}
/// Reset directory stream, see `rewinddir(3)`.
pub(crate) 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(crate) fn tell(&self) -> SeekLoc {
let loc = unsafe { libc::telldir(self.0.as_ptr()) };
SeekLoc(loc)
}
}
// `Dir` is not `Sync`. With the current implementation, it could be, but according to
// https://www.gnu.org/software/libc/manual/html_node/Reading_002fClosing-Directory.html,
// future versions of POSIX are likely to obsolete `readdir_r` and specify that it's unsafe to
// call `readdir` simultaneously from multiple threads.
//
// `Dir` is safe to pass from one thread to another, as it's not reference-counted.
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()) };
}
}
/// A directory entry, similar to `std::fs::DirEntry`.
///
/// Note that unlike the std version, this may represent the `.` or `..` entries.
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
#[repr(transparent)]
pub(crate) struct Entry(pub(crate) dirent);
pub(crate) type Type = FileType;
impl Entry {
/// Returns the inode number (`d_ino`) of the underlying `dirent`.
#[cfg(any(
target_os = "android",
target_os = "emscripten",
target_os = "fuchsia",
target_os = "haiku",
target_os = "ios",
target_os = "l4re",
target_os = "linux",
target_os = "macos",
target_os = "solaris"
))]
pub(crate) fn ino(&self) -> u64 {
self.0.d_ino.into()
}
/// Returns the inode number (`d_fileno`) of the underlying `dirent`.
#[cfg(not(any(
target_os = "android",
target_os = "emscripten",
target_os = "fuchsia",
target_os = "haiku",
target_os = "ios",
target_os = "l4re",
target_os = "linux",
target_os = "macos",
target_os = "solaris"
)))]
pub(crate) fn ino(&self) -> u64 {
u64::from(self.0.d_fileno)
}
/// Returns the bare file name of this directory entry without any other leading path component.
pub(crate) fn file_name(&self) -> &ffi::CStr {
unsafe { ::std::ffi::CStr::from_ptr(self.0.d_name.as_ptr()) }
}
/// Returns the type of this directory entry, if known.
///
/// See platform `readdir(3)` or `dirent(5)` manpage for when the file type is known;
/// notably, some Linux filesystems don't implement this. The caller should use `stat` or
/// `fstat` if this returns `None`.
pub(crate) fn file_type(&self) -> FileType {
match self.0.d_type {
libc::DT_CHR => Type::CharacterDevice,
libc::DT_DIR => Type::Directory,
libc::DT_BLK => Type::BlockDevice,
libc::DT_REG => Type::RegularFile,
libc::DT_LNK => Type::Symlink,
/* libc::DT_UNKNOWN | libc::DT_SOCK | libc::DT_FIFO */ _ => Type::Unknown,
}
}
#[cfg(target_os = "linux")]
pub(crate) fn seek_loc(&self) -> SeekLoc {
unsafe { SeekLoc::from_raw(self.0.d_off) }
}
}
#[cfg(not(target_os = "android"))]
#[derive(Clone, Copy, Debug)]
pub(crate) struct SeekLoc(libc::c_long);
#[cfg(not(target_os = "android"))]
impl SeekLoc {
pub(crate) unsafe fn from_raw(loc: i64) -> Self {
Self(loc.into())
}
pub(crate) fn to_raw(&self) -> i64 {
self.0.into()
}
}

View File

@@ -8,7 +8,6 @@ use std::os::unix::prelude::{AsRawFd, FileTypeExt, FromRawFd, RawFd};
cfg_if::cfg_if! {
if #[cfg(target_os = "linux")] {
pub(crate) use super::linux::oshandle::*;
pub(crate) use super::linux::fdentry_impl::*;
} else if #[cfg(any(
target_os = "macos",
target_os = "netbsd",
@@ -18,7 +17,6 @@ cfg_if::cfg_if! {
target_os = "dragonfly"
))] {
pub(crate) use super::bsd::oshandle::*;
pub(crate) use super::bsd::fdentry_impl::*;
}
}
@@ -51,13 +49,12 @@ pub(crate) unsafe fn determine_type_and_access_rights<Fd: AsRawFd>(
)> {
let (file_type, mut rights_base, rights_inheriting) = determine_type_rights(fd)?;
use nix::fcntl::{fcntl, OFlag, F_GETFL};
let flags_bits = fcntl(fd.as_raw_fd(), F_GETFL)?;
let flags = OFlag::from_bits_truncate(flags_bits);
let accmode = flags & OFlag::O_ACCMODE;
if accmode == OFlag::O_RDONLY {
use yanix::{fcntl, file::OFlag};
let flags = fcntl::get_status_flags(fd.as_raw_fd())?;
let accmode = flags & OFlag::ACCMODE;
if accmode == OFlag::RDONLY {
rights_base &= !wasi::__WASI_RIGHTS_FD_WRITE;
} else if accmode == OFlag::O_WRONLY {
} else if accmode == OFlag::WRONLY {
rights_base &= !wasi::__WASI_RIGHTS_FD_READ;
}
@@ -85,7 +82,8 @@ pub(crate) unsafe fn determine_type_rights<Fd: AsRawFd>(
)
} else if ft.is_char_device() {
log::debug!("Host fd {:?} is a char device", fd.as_raw_fd());
if isatty(fd)? {
use yanix::file::isatty;
if isatty(fd.as_raw_fd())? {
(
wasi::__WASI_FILETYPE_CHARACTER_DEVICE,
wasi::RIGHTS_TTY_BASE,
@@ -114,14 +112,14 @@ pub(crate) unsafe fn determine_type_rights<Fd: AsRawFd>(
)
} else if ft.is_socket() {
log::debug!("Host fd {:?} is a socket", fd.as_raw_fd());
use nix::sys::socket;
match socket::getsockopt(fd.as_raw_fd(), socket::sockopt::SockType)? {
socket::SockType::Datagram => (
use yanix::socket::{get_socket_type, SockType};
match get_socket_type(fd.as_raw_fd())? {
SockType::Datagram => (
wasi::__WASI_FILETYPE_SOCKET_DGRAM,
wasi::RIGHTS_SOCKET_BASE,
wasi::RIGHTS_SOCKET_INHERITING,
),
socket::SockType::Stream => (
SockType::Stream => (
wasi::__WASI_FILETYPE_SOCKET_STREAM,
wasi::RIGHTS_SOCKET_BASE,
wasi::RIGHTS_SOCKET_INHERITING,

View File

@@ -2,11 +2,14 @@
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(dead_code)]
use crate::hostcalls_impl::FileType;
use crate::host::FileType;
use crate::{helpers, wasi, Error, Result};
use log::warn;
use std::ffi::OsStr;
use std::os::unix::prelude::OsStrExt;
use yanix::{
file::{OFlag, SFlag},
Errno,
};
cfg_if::cfg_if! {
if #[cfg(target_os = "linux")] {
@@ -23,178 +26,168 @@ cfg_if::cfg_if! {
}
}
pub(crate) fn errno_from_nix(errno: nix::errno::Errno) -> Error {
pub(crate) fn errno_from_nix(errno: Errno) -> Error {
match errno {
nix::errno::Errno::EPERM => Error::EPERM,
nix::errno::Errno::ENOENT => Error::ENOENT,
nix::errno::Errno::ESRCH => Error::ESRCH,
nix::errno::Errno::EINTR => Error::EINTR,
nix::errno::Errno::EIO => Error::EIO,
nix::errno::Errno::ENXIO => Error::ENXIO,
nix::errno::Errno::E2BIG => Error::E2BIG,
nix::errno::Errno::ENOEXEC => Error::ENOEXEC,
nix::errno::Errno::EBADF => Error::EBADF,
nix::errno::Errno::ECHILD => Error::ECHILD,
nix::errno::Errno::EAGAIN => Error::EAGAIN,
nix::errno::Errno::ENOMEM => Error::ENOMEM,
nix::errno::Errno::EACCES => Error::EACCES,
nix::errno::Errno::EFAULT => Error::EFAULT,
nix::errno::Errno::EBUSY => Error::EBUSY,
nix::errno::Errno::EEXIST => Error::EEXIST,
nix::errno::Errno::EXDEV => Error::EXDEV,
nix::errno::Errno::ENODEV => Error::ENODEV,
nix::errno::Errno::ENOTDIR => Error::ENOTDIR,
nix::errno::Errno::EISDIR => Error::EISDIR,
nix::errno::Errno::EINVAL => Error::EINVAL,
nix::errno::Errno::ENFILE => Error::ENFILE,
nix::errno::Errno::EMFILE => Error::EMFILE,
nix::errno::Errno::ENOTTY => Error::ENOTTY,
nix::errno::Errno::ETXTBSY => Error::ETXTBSY,
nix::errno::Errno::EFBIG => Error::EFBIG,
nix::errno::Errno::ENOSPC => Error::ENOSPC,
nix::errno::Errno::ESPIPE => Error::ESPIPE,
nix::errno::Errno::EROFS => Error::EROFS,
nix::errno::Errno::EMLINK => Error::EMLINK,
nix::errno::Errno::EPIPE => Error::EPIPE,
nix::errno::Errno::EDOM => Error::EDOM,
nix::errno::Errno::ERANGE => Error::ERANGE,
nix::errno::Errno::EDEADLK => Error::EDEADLK,
nix::errno::Errno::ENAMETOOLONG => Error::ENAMETOOLONG,
nix::errno::Errno::ENOLCK => Error::ENOLCK,
nix::errno::Errno::ENOSYS => Error::ENOSYS,
nix::errno::Errno::ENOTEMPTY => Error::ENOTEMPTY,
nix::errno::Errno::ELOOP => Error::ELOOP,
nix::errno::Errno::ENOMSG => Error::ENOMSG,
nix::errno::Errno::EIDRM => Error::EIDRM,
nix::errno::Errno::ENOLINK => Error::ENOLINK,
nix::errno::Errno::EPROTO => Error::EPROTO,
nix::errno::Errno::EMULTIHOP => Error::EMULTIHOP,
nix::errno::Errno::EBADMSG => Error::EBADMSG,
nix::errno::Errno::EOVERFLOW => Error::EOVERFLOW,
nix::errno::Errno::EILSEQ => Error::EILSEQ,
nix::errno::Errno::ENOTSOCK => Error::ENOTSOCK,
nix::errno::Errno::EDESTADDRREQ => Error::EDESTADDRREQ,
nix::errno::Errno::EMSGSIZE => Error::EMSGSIZE,
nix::errno::Errno::EPROTOTYPE => Error::EPROTOTYPE,
nix::errno::Errno::ENOPROTOOPT => Error::ENOPROTOOPT,
nix::errno::Errno::EPROTONOSUPPORT => Error::EPROTONOSUPPORT,
nix::errno::Errno::EAFNOSUPPORT => Error::EAFNOSUPPORT,
nix::errno::Errno::EADDRINUSE => Error::EADDRINUSE,
nix::errno::Errno::EADDRNOTAVAIL => Error::EADDRNOTAVAIL,
nix::errno::Errno::ENETDOWN => Error::ENETDOWN,
nix::errno::Errno::ENETUNREACH => Error::ENETUNREACH,
nix::errno::Errno::ENETRESET => Error::ENETRESET,
nix::errno::Errno::ECONNABORTED => Error::ECONNABORTED,
nix::errno::Errno::ECONNRESET => Error::ECONNRESET,
nix::errno::Errno::ENOBUFS => Error::ENOBUFS,
nix::errno::Errno::EISCONN => Error::EISCONN,
nix::errno::Errno::ENOTCONN => Error::ENOTCONN,
nix::errno::Errno::ETIMEDOUT => Error::ETIMEDOUT,
nix::errno::Errno::ECONNREFUSED => Error::ECONNREFUSED,
nix::errno::Errno::EHOSTUNREACH => Error::EHOSTUNREACH,
nix::errno::Errno::EALREADY => Error::EALREADY,
nix::errno::Errno::EINPROGRESS => Error::EINPROGRESS,
nix::errno::Errno::ESTALE => Error::ESTALE,
nix::errno::Errno::EDQUOT => Error::EDQUOT,
nix::errno::Errno::ECANCELED => Error::ECANCELED,
nix::errno::Errno::EOWNERDEAD => Error::EOWNERDEAD,
nix::errno::Errno::ENOTRECOVERABLE => Error::ENOTRECOVERABLE,
other => {
warn!("Unknown error from nix: {}", other);
Error::ENOSYS
}
Errno::EPERM => Error::EPERM,
Errno::ENOENT => Error::ENOENT,
Errno::ESRCH => Error::ESRCH,
Errno::EINTR => Error::EINTR,
Errno::EIO => Error::EIO,
Errno::ENXIO => Error::ENXIO,
Errno::E2BIG => Error::E2BIG,
Errno::ENOEXEC => Error::ENOEXEC,
Errno::EBADF => Error::EBADF,
Errno::ECHILD => Error::ECHILD,
Errno::EAGAIN => Error::EAGAIN,
Errno::ENOMEM => Error::ENOMEM,
Errno::EACCES => Error::EACCES,
Errno::EFAULT => Error::EFAULT,
Errno::EBUSY => Error::EBUSY,
Errno::EEXIST => Error::EEXIST,
Errno::EXDEV => Error::EXDEV,
Errno::ENODEV => Error::ENODEV,
Errno::ENOTDIR => Error::ENOTDIR,
Errno::EISDIR => Error::EISDIR,
Errno::EINVAL => Error::EINVAL,
Errno::ENFILE => Error::ENFILE,
Errno::EMFILE => Error::EMFILE,
Errno::ENOTTY => Error::ENOTTY,
Errno::ETXTBSY => Error::ETXTBSY,
Errno::EFBIG => Error::EFBIG,
Errno::ENOSPC => Error::ENOSPC,
Errno::ESPIPE => Error::ESPIPE,
Errno::EROFS => Error::EROFS,
Errno::EMLINK => Error::EMLINK,
Errno::EPIPE => Error::EPIPE,
Errno::EDOM => Error::EDOM,
Errno::ERANGE => Error::ERANGE,
Errno::EDEADLK => Error::EDEADLK,
Errno::ENAMETOOLONG => Error::ENAMETOOLONG,
Errno::ENOLCK => Error::ENOLCK,
Errno::ENOSYS => Error::ENOSYS,
Errno::ENOTEMPTY => Error::ENOTEMPTY,
Errno::ELOOP => Error::ELOOP,
Errno::ENOMSG => Error::ENOMSG,
Errno::EIDRM => Error::EIDRM,
Errno::ENOLINK => Error::ENOLINK,
Errno::EPROTO => Error::EPROTO,
Errno::EMULTIHOP => Error::EMULTIHOP,
Errno::EBADMSG => Error::EBADMSG,
Errno::EOVERFLOW => Error::EOVERFLOW,
Errno::EILSEQ => Error::EILSEQ,
Errno::ENOTSOCK => Error::ENOTSOCK,
Errno::EDESTADDRREQ => Error::EDESTADDRREQ,
Errno::EMSGSIZE => Error::EMSGSIZE,
Errno::EPROTOTYPE => Error::EPROTOTYPE,
Errno::ENOPROTOOPT => Error::ENOPROTOOPT,
Errno::EPROTONOSUPPORT => Error::EPROTONOSUPPORT,
Errno::EAFNOSUPPORT => Error::EAFNOSUPPORT,
Errno::EADDRINUSE => Error::EADDRINUSE,
Errno::EADDRNOTAVAIL => Error::EADDRNOTAVAIL,
Errno::ENETDOWN => Error::ENETDOWN,
Errno::ENETUNREACH => Error::ENETUNREACH,
Errno::ENETRESET => Error::ENETRESET,
Errno::ECONNABORTED => Error::ECONNABORTED,
Errno::ECONNRESET => Error::ECONNRESET,
Errno::ENOBUFS => Error::ENOBUFS,
Errno::EISCONN => Error::EISCONN,
Errno::ENOTCONN => Error::ENOTCONN,
Errno::ETIMEDOUT => Error::ETIMEDOUT,
Errno::ECONNREFUSED => Error::ECONNREFUSED,
Errno::EHOSTUNREACH => Error::EHOSTUNREACH,
Errno::EALREADY => Error::EALREADY,
Errno::EINPROGRESS => Error::EINPROGRESS,
Errno::ESTALE => Error::ESTALE,
Errno::EDQUOT => Error::EDQUOT,
Errno::ECANCELED => Error::ECANCELED,
Errno::EOWNERDEAD => Error::EOWNERDEAD,
Errno::ENOTRECOVERABLE => Error::ENOTRECOVERABLE,
}
}
pub(crate) fn nix_from_fdflags(fdflags: wasi::__wasi_fdflags_t) -> nix::fcntl::OFlag {
use nix::fcntl::OFlag;
pub(crate) fn nix_from_fdflags(fdflags: wasi::__wasi_fdflags_t) -> OFlag {
let mut nix_flags = OFlag::empty();
if fdflags & wasi::__WASI_FDFLAGS_APPEND != 0 {
nix_flags.insert(OFlag::O_APPEND);
nix_flags.insert(OFlag::APPEND);
}
if fdflags & wasi::__WASI_FDFLAGS_DSYNC != 0 {
nix_flags.insert(OFlag::O_DSYNC);
nix_flags.insert(OFlag::DSYNC);
}
if fdflags & wasi::__WASI_FDFLAGS_NONBLOCK != 0 {
nix_flags.insert(OFlag::O_NONBLOCK);
nix_flags.insert(OFlag::NONBLOCK);
}
if fdflags & wasi::__WASI_FDFLAGS_RSYNC != 0 {
nix_flags.insert(O_RSYNC);
}
if fdflags & wasi::__WASI_FDFLAGS_SYNC != 0 {
nix_flags.insert(OFlag::O_SYNC);
nix_flags.insert(OFlag::SYNC);
}
nix_flags
}
pub(crate) fn fdflags_from_nix(oflags: nix::fcntl::OFlag) -> wasi::__wasi_fdflags_t {
use nix::fcntl::OFlag;
pub(crate) fn fdflags_from_nix(oflags: OFlag) -> wasi::__wasi_fdflags_t {
let mut fdflags = 0;
if oflags.contains(OFlag::O_APPEND) {
if oflags.contains(OFlag::APPEND) {
fdflags |= wasi::__WASI_FDFLAGS_APPEND;
}
if oflags.contains(OFlag::O_DSYNC) {
if oflags.contains(OFlag::DSYNC) {
fdflags |= wasi::__WASI_FDFLAGS_DSYNC;
}
if oflags.contains(OFlag::O_NONBLOCK) {
if oflags.contains(OFlag::NONBLOCK) {
fdflags |= wasi::__WASI_FDFLAGS_NONBLOCK;
}
if oflags.contains(O_RSYNC) {
fdflags |= wasi::__WASI_FDFLAGS_RSYNC;
}
if oflags.contains(OFlag::O_SYNC) {
if oflags.contains(OFlag::SYNC) {
fdflags |= wasi::__WASI_FDFLAGS_SYNC;
}
fdflags
}
pub(crate) fn nix_from_oflags(oflags: wasi::__wasi_oflags_t) -> nix::fcntl::OFlag {
use nix::fcntl::OFlag;
pub(crate) fn nix_from_oflags(oflags: wasi::__wasi_oflags_t) -> OFlag {
let mut nix_flags = OFlag::empty();
if oflags & wasi::__WASI_OFLAGS_CREAT != 0 {
nix_flags.insert(OFlag::O_CREAT);
nix_flags.insert(OFlag::CREAT);
}
if oflags & wasi::__WASI_OFLAGS_DIRECTORY != 0 {
nix_flags.insert(OFlag::O_DIRECTORY);
nix_flags.insert(OFlag::DIRECTORY);
}
if oflags & wasi::__WASI_OFLAGS_EXCL != 0 {
nix_flags.insert(OFlag::O_EXCL);
nix_flags.insert(OFlag::EXCL);
}
if oflags & wasi::__WASI_OFLAGS_TRUNC != 0 {
nix_flags.insert(OFlag::O_TRUNC);
nix_flags.insert(OFlag::TRUNC);
}
nix_flags
}
pub(crate) fn filetype_from_nix(sflags: nix::sys::stat::SFlag) -> FileType {
use nix::sys::stat::SFlag;
if sflags.contains(SFlag::S_IFCHR) {
pub(crate) fn filetype_from_nix(sflags: SFlag) -> FileType {
if sflags.contains(SFlag::IFCHR) {
FileType::CharacterDevice
} else if sflags.contains(SFlag::S_IFBLK) {
} else if sflags.contains(SFlag::IFBLK) {
FileType::BlockDevice
} else if sflags.contains(SFlag::S_IFSOCK) {
} else if sflags.contains(SFlag::IFSOCK) {
FileType::SocketStream
} else if sflags.contains(SFlag::S_IFDIR) {
} else if sflags.contains(SFlag::IFDIR) {
FileType::Directory
} else if sflags.contains(SFlag::S_IFREG) {
} else if sflags.contains(SFlag::IFREG) {
FileType::RegularFile
} else if sflags.contains(SFlag::S_IFLNK) {
} else if sflags.contains(SFlag::IFLNK) {
FileType::Symlink
} else {
FileType::Unknown
}
}
pub(crate) fn filestat_from_nix(
filestat: nix::sys::stat::FileStat,
) -> Result<wasi::__wasi_filestat_t> {
pub(crate) fn filestat_from_nix(filestat: libc::stat) -> Result<wasi::__wasi_filestat_t> {
fn filestat_to_timestamp(secs: u64, nsecs: u64) -> Result<wasi::__wasi_timestamp_t> {
secs.checked_mul(1_000_000_000)
.and_then(|sec_nsec| sec_nsec.checked_add(nsecs))
.ok_or(Error::EOVERFLOW)
}
let filetype = nix::sys::stat::SFlag::from_bits_truncate(filestat.st_mode);
let filetype = SFlag::from_bits_truncate(filestat.st_mode);
let dev = stdev_from_nix(filestat.st_dev)?;
let ino = stino_from_nix(filestat.st_ino)?;
let atim = filestat_to_timestamp(filestat.st_atime as u64, filestat.st_atime_nsec as u64)?;
@@ -214,7 +207,7 @@ pub(crate) fn filestat_from_nix(
}
pub(crate) fn dirent_filetype_from_host(
host_entry: &nix::libc::dirent,
host_entry: &libc::dirent,
) -> Result<wasi::__wasi_filetype_t> {
match host_entry.d_type {
libc::DT_FIFO => Ok(wasi::__WASI_FILETYPE_UNKNOWN),
@@ -243,3 +236,17 @@ pub(crate) fn dirent_filetype_from_host(
pub(crate) fn path_from_host<S: AsRef<OsStr>>(s: S) -> Result<String> {
helpers::path_from_slice(s.as_ref().as_bytes()).map(String::from)
}
impl From<yanix::dir::FileType> for FileType {
fn from(ft: yanix::dir::FileType) -> Self {
use yanix::dir::FileType::*;
match ft {
RegularFile => Self::RegularFile,
Symlink => Self::Symlink,
Directory => Self::Directory,
BlockDevice => Self::BlockDevice,
CharacterDevice => Self::CharacterDevice,
/* Unknown | Socket | Fifo */ _ => Self::Unknown,
}
}
}

View File

@@ -1,11 +1,10 @@
#![allow(non_camel_case_types)]
#![allow(unused_unsafe)]
use crate::helpers::systemtime_to_timestamp;
use crate::hostcalls_impl::{FileType, PathGet};
use crate::sys::host_impl;
use crate::sys::unix::str_to_cstring;
use crate::host::{Dirent, FileType};
use crate::hostcalls_impl::PathGet;
use crate::sys::{fdentry_impl::OsHandle, host_impl};
use crate::{wasi, Error, Result};
use nix::libc;
use std::convert::TryInto;
use std::fs::{File, Metadata};
use std::os::unix::fs::FileExt;
@@ -39,53 +38,61 @@ pub(crate) fn fd_pwrite(file: &File, buf: &[u8], offset: wasi::__wasi_filesize_t
}
pub(crate) fn fd_fdstat_get(fd: &File) -> Result<wasi::__wasi_fdflags_t> {
use nix::fcntl::{fcntl, OFlag, F_GETFL};
match fcntl(fd.as_raw_fd(), F_GETFL).map(OFlag::from_bits_truncate) {
Ok(flags) => Ok(host_impl::fdflags_from_nix(flags)),
Err(e) => Err(host_impl::errno_from_nix(e.as_errno().unwrap())),
}
unsafe { yanix::fcntl::get_status_flags(fd.as_raw_fd()) }
.map(host_impl::fdflags_from_nix)
.map_err(Into::into)
}
pub(crate) fn fd_fdstat_set_flags(fd: &File, fdflags: wasi::__wasi_fdflags_t) -> Result<()> {
use nix::fcntl::{fcntl, F_SETFL};
let nix_flags = host_impl::nix_from_fdflags(fdflags);
match fcntl(fd.as_raw_fd(), F_SETFL(nix_flags)) {
Ok(_) => Ok(()),
Err(e) => Err(host_impl::errno_from_nix(e.as_errno().unwrap())),
}
unsafe { yanix::fcntl::set_status_flags(fd.as_raw_fd(), nix_flags) }.map_err(Into::into)
}
pub(crate) fn fd_advise(
file: &File,
advice: wasi::__wasi_advice_t,
offset: wasi::__wasi_filesize_t,
len: wasi::__wasi_filesize_t,
) -> Result<()> {
use yanix::fadvise::{posix_fadvise, PosixFadviseAdvice};
let offset = offset.try_into()?;
let len = len.try_into()?;
let host_advice = match advice {
wasi::__WASI_ADVICE_DONTNEED => PosixFadviseAdvice::DontNeed,
wasi::__WASI_ADVICE_SEQUENTIAL => PosixFadviseAdvice::Sequential,
wasi::__WASI_ADVICE_WILLNEED => PosixFadviseAdvice::WillNeed,
wasi::__WASI_ADVICE_NOREUSE => PosixFadviseAdvice::NoReuse,
wasi::__WASI_ADVICE_RANDOM => PosixFadviseAdvice::Random,
wasi::__WASI_ADVICE_NORMAL => PosixFadviseAdvice::Normal,
_ => return Err(Error::EINVAL),
};
unsafe { posix_fadvise(file.as_raw_fd(), offset, len, host_advice) }.map_err(Into::into)
}
pub(crate) fn path_create_directory(resolved: PathGet) -> Result<()> {
use nix::libc::mkdirat;
let path_cstr = str_to_cstring(resolved.path())?;
// nix doesn't expose mkdirat() yet
match unsafe { mkdirat(resolved.dirfd().as_raw_fd(), path_cstr.as_ptr(), 0o777) } {
0 => Ok(()),
_ => Err(host_impl::errno_from_nix(nix::errno::Errno::last())),
use yanix::file::{mkdirat, Mode};
unsafe {
mkdirat(
resolved.dirfd().as_raw_fd(),
resolved.path(),
Mode::from_bits_truncate(0o777),
)
}
.map_err(Into::into)
}
pub(crate) fn path_link(resolved_old: PathGet, resolved_new: PathGet) -> Result<()> {
use nix::libc::linkat;
let old_path_cstr = str_to_cstring(resolved_old.path())?;
let new_path_cstr = str_to_cstring(resolved_new.path())?;
// Not setting AT_SYMLINK_FOLLOW fails on most filesystems
let atflags = libc::AT_SYMLINK_FOLLOW;
let res = unsafe {
use yanix::file::{linkat, AtFlag};
unsafe {
linkat(
resolved_old.dirfd().as_raw_fd(),
old_path_cstr.as_ptr(),
resolved_old.path(),
resolved_new.dirfd().as_raw_fd(),
new_path_cstr.as_ptr(),
atflags,
resolved_new.path(),
AtFlag::SYMLINK_FOLLOW,
)
};
if res != 0 {
Err(host_impl::errno_from_nix(nix::errno::Errno::last()))
} else {
Ok(())
}
.map_err(Into::into)
}
pub(crate) fn path_open(
@@ -95,20 +102,21 @@ pub(crate) fn path_open(
oflags: wasi::__wasi_oflags_t,
fs_flags: wasi::__wasi_fdflags_t,
) -> Result<File> {
use nix::errno::Errno;
use nix::fcntl::{openat, AtFlags, OFlag};
use nix::sys::stat::{fstatat, Mode, SFlag};
use yanix::{
file::{fstatat, openat, AtFlag, Mode, OFlag, SFlag},
Errno,
};
let mut nix_all_oflags = if read && write {
OFlag::O_RDWR
OFlag::RDWR
} else if write {
OFlag::O_WRONLY
OFlag::WRONLY
} else {
OFlag::O_RDONLY
OFlag::RDONLY
};
// on non-Capsicum systems, we always want nofollow
nix_all_oflags.insert(OFlag::O_NOFOLLOW);
nix_all_oflags.insert(OFlag::NOFOLLOW);
// convert open flags
nix_all_oflags.insert(host_impl::nix_from_oflags(oflags));
@@ -123,54 +131,63 @@ pub(crate) fn path_open(
log::debug!("path_open resolved = {:?}", resolved);
log::debug!("path_open oflags = {:?}", nix_all_oflags);
let new_fd = match openat(
resolved.dirfd().as_raw_fd(),
resolved.path(),
nix_all_oflags,
Mode::from_bits_truncate(0o666),
) {
let new_fd = match unsafe {
openat(
resolved.dirfd().as_raw_fd(),
resolved.path(),
nix_all_oflags,
Mode::from_bits_truncate(0o666),
)
} {
Ok(fd) => fd,
Err(e) => {
match e.as_errno() {
// Linux returns ENXIO instead of EOPNOTSUPP when opening a socket
Some(Errno::ENXIO) => {
if let Ok(stat) = fstatat(
resolved.dirfd().as_raw_fd(),
resolved.path(),
AtFlags::AT_SYMLINK_NOFOLLOW,
) {
if SFlag::from_bits_truncate(stat.st_mode).contains(SFlag::S_IFSOCK) {
return Err(Error::ENOTSUP);
if let yanix::YanixError::Errno(errno) = e {
match errno {
// Linux returns ENXIO instead of EOPNOTSUPP when opening a socket
Errno::ENXIO => {
if let Ok(stat) = unsafe {
fstatat(
resolved.dirfd().as_raw_fd(),
resolved.path(),
AtFlag::SYMLINK_NOFOLLOW,
)
} {
if SFlag::from_bits_truncate(stat.st_mode).contains(SFlag::IFSOCK) {
return Err(Error::ENOTSUP);
} else {
return Err(Error::ENXIO);
}
} else {
return Err(Error::ENXIO);
}
} else {
return Err(Error::ENXIO);
}
}
// Linux returns ENOTDIR instead of ELOOP when using O_NOFOLLOW|O_DIRECTORY
// on a symlink.
Some(Errno::ENOTDIR)
if !(nix_all_oflags & (OFlag::O_NOFOLLOW | OFlag::O_DIRECTORY)).is_empty() =>
{
if let Ok(stat) = fstatat(
resolved.dirfd().as_raw_fd(),
resolved.path(),
AtFlags::AT_SYMLINK_NOFOLLOW,
) {
if SFlag::from_bits_truncate(stat.st_mode).contains(SFlag::S_IFLNK) {
return Err(Error::ELOOP);
// Linux returns ENOTDIR instead of ELOOP when using O_NOFOLLOW|O_DIRECTORY
// on a symlink.
Errno::ENOTDIR
if !(nix_all_oflags & (OFlag::NOFOLLOW | OFlag::DIRECTORY)).is_empty() =>
{
if let Ok(stat) = unsafe {
fstatat(
resolved.dirfd().as_raw_fd(),
resolved.path(),
AtFlag::SYMLINK_NOFOLLOW,
)
} {
if SFlag::from_bits_truncate(stat.st_mode).contains(SFlag::IFLNK) {
return Err(Error::ELOOP);
}
}
return Err(Error::ENOTDIR);
}
return Err(Error::ENOTDIR);
// FreeBSD returns EMLINK instead of ELOOP when using O_NOFOLLOW on
// a symlink.
Errno::EMLINK if !(nix_all_oflags & OFlag::NOFOLLOW).is_empty() => {
return Err(Error::ELOOP);
}
errno => return Err(host_impl::errno_from_nix(errno)),
}
// FreeBSD returns EMLINK instead of ELOOP when using O_NOFOLLOW on
// a symlink.
Some(Errno::EMLINK) if !(nix_all_oflags & OFlag::O_NOFOLLOW).is_empty() => {
return Err(Error::ELOOP);
}
Some(e) => return Err(host_impl::errno_from_nix(e)),
None => return Err(Error::ENOSYS),
} else {
return Err(e.into());
}
}
};
@@ -182,34 +199,16 @@ pub(crate) fn path_open(
}
pub(crate) fn path_readlink(resolved: PathGet, buf: &mut [u8]) -> Result<usize> {
use nix::errno::Errno;
let path_cstr = str_to_cstring(resolved.path())?;
// Linux requires that the buffer size is positive, whereas POSIX does not.
// Use a fake buffer to store the results if the size is zero.
// TODO: instead of using raw libc::readlinkat call here, this should really
// be fixed in `nix` crate
let fakebuf: &mut [u8] = &mut [0];
let buf_len = buf.len();
let len = unsafe {
libc::readlinkat(
resolved.dirfd().as_raw_fd(),
path_cstr.as_ptr() as *const libc::c_char,
if buf_len == 0 {
fakebuf.as_mut_ptr()
} else {
buf.as_mut_ptr()
} as *mut libc::c_char,
if buf_len == 0 { fakebuf.len() } else { buf_len },
)
};
if len < 0 {
Err(host_impl::errno_from_nix(Errno::last()))
} else {
let len = len as usize;
Ok(if len < buf_len { len } else { buf_len })
use std::cmp::min;
use yanix::file::readlinkat;
let read_link = unsafe { readlinkat(resolved.dirfd().as_raw_fd(), resolved.path()) }
.map_err(Into::into)
.and_then(host_impl::path_from_host)?;
let copy_len = min(read_link.len(), buf.len());
if copy_len > 0 {
buf[..copy_len].copy_from_slice(&read_link.as_bytes()[..copy_len]);
}
Ok(copy_len)
}
pub(crate) fn fd_filestat_get_impl(file: &std::fs::File) -> Result<wasi::__wasi_filestat_t> {
@@ -229,8 +228,8 @@ pub(crate) fn fd_filestat_get_impl(file: &std::fs::File) -> Result<wasi::__wasi_
}
fn filetype(file: &File, metadata: &Metadata) -> Result<FileType> {
use nix::sys::socket::{self, SockType};
use std::os::unix::fs::FileTypeExt;
use yanix::socket::{get_socket_type, SockType};
let ftype = metadata.file_type();
if ftype.is_file() {
Ok(FileType::RegularFile)
@@ -243,10 +242,7 @@ fn filetype(file: &File, metadata: &Metadata) -> Result<FileType> {
} else if ftype.is_block_device() {
Ok(FileType::BlockDevice)
} else if ftype.is_socket() {
match socket::getsockopt(file.as_raw_fd(), socket::sockopt::SockType)
.map_err(|err| err.as_errno().unwrap())
.map_err(host_impl::errno_from_nix)?
{
match unsafe { get_socket_type(file.as_raw_fd())? } {
SockType::Datagram => Ok(FileType::SocketDgram),
SockType::Stream => Ok(FileType::SocketStream),
_ => Ok(FileType::Unknown),
@@ -260,17 +256,14 @@ pub(crate) fn path_filestat_get(
resolved: PathGet,
dirflags: wasi::__wasi_lookupflags_t,
) -> Result<wasi::__wasi_filestat_t> {
use nix::fcntl::AtFlags;
use nix::sys::stat::fstatat;
use yanix::file::{fstatat, AtFlag};
let atflags = match dirflags {
0 => AtFlags::empty(),
_ => AtFlags::AT_SYMLINK_NOFOLLOW,
0 => AtFlag::empty(),
_ => AtFlag::SYMLINK_NOFOLLOW,
};
let filestat = fstatat(resolved.dirfd().as_raw_fd(), resolved.path(), atflags)
.map_err(|err| host_impl::errno_from_nix(err.as_errno().unwrap()))?;
host_impl::filestat_from_nix(filestat)
unsafe { fstatat(resolved.dirfd().as_raw_fd(), resolved.path(), atflags) }
.map_err(Into::into)
.and_then(host_impl::filestat_from_nix)
}
pub(crate) fn path_filestat_set_times(
@@ -321,20 +314,49 @@ pub(crate) fn path_filestat_set_times(
}
pub(crate) fn path_remove_directory(resolved: PathGet) -> Result<()> {
use nix::errno;
use nix::libc::{unlinkat, AT_REMOVEDIR};
let path_cstr = str_to_cstring(resolved.path())?;
// nix doesn't expose unlinkat() yet
match unsafe {
use yanix::file::{unlinkat, AtFlag};
unsafe {
unlinkat(
resolved.dirfd().as_raw_fd(),
path_cstr.as_ptr(),
AT_REMOVEDIR,
resolved.path(),
AtFlag::REMOVEDIR,
)
} {
0 => Ok(()),
_ => Err(host_impl::errno_from_nix(errno::Errno::last())),
}
.map_err(Into::into)
}
pub(crate) fn fd_readdir<'a>(
os_handle: &'a mut OsHandle,
cookie: wasi::__wasi_dircookie_t,
) -> Result<impl Iterator<Item = Result<Dirent>> + 'a> {
use yanix::dir::{DirIter, Entry, EntryExt, SeekLoc};
// Get an instance of `Dir`; this is host-specific due to intricasies
// of managing a dir stream between Linux and BSD *nixes
let mut dir = fd_readdir_impl::get_dir_from_os_handle(os_handle)?;
// Seek if needed. Unless cookie is wasi::__WASI_DIRCOOKIE_START,
// new items may not be returned to the caller.
if cookie == wasi::__WASI_DIRCOOKIE_START {
log::trace!(" | fd_readdir: doing rewinddir");
dir.rewind();
} else {
log::trace!(" | fd_readdir: doing seekdir to {}", cookie);
let loc = unsafe { SeekLoc::from_raw(cookie as i64) };
dir.seek(loc);
}
Ok(DirIter::new(dir).map(|entry| {
let entry: Entry = entry?;
Ok(Dirent {
name: entry
// TODO can we reuse path_from_host for CStr?
.file_name()
.to_str()?
.to_owned(),
ino: entry.ino(),
ftype: entry.file_type().into(),
cookie: entry.seek_loc().to_raw().try_into()?,
})
}))
}

View File

@@ -3,6 +3,7 @@
use crate::sys::host_impl;
use crate::{wasi, Result};
use std::fs::File;
use yanix::file::OFlag;
pub(crate) fn path_open_rights(
rights_base: wasi::__wasi_rights_t,
@@ -10,27 +11,25 @@ pub(crate) fn path_open_rights(
oflags: wasi::__wasi_oflags_t,
fs_flags: wasi::__wasi_fdflags_t,
) -> (wasi::__wasi_rights_t, wasi::__wasi_rights_t) {
use nix::fcntl::OFlag;
// which rights are needed on the dirfd?
let mut needed_base = wasi::__WASI_RIGHTS_PATH_OPEN;
let mut needed_inheriting = rights_base | rights_inheriting;
// convert open flags
let oflags = host_impl::nix_from_oflags(oflags);
if oflags.contains(OFlag::O_CREAT) {
if oflags.contains(OFlag::CREAT) {
needed_base |= wasi::__WASI_RIGHTS_PATH_CREATE_FILE;
}
if oflags.contains(OFlag::O_TRUNC) {
if oflags.contains(OFlag::TRUNC) {
needed_base |= wasi::__WASI_RIGHTS_PATH_FILESTAT_SET_SIZE;
}
// convert file descriptor flags
let fdflags = host_impl::nix_from_fdflags(fs_flags);
if fdflags.contains(OFlag::O_DSYNC) {
if fdflags.contains(OFlag::DSYNC) {
needed_inheriting |= wasi::__WASI_RIGHTS_FD_DATASYNC;
}
if fdflags.intersects(host_impl::O_RSYNC | OFlag::O_SYNC) {
if fdflags.intersects(host_impl::O_RSYNC | OFlag::SYNC) {
needed_inheriting |= wasi::__WASI_RIGHTS_FD_SYNC;
}
@@ -38,31 +37,30 @@ pub(crate) fn path_open_rights(
}
pub(crate) fn openat(dirfd: &File, path: &str) -> Result<File> {
use nix::fcntl::{self, OFlag};
use nix::sys::stat::Mode;
use std::os::unix::prelude::{AsRawFd, FromRawFd};
use yanix::file::{openat, Mode};
log::debug!("path_get openat path = {:?}", path);
fcntl::openat(
dirfd.as_raw_fd(),
path,
OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW,
Mode::empty(),
)
unsafe {
openat(
dirfd.as_raw_fd(),
path,
OFlag::RDONLY | OFlag::DIRECTORY | OFlag::NOFOLLOW,
Mode::empty(),
)
}
.map(|new_fd| unsafe { File::from_raw_fd(new_fd) })
.map_err(Into::into)
}
pub(crate) fn readlinkat(dirfd: &File, path: &str) -> Result<String> {
use nix::fcntl;
use std::os::unix::prelude::AsRawFd;
use yanix::file::readlinkat;
log::debug!("path_get readlinkat path = {:?}", path);
let readlink_buf = &mut [0u8; libc::PATH_MAX as usize + 1];
fcntl::readlinkat(dirfd.as_raw_fd(), path, readlink_buf)
unsafe { readlinkat(dirfd.as_raw_fd(), path) }
.map_err(Into::into)
.and_then(host_impl::path_from_host)
}

View File

@@ -3,29 +3,22 @@
use crate::hostcalls_impl::{ClockEventData, FdEventData};
use crate::sys::host_impl;
use crate::{wasi, Error, Result};
use nix::libc::{self, c_int};
use std::mem::MaybeUninit;
use yanix::clock::{clock_getres, ClockId};
fn wasi_clock_id_to_unix(clock_id: wasi::__wasi_clockid_t) -> Result<libc::clockid_t> {
// convert the supported clocks to the libc types, or return EINVAL
fn wasi_clock_id_to_unix(clock_id: wasi::__wasi_clockid_t) -> Result<ClockId> {
// convert the supported clocks to libc types, or return EINVAL
match clock_id {
wasi::__WASI_CLOCKID_REALTIME => Ok(libc::CLOCK_REALTIME),
wasi::__WASI_CLOCKID_MONOTONIC => Ok(libc::CLOCK_MONOTONIC),
wasi::__WASI_CLOCKID_PROCESS_CPUTIME_ID => Ok(libc::CLOCK_PROCESS_CPUTIME_ID),
wasi::__WASI_CLOCKID_THREAD_CPUTIME_ID => Ok(libc::CLOCK_THREAD_CPUTIME_ID),
wasi::__WASI_CLOCKID_REALTIME => Ok(ClockId::Realtime),
wasi::__WASI_CLOCKID_MONOTONIC => Ok(ClockId::Monotonic),
wasi::__WASI_CLOCKID_PROCESS_CPUTIME_ID => Ok(ClockId::ProcessCPUTime),
wasi::__WASI_CLOCKID_THREAD_CPUTIME_ID => Ok(ClockId::ThreadCPUTime),
_ => Err(Error::EINVAL),
}
}
pub(crate) fn clock_res_get(clock_id: wasi::__wasi_clockid_t) -> Result<wasi::__wasi_timestamp_t> {
let clock_id = wasi_clock_id_to_unix(clock_id)?;
// no `nix` wrapper for clock_getres, so we do it ourselves
let mut timespec = MaybeUninit::<libc::timespec>::uninit();
let res = unsafe { libc::clock_getres(clock_id, timespec.as_mut_ptr()) };
if res != 0 {
return Err(host_impl::errno_from_nix(nix::errno::Errno::last()));
}
let timespec = unsafe { timespec.assume_init() };
let timespec = clock_getres(clock_id)?;
// convert to nanoseconds, returning EOVERFLOW in case of overflow;
// this is freelancing a bit from the spec but seems like it'll
@@ -46,13 +39,7 @@ pub(crate) fn clock_res_get(clock_id: wasi::__wasi_clockid_t) -> Result<wasi::__
pub(crate) fn clock_time_get(clock_id: wasi::__wasi_clockid_t) -> Result<wasi::__wasi_timestamp_t> {
let clock_id = wasi_clock_id_to_unix(clock_id)?;
// no `nix` wrapper for clock_getres, so we do it ourselves
let mut timespec = MaybeUninit::<libc::timespec>::uninit();
let res = unsafe { libc::clock_gettime(clock_id, timespec.as_mut_ptr()) };
if res != 0 {
return Err(host_impl::errno_from_nix(nix::errno::Errno::last()));
}
let timespec = unsafe { timespec.assume_init() };
let timespec = clock_getres(clock_id)?;
// convert to nanoseconds, returning EOVERFLOW in case of overflow; this is freelancing a bit
// from the spec but seems like it'll be an unusual situation to hit
@@ -67,11 +54,11 @@ pub(crate) fn poll_oneoff(
fd_events: Vec<FdEventData>,
events: &mut Vec<wasi::__wasi_event_t>,
) -> Result<()> {
use nix::{
errno::Errno,
poll::{poll, PollFd, PollFlags},
};
use std::{convert::TryInto, os::unix::prelude::AsRawFd};
use yanix::{
poll::{poll, PollFd, PollFlags},
Errno,
};
if fd_events.is_empty() && timeout.is_none() {
return Ok(());
@@ -89,13 +76,13 @@ pub(crate) fn poll_oneoff(
// events we filtered before. If we get something else here, the code has a serious bug.
_ => unreachable!(),
};
PollFd::new(event.descriptor.as_raw_fd(), flags)
unsafe { PollFd::new(event.descriptor.as_raw_fd(), flags) }
})
.collect();
let poll_timeout = timeout.map_or(-1, |timeout| {
let delay = timeout.delay / 1_000_000; // poll syscall requires delay to expressed in milliseconds
delay.try_into().unwrap_or(c_int::max_value())
delay.try_into().unwrap_or(libc::c_int::max_value())
});
log::debug!("poll_oneoff poll_timeout = {:?}", poll_timeout);
@@ -107,7 +94,7 @@ pub(crate) fn poll_oneoff(
}
return Err(host_impl::errno_from_nix(Errno::last()));
}
Ok(ready) => break ready as usize,
Ok(ready) => break ready,
}
};
@@ -119,9 +106,6 @@ pub(crate) fn poll_oneoff(
})
}
// define the `fionread()` function, equivalent to `ioctl(fd, FIONREAD, *bytes)`
nix::ioctl_read_bad!(fionread, nix::libc::FIONREAD, c_int);
fn poll_oneoff_handle_timeout_event(
timeout: ClockEventData,
events: &mut Vec<wasi::__wasi_event_t>,
@@ -140,11 +124,11 @@ fn poll_oneoff_handle_timeout_event(
}
fn poll_oneoff_handle_fd_event<'a>(
ready_events: impl Iterator<Item = (FdEventData<'a>, nix::poll::PollFd)>,
ready_events: impl Iterator<Item = (FdEventData<'a>, yanix::poll::PollFd)>,
events: &mut Vec<wasi::__wasi_event_t>,
) -> Result<()> {
use nix::poll::PollFlags;
use std::{convert::TryInto, os::unix::prelude::AsRawFd};
use yanix::{file::fionread, poll::PollFlags};
for (fd_event, poll_fd) in ready_events {
log::debug!("poll_oneoff_handle_fd_event fd_event = {:?}", fd_event);
@@ -157,10 +141,11 @@ fn poll_oneoff_handle_fd_event<'a>(
log::debug!("poll_oneoff_handle_fd_event revents = {:?}", revents);
let mut nbytes = 0;
if fd_event.r#type == wasi::__WASI_EVENTTYPE_FD_READ {
let _ = unsafe { fionread(fd_event.descriptor.as_raw_fd(), &mut nbytes) };
}
let nbytes = if fd_event.r#type == wasi::__WASI_EVENTTYPE_FD_READ {
unsafe { fionread(fd_event.descriptor.as_raw_fd())? }
} else {
0
};
let output_event = if revents.contains(PollFlags::POLLNVAL) {
wasi::__wasi_event_t {

View File

@@ -1,176 +1,60 @@
use super::super::dir::{Dir, Entry, SeekLoc};
use crate::hostcalls_impl::{Dirent, PathGet};
use crate::sys::host_impl;
use crate::sys::unix::str_to_cstring;
use crate::{wasi, Error, Result};
use log::trace;
use std::convert::TryInto;
use std::fs::File;
use crate::hostcalls_impl::PathGet;
use crate::Result;
use std::os::unix::prelude::AsRawFd;
pub(crate) fn path_unlink_file(resolved: PathGet) -> Result<()> {
use nix::errno;
use nix::libc::unlinkat;
let path_cstr = str_to_cstring(resolved.path())?;
// nix doesn't expose unlinkat() yet
let res = unsafe { unlinkat(resolved.dirfd().as_raw_fd(), path_cstr.as_ptr(), 0) };
if res == 0 {
Ok(())
} else {
Err(host_impl::errno_from_nix(errno::Errno::last()))
use yanix::file::{unlinkat, AtFlag};
unsafe {
unlinkat(
resolved.dirfd().as_raw_fd(),
resolved.path(),
AtFlag::empty(),
)
}
.map_err(Into::into)
}
pub(crate) fn path_symlink(old_path: &str, resolved: PathGet) -> Result<()> {
use nix::{errno::Errno, libc::symlinkat};
let old_path_cstr = str_to_cstring(old_path)?;
let new_path_cstr = str_to_cstring(resolved.path())?;
use yanix::file::symlinkat;
log::debug!("path_symlink old_path = {:?}", old_path);
log::debug!("path_symlink resolved = {:?}", resolved);
let res = unsafe {
symlinkat(
old_path_cstr.as_ptr(),
resolved.dirfd().as_raw_fd(),
new_path_cstr.as_ptr(),
)
};
if res != 0 {
Err(host_impl::errno_from_nix(Errno::last()))
} else {
Ok(())
}
unsafe { symlinkat(old_path, resolved.dirfd().as_raw_fd(), resolved.path()) }
.map_err(Into::into)
}
pub(crate) fn path_rename(resolved_old: PathGet, resolved_new: PathGet) -> Result<()> {
use nix::libc::renameat;
let old_path_cstr = str_to_cstring(resolved_old.path())?;
let new_path_cstr = str_to_cstring(resolved_new.path())?;
let res = unsafe {
use yanix::file::renameat;
unsafe {
renameat(
resolved_old.dirfd().as_raw_fd(),
old_path_cstr.as_ptr(),
resolved_old.path(),
resolved_new.dirfd().as_raw_fd(),
new_path_cstr.as_ptr(),
resolved_new.path(),
)
};
if res != 0 {
Err(host_impl::errno_from_nix(nix::errno::Errno::last()))
} else {
Ok(())
}
.map_err(Into::into)
}
pub(crate) fn fd_readdir(
fd: &File,
cookie: wasi::__wasi_dircookie_t,
) -> Result<impl Iterator<Item = Result<Dirent>>> {
// We need to duplicate the fd, because `opendir(3)`:
// After a successful call to fdopendir(), fd is used internally by the implementation,
// and should not otherwise be used by the application.
// `opendir(3p)` also says that it's undefined behavior to
// modify the state of the fd in a different way than by accessing DIR*.
//
// Still, rewinddir will be needed because the two file descriptors
// share progress. But we can safely execute closedir now.
let fd = fd.try_clone()?;
let mut dir = Dir::from(fd)?;
pub(crate) mod fd_readdir_impl {
use crate::sys::fdentry_impl::OsHandle;
use crate::Result;
use yanix::dir::Dir;
// Seek if needed. Unless cookie is wasi::__WASI_DIRCOOKIE_START,
// new items may not be returned to the caller.
//
// According to `opendir(3p)`:
// If a file is removed from or added to the directory after the most recent call
// to opendir() or rewinddir(), whether a subsequent call to readdir() returns an entry
// for that file is unspecified.
if cookie == wasi::__WASI_DIRCOOKIE_START {
trace!(" | fd_readdir: doing rewinddir");
dir.rewind();
} else {
trace!(" | fd_readdir: doing seekdir to {}", cookie);
let loc = unsafe { SeekLoc::from_raw(cookie as i64) };
dir.seek(loc);
}
Ok(DirIter(dir).map(|entry| {
let entry: Entry = entry?;
Ok(Dirent {
name: entry // TODO can we reuse path_from_host for CStr?
.file_name()
.to_str()?
.to_owned(),
ino: entry.ino(),
ftype: entry.file_type().into(),
cookie: entry.seek_loc().to_raw().try_into()?,
})
}))
}
struct DirIter(Dir);
impl Iterator for DirIter {
type Item = nix::Result<Entry>;
fn next(&mut self) -> Option<Self::Item> {
use libc::{dirent64, readdir64_r};
use nix::errno::Errno;
unsafe {
// Note: POSIX specifies that portable applications should dynamically allocate a
// buffer with room for a `d_name` field of size `pathconf(..., _PC_NAME_MAX)` plus 1
// for the NUL byte. It doesn't look like the std library does this; it just uses
// fixed-sized buffers (and libc's dirent seems to be sized so this is appropriate).
// Probably fine here too then.
//
// See `impl Iterator for ReadDir` [1] for more details.
// [1] https://github.com/rust-lang/rust/blob/master/src/libstd/sys/unix/fs.rs
let mut ent = std::mem::MaybeUninit::<dirent64>::uninit();
let mut result = std::ptr::null_mut();
if let Err(e) = Errno::result(readdir64_r(
(self.0).0.as_ptr(),
ent.as_mut_ptr(),
&mut result,
)) {
return Some(Err(e));
}
if result.is_null() {
None
} else {
assert_eq!(result, ent.as_mut_ptr(), "readdir_r specification violated");
Some(Ok(Entry(ent.assume_init())))
}
}
pub(crate) fn get_dir_from_os_handle(os_handle: &mut OsHandle) -> Result<Box<Dir>> {
// We need to duplicate the fd, because `opendir(3)`:
// After a successful call to fdopendir(), fd is used internally by the implementation,
// and should not otherwise be used by the application.
// `opendir(3p)` also says that it's undefined behavior to
// modify the state of the fd in a different way than by accessing DIR*.
//
// Still, rewinddir will be needed because the two file descriptors
// share progress. But we can safely execute closedir now.
let fd = os_handle.try_clone()?;
// TODO This doesn't look very clean. Can we do something about it?
// Boxing is needed here in order to satisfy `yanix`'s trait requirement for the `DirIter`
// where `T: Deref<Target = Dir>`.
Ok(Box::new(Dir::from(fd)?))
}
}
pub(crate) fn fd_advise(
file: &File,
advice: wasi::__wasi_advice_t,
offset: wasi::__wasi_filesize_t,
len: wasi::__wasi_filesize_t,
) -> Result<()> {
{
use nix::fcntl::{posix_fadvise, PosixFadviseAdvice};
let offset = offset.try_into()?;
let len = len.try_into()?;
let host_advice = match advice {
wasi::__WASI_ADVICE_DONTNEED => PosixFadviseAdvice::POSIX_FADV_DONTNEED,
wasi::__WASI_ADVICE_SEQUENTIAL => PosixFadviseAdvice::POSIX_FADV_SEQUENTIAL,
wasi::__WASI_ADVICE_WILLNEED => PosixFadviseAdvice::POSIX_FADV_WILLNEED,
wasi::__WASI_ADVICE_NOREUSE => PosixFadviseAdvice::POSIX_FADV_NOREUSE,
wasi::__WASI_ADVICE_RANDOM => PosixFadviseAdvice::POSIX_FADV_RANDOM,
wasi::__WASI_ADVICE_NORMAL => PosixFadviseAdvice::POSIX_FADV_NORMAL,
_ => return Err(Error::EINVAL),
};
posix_fadvise(file.as_raw_fd(), offset, len, host_advice)?;
}
Ok(())
}

View File

@@ -2,42 +2,16 @@ pub(crate) mod filetime;
pub(crate) mod hostcalls_impl;
pub(crate) mod oshandle;
pub(crate) mod fdentry_impl {
use crate::{sys::host_impl, Result};
use std::os::unix::prelude::AsRawFd;
pub(crate) unsafe fn isatty(fd: &impl AsRawFd) -> Result<bool> {
use nix::errno::Errno;
let res = libc::isatty(fd.as_raw_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.
match 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
Errno::ENOTTY | Errno::EINVAL => Ok(false),
x => Err(host_impl::errno_from_nix(x)),
}
}
}
}
pub(crate) mod host_impl {
use crate::{wasi, Result};
pub(crate) const O_RSYNC: nix::fcntl::OFlag = nix::fcntl::OFlag::O_RSYNC;
pub(crate) const O_RSYNC: yanix::file::OFlag = yanix::file::OFlag::RSYNC;
pub(crate) fn stdev_from_nix(dev: nix::libc::dev_t) -> Result<wasi::__wasi_device_t> {
pub(crate) fn stdev_from_nix(dev: libc::dev_t) -> Result<wasi::__wasi_device_t> {
Ok(wasi::__wasi_device_t::from(dev))
}
pub(crate) fn stino_from_nix(ino: nix::libc::ino_t) -> Result<wasi::__wasi_inode_t> {
pub(crate) fn stino_from_nix(ino: libc::ino_t) -> Result<wasi::__wasi_inode_t> {
Ok(wasi::__wasi_device_t::from(ino))
}
}

View File

@@ -2,7 +2,6 @@ pub(crate) mod fdentry_impl;
pub(crate) mod host_impl;
pub(crate) mod hostcalls_impl;
mod dir;
mod filetime;
#[cfg(any(
@@ -17,8 +16,7 @@ mod bsd;
#[cfg(target_os = "linux")]
mod linux;
use crate::{Error, Result};
use std::ffi::CString;
use crate::Result;
use std::fs::{File, OpenOptions};
use std::path::Path;
@@ -30,10 +28,6 @@ pub(crate) fn dev_null() -> Result<File> {
.map_err(Into::into)
}
pub(crate) fn str_to_cstring(s: &str) -> Result<CString> {
CString::new(s.as_bytes()).map_err(|_| Error::EILSEQ)
}
pub fn preopen_dir<P: AsRef<Path>>(path: P) -> Result<File> {
File::open(path).map_err(Into::into)
}

View File

@@ -4,7 +4,8 @@ use super::fs_helpers::*;
use crate::ctx::WasiCtx;
use crate::fdentry::FdEntry;
use crate::helpers::systemtime_to_timestamp;
use crate::hostcalls_impl::{fd_filestat_set_times_impl, Dirent, FileType, PathGet};
use crate::host::{Dirent, FileType};
use crate::hostcalls_impl::{fd_filestat_set_times_impl, PathGet};
use crate::sys::fdentry_impl::determine_type_rights;
use crate::sys::host_impl::{self, path_from_host};
use crate::sys::hostcalls_impl::fs_helpers::PathGetExt;