wasi-common error cleanup: part 1, yanix (#1226)

* Reuse std::io::Error for raw *nix errno

This commit removes custom `yanix::Errno` and instead (as was
previously suggested) reuses `std::io::Error` to generate and wrap
raw *nix errno value.

* Update wasi-common to use new Yanix error type

This commit updates `wasi-common` to use new way of handling raw
OS error in `yanix`; i.e., via re-use of `std::io::Error` instead
of a custom `Errno` enum.

* Fix formatting

* Unwrap if io::Error created from raw OS error

This commit calls `unwrap` on `err` if that one was created via
`io::Error::last_os_error()`. It also refactors error matching
in several syscalls on the BSD platform (mainly).
This commit is contained in:
Jakub Konka
2020-03-05 10:08:28 +01:00
committed by GitHub
parent 19d8ff2bf5
commit 135a48ca7e
25 changed files with 524 additions and 705 deletions

View File

@@ -101,9 +101,6 @@ pub enum Error {
Wasi(#[from] WasiError), Wasi(#[from] WasiError),
#[error("IO error: {0}")] #[error("IO error: {0}")]
Io(#[from] std::io::Error), Io(#[from] std::io::Error),
#[cfg(unix)]
#[error("Yanix error: {0}")]
Yanix(#[from] yanix::YanixError),
} }
impl From<TryFromIntError> for Error { impl From<TryFromIntError> for Error {
@@ -150,16 +147,6 @@ impl Error {
}; };
err.as_wasi_error() err.as_wasi_error()
} }
#[cfg(unix)]
Self::Yanix(err) => {
use yanix::YanixError::*;
let err: Self = match err {
Errno(errno) => (*errno).into(),
NulError(err) => err.into(),
TryFromIntError(err) => (*err).into(),
};
err.as_wasi_error()
}
} }
} }

View File

@@ -101,9 +101,6 @@ pub enum Error {
Wasi(#[from] WasiError), Wasi(#[from] WasiError),
#[error("IO error: {0}")] #[error("IO error: {0}")]
Io(#[from] std::io::Error), Io(#[from] std::io::Error),
#[cfg(unix)]
#[error("Yanix error: {0}")]
Yanix(#[from] yanix::YanixError),
} }
impl From<TryFromIntError> for Error { impl From<TryFromIntError> for Error {
@@ -150,16 +147,6 @@ impl Error {
}; };
err.as_wasi_error() err.as_wasi_error()
} }
#[cfg(unix)]
Self::Yanix(err) => {
use yanix::YanixError::*;
let err: Self = match err {
Errno(errno) => (*errno).into(),
NulError(err) => err.into(),
TryFromIntError(err) => (*err).into(),
};
err.as_wasi_error()
}
} }
} }

View File

@@ -1,21 +1,19 @@
use crate::old::snapshot_0::hostcalls_impl::PathGet; use crate::old::snapshot_0::hostcalls_impl::PathGet;
use crate::old::snapshot_0::{Error, Result}; use crate::old::snapshot_0::{Error, Result};
use std::os::unix::prelude::AsRawFd; use std::{io, os::unix::prelude::AsRawFd};
pub(crate) fn path_unlink_file(resolved: PathGet) -> Result<()> { pub(crate) fn path_unlink_file(resolved: PathGet) -> Result<()> {
use yanix::{ use yanix::file::{unlinkat, AtFlag};
file::{unlinkat, AtFlag}, match unsafe {
Errno, YanixError,
};
unsafe {
unlinkat( unlinkat(
resolved.dirfd().as_raw_fd(), resolved.dirfd().as_raw_fd(),
resolved.path(), resolved.path(),
AtFlag::empty(), AtFlag::empty(),
) )
} } {
.map_err(|err| { Err(err) => {
if let YanixError::Errno(mut errno) = err { if let yanix::Error::Io(ref errno) = err {
let raw_errno = errno.raw_os_error().unwrap();
// Non-Linux implementations may return EPERM when attempting to remove a // Non-Linux implementations may return EPERM when attempting to remove a
// directory without REMOVEDIR. While that's what POSIX specifies, it's // 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 // less useful. Adjust this to EISDIR. It doesn't matter that this is not
@@ -25,82 +23,79 @@ pub(crate) fn path_unlink_file(resolved: PathGet) -> Result<()> {
// turned out differently. // turned out differently.
use yanix::file::{fstatat, FileType}; use yanix::file::{fstatat, FileType};
if errno == Errno::EPERM { if raw_errno == libc::EPERM {
if let Ok(stat) = unsafe { match unsafe {
fstatat( fstatat(
resolved.dirfd().as_raw_fd(), resolved.dirfd().as_raw_fd(),
resolved.path(), resolved.path(),
AtFlag::SYMLINK_NOFOLLOW, AtFlag::SYMLINK_NOFOLLOW,
) )
} { } {
Ok(stat) => {
if FileType::from_stat_st_mode(stat.st_mode) == FileType::Directory { if FileType::from_stat_st_mode(stat.st_mode) == FileType::Directory {
errno = Errno::EISDIR; return Err(io::Error::from_raw_os_error(libc::EISDIR).into());
}
} else {
errno = Errno::last();
} }
} }
errno.into() Err(err) => {
} else { log::debug!("path_unlink_file fstatat error: {:?}", err);
err }
}
}
}
Err(err.into())
}
Ok(()) => Ok(()),
} }
})
.map_err(Into::into)
} }
pub(crate) fn path_symlink(old_path: &str, resolved: PathGet) -> Result<()> { pub(crate) fn path_symlink(old_path: &str, resolved: PathGet) -> Result<()> {
use yanix::{ use yanix::file::{fstatat, symlinkat, AtFlag};
file::{fstatat, symlinkat, AtFlag},
Errno, YanixError,
};
log::debug!("path_symlink old_path = {:?}", old_path); log::debug!("path_symlink old_path = {:?}", old_path);
log::debug!("path_symlink resolved = {:?}", resolved); log::debug!("path_symlink resolved = {:?}", resolved);
unsafe { symlinkat(old_path, resolved.dirfd().as_raw_fd(), resolved.path()) }.or_else(|err| { match unsafe { symlinkat(old_path, resolved.dirfd().as_raw_fd(), resolved.path()) } {
if let YanixError::Errno(errno) = err { Err(err) => {
match errno { if let yanix::Error::Io(ref errno) = err {
Errno::ENOTDIR => { if errno.raw_os_error().unwrap() == libc::ENOTDIR {
// On BSD, symlinkat returns ENOTDIR when it should in fact // On BSD, symlinkat returns ENOTDIR when it should in fact
// return a EEXIST. It seems that it gets confused with by // return a EEXIST. It seems that it gets confused with by
// the trailing slash in the target path. Thus, we strip // the trailing slash in the target path. Thus, we strip
// the trailing slash and check if the path exists, and // the trailing slash and check if the path exists, and
// adjust the error code appropriately. // adjust the error code appropriately.
let new_path = resolved.path().trim_end_matches('/'); let new_path = resolved.path().trim_end_matches('/');
if let Ok(_) = unsafe { match unsafe {
fstatat( fstatat(
resolved.dirfd().as_raw_fd(), resolved.dirfd().as_raw_fd(),
new_path, new_path,
AtFlag::SYMLINK_NOFOLLOW, AtFlag::SYMLINK_NOFOLLOW,
) )
} { } {
Err(Error::EEXIST) Ok(_) => return Err(Error::EEXIST),
} else { Err(err) => {
Err(Error::ENOTDIR) log::debug!("path_symlink fstatat error: {:?}", err);
}
} }
} }
x => Err(x.into()),
} }
} else {
Err(err.into()) Err(err.into())
} }
}) Ok(()) => Ok(()),
}
} }
pub(crate) fn path_rename(resolved_old: PathGet, resolved_new: PathGet) -> Result<()> { pub(crate) fn path_rename(resolved_old: PathGet, resolved_new: PathGet) -> Result<()> {
use yanix::{ use yanix::file::{fstatat, renameat, AtFlag};
file::{fstatat, renameat, AtFlag}, match unsafe {
Errno, YanixError,
};
unsafe {
renameat( renameat(
resolved_old.dirfd().as_raw_fd(), resolved_old.dirfd().as_raw_fd(),
resolved_old.path(), resolved_old.path(),
resolved_new.dirfd().as_raw_fd(), resolved_new.dirfd().as_raw_fd(),
resolved_new.path(), resolved_new.path(),
) )
} } {
.or_else(|err| { Err(err) => {
// Currently, this is verified to be correct on macOS, where // Currently, this is verified to be correct on macOS, where
// ENOENT can be returned in case when we try to rename a file // 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 // into a name with a trailing slash. On macOS, if the latter does
@@ -110,33 +105,35 @@ pub(crate) fn path_rename(resolved_old: PathGet, resolved_new: PathGet) -> Resul
// //
// TODO // TODO
// Verify on other BSD-based OSes. // Verify on other BSD-based OSes.
if let YanixError::Errno(errno) = err { if let yanix::Error::Io(ref errno) = err {
match errno { if errno.raw_os_error().unwrap() == libc::ENOENT {
Errno::ENOENT => {
// check if the source path exists // check if the source path exists
if let Ok(_) = unsafe { match unsafe {
fstatat( fstatat(
resolved_old.dirfd().as_raw_fd(), resolved_old.dirfd().as_raw_fd(),
resolved_old.path(), resolved_old.path(),
AtFlag::SYMLINK_NOFOLLOW, AtFlag::SYMLINK_NOFOLLOW,
) )
} { } {
Ok(_) => {
// check if destination contains a trailing slash // check if destination contains a trailing slash
if resolved_new.path().contains('/') { if resolved_new.path().contains('/') {
Err(Error::ENOTDIR) return Err(Error::ENOTDIR);
} else { } else {
Err(Error::ENOENT) return Err(Error::ENOENT);
}
} else {
Err(Error::ENOENT)
} }
} }
x => Err(x.into()), Err(err) => {
log::debug!("path_rename fstatat error: {:?}", err);
} }
} else { }
}
}
Err(err.into()) Err(err.into())
} }
}) Ok(()) => Ok(()),
}
} }
pub(crate) mod fd_readdir_impl { pub(crate) mod fd_readdir_impl {

View File

@@ -8,93 +8,102 @@ use crate::old::snapshot_0::{
}; };
use std::ffi::OsStr; use std::ffi::OsStr;
use std::os::unix::prelude::OsStrExt; use std::os::unix::prelude::OsStrExt;
use yanix::{file::OFlag, Errno}; use yanix::file::OFlag;
pub(crate) use sys_impl::host_impl::*; pub(crate) use sys_impl::host_impl::*;
impl FromRawOsError for Error { impl From<yanix::Error> for Error {
fn from_raw_os_error(code: i32) -> Self { fn from(err: yanix::Error) -> Self {
Self::from(Errno::from_i32(code)) use yanix::Error::*;
match err {
Io(err) => err.into(),
Nul(err) => err.into(),
IntConversion(err) => err.into(),
}
} }
} }
impl From<Errno> for Error { impl FromRawOsError for Error {
fn from(errno: Errno) -> Self { fn from_raw_os_error(code: i32) -> Self {
match errno { match code {
Errno::EPERM => Self::EPERM, libc::EPERM => Self::EPERM,
Errno::ENOENT => Self::ENOENT, libc::ENOENT => Self::ENOENT,
Errno::ESRCH => Self::ESRCH, libc::ESRCH => Self::ESRCH,
Errno::EINTR => Self::EINTR, libc::EINTR => Self::EINTR,
Errno::EIO => Self::EIO, libc::EIO => Self::EIO,
Errno::ENXIO => Self::ENXIO, libc::ENXIO => Self::ENXIO,
Errno::E2BIG => Self::E2BIG, libc::E2BIG => Self::E2BIG,
Errno::ENOEXEC => Self::ENOEXEC, libc::ENOEXEC => Self::ENOEXEC,
Errno::EBADF => Self::EBADF, libc::EBADF => Self::EBADF,
Errno::ECHILD => Self::ECHILD, libc::ECHILD => Self::ECHILD,
Errno::EAGAIN => Self::EAGAIN, libc::EAGAIN => Self::EAGAIN,
Errno::ENOMEM => Self::ENOMEM, libc::ENOMEM => Self::ENOMEM,
Errno::EACCES => Self::EACCES, libc::EACCES => Self::EACCES,
Errno::EFAULT => Self::EFAULT, libc::EFAULT => Self::EFAULT,
Errno::EBUSY => Self::EBUSY, libc::EBUSY => Self::EBUSY,
Errno::EEXIST => Self::EEXIST, libc::EEXIST => Self::EEXIST,
Errno::EXDEV => Self::EXDEV, libc::EXDEV => Self::EXDEV,
Errno::ENODEV => Self::ENODEV, libc::ENODEV => Self::ENODEV,
Errno::ENOTDIR => Self::ENOTDIR, libc::ENOTDIR => Self::ENOTDIR,
Errno::EISDIR => Self::EISDIR, libc::EISDIR => Self::EISDIR,
Errno::EINVAL => Self::EINVAL, libc::EINVAL => Self::EINVAL,
Errno::ENFILE => Self::ENFILE, libc::ENFILE => Self::ENFILE,
Errno::EMFILE => Self::EMFILE, libc::EMFILE => Self::EMFILE,
Errno::ENOTTY => Self::ENOTTY, libc::ENOTTY => Self::ENOTTY,
Errno::ETXTBSY => Self::ETXTBSY, libc::ETXTBSY => Self::ETXTBSY,
Errno::EFBIG => Self::EFBIG, libc::EFBIG => Self::EFBIG,
Errno::ENOSPC => Self::ENOSPC, libc::ENOSPC => Self::ENOSPC,
Errno::ESPIPE => Self::ESPIPE, libc::ESPIPE => Self::ESPIPE,
Errno::EROFS => Self::EROFS, libc::EROFS => Self::EROFS,
Errno::EMLINK => Self::EMLINK, libc::EMLINK => Self::EMLINK,
Errno::EPIPE => Self::EPIPE, libc::EPIPE => Self::EPIPE,
Errno::EDOM => Self::EDOM, libc::EDOM => Self::EDOM,
Errno::ERANGE => Self::ERANGE, libc::ERANGE => Self::ERANGE,
Errno::EDEADLK => Self::EDEADLK, libc::EDEADLK => Self::EDEADLK,
Errno::ENAMETOOLONG => Self::ENAMETOOLONG, libc::ENAMETOOLONG => Self::ENAMETOOLONG,
Errno::ENOLCK => Self::ENOLCK, libc::ENOLCK => Self::ENOLCK,
Errno::ENOSYS => Self::ENOSYS, libc::ENOSYS => Self::ENOSYS,
Errno::ENOTEMPTY => Self::ENOTEMPTY, libc::ENOTEMPTY => Self::ENOTEMPTY,
Errno::ELOOP => Self::ELOOP, libc::ELOOP => Self::ELOOP,
Errno::ENOMSG => Self::ENOMSG, libc::ENOMSG => Self::ENOMSG,
Errno::EIDRM => Self::EIDRM, libc::EIDRM => Self::EIDRM,
Errno::ENOLINK => Self::ENOLINK, libc::ENOLINK => Self::ENOLINK,
Errno::EPROTO => Self::EPROTO, libc::EPROTO => Self::EPROTO,
Errno::EMULTIHOP => Self::EMULTIHOP, libc::EMULTIHOP => Self::EMULTIHOP,
Errno::EBADMSG => Self::EBADMSG, libc::EBADMSG => Self::EBADMSG,
Errno::EOVERFLOW => Self::EOVERFLOW, libc::EOVERFLOW => Self::EOVERFLOW,
Errno::EILSEQ => Self::EILSEQ, libc::EILSEQ => Self::EILSEQ,
Errno::ENOTSOCK => Self::ENOTSOCK, libc::ENOTSOCK => Self::ENOTSOCK,
Errno::EDESTADDRREQ => Self::EDESTADDRREQ, libc::EDESTADDRREQ => Self::EDESTADDRREQ,
Errno::EMSGSIZE => Self::EMSGSIZE, libc::EMSGSIZE => Self::EMSGSIZE,
Errno::EPROTOTYPE => Self::EPROTOTYPE, libc::EPROTOTYPE => Self::EPROTOTYPE,
Errno::ENOPROTOOPT => Self::ENOPROTOOPT, libc::ENOPROTOOPT => Self::ENOPROTOOPT,
Errno::EPROTONOSUPPORT => Self::EPROTONOSUPPORT, libc::EPROTONOSUPPORT => Self::EPROTONOSUPPORT,
Errno::EAFNOSUPPORT => Self::EAFNOSUPPORT, libc::EAFNOSUPPORT => Self::EAFNOSUPPORT,
Errno::EADDRINUSE => Self::EADDRINUSE, libc::EADDRINUSE => Self::EADDRINUSE,
Errno::EADDRNOTAVAIL => Self::EADDRNOTAVAIL, libc::EADDRNOTAVAIL => Self::EADDRNOTAVAIL,
Errno::ENETDOWN => Self::ENETDOWN, libc::ENETDOWN => Self::ENETDOWN,
Errno::ENETUNREACH => Self::ENETUNREACH, libc::ENETUNREACH => Self::ENETUNREACH,
Errno::ENETRESET => Self::ENETRESET, libc::ENETRESET => Self::ENETRESET,
Errno::ECONNABORTED => Self::ECONNABORTED, libc::ECONNABORTED => Self::ECONNABORTED,
Errno::ECONNRESET => Self::ECONNRESET, libc::ECONNRESET => Self::ECONNRESET,
Errno::ENOBUFS => Self::ENOBUFS, libc::ENOBUFS => Self::ENOBUFS,
Errno::EISCONN => Self::EISCONN, libc::EISCONN => Self::EISCONN,
Errno::ENOTCONN => Self::ENOTCONN, libc::ENOTCONN => Self::ENOTCONN,
Errno::ETIMEDOUT => Self::ETIMEDOUT, libc::ETIMEDOUT => Self::ETIMEDOUT,
Errno::ECONNREFUSED => Self::ECONNREFUSED, libc::ECONNREFUSED => Self::ECONNREFUSED,
Errno::EHOSTUNREACH => Self::EHOSTUNREACH, libc::EHOSTUNREACH => Self::EHOSTUNREACH,
Errno::EALREADY => Self::EALREADY, libc::EALREADY => Self::EALREADY,
Errno::EINPROGRESS => Self::EINPROGRESS, libc::EINPROGRESS => Self::EINPROGRESS,
Errno::ESTALE => Self::ESTALE, libc::ESTALE => Self::ESTALE,
Errno::EDQUOT => Self::EDQUOT, libc::EDQUOT => Self::EDQUOT,
Errno::ECANCELED => Self::ECANCELED, libc::ECANCELED => Self::ECANCELED,
Errno::EOWNERDEAD => Self::EOWNERDEAD, libc::EOWNERDEAD => Self::EOWNERDEAD,
Errno::ENOTRECOVERABLE => Self::ENOTRECOVERABLE, libc::ENOTRECOVERABLE => Self::ENOTRECOVERABLE,
x => {
log::debug!("Unknown errno value: {}", x);
Self::EIO
}
} }
} }
} }

View File

@@ -88,10 +88,7 @@ pub(crate) fn path_open(
oflags: wasi::__wasi_oflags_t, oflags: wasi::__wasi_oflags_t,
fs_flags: wasi::__wasi_fdflags_t, fs_flags: wasi::__wasi_fdflags_t,
) -> Result<File> { ) -> Result<File> {
use yanix::{ use yanix::file::{fstatat, openat, AtFlag, FileType, Mode, OFlag};
file::{fstatat, openat, AtFlag, FileType, Mode, OFlag},
Errno,
};
let mut nix_all_oflags = if read && write { let mut nix_all_oflags = if read && write {
OFlag::RDWR OFlag::RDWR
@@ -127,55 +124,60 @@ pub(crate) fn path_open(
} { } {
Ok(fd) => fd, Ok(fd) => fd,
Err(e) => { Err(e) => {
if let yanix::YanixError::Errno(errno) = e { if let yanix::Error::Io(ref err) = e {
match errno { match err.raw_os_error().unwrap() {
// Linux returns ENXIO instead of EOPNOTSUPP when opening a socket // Linux returns ENXIO instead of EOPNOTSUPP when opening a socket
Errno::ENXIO => { libc::ENXIO => {
if let Ok(stat) = unsafe { match unsafe {
fstatat( fstatat(
resolved.dirfd().as_raw_fd(), resolved.dirfd().as_raw_fd(),
resolved.path(), resolved.path(),
AtFlag::SYMLINK_NOFOLLOW, AtFlag::SYMLINK_NOFOLLOW,
) )
} { } {
Ok(stat) => {
if FileType::from_stat_st_mode(stat.st_mode) == FileType::Socket { if FileType::from_stat_st_mode(stat.st_mode) == FileType::Socket {
return Err(Error::ENOTSUP); return Err(Error::ENOTSUP);
} else {
return Err(Error::ENXIO);
} }
} else { }
return Err(Error::ENXIO); Err(err) => {
log::debug!("path_open fstatat error: {:?}", err);
}
} }
} }
// Linux returns ENOTDIR instead of ELOOP when using O_NOFOLLOW|O_DIRECTORY // Linux returns ENOTDIR instead of ELOOP when using O_NOFOLLOW|O_DIRECTORY
// on a symlink. // on a symlink.
Errno::ENOTDIR libc::ENOTDIR
if !(nix_all_oflags & (OFlag::NOFOLLOW | OFlag::DIRECTORY)).is_empty() => if !(nix_all_oflags & (OFlag::NOFOLLOW | OFlag::DIRECTORY)).is_empty() =>
{ {
if let Ok(stat) = unsafe { match unsafe {
fstatat( fstatat(
resolved.dirfd().as_raw_fd(), resolved.dirfd().as_raw_fd(),
resolved.path(), resolved.path(),
AtFlag::SYMLINK_NOFOLLOW, AtFlag::SYMLINK_NOFOLLOW,
) )
} { } {
Ok(stat) => {
if FileType::from_stat_st_mode(stat.st_mode) == FileType::Symlink { if FileType::from_stat_st_mode(stat.st_mode) == FileType::Symlink {
return Err(Error::ELOOP); return Err(Error::ELOOP);
} }
} }
return Err(Error::ENOTDIR); Err(err) => {
log::debug!("path_open fstatat error: {:?}", err);
}
}
} }
// FreeBSD returns EMLINK instead of ELOOP when using O_NOFOLLOW on // FreeBSD returns EMLINK instead of ELOOP when using O_NOFOLLOW on
// a symlink. // a symlink.
Errno::EMLINK if !(nix_all_oflags & OFlag::NOFOLLOW).is_empty() => { libc::EMLINK if !(nix_all_oflags & OFlag::NOFOLLOW).is_empty() => {
return Err(Error::ELOOP); return Err(Error::ELOOP);
} }
errno => return Err(errno.into()), _ => {}
} }
} else { }
return Err(e.into()); return Err(e.into());
} }
}
}; };
log::debug!("path_open (host) new_fd = {:?}", new_fd); log::debug!("path_open (host) new_fd = {:?}", new_fd);

View File

@@ -2,6 +2,7 @@
#![allow(unused_unsafe)] #![allow(unused_unsafe)]
use crate::old::snapshot_0::hostcalls_impl::{ClockEventData, FdEventData}; use crate::old::snapshot_0::hostcalls_impl::{ClockEventData, FdEventData};
use crate::old::snapshot_0::{wasi, Error, Result}; use crate::old::snapshot_0::{wasi, Error, Result};
use std::io;
use yanix::clock::{clock_getres, clock_gettime, ClockId}; use yanix::clock::{clock_getres, clock_gettime, ClockId};
fn wasi_clock_id_to_unix(clock_id: wasi::__wasi_clockid_t) -> Result<ClockId> { fn wasi_clock_id_to_unix(clock_id: wasi::__wasi_clockid_t) -> Result<ClockId> {
@@ -54,10 +55,7 @@ pub(crate) fn poll_oneoff(
events: &mut Vec<wasi::__wasi_event_t>, events: &mut Vec<wasi::__wasi_event_t>,
) -> Result<()> { ) -> Result<()> {
use std::{convert::TryInto, os::unix::prelude::AsRawFd}; use std::{convert::TryInto, os::unix::prelude::AsRawFd};
use yanix::{ use yanix::poll::{poll, PollFd, PollFlags};
poll::{poll, PollFd, PollFlags},
Errno,
};
if fd_events.is_empty() && timeout.is_none() { if fd_events.is_empty() && timeout.is_none() {
return Ok(()); return Ok(());
@@ -88,10 +86,11 @@ pub(crate) fn poll_oneoff(
let ready = loop { let ready = loop {
match poll(&mut poll_fds, poll_timeout) { match poll(&mut poll_fds, poll_timeout) {
Err(_) => { Err(_) => {
if Errno::last() == Errno::EINTR { let last_err = io::Error::last_os_error();
if last_err.raw_os_error().unwrap() == libc::EINTR {
continue; continue;
} }
return Err(Errno::last().into()); return Err(last_err.into());
} }
Ok(ready) => break ready, Ok(ready) => break ready,
} }

View File

@@ -1,21 +1,19 @@
use crate::hostcalls_impl::PathGet; use crate::hostcalls_impl::PathGet;
use crate::{Error, Result}; use crate::{Error, Result};
use std::os::unix::prelude::AsRawFd; use std::{io, os::unix::prelude::AsRawFd};
pub(crate) fn path_unlink_file(resolved: PathGet) -> Result<()> { pub(crate) fn path_unlink_file(resolved: PathGet) -> Result<()> {
use yanix::{ use yanix::file::{unlinkat, AtFlag};
file::{unlinkat, AtFlag}, match unsafe {
Errno, YanixError,
};
unsafe {
unlinkat( unlinkat(
resolved.dirfd().as_raw_fd(), resolved.dirfd().as_raw_fd(),
resolved.path(), resolved.path(),
AtFlag::empty(), AtFlag::empty(),
) )
} } {
.map_err(|err| { Err(err) => {
if let YanixError::Errno(mut errno) = err { if let yanix::Error::Io(ref errno) = err {
let raw_errno = errno.raw_os_error().unwrap();
// Non-Linux implementations may return EPERM when attempting to remove a // Non-Linux implementations may return EPERM when attempting to remove a
// directory without REMOVEDIR. While that's what POSIX specifies, it's // 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 // less useful. Adjust this to EISDIR. It doesn't matter that this is not
@@ -25,82 +23,79 @@ pub(crate) fn path_unlink_file(resolved: PathGet) -> Result<()> {
// turned out differently. // turned out differently.
use yanix::file::{fstatat, FileType}; use yanix::file::{fstatat, FileType};
if errno == Errno::EPERM { if raw_errno == libc::EPERM {
if let Ok(stat) = unsafe { match unsafe {
fstatat( fstatat(
resolved.dirfd().as_raw_fd(), resolved.dirfd().as_raw_fd(),
resolved.path(), resolved.path(),
AtFlag::SYMLINK_NOFOLLOW, AtFlag::SYMLINK_NOFOLLOW,
) )
} { } {
Ok(stat) => {
if FileType::from_stat_st_mode(stat.st_mode) == FileType::Directory { if FileType::from_stat_st_mode(stat.st_mode) == FileType::Directory {
errno = Errno::EISDIR; return Err(io::Error::from_raw_os_error(libc::EISDIR).into());
}
} else {
errno = Errno::last();
} }
} }
errno.into() Err(err) => {
} else { log::debug!("path_unlink_file fstatat error: {:?}", err);
err }
}
}
}
Err(err.into())
}
Ok(()) => Ok(()),
} }
})
.map_err(Into::into)
} }
pub(crate) fn path_symlink(old_path: &str, resolved: PathGet) -> Result<()> { pub(crate) fn path_symlink(old_path: &str, resolved: PathGet) -> Result<()> {
use yanix::{ use yanix::file::{fstatat, symlinkat, AtFlag};
file::{fstatat, symlinkat, AtFlag},
Errno, YanixError,
};
log::debug!("path_symlink old_path = {:?}", old_path); log::debug!("path_symlink old_path = {:?}", old_path);
log::debug!("path_symlink resolved = {:?}", resolved); log::debug!("path_symlink resolved = {:?}", resolved);
unsafe { symlinkat(old_path, resolved.dirfd().as_raw_fd(), resolved.path()) }.or_else(|err| { match unsafe { symlinkat(old_path, resolved.dirfd().as_raw_fd(), resolved.path()) } {
if let YanixError::Errno(errno) = err { Err(err) => {
match errno { if let yanix::Error::Io(ref errno) = err {
Errno::ENOTDIR => { if errno.raw_os_error().unwrap() == libc::ENOTDIR {
// On BSD, symlinkat returns ENOTDIR when it should in fact // On BSD, symlinkat returns ENOTDIR when it should in fact
// return a EEXIST. It seems that it gets confused with by // return a EEXIST. It seems that it gets confused with by
// the trailing slash in the target path. Thus, we strip // the trailing slash in the target path. Thus, we strip
// the trailing slash and check if the path exists, and // the trailing slash and check if the path exists, and
// adjust the error code appropriately. // adjust the error code appropriately.
let new_path = resolved.path().trim_end_matches('/'); let new_path = resolved.path().trim_end_matches('/');
if let Ok(_) = unsafe { match unsafe {
fstatat( fstatat(
resolved.dirfd().as_raw_fd(), resolved.dirfd().as_raw_fd(),
new_path, new_path,
AtFlag::SYMLINK_NOFOLLOW, AtFlag::SYMLINK_NOFOLLOW,
) )
} { } {
Err(Error::EEXIST) Ok(_) => return Err(Error::EEXIST),
} else { Err(err) => {
Err(Error::ENOTDIR) log::debug!("path_symlink fstatat error: {:?}", err);
}
} }
} }
x => Err(x.into()),
} }
} else {
Err(err.into()) Err(err.into())
} }
}) Ok(()) => Ok(()),
}
} }
pub(crate) fn path_rename(resolved_old: PathGet, resolved_new: PathGet) -> Result<()> { pub(crate) fn path_rename(resolved_old: PathGet, resolved_new: PathGet) -> Result<()> {
use yanix::{ use yanix::file::{fstatat, renameat, AtFlag};
file::{fstatat, renameat, AtFlag}, match unsafe {
Errno, YanixError,
};
unsafe {
renameat( renameat(
resolved_old.dirfd().as_raw_fd(), resolved_old.dirfd().as_raw_fd(),
resolved_old.path(), resolved_old.path(),
resolved_new.dirfd().as_raw_fd(), resolved_new.dirfd().as_raw_fd(),
resolved_new.path(), resolved_new.path(),
) )
} } {
.or_else(|err| { Err(err) => {
// Currently, this is verified to be correct on macOS, where // Currently, this is verified to be correct on macOS, where
// ENOENT can be returned in case when we try to rename a file // 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 // into a name with a trailing slash. On macOS, if the latter does
@@ -110,33 +105,35 @@ pub(crate) fn path_rename(resolved_old: PathGet, resolved_new: PathGet) -> Resul
// //
// TODO // TODO
// Verify on other BSD-based OSes. // Verify on other BSD-based OSes.
if let YanixError::Errno(errno) = err { if let yanix::Error::Io(ref errno) = err {
match errno { if errno.raw_os_error().unwrap() == libc::ENOENT {
Errno::ENOENT => {
// check if the source path exists // check if the source path exists
if let Ok(_) = unsafe { match unsafe {
fstatat( fstatat(
resolved_old.dirfd().as_raw_fd(), resolved_old.dirfd().as_raw_fd(),
resolved_old.path(), resolved_old.path(),
AtFlag::SYMLINK_NOFOLLOW, AtFlag::SYMLINK_NOFOLLOW,
) )
} { } {
Ok(_) => {
// check if destination contains a trailing slash // check if destination contains a trailing slash
if resolved_new.path().contains('/') { if resolved_new.path().contains('/') {
Err(Error::ENOTDIR) return Err(Error::ENOTDIR);
} else { } else {
Err(Error::ENOENT) return Err(Error::ENOENT);
}
} else {
Err(Error::ENOENT)
} }
} }
x => Err(x.into()), Err(err) => {
log::debug!("path_rename fstatat error: {:?}", err);
} }
} else { }
}
}
Err(err.into()) Err(err.into())
} }
}) Ok(()) => Ok(()),
}
} }
pub(crate) mod fd_readdir_impl { pub(crate) mod fd_readdir_impl {

View File

@@ -6,93 +6,102 @@ use crate::host::FileType;
use crate::{error::FromRawOsError, helpers, sys::unix::sys_impl, wasi, Error, Result}; use crate::{error::FromRawOsError, helpers, sys::unix::sys_impl, wasi, Error, Result};
use std::ffi::OsStr; use std::ffi::OsStr;
use std::os::unix::prelude::OsStrExt; use std::os::unix::prelude::OsStrExt;
use yanix::{file::OFlag, Errno}; use yanix::file::OFlag;
pub(crate) use sys_impl::host_impl::*; pub(crate) use sys_impl::host_impl::*;
impl FromRawOsError for Error { impl From<yanix::Error> for Error {
fn from_raw_os_error(code: i32) -> Self { fn from(err: yanix::Error) -> Self {
Self::from(Errno::from_i32(code)) use yanix::Error::*;
match err {
Io(err) => err.into(),
Nul(err) => err.into(),
IntConversion(err) => err.into(),
}
} }
} }
impl From<Errno> for Error { impl FromRawOsError for Error {
fn from(errno: Errno) -> Self { fn from_raw_os_error(code: i32) -> Self {
match errno { match code {
Errno::EPERM => Self::EPERM, libc::EPERM => Self::EPERM,
Errno::ENOENT => Self::ENOENT, libc::ENOENT => Self::ENOENT,
Errno::ESRCH => Self::ESRCH, libc::ESRCH => Self::ESRCH,
Errno::EINTR => Self::EINTR, libc::EINTR => Self::EINTR,
Errno::EIO => Self::EIO, libc::EIO => Self::EIO,
Errno::ENXIO => Self::ENXIO, libc::ENXIO => Self::ENXIO,
Errno::E2BIG => Self::E2BIG, libc::E2BIG => Self::E2BIG,
Errno::ENOEXEC => Self::ENOEXEC, libc::ENOEXEC => Self::ENOEXEC,
Errno::EBADF => Self::EBADF, libc::EBADF => Self::EBADF,
Errno::ECHILD => Self::ECHILD, libc::ECHILD => Self::ECHILD,
Errno::EAGAIN => Self::EAGAIN, libc::EAGAIN => Self::EAGAIN,
Errno::ENOMEM => Self::ENOMEM, libc::ENOMEM => Self::ENOMEM,
Errno::EACCES => Self::EACCES, libc::EACCES => Self::EACCES,
Errno::EFAULT => Self::EFAULT, libc::EFAULT => Self::EFAULT,
Errno::EBUSY => Self::EBUSY, libc::EBUSY => Self::EBUSY,
Errno::EEXIST => Self::EEXIST, libc::EEXIST => Self::EEXIST,
Errno::EXDEV => Self::EXDEV, libc::EXDEV => Self::EXDEV,
Errno::ENODEV => Self::ENODEV, libc::ENODEV => Self::ENODEV,
Errno::ENOTDIR => Self::ENOTDIR, libc::ENOTDIR => Self::ENOTDIR,
Errno::EISDIR => Self::EISDIR, libc::EISDIR => Self::EISDIR,
Errno::EINVAL => Self::EINVAL, libc::EINVAL => Self::EINVAL,
Errno::ENFILE => Self::ENFILE, libc::ENFILE => Self::ENFILE,
Errno::EMFILE => Self::EMFILE, libc::EMFILE => Self::EMFILE,
Errno::ENOTTY => Self::ENOTTY, libc::ENOTTY => Self::ENOTTY,
Errno::ETXTBSY => Self::ETXTBSY, libc::ETXTBSY => Self::ETXTBSY,
Errno::EFBIG => Self::EFBIG, libc::EFBIG => Self::EFBIG,
Errno::ENOSPC => Self::ENOSPC, libc::ENOSPC => Self::ENOSPC,
Errno::ESPIPE => Self::ESPIPE, libc::ESPIPE => Self::ESPIPE,
Errno::EROFS => Self::EROFS, libc::EROFS => Self::EROFS,
Errno::EMLINK => Self::EMLINK, libc::EMLINK => Self::EMLINK,
Errno::EPIPE => Self::EPIPE, libc::EPIPE => Self::EPIPE,
Errno::EDOM => Self::EDOM, libc::EDOM => Self::EDOM,
Errno::ERANGE => Self::ERANGE, libc::ERANGE => Self::ERANGE,
Errno::EDEADLK => Self::EDEADLK, libc::EDEADLK => Self::EDEADLK,
Errno::ENAMETOOLONG => Self::ENAMETOOLONG, libc::ENAMETOOLONG => Self::ENAMETOOLONG,
Errno::ENOLCK => Self::ENOLCK, libc::ENOLCK => Self::ENOLCK,
Errno::ENOSYS => Self::ENOSYS, libc::ENOSYS => Self::ENOSYS,
Errno::ENOTEMPTY => Self::ENOTEMPTY, libc::ENOTEMPTY => Self::ENOTEMPTY,
Errno::ELOOP => Self::ELOOP, libc::ELOOP => Self::ELOOP,
Errno::ENOMSG => Self::ENOMSG, libc::ENOMSG => Self::ENOMSG,
Errno::EIDRM => Self::EIDRM, libc::EIDRM => Self::EIDRM,
Errno::ENOLINK => Self::ENOLINK, libc::ENOLINK => Self::ENOLINK,
Errno::EPROTO => Self::EPROTO, libc::EPROTO => Self::EPROTO,
Errno::EMULTIHOP => Self::EMULTIHOP, libc::EMULTIHOP => Self::EMULTIHOP,
Errno::EBADMSG => Self::EBADMSG, libc::EBADMSG => Self::EBADMSG,
Errno::EOVERFLOW => Self::EOVERFLOW, libc::EOVERFLOW => Self::EOVERFLOW,
Errno::EILSEQ => Self::EILSEQ, libc::EILSEQ => Self::EILSEQ,
Errno::ENOTSOCK => Self::ENOTSOCK, libc::ENOTSOCK => Self::ENOTSOCK,
Errno::EDESTADDRREQ => Self::EDESTADDRREQ, libc::EDESTADDRREQ => Self::EDESTADDRREQ,
Errno::EMSGSIZE => Self::EMSGSIZE, libc::EMSGSIZE => Self::EMSGSIZE,
Errno::EPROTOTYPE => Self::EPROTOTYPE, libc::EPROTOTYPE => Self::EPROTOTYPE,
Errno::ENOPROTOOPT => Self::ENOPROTOOPT, libc::ENOPROTOOPT => Self::ENOPROTOOPT,
Errno::EPROTONOSUPPORT => Self::EPROTONOSUPPORT, libc::EPROTONOSUPPORT => Self::EPROTONOSUPPORT,
Errno::EAFNOSUPPORT => Self::EAFNOSUPPORT, libc::EAFNOSUPPORT => Self::EAFNOSUPPORT,
Errno::EADDRINUSE => Self::EADDRINUSE, libc::EADDRINUSE => Self::EADDRINUSE,
Errno::EADDRNOTAVAIL => Self::EADDRNOTAVAIL, libc::EADDRNOTAVAIL => Self::EADDRNOTAVAIL,
Errno::ENETDOWN => Self::ENETDOWN, libc::ENETDOWN => Self::ENETDOWN,
Errno::ENETUNREACH => Self::ENETUNREACH, libc::ENETUNREACH => Self::ENETUNREACH,
Errno::ENETRESET => Self::ENETRESET, libc::ENETRESET => Self::ENETRESET,
Errno::ECONNABORTED => Self::ECONNABORTED, libc::ECONNABORTED => Self::ECONNABORTED,
Errno::ECONNRESET => Self::ECONNRESET, libc::ECONNRESET => Self::ECONNRESET,
Errno::ENOBUFS => Self::ENOBUFS, libc::ENOBUFS => Self::ENOBUFS,
Errno::EISCONN => Self::EISCONN, libc::EISCONN => Self::EISCONN,
Errno::ENOTCONN => Self::ENOTCONN, libc::ENOTCONN => Self::ENOTCONN,
Errno::ETIMEDOUT => Self::ETIMEDOUT, libc::ETIMEDOUT => Self::ETIMEDOUT,
Errno::ECONNREFUSED => Self::ECONNREFUSED, libc::ECONNREFUSED => Self::ECONNREFUSED,
Errno::EHOSTUNREACH => Self::EHOSTUNREACH, libc::EHOSTUNREACH => Self::EHOSTUNREACH,
Errno::EALREADY => Self::EALREADY, libc::EALREADY => Self::EALREADY,
Errno::EINPROGRESS => Self::EINPROGRESS, libc::EINPROGRESS => Self::EINPROGRESS,
Errno::ESTALE => Self::ESTALE, libc::ESTALE => Self::ESTALE,
Errno::EDQUOT => Self::EDQUOT, libc::EDQUOT => Self::EDQUOT,
Errno::ECANCELED => Self::ECANCELED, libc::ECANCELED => Self::ECANCELED,
Errno::EOWNERDEAD => Self::EOWNERDEAD, libc::EOWNERDEAD => Self::EOWNERDEAD,
Errno::ENOTRECOVERABLE => Self::ENOTRECOVERABLE, libc::ENOTRECOVERABLE => Self::ENOTRECOVERABLE,
x => {
log::debug!("Unknown errno value: {}", x);
Self::EIO
}
} }
} }
} }

View File

@@ -93,10 +93,7 @@ pub(crate) fn path_open(
oflags: wasi::__wasi_oflags_t, oflags: wasi::__wasi_oflags_t,
fs_flags: wasi::__wasi_fdflags_t, fs_flags: wasi::__wasi_fdflags_t,
) -> Result<File> { ) -> Result<File> {
use yanix::{ use yanix::file::{fstatat, openat, AtFlag, FileType, Mode, OFlag};
file::{fstatat, openat, AtFlag, FileType, Mode, OFlag},
Errno,
};
let mut nix_all_oflags = if read && write { let mut nix_all_oflags = if read && write {
OFlag::RDWR OFlag::RDWR
@@ -132,55 +129,60 @@ pub(crate) fn path_open(
} { } {
Ok(fd) => fd, Ok(fd) => fd,
Err(e) => { Err(e) => {
if let yanix::YanixError::Errno(errno) = e { if let yanix::Error::Io(ref err) = e {
match errno { match err.raw_os_error().unwrap() {
// Linux returns ENXIO instead of EOPNOTSUPP when opening a socket // Linux returns ENXIO instead of EOPNOTSUPP when opening a socket
Errno::ENXIO => { libc::ENXIO => {
if let Ok(stat) = unsafe { match unsafe {
fstatat( fstatat(
resolved.dirfd().as_raw_fd(), resolved.dirfd().as_raw_fd(),
resolved.path(), resolved.path(),
AtFlag::SYMLINK_NOFOLLOW, AtFlag::SYMLINK_NOFOLLOW,
) )
} { } {
Ok(stat) => {
if FileType::from_stat_st_mode(stat.st_mode) == FileType::Socket { if FileType::from_stat_st_mode(stat.st_mode) == FileType::Socket {
return Err(Error::ENOTSUP); return Err(Error::ENOTSUP);
} else {
return Err(Error::ENXIO);
} }
} else { }
return Err(Error::ENXIO); Err(err) => {
log::debug!("path_open fstatat error: {:?}", err);
}
} }
} }
// Linux returns ENOTDIR instead of ELOOP when using O_NOFOLLOW|O_DIRECTORY // Linux returns ENOTDIR instead of ELOOP when using O_NOFOLLOW|O_DIRECTORY
// on a symlink. // on a symlink.
Errno::ENOTDIR libc::ENOTDIR
if !(nix_all_oflags & (OFlag::NOFOLLOW | OFlag::DIRECTORY)).is_empty() => if !(nix_all_oflags & (OFlag::NOFOLLOW | OFlag::DIRECTORY)).is_empty() =>
{ {
if let Ok(stat) = unsafe { match unsafe {
fstatat( fstatat(
resolved.dirfd().as_raw_fd(), resolved.dirfd().as_raw_fd(),
resolved.path(), resolved.path(),
AtFlag::SYMLINK_NOFOLLOW, AtFlag::SYMLINK_NOFOLLOW,
) )
} { } {
Ok(stat) => {
if FileType::from_stat_st_mode(stat.st_mode) == FileType::Symlink { if FileType::from_stat_st_mode(stat.st_mode) == FileType::Symlink {
return Err(Error::ELOOP); return Err(Error::ELOOP);
} }
} }
return Err(Error::ENOTDIR); Err(err) => {
log::debug!("path_open fstatat error: {:?}", err);
}
}
} }
// FreeBSD returns EMLINK instead of ELOOP when using O_NOFOLLOW on // FreeBSD returns EMLINK instead of ELOOP when using O_NOFOLLOW on
// a symlink. // a symlink.
Errno::EMLINK if !(nix_all_oflags & OFlag::NOFOLLOW).is_empty() => { libc::EMLINK if !(nix_all_oflags & OFlag::NOFOLLOW).is_empty() => {
return Err(Error::ELOOP); return Err(Error::ELOOP);
} }
errno => return Err(errno.into()), _ => {}
} }
} else { }
return Err(e.into()); return Err(e.into());
} }
}
}; };
log::debug!("path_open (host) new_fd = {:?}", new_fd); log::debug!("path_open (host) new_fd = {:?}", new_fd);

View File

@@ -2,6 +2,7 @@
#![allow(unused_unsafe)] #![allow(unused_unsafe)]
use crate::hostcalls_impl::{ClockEventData, FdEventData}; use crate::hostcalls_impl::{ClockEventData, FdEventData};
use crate::{wasi, Error, Result}; use crate::{wasi, Error, Result};
use std::io;
use yanix::clock::{clock_getres, clock_gettime, ClockId}; use yanix::clock::{clock_getres, clock_gettime, ClockId};
fn wasi_clock_id_to_unix(clock_id: wasi::__wasi_clockid_t) -> Result<ClockId> { fn wasi_clock_id_to_unix(clock_id: wasi::__wasi_clockid_t) -> Result<ClockId> {
@@ -54,10 +55,7 @@ pub(crate) fn poll_oneoff(
events: &mut Vec<wasi::__wasi_event_t>, events: &mut Vec<wasi::__wasi_event_t>,
) -> Result<()> { ) -> Result<()> {
use std::{convert::TryInto, os::unix::prelude::AsRawFd}; use std::{convert::TryInto, os::unix::prelude::AsRawFd};
use yanix::{ use yanix::poll::{poll, PollFd, PollFlags};
poll::{poll, PollFd, PollFlags},
Errno,
};
if fd_events.is_empty() && timeout.is_none() { if fd_events.is_empty() && timeout.is_none() {
return Ok(()); return Ok(());
@@ -88,10 +86,11 @@ pub(crate) fn poll_oneoff(
let ready = loop { let ready = loop {
match poll(&mut poll_fds, poll_timeout) { match poll(&mut poll_fds, poll_timeout) {
Err(_) => { Err(_) => {
if Errno::last() == Errno::EINTR { let last_err = io::Error::last_os_error();
if last_err.raw_os_error().unwrap() == libc::EINTR {
continue; continue;
} }
return Err(Errno::last().into()); return Err(last_err.into());
} }
Ok(ready) => break ready, Ok(ready) => break ready,
} }

View File

@@ -1,4 +1,4 @@
use crate::{Errno, Result}; use crate::{Error, Result};
use std::mem::MaybeUninit; use std::mem::MaybeUninit;
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone)]
@@ -22,7 +22,7 @@ impl ClockId {
pub fn clock_getres(clock_id: ClockId) -> Result<libc::timespec> { pub fn clock_getres(clock_id: ClockId) -> Result<libc::timespec> {
let mut timespec = MaybeUninit::<libc::timespec>::uninit(); let mut timespec = MaybeUninit::<libc::timespec>::uninit();
Errno::from_success_code(unsafe { Error::from_success_code(unsafe {
libc::clock_getres(clock_id.as_raw(), timespec.as_mut_ptr()) libc::clock_getres(clock_id.as_raw(), timespec.as_mut_ptr())
})?; })?;
Ok(unsafe { timespec.assume_init() }) Ok(unsafe { timespec.assume_init() })
@@ -30,7 +30,7 @@ pub fn clock_getres(clock_id: ClockId) -> Result<libc::timespec> {
pub fn clock_gettime(clock_id: ClockId) -> Result<libc::timespec> { pub fn clock_gettime(clock_id: ClockId) -> Result<libc::timespec> {
let mut timespec = MaybeUninit::<libc::timespec>::uninit(); let mut timespec = MaybeUninit::<libc::timespec>::uninit();
Errno::from_success_code(unsafe { Error::from_success_code(unsafe {
libc::clock_gettime(clock_id.as_raw(), timespec.as_mut_ptr()) libc::clock_gettime(clock_id.as_raw(), timespec.as_mut_ptr())
})?; })?;
Ok(unsafe { timespec.assume_init() }) Ok(unsafe { timespec.assume_init() })

View File

@@ -1,10 +1,10 @@
use crate::{ use crate::{
file::FileType, file::FileType,
sys::dir::{iter_impl, EntryImpl}, sys::dir::{iter_impl, EntryImpl},
Errno, Result, Result,
}; };
use std::os::unix::io::{AsRawFd, IntoRawFd, RawFd}; use std::os::unix::io::{AsRawFd, IntoRawFd, RawFd};
use std::{ffi::CStr, ops::Deref, ptr}; use std::{ffi::CStr, io, ops::Deref, ptr};
pub use crate::sys::EntryExt; pub use crate::sys::EntryExt;
@@ -25,7 +25,7 @@ impl Dir {
if let Some(d) = ptr::NonNull::new(d) { if let Some(d) = ptr::NonNull::new(d) {
Ok(Self(d)) Ok(Self(d))
} else { } else {
let e = Errno::last(); let e = io::Error::last_os_error();
libc::close(fd); libc::close(fd);
Err(e.into()) Err(e.into())
} }

View File

@@ -1,227 +0,0 @@
//! 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,61 @@
//! Error type
use crate::Result;
use std::{ffi, io, num};
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("I/O error {0}")]
Io(#[from] io::Error),
#[error("a nul byte was not found in the expected position")]
Nul(#[from] ffi::NulError),
#[error("integral type conversion failed")]
IntConversion(#[from] num::TryFromIntError),
}
impl Error {
pub fn from_success_code<T: IsZero>(t: T) -> Result<()> {
if t.is_zero() {
Ok(())
} else {
Err(Self::from(io::Error::last_os_error()))
}
}
pub fn from_result<T: IsMinusOne>(t: T) -> Result<T> {
if t.is_minus_one() {
Err(Self::from(io::Error::last_os_error()))
} else {
Ok(t)
}
}
}
#[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

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

View File

@@ -1,4 +1,4 @@
use crate::{Errno, Result}; use crate::{Error, Result};
use bitflags::bitflags; use bitflags::bitflags;
use cfg_if::cfg_if; use cfg_if::cfg_if;
use std::{ use std::{
@@ -137,7 +137,7 @@ pub unsafe fn openat<P: AsRef<OsStr>>(
mode: Mode, mode: Mode,
) -> Result<RawFd> { ) -> Result<RawFd> {
let path = CString::new(path.as_ref().as_bytes())?; let path = CString::new(path.as_ref().as_bytes())?;
Errno::from_result(libc::openat( Error::from_result(libc::openat(
dirfd, dirfd,
path.as_ptr(), path.as_ptr(),
oflag.bits(), oflag.bits(),
@@ -148,7 +148,7 @@ pub unsafe fn openat<P: AsRef<OsStr>>(
pub unsafe fn readlinkat<P: AsRef<OsStr>>(dirfd: RawFd, path: P) -> Result<OsString> { pub unsafe fn readlinkat<P: AsRef<OsStr>>(dirfd: RawFd, path: P) -> Result<OsString> {
let path = CString::new(path.as_ref().as_bytes())?; let path = CString::new(path.as_ref().as_bytes())?;
let buffer = &mut [0u8; libc::PATH_MAX as usize + 1]; let buffer = &mut [0u8; libc::PATH_MAX as usize + 1];
Errno::from_result(libc::readlinkat( Error::from_result(libc::readlinkat(
dirfd, dirfd,
path.as_ptr(), path.as_ptr(),
buffer.as_mut_ptr() as *mut _, buffer.as_mut_ptr() as *mut _,
@@ -162,7 +162,7 @@ pub unsafe fn readlinkat<P: AsRef<OsStr>>(dirfd: RawFd, path: P) -> Result<OsStr
pub unsafe fn mkdirat<P: AsRef<OsStr>>(dirfd: RawFd, path: P, mode: Mode) -> Result<()> { pub unsafe fn mkdirat<P: AsRef<OsStr>>(dirfd: RawFd, path: P, mode: Mode) -> Result<()> {
let path = CString::new(path.as_ref().as_bytes())?; let path = CString::new(path.as_ref().as_bytes())?;
Errno::from_success_code(libc::mkdirat(dirfd, path.as_ptr(), mode.bits())) Error::from_success_code(libc::mkdirat(dirfd, path.as_ptr(), mode.bits()))
} }
pub unsafe fn linkat<P: AsRef<OsStr>>( pub unsafe fn linkat<P: AsRef<OsStr>>(
@@ -174,7 +174,7 @@ pub unsafe fn linkat<P: AsRef<OsStr>>(
) -> Result<()> { ) -> Result<()> {
let old_path = CString::new(old_path.as_ref().as_bytes())?; let old_path = CString::new(old_path.as_ref().as_bytes())?;
let new_path = CString::new(new_path.as_ref().as_bytes())?; let new_path = CString::new(new_path.as_ref().as_bytes())?;
Errno::from_success_code(libc::linkat( Error::from_success_code(libc::linkat(
old_dirfd, old_dirfd,
old_path.as_ptr(), old_path.as_ptr(),
new_dirfd, new_dirfd,
@@ -185,7 +185,7 @@ pub unsafe fn linkat<P: AsRef<OsStr>>(
pub unsafe fn unlinkat<P: AsRef<OsStr>>(dirfd: RawFd, path: P, flags: AtFlag) -> Result<()> { pub unsafe fn unlinkat<P: AsRef<OsStr>>(dirfd: RawFd, path: P, flags: AtFlag) -> Result<()> {
let path = CString::new(path.as_ref().as_bytes())?; let path = CString::new(path.as_ref().as_bytes())?;
Errno::from_success_code(libc::unlinkat(dirfd, path.as_ptr(), flags.bits())) Error::from_success_code(libc::unlinkat(dirfd, path.as_ptr(), flags.bits()))
} }
pub unsafe fn renameat<P: AsRef<OsStr>>( pub unsafe fn renameat<P: AsRef<OsStr>>(
@@ -196,7 +196,7 @@ pub unsafe fn renameat<P: AsRef<OsStr>>(
) -> Result<()> { ) -> Result<()> {
let old_path = CString::new(old_path.as_ref().as_bytes())?; let old_path = CString::new(old_path.as_ref().as_bytes())?;
let new_path = CString::new(new_path.as_ref().as_bytes())?; let new_path = CString::new(new_path.as_ref().as_bytes())?;
Errno::from_success_code(libc::renameat( Error::from_success_code(libc::renameat(
old_dirfd, old_dirfd,
old_path.as_ptr(), old_path.as_ptr(),
new_dirfd, new_dirfd,
@@ -207,7 +207,7 @@ pub unsafe fn renameat<P: AsRef<OsStr>>(
pub unsafe fn symlinkat<P: AsRef<OsStr>>(old_path: P, new_dirfd: RawFd, new_path: P) -> Result<()> { 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 old_path = CString::new(old_path.as_ref().as_bytes())?;
let new_path = CString::new(new_path.as_ref().as_bytes())?; let new_path = CString::new(new_path.as_ref().as_bytes())?;
Errno::from_success_code(libc::symlinkat( Error::from_success_code(libc::symlinkat(
old_path.as_ptr(), old_path.as_ptr(),
new_dirfd, new_dirfd,
new_path.as_ptr(), new_path.as_ptr(),
@@ -218,7 +218,7 @@ pub unsafe fn fstatat<P: AsRef<OsStr>>(dirfd: RawFd, path: P, flags: AtFlag) ->
use std::mem::MaybeUninit; use std::mem::MaybeUninit;
let path = CString::new(path.as_ref().as_bytes())?; let path = CString::new(path.as_ref().as_bytes())?;
let mut filestat = MaybeUninit::<libc::stat>::uninit(); let mut filestat = MaybeUninit::<libc::stat>::uninit();
Errno::from_result(libc::fstatat( Error::from_result(libc::fstatat(
dirfd, dirfd,
path.as_ptr(), path.as_ptr(),
filestat.as_mut_ptr(), filestat.as_mut_ptr(),
@@ -230,20 +230,20 @@ pub unsafe fn fstatat<P: AsRef<OsStr>>(dirfd: RawFd, path: P, flags: AtFlag) ->
pub unsafe fn fstat(fd: RawFd) -> Result<libc::stat> { pub unsafe fn fstat(fd: RawFd) -> Result<libc::stat> {
use std::mem::MaybeUninit; use std::mem::MaybeUninit;
let mut filestat = MaybeUninit::<libc::stat>::uninit(); let mut filestat = MaybeUninit::<libc::stat>::uninit();
Errno::from_result(libc::fstat(fd, filestat.as_mut_ptr()))?; Error::from_result(libc::fstat(fd, filestat.as_mut_ptr()))?;
Ok(filestat.assume_init()) Ok(filestat.assume_init())
} }
/// `fionread()` function, equivalent to `ioctl(fd, FIONREAD, *bytes)`. /// `fionread()` function, equivalent to `ioctl(fd, FIONREAD, *bytes)`.
pub unsafe fn fionread(fd: RawFd) -> Result<u32> { pub unsafe fn fionread(fd: RawFd) -> Result<u32> {
let mut nread: libc::c_int = 0; let mut nread: libc::c_int = 0;
Errno::from_result(libc::ioctl(fd, libc::FIONREAD, &mut nread as *mut _))?; Error::from_result(libc::ioctl(fd, libc::FIONREAD, &mut nread as *mut _))?;
Ok(nread.try_into()?) Ok(nread.try_into()?)
} }
/// This function is unsafe because it operates on a raw file descriptor. /// This function is unsafe because it operates on a raw file descriptor.
/// It's provided, because std::io::Seek requires a mutable borrow. /// It's provided, because std::io::Seek requires a mutable borrow.
pub unsafe fn tell(fd: RawFd) -> Result<u64> { pub unsafe fn tell(fd: RawFd) -> Result<u64> {
let offset: i64 = Errno::from_result(libc::lseek(fd, 0, libc::SEEK_CUR))?; let offset: i64 = Error::from_result(libc::lseek(fd, 0, libc::SEEK_CUR))?;
Ok(offset.try_into()?) Ok(offset.try_into()?)
} }

View File

@@ -16,25 +16,12 @@ pub mod file;
pub mod poll; pub mod poll;
pub mod socket; pub mod socket;
mod errno; mod error;
mod sys; mod sys;
pub mod fadvise { pub mod fadvise {
pub use super::sys::fadvise::*; pub use super::sys::fadvise::*;
} }
pub use errno::Errno; pub use error::Error;
use std::{ffi, num}; pub type Result<T> = std::result::Result<T, Error>;
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

@@ -1,4 +1,4 @@
use crate::{Errno, Result}; use crate::{Error, Result};
use bitflags::bitflags; use bitflags::bitflags;
use std::{convert::TryInto, os::unix::prelude::*}; use std::{convert::TryInto, os::unix::prelude::*};
@@ -36,7 +36,7 @@ impl PollFd {
} }
pub fn poll(fds: &mut [PollFd], timeout: libc::c_int) -> Result<usize> { pub fn poll(fds: &mut [PollFd], timeout: libc::c_int) -> Result<usize> {
Errno::from_result(unsafe { Error::from_result(unsafe {
libc::poll( libc::poll(
fds.as_mut_ptr() as *mut libc::pollfd, fds.as_mut_ptr() as *mut libc::pollfd,
fds.len() as libc::nfds_t, fds.len() as libc::nfds_t,

View File

@@ -1,4 +1,4 @@
use crate::{Errno, Result}; use crate::{Error, Result};
use std::os::unix::prelude::*; use std::os::unix::prelude::*;
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
@@ -15,7 +15,7 @@ pub unsafe fn get_socket_type(fd: RawFd) -> Result<SockType> {
use std::mem::{self, MaybeUninit}; use std::mem::{self, MaybeUninit};
let mut buffer = MaybeUninit::<SockType>::zeroed().assume_init(); let mut buffer = MaybeUninit::<SockType>::zeroed().assume_init();
let mut out_len = mem::size_of::<SockType>() as libc::socklen_t; let mut out_len = mem::size_of::<SockType>() as libc::socklen_t;
Errno::from_success_code(libc::getsockopt( Error::from_success_code(libc::getsockopt(
fd, fd,
libc::SOL_SOCKET, libc::SOL_SOCKET,
libc::SO_TYPE, libc::SO_TYPE,

View File

@@ -1,8 +1,8 @@
use crate::{ use crate::{
dir::{Dir, Entry, EntryExt, SeekLoc}, dir::{Dir, Entry, EntryExt, SeekLoc},
Errno, Result, Result,
}; };
use std::ops::Deref; use std::{io, ops::Deref};
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
pub(crate) struct EntryImpl { pub(crate) struct EntryImpl {
@@ -19,16 +19,17 @@ impl Deref for EntryImpl {
} }
pub(crate) fn iter_impl(dir: &Dir) -> Option<Result<EntryImpl>> { pub(crate) fn iter_impl(dir: &Dir) -> Option<Result<EntryImpl>> {
let errno = Errno::last(); let errno = io::Error::last_os_error();
let dirent = unsafe { libc::readdir(dir.as_raw().as_ptr()) }; let dirent = unsafe { libc::readdir(dir.as_raw().as_ptr()) };
if dirent.is_null() { if dirent.is_null() {
if errno != Errno::last() { let curr_errno = io::Error::last_os_error();
if errno.raw_os_error() != curr_errno.raw_os_error() {
// TODO This should be verified on different BSD-flavours. // TODO This should be verified on different BSD-flavours.
// //
// According to 4.3BSD/POSIX.1-2001 man pages, there was an error // 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 // if the errno value has changed at some point during the sequence
// of readdir calls. // of readdir calls.
Some(Err(Errno::last().into())) Some(Err(curr_errno.into()))
} else { } else {
// Not an error. We've simply reached the end of the stream. // Not an error. We've simply reached the end of the stream.
None None

View File

@@ -1,4 +1,4 @@
use crate::{Errno, Result}; use crate::{Error, Result};
use std::{convert::TryInto, os::unix::prelude::*}; use std::{convert::TryInto, os::unix::prelude::*};
#[cfg(not(any(target_os = "freebsd", target_os = "netbsd")))] #[cfg(not(any(target_os = "freebsd", target_os = "netbsd")))]
@@ -48,7 +48,7 @@ pub unsafe fn posix_fadvise(
ra_offset: offset, ra_offset: offset,
ra_count: len.try_into()?, ra_count: len.try_into()?,
}; };
Errno::from_success_code(libc::fcntl(fd, libc::F_RDADVISE, &advisory)) Error::from_success_code(libc::fcntl(fd, libc::F_RDADVISE, &advisory))
} }
#[cfg(any(target_os = "freebsd", target_os = "netbsd"))] #[cfg(any(target_os = "freebsd", target_os = "netbsd"))]
@@ -58,7 +58,7 @@ pub unsafe fn posix_fadvise(
len: libc::off_t, len: libc::off_t,
advice: PosixFadviseAdvice, advice: PosixFadviseAdvice,
) -> Result<()> { ) -> Result<()> {
Errno::from_success_code(libc::posix_fadvise(fd, offset, len, advice as libc::c_int)) Error::from_success_code(libc::posix_fadvise(fd, offset, len, advice as libc::c_int))
} }
// On BSDs without support we leave it as no-op // On BSDs without support we leave it as no-op

View File

@@ -1,5 +1,5 @@
use crate::{Errno, Result}; use crate::Result;
use std::os::unix::prelude::*; use std::{io, os::unix::prelude::*};
pub unsafe fn isatty(fd: RawFd) -> Result<bool> { pub unsafe fn isatty(fd: RawFd) -> Result<bool> {
let res = libc::isatty(fd); let res = libc::isatty(fd);
@@ -8,11 +8,15 @@ pub unsafe fn isatty(fd: RawFd) -> Result<bool> {
Ok(true) Ok(true)
} else { } else {
// ... otherwise 0 is returned, and errno is set to indicate the error. // ... otherwise 0 is returned, and errno is set to indicate the error.
let errno = Errno::last(); let errno = io::Error::last_os_error();
if errno == Errno::ENOTTY { if let Some(raw_errno) = errno.raw_os_error() {
if raw_errno == libc::ENOTTY {
Ok(false) Ok(false)
} else { } else {
Err(errno.into()) Err(errno.into())
} }
} else {
Err(errno.into())
}
} }
} }

View File

@@ -1,8 +1,8 @@
use crate::{ use crate::{
dir::{Dir, Entry, EntryExt, SeekLoc}, dir::{Dir, Entry, EntryExt, SeekLoc},
Errno, Result, Result,
}; };
use std::ops::Deref; use std::{io, ops::Deref};
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
pub(crate) struct EntryImpl(libc::dirent64); pub(crate) struct EntryImpl(libc::dirent64);
@@ -26,16 +26,17 @@ impl EntryExt for Entry {
} }
pub(crate) fn iter_impl(dir: &Dir) -> Option<Result<EntryImpl>> { pub(crate) fn iter_impl(dir: &Dir) -> Option<Result<EntryImpl>> {
let errno = Errno::last(); let errno = io::Error::last_os_error();
let dirent = unsafe { libc::readdir64(dir.as_raw().as_ptr()) }; let dirent = unsafe { libc::readdir64(dir.as_raw().as_ptr()) };
if dirent.is_null() { if dirent.is_null() {
if errno != Errno::last() { let curr_errno = io::Error::last_os_error();
if errno.raw_os_error() != curr_errno.raw_os_error() {
// TODO This should be verified on different BSD-flavours. // TODO This should be verified on different BSD-flavours.
// //
// According to 4.3BSD/POSIX.1-2001 man pages, there was an error // 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 // if the errno value has changed at some point during the sequence
// of readdir calls. // of readdir calls.
Some(Err(Errno::last().into())) Some(Err(curr_errno.into()))
} else { } else {
// Not an error. We've simply reached the end of the stream. // Not an error. We've simply reached the end of the stream.
None None

View File

@@ -1,4 +1,4 @@
use crate::{Errno, Result}; use crate::{Error, Result};
use std::os::unix::prelude::*; use std::os::unix::prelude::*;
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone)]
@@ -18,5 +18,5 @@ pub unsafe fn posix_fadvise(
len: libc::off_t, len: libc::off_t,
advice: PosixFadviseAdvice, advice: PosixFadviseAdvice,
) -> Result<()> { ) -> Result<()> {
Errno::from_success_code(libc::posix_fadvise(fd, offset, len, advice as libc::c_int)) Error::from_success_code(libc::posix_fadvise(fd, offset, len, advice as libc::c_int))
} }

View File

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