Move common functionality into hostcalls mod
This commit is contained in:
807
src/sys/unix/hostcalls_impl/fs.rs
Normal file
807
src/sys/unix/hostcalls_impl/fs.rs
Normal file
@@ -0,0 +1,807 @@
|
||||
#![allow(non_camel_case_types)]
|
||||
#![allow(unused_unsafe)]
|
||||
use super::fdentry::{determine_type_rights, FdEntry};
|
||||
use super::fs_helpers::*;
|
||||
use super::host_impl;
|
||||
|
||||
use crate::ctx::WasiCtx;
|
||||
use crate::{host, wasm32};
|
||||
|
||||
use nix::libc::{self, c_long, c_void, off_t};
|
||||
use std::ffi::OsStr;
|
||||
use std::os::unix::prelude::{FromRawFd, OsStrExt};
|
||||
|
||||
pub(crate) fn fd_close(fd_entry: FdEntry) -> Result<(), host::__wasi_errno_t> {
|
||||
nix::unistd::close(fd_entry.fd_object.rawfd)
|
||||
.map_err(|e| host_impl::errno_from_nix(e.as_errno().unwrap()))
|
||||
}
|
||||
|
||||
pub(crate) fn fd_datasync(fd_entry: &FdEntry) -> Result<(), host::__wasi_errno_t> {
|
||||
let res;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
res = nix::unistd::fdatasync(fd_entry.fd_object.rawfd);
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
res = nix::unistd::fsync(fd_entry.fd_object.rawfd);
|
||||
}
|
||||
|
||||
res.map_err(|e| host_impl::errno_from_nix(e.as_errno().unwrap()))
|
||||
}
|
||||
|
||||
pub(crate) fn fd_pread(
|
||||
fd_entry: &FdEntry,
|
||||
buf: &mut [u8],
|
||||
offset: host::__wasi_filesize_t,
|
||||
) -> Result<usize, host::__wasi_errno_t> {
|
||||
nix::sys::uio::pread(fd_entry.fd_object.rawfd, buf, offset as off_t)
|
||||
.map_err(|e| host_impl::errno_from_nix(e.as_errno().unwrap()))
|
||||
}
|
||||
|
||||
pub(crate) fn fd_pwrite(
|
||||
fd_entry: &FdEntry,
|
||||
buf: &[u8],
|
||||
offset: host::__wasi_filesize_t,
|
||||
) -> Result<usize, host::__wasi_errno_t> {
|
||||
nix::sys::uio::pwrite(fd_entry.fd_object.rawfd, buf, offset as off_t)
|
||||
.map_err(|e| host_impl::errno_from_nix(e.as_errno().unwrap()))
|
||||
}
|
||||
|
||||
pub(crate) fn fd_read(
|
||||
fd_entry: &FdEntry,
|
||||
iovs: &mut [host::__wasi_iovec_t],
|
||||
) -> Result<usize, host::__wasi_errno_t> {
|
||||
use nix::sys::uio::{readv, IoVec};
|
||||
|
||||
let mut iovs: Vec<IoVec<&mut [u8]>> = iovs
|
||||
.iter_mut()
|
||||
.map(|iov| unsafe { host_impl::iovec_to_nix_mut(iov) })
|
||||
.collect();
|
||||
|
||||
readv(fd_entry.fd_object.rawfd, &mut iovs)
|
||||
.map_err(|e| host_impl::errno_from_nix(e.as_errno().unwrap()))
|
||||
}
|
||||
|
||||
pub(crate) fn fd_renumber(
|
||||
wasi_ctx: &mut WasiCtx,
|
||||
from: host::__wasi_fd_t,
|
||||
to: host::__wasi_fd_t,
|
||||
) -> Result<(), host::__wasi_errno_t> {
|
||||
let fe_from = match wasi_ctx.fds.get(&from) {
|
||||
Some(fe_from) => fe_from,
|
||||
None => return Err(host::__WASI_EBADF),
|
||||
};
|
||||
let fe_to = match wasi_ctx.fds.get(&to) {
|
||||
Some(fe_to) => fe_to,
|
||||
None => return Err(host::__WASI_EBADF),
|
||||
};
|
||||
if let Err(e) = nix::unistd::dup2(fe_from.fd_object.rawfd, fe_to.fd_object.rawfd) {
|
||||
return Err(host_impl::errno_from_nix(e.as_errno().unwrap()));
|
||||
}
|
||||
|
||||
let fe_from_rawfd = fe_from.fd_object.rawfd;
|
||||
wasi_ctx.fds.remove(&(fe_from_rawfd as host::__wasi_fd_t));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn fd_seek(
|
||||
fd_entry: &FdEntry,
|
||||
offset: host::__wasi_filedelta_t,
|
||||
whence: host::__wasi_whence_t,
|
||||
) -> Result<u64, host::__wasi_errno_t> {
|
||||
use nix::unistd::{lseek, Whence};
|
||||
let nwhence = match whence {
|
||||
host::__WASI_WHENCE_CUR => Whence::SeekCur,
|
||||
host::__WASI_WHENCE_END => Whence::SeekEnd,
|
||||
host::__WASI_WHENCE_SET => Whence::SeekSet,
|
||||
_ => return Err(host::__WASI_EINVAL),
|
||||
};
|
||||
|
||||
match lseek(fd_entry.fd_object.rawfd, offset, nwhence) {
|
||||
Ok(offset) => Ok(offset as u64),
|
||||
Err(e) => Err(host_impl::errno_from_nix(e.as_errno().unwrap())),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn fd_tell(fd_entry: &FdEntry) -> Result<u64, host::__wasi_errno_t> {
|
||||
use nix::unistd::{lseek, Whence};
|
||||
match lseek(fd_entry.fd_object.rawfd, 0, Whence::SeekCur) {
|
||||
Ok(newoffset) => Ok(newoffset as u64),
|
||||
Err(e) => Err(host_impl::errno_from_nix(e.as_errno().unwrap())),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn fd_fdstat_get(
|
||||
fd_entry: &FdEntry,
|
||||
) -> Result<host::__wasi_fdflags_t, host::__wasi_errno_t> {
|
||||
use nix::fcntl::{fcntl, OFlag, F_GETFL};
|
||||
match fcntl(fd_entry.fd_object.rawfd, 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())),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn fd_fdstat_set_flags(
|
||||
fd_entry: &FdEntry,
|
||||
fdflags: host::__wasi_fdflags_t,
|
||||
) -> Result<(), host::__wasi_errno_t> {
|
||||
let nix_flags = host_impl::nix_from_fdflags(fdflags);
|
||||
match nix::fcntl::fcntl(fd_entry.fd_object.rawfd, nix::fcntl::F_SETFL(nix_flags)) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) => Err(host_impl::errno_from_nix(e.as_errno().unwrap())),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn fd_sync(fd_entry: &FdEntry) -> Result<(), host::__wasi_errno_t> {
|
||||
nix::unistd::fsync(fd_entry.fd_object.rawfd)
|
||||
.map_err(|e| host_impl::errno_from_nix(e.as_errno().unwrap()))
|
||||
}
|
||||
|
||||
pub(crate) fn fd_write(
|
||||
fd_entry: &FdEntry,
|
||||
iovs: &[host::__wasi_iovec_t],
|
||||
) -> Result<usize, host::__wasi_errno_t> {
|
||||
use nix::sys::uio::{writev, IoVec};
|
||||
let iovs: Vec<IoVec<&[u8]>> = iovs
|
||||
.iter()
|
||||
.map(|iov| unsafe { host_impl::iovec_to_nix(iov) })
|
||||
.collect();
|
||||
writev(fd_entry.fd_object.rawfd, &iovs)
|
||||
.map_err(|e| host_impl::errno_from_nix(e.as_errno().unwrap()))
|
||||
}
|
||||
|
||||
pub(crate) fn fd_advise(
|
||||
fd_entry: &FdEntry,
|
||||
advice: host::__wasi_advice_t,
|
||||
offset: host::__wasi_filesize_t,
|
||||
len: host::__wasi_filesize_t,
|
||||
) -> Result<(), host::__wasi_errno_t> {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let host_advice = match advice {
|
||||
host::__WASI_ADVICE_DONTNEED => libc::POSIX_FADV_DONTNEED,
|
||||
host::__WASI_ADVICE_SEQUENTIAL => libc::POSIX_FADV_SEQUENTIAL,
|
||||
host::__WASI_ADVICE_WILLNEED => libc::POSIX_FADV_DONTNEED,
|
||||
host::__WASI_ADVICE_NOREUSE => libc::POSIX_FADV_NOREUSE,
|
||||
host::__WASI_ADVICE_RANDOM => libc::POSIX_FADV_RANDOM,
|
||||
host::__WASI_ADVICE_NORMAL => libc::POSIX_FADV_NORMAL,
|
||||
_ => return Err(host::__WASI_EINVAL),
|
||||
};
|
||||
let res = unsafe {
|
||||
libc::posix_fadvise(
|
||||
fd_entry.fd_object.rawfd,
|
||||
offset as off_t,
|
||||
len as off_t,
|
||||
host_advice,
|
||||
)
|
||||
};
|
||||
if res != 0 {
|
||||
return Err(host_impl::errno_from_nix(nix::errno::Errno::last()));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
let _ = (fd_entry, offset, len);
|
||||
match advice {
|
||||
host::__WASI_ADVICE_DONTNEED
|
||||
| host::__WASI_ADVICE_SEQUENTIAL
|
||||
| host::__WASI_ADVICE_WILLNEED
|
||||
| host::__WASI_ADVICE_NOREUSE
|
||||
| host::__WASI_ADVICE_RANDOM
|
||||
| host::__WASI_ADVICE_NORMAL => {}
|
||||
_ => return Err(host::__WASI_EINVAL),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn fd_allocate(
|
||||
fd_entry: &FdEntry,
|
||||
offset: host::__wasi_filesize_t,
|
||||
len: host::__wasi_filesize_t,
|
||||
) -> Result<(), host::__wasi_errno_t> {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let res = unsafe {
|
||||
libc::posix_fallocate(fd_entry.fd_object.rawfd, offset as off_t, len as off_t)
|
||||
};
|
||||
if res != 0 {
|
||||
return Err(host_impl::errno_from_nix(nix::errno::Errno::last()));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
use nix::sys::stat::fstat;
|
||||
use nix::unistd::ftruncate;
|
||||
|
||||
match fstat(fd_entry.fd_object.rawfd) {
|
||||
Err(e) => return Err(host_impl::errno_from_nix(e.as_errno().unwrap())),
|
||||
Ok(st) => {
|
||||
let current_size = st.st_size as u64;
|
||||
let wanted_size = match offset.checked_add(len) {
|
||||
Some(wanted_size) => wanted_size,
|
||||
None => return Err(host::__WASI_E2BIG),
|
||||
};
|
||||
if wanted_size > i64::max_value() as u64 {
|
||||
return Err(host::__WASI_E2BIG);
|
||||
}
|
||||
if wanted_size > current_size {
|
||||
if let Err(e) = ftruncate(fd_entry.fd_object.rawfd, wanted_size as off_t) {
|
||||
return Err(host_impl::errno_from_nix(e.as_errno().unwrap()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn path_create_directory(
|
||||
ctx: &WasiCtx,
|
||||
dirfd: host::__wasi_fd_t,
|
||||
path: &OsStr,
|
||||
) -> Result<(), host::__wasi_errno_t> {
|
||||
use nix::libc::mkdirat;
|
||||
|
||||
let (dir, path) = match path_get(
|
||||
ctx,
|
||||
dirfd,
|
||||
0,
|
||||
path,
|
||||
host::__WASI_RIGHT_PATH_OPEN | host::__WASI_RIGHT_PATH_CREATE_DIRECTORY,
|
||||
0,
|
||||
false,
|
||||
) {
|
||||
Ok((dir, path)) => (dir, path),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let path_cstr = match std::ffi::CString::new(path.as_os_str().as_bytes()) {
|
||||
Ok(path_cstr) => path_cstr,
|
||||
Err(_) => return Err(host::__WASI_EINVAL),
|
||||
};
|
||||
// nix doesn't expose mkdirat() yet
|
||||
match unsafe { mkdirat(dir, path_cstr.as_ptr(), 0o777) } {
|
||||
0 => Ok(()),
|
||||
_ => Err(host_impl::errno_from_nix(nix::errno::Errno::last())),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn path_link(
|
||||
ctx: &WasiCtx,
|
||||
old_dirfd: host::__wasi_fd_t,
|
||||
new_dirfd: host::__wasi_fd_t,
|
||||
old_path: &OsStr,
|
||||
new_path: &OsStr,
|
||||
source_rights: host::__wasi_rights_t,
|
||||
target_rights: host::__wasi_rights_t,
|
||||
) -> Result<(), host::__wasi_errno_t> {
|
||||
use nix::libc::linkat;
|
||||
let (old_dir, old_path) = match path_get(ctx, old_dirfd, 0, old_path, source_rights, 0, false) {
|
||||
Ok((dir, path)) => (dir, path),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let (new_dir, new_path) = match path_get(ctx, new_dirfd, 0, new_path, target_rights, 0, false) {
|
||||
Ok((dir, path)) => (dir, path),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let old_path_cstr = match std::ffi::CString::new(old_path.as_bytes()) {
|
||||
Ok(old_path_cstr) => old_path_cstr,
|
||||
Err(_) => return Err(host::__WASI_EINVAL),
|
||||
};
|
||||
let new_path_cstr = match std::ffi::CString::new(new_path.as_bytes()) {
|
||||
Ok(new_path_cstr) => new_path_cstr,
|
||||
Err(_) => return Err(host::__WASI_EINVAL),
|
||||
};
|
||||
|
||||
// Not setting AT_SYMLINK_FOLLOW fails on most filesystems
|
||||
let atflags = libc::AT_SYMLINK_FOLLOW;
|
||||
let res = unsafe {
|
||||
linkat(
|
||||
old_dir,
|
||||
old_path_cstr.as_ptr(),
|
||||
new_dir,
|
||||
new_path_cstr.as_ptr(),
|
||||
atflags,
|
||||
)
|
||||
};
|
||||
if res != 0 {
|
||||
Err(host_impl::errno_from_nix(nix::errno::Errno::last()))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn path_open(
|
||||
ctx: &WasiCtx,
|
||||
dirfd: host::__wasi_fd_t,
|
||||
dirflags: host::__wasi_lookupflags_t,
|
||||
path: &OsStr,
|
||||
oflags: host::__wasi_oflags_t,
|
||||
read: bool,
|
||||
write: bool,
|
||||
mut needed_base: host::__wasi_rights_t,
|
||||
mut needed_inheriting: host::__wasi_rights_t,
|
||||
fs_flags: host::__wasi_fdflags_t,
|
||||
) -> Result<FdEntry, host::__wasi_errno_t> {
|
||||
use nix::errno::Errno;
|
||||
use nix::fcntl::{openat, AtFlags, OFlag};
|
||||
use nix::sys::stat::{fstatat, Mode, SFlag};
|
||||
|
||||
let mut nix_all_oflags = if read && write {
|
||||
OFlag::O_RDWR
|
||||
} else if read {
|
||||
OFlag::O_RDONLY
|
||||
} else {
|
||||
OFlag::O_WRONLY
|
||||
};
|
||||
|
||||
// on non-Capsicum systems, we always want nofollow
|
||||
nix_all_oflags.insert(OFlag::O_NOFOLLOW);
|
||||
|
||||
// convert open flags
|
||||
let nix_oflags = host_impl::nix_from_oflags(oflags);
|
||||
nix_all_oflags.insert(nix_oflags);
|
||||
if nix_all_oflags.contains(OFlag::O_CREAT) {
|
||||
needed_base |= host::__WASI_RIGHT_PATH_CREATE_FILE;
|
||||
}
|
||||
if nix_all_oflags.contains(OFlag::O_TRUNC) {
|
||||
needed_inheriting |= host::__WASI_RIGHT_PATH_FILESTAT_SET_SIZE;
|
||||
}
|
||||
|
||||
// convert file descriptor flags
|
||||
nix_all_oflags.insert(host_impl::nix_from_fdflags(fs_flags));
|
||||
if nix_all_oflags.contains(OFlag::O_DSYNC) {
|
||||
needed_inheriting |= host::__WASI_RIGHT_FD_DATASYNC;
|
||||
}
|
||||
if nix_all_oflags.intersects(host_impl::O_RSYNC | OFlag::O_SYNC) {
|
||||
needed_inheriting |= host::__WASI_RIGHT_FD_SYNC;
|
||||
}
|
||||
|
||||
let (dir, path) = match path_get(
|
||||
ctx,
|
||||
dirfd,
|
||||
dirflags,
|
||||
path,
|
||||
needed_base,
|
||||
needed_inheriting,
|
||||
nix_oflags.contains(OFlag::O_CREAT),
|
||||
) {
|
||||
Ok((dir, path)) => (dir, path),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
|
||||
// Call openat. Use mode 0o666 so that we follow whatever the user's
|
||||
// umask is, but don't set the executable flag, because it isn't yet
|
||||
// meaningful for WASI programs to create executable files.
|
||||
let new_fd = match openat(
|
||||
dir,
|
||||
path.as_os_str(),
|
||||
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(dir, path.as_os_str(), AtFlags::AT_SYMLINK_NOFOLLOW) {
|
||||
if SFlag::from_bits_truncate(stat.st_mode).contains(SFlag::S_IFSOCK) {
|
||||
return Err(host::__WASI_ENOTSUP);
|
||||
} else {
|
||||
return Err(host::__WASI_ENXIO);
|
||||
}
|
||||
} else {
|
||||
return Err(host::__WASI_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(dir, path.as_os_str(), AtFlags::AT_SYMLINK_NOFOLLOW) {
|
||||
if SFlag::from_bits_truncate(stat.st_mode).contains(SFlag::S_IFLNK) {
|
||||
return Err(host::__WASI_ELOOP);
|
||||
}
|
||||
}
|
||||
return Err(host::__WASI_ENOTDIR);
|
||||
}
|
||||
// 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(host::__WASI_ELOOP);
|
||||
}
|
||||
Some(e) => return Err(host_impl::errno_from_nix(e)),
|
||||
None => return Err(host::__WASI_ENOSYS),
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Determine the type of the new file descriptor and which rights contradict with this type
|
||||
match unsafe { determine_type_rights(new_fd) } {
|
||||
Err(e) => {
|
||||
// if `close` fails, note it but do not override the underlying errno
|
||||
nix::unistd::close(new_fd).unwrap_or_else(|e| {
|
||||
dbg!(e);
|
||||
});
|
||||
Err(e)
|
||||
}
|
||||
Ok((_ty, max_base, max_inheriting)) => {
|
||||
let mut fe = unsafe { FdEntry::from_raw_fd(new_fd) };
|
||||
fe.rights_base &= max_base;
|
||||
fe.rights_inheriting &= max_inheriting;
|
||||
Ok(fe)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn fd_readdir(
|
||||
fd_entry: &FdEntry,
|
||||
host_buf: &mut [u8],
|
||||
cookie: host::__wasi_dircookie_t,
|
||||
) -> Result<usize, host::__wasi_errno_t> {
|
||||
use libc::{dirent, fdopendir, memcpy, readdir_r, seekdir};
|
||||
|
||||
let host_buf_ptr = host_buf.as_mut_ptr();
|
||||
let host_buf_len = host_buf.len();
|
||||
let dir = unsafe { fdopendir(fd_entry.fd_object.rawfd) };
|
||||
if dir.is_null() {
|
||||
return Err(host_impl::errno_from_nix(nix::errno::Errno::last()));
|
||||
}
|
||||
if cookie != wasm32::__WASI_DIRCOOKIE_START {
|
||||
unsafe { seekdir(dir, cookie as c_long) };
|
||||
}
|
||||
let mut entry_buf = unsafe { std::mem::uninitialized::<dirent>() };
|
||||
let mut left = host_buf_len;
|
||||
let mut host_buf_offset: usize = 0;
|
||||
while left > 0 {
|
||||
let mut host_entry: *mut dirent = std::ptr::null_mut();
|
||||
let res = unsafe { readdir_r(dir, &mut entry_buf, &mut host_entry) };
|
||||
if res == -1 {
|
||||
return Err(host_impl::errno_from_nix(nix::errno::Errno::last()));
|
||||
}
|
||||
if host_entry.is_null() {
|
||||
break;
|
||||
}
|
||||
let entry: wasm32::__wasi_dirent_t =
|
||||
match host_impl::dirent_from_host(&unsafe { *host_entry }) {
|
||||
Ok(entry) => entry,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let name_len = entry.d_namlen as usize;
|
||||
let required_space = std::mem::size_of_val(&entry) + name_len;
|
||||
if required_space > left {
|
||||
break;
|
||||
}
|
||||
unsafe {
|
||||
let ptr = host_buf_ptr.offset(host_buf_offset as isize) as *mut c_void
|
||||
as *mut wasm32::__wasi_dirent_t;
|
||||
*ptr = entry;
|
||||
}
|
||||
host_buf_offset += std::mem::size_of_val(&entry);
|
||||
let name_ptr = unsafe { *host_entry }.d_name.as_ptr();
|
||||
unsafe {
|
||||
memcpy(
|
||||
host_buf_ptr.offset(host_buf_offset as isize) as *mut _,
|
||||
name_ptr as *const _,
|
||||
name_len,
|
||||
)
|
||||
};
|
||||
host_buf_offset += name_len;
|
||||
left -= required_space;
|
||||
}
|
||||
Ok(host_buf_len - left)
|
||||
}
|
||||
|
||||
pub(crate) fn path_readlink(
|
||||
wasi_ctx: &WasiCtx,
|
||||
dirfd: host::__wasi_fd_t,
|
||||
path: &OsStr,
|
||||
rights: host::__wasi_rights_t,
|
||||
buf: &mut [u8],
|
||||
) -> Result<usize, host::__wasi_errno_t> {
|
||||
use nix::fcntl::readlinkat;
|
||||
|
||||
let (dir, path) = match path_get(wasi_ctx, dirfd, 0, path, rights, 0, false) {
|
||||
Ok((dir, path)) => (dir, path),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
|
||||
let target_path = match readlinkat(dir, path.as_os_str(), buf) {
|
||||
Err(e) => return Err(host_impl::errno_from_nix(e.as_errno().unwrap())),
|
||||
Ok(target_path) => target_path,
|
||||
};
|
||||
Ok(target_path.len())
|
||||
}
|
||||
|
||||
pub(crate) fn path_rename(
|
||||
wasi_ctx: &WasiCtx,
|
||||
old_dirfd: host::__wasi_fd_t,
|
||||
old_path: &OsStr,
|
||||
old_rights: host::__wasi_rights_t,
|
||||
new_dirfd: host::__wasi_fd_t,
|
||||
new_path: &OsStr,
|
||||
new_rights: host::__wasi_rights_t,
|
||||
) -> Result<(), host::__wasi_errno_t> {
|
||||
use nix::libc::renameat;
|
||||
|
||||
let (old_dir, old_path) = match path_get(wasi_ctx, old_dirfd, 0, old_path, old_rights, 0, false)
|
||||
{
|
||||
Ok((dir, path)) => (dir, path),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let (new_dir, new_path) = match path_get(wasi_ctx, new_dirfd, 0, new_path, new_rights, 0, false)
|
||||
{
|
||||
Ok((dir, path)) => (dir, path),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let old_path_cstr = match std::ffi::CString::new(old_path.as_bytes()) {
|
||||
Ok(old_path_cstr) => old_path_cstr,
|
||||
Err(_) => return Err(host::__WASI_EINVAL),
|
||||
};
|
||||
let new_path_cstr = match std::ffi::CString::new(new_path.as_bytes()) {
|
||||
Ok(new_path_cstr) => new_path_cstr,
|
||||
Err(_) => return Err(host::__WASI_EINVAL),
|
||||
};
|
||||
let res = unsafe {
|
||||
renameat(
|
||||
old_dir,
|
||||
old_path_cstr.as_ptr(),
|
||||
new_dir,
|
||||
new_path_cstr.as_ptr(),
|
||||
)
|
||||
};
|
||||
if res != 0 {
|
||||
Err(host_impl::errno_from_nix(nix::errno::Errno::last()))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn fd_filestat_get(
|
||||
fd_entry: &FdEntry,
|
||||
) -> Result<host::__wasi_filestat_t, host::__wasi_errno_t> {
|
||||
use nix::sys::stat::fstat;
|
||||
|
||||
match fstat(fd_entry.fd_object.rawfd) {
|
||||
Err(e) => Err(host_impl::errno_from_nix(e.as_errno().unwrap())),
|
||||
Ok(filestat) => Ok(host_impl::filestat_from_nix(filestat)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn fd_filestat_set_times(
|
||||
fd_entry: &FdEntry,
|
||||
st_atim: host::__wasi_timestamp_t,
|
||||
mut st_mtim: host::__wasi_timestamp_t,
|
||||
fst_flags: host::__wasi_fstflags_t,
|
||||
) -> Result<(), host::__wasi_errno_t> {
|
||||
use nix::sys::time::{TimeSpec, TimeValLike};
|
||||
|
||||
if fst_flags & host::__WASI_FILESTAT_SET_MTIM_NOW != 0 {
|
||||
let clock_id = libc::CLOCK_REALTIME;
|
||||
let mut timespec = unsafe { std::mem::uninitialized::<libc::timespec>() };
|
||||
let res = unsafe { libc::clock_gettime(clock_id, &mut timespec as *mut libc::timespec) };
|
||||
if res != 0 {
|
||||
return Err(host_impl::errno_from_nix(nix::errno::Errno::last()));
|
||||
}
|
||||
let time_ns = match (timespec.tv_sec as host::__wasi_timestamp_t)
|
||||
.checked_mul(1_000_000_000)
|
||||
.and_then(|sec_ns| sec_ns.checked_add(timespec.tv_nsec as host::__wasi_timestamp_t))
|
||||
{
|
||||
Some(time_ns) => time_ns,
|
||||
None => return Err(host::__WASI_EOVERFLOW),
|
||||
};
|
||||
st_mtim = time_ns;
|
||||
}
|
||||
let ts_atime = match fst_flags {
|
||||
f if f & host::__WASI_FILESTAT_SET_ATIM_NOW != 0 => libc::timespec {
|
||||
tv_sec: 0,
|
||||
tv_nsec: utime_now(),
|
||||
},
|
||||
f if f & host::__WASI_FILESTAT_SET_ATIM != 0 => {
|
||||
*TimeSpec::nanoseconds(st_atim as i64).as_ref()
|
||||
}
|
||||
_ => libc::timespec {
|
||||
tv_sec: 0,
|
||||
tv_nsec: utime_omit(),
|
||||
},
|
||||
};
|
||||
let ts_mtime = *TimeSpec::nanoseconds(st_mtim as i64).as_ref();
|
||||
let times = [ts_atime, ts_mtime];
|
||||
let res = unsafe { libc::futimens(fd_entry.fd_object.rawfd, times.as_ptr()) };
|
||||
if res != 0 {
|
||||
Err(host_impl::errno_from_nix(nix::errno::Errno::last()))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn fd_filestat_set_size(
|
||||
fd_entry: &FdEntry,
|
||||
st_size: host::__wasi_filesize_t,
|
||||
) -> Result<(), host::__wasi_errno_t> {
|
||||
use nix::unistd::ftruncate;
|
||||
|
||||
ftruncate(fd_entry.fd_object.rawfd, st_size as off_t)
|
||||
.map_err(|e| host_impl::errno_from_nix(e.as_errno().unwrap()))
|
||||
}
|
||||
|
||||
pub(crate) fn path_filestat_get(
|
||||
wasi_ctx: &WasiCtx,
|
||||
dirfd: host::__wasi_fd_t,
|
||||
dirflags: host::__wasi_lookupflags_t,
|
||||
path: &OsStr,
|
||||
) -> Result<host::__wasi_filestat_t, host::__wasi_errno_t> {
|
||||
use nix::fcntl::AtFlags;
|
||||
use nix::sys::stat::fstatat;
|
||||
|
||||
let (dir, path) = match path_get(
|
||||
wasi_ctx,
|
||||
dirfd,
|
||||
dirflags,
|
||||
path,
|
||||
host::__WASI_RIGHT_PATH_FILESTAT_GET,
|
||||
0,
|
||||
false,
|
||||
) {
|
||||
Ok((dir, path)) => (dir, path),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let atflags = match dirflags {
|
||||
0 => AtFlags::empty(),
|
||||
_ => AtFlags::AT_SYMLINK_NOFOLLOW,
|
||||
};
|
||||
|
||||
match fstatat(dir, path.as_os_str(), atflags) {
|
||||
Err(e) => Err(host_impl::errno_from_nix(e.as_errno().unwrap())),
|
||||
Ok(filestat) => Ok(host_impl::filestat_from_nix(filestat)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn path_filestat_set_times(
|
||||
wasi_ctx: &WasiCtx,
|
||||
dirfd: host::__wasi_fd_t,
|
||||
dirflags: host::__wasi_lookupflags_t,
|
||||
path: &OsStr,
|
||||
rights: host::__wasi_rights_t,
|
||||
st_atim: host::__wasi_timestamp_t,
|
||||
mut st_mtim: host::__wasi_timestamp_t,
|
||||
fst_flags: host::__wasi_fstflags_t,
|
||||
) -> Result<(), host::__wasi_errno_t> {
|
||||
use nix::sys::time::{TimeSpec, TimeValLike};
|
||||
|
||||
let (dir, path) = match path_get(wasi_ctx, dirfd, dirflags, path, rights, 0, false) {
|
||||
Ok((dir, path)) => (dir, path),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let atflags = match dirflags {
|
||||
wasm32::__WASI_LOOKUP_SYMLINK_FOLLOW => 0,
|
||||
_ => libc::AT_SYMLINK_NOFOLLOW,
|
||||
};
|
||||
if fst_flags & host::__WASI_FILESTAT_SET_MTIM_NOW != 0 {
|
||||
let clock_id = libc::CLOCK_REALTIME;
|
||||
let mut timespec = unsafe { std::mem::uninitialized::<libc::timespec>() };
|
||||
let res = unsafe { libc::clock_gettime(clock_id, &mut timespec as *mut libc::timespec) };
|
||||
if res != 0 {
|
||||
return Err(host_impl::errno_from_nix(nix::errno::Errno::last()));
|
||||
}
|
||||
let time_ns = match (timespec.tv_sec as host::__wasi_timestamp_t)
|
||||
.checked_mul(1_000_000_000)
|
||||
.and_then(|sec_ns| sec_ns.checked_add(timespec.tv_nsec as host::__wasi_timestamp_t))
|
||||
{
|
||||
Some(time_ns) => time_ns,
|
||||
None => return Err(host::__WASI_EOVERFLOW),
|
||||
};
|
||||
st_mtim = time_ns;
|
||||
}
|
||||
let ts_atime = match fst_flags {
|
||||
f if f & host::__WASI_FILESTAT_SET_ATIM_NOW != 0 => libc::timespec {
|
||||
tv_sec: 0,
|
||||
tv_nsec: utime_now(),
|
||||
},
|
||||
f if f & host::__WASI_FILESTAT_SET_ATIM != 0 => {
|
||||
*TimeSpec::nanoseconds(st_atim as i64).as_ref()
|
||||
}
|
||||
_ => libc::timespec {
|
||||
tv_sec: 0,
|
||||
tv_nsec: utime_omit(),
|
||||
},
|
||||
};
|
||||
let ts_mtime = *TimeSpec::nanoseconds(st_mtim as i64).as_ref();
|
||||
let times = [ts_atime, ts_mtime];
|
||||
let path_cstr = match std::ffi::CString::new(path.as_os_str().as_bytes()) {
|
||||
Ok(path_cstr) => path_cstr,
|
||||
Err(_) => return Err(host::__WASI_EINVAL),
|
||||
};
|
||||
let res = unsafe { libc::utimensat(dir, path_cstr.as_ptr(), times.as_ptr(), atflags) };
|
||||
if res != 0 {
|
||||
Err(host_impl::errno_from_nix(nix::errno::Errno::last()))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn path_symlink(
|
||||
wasi_ctx: &WasiCtx,
|
||||
dirfd: host::__wasi_fd_t,
|
||||
rights: host::__wasi_rights_t,
|
||||
old_path: &OsStr,
|
||||
new_path: &OsStr,
|
||||
) -> Result<(), host::__wasi_errno_t> {
|
||||
use nix::libc::symlinkat;
|
||||
|
||||
let (dir, new_path) = match path_get(wasi_ctx, dirfd, 0, new_path, rights, 0, false) {
|
||||
Ok((dir, path)) => (dir, path),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let old_path_cstr = match std::ffi::CString::new(old_path.as_bytes()) {
|
||||
Ok(old_path_cstr) => old_path_cstr,
|
||||
Err(_) => return Err(host::__WASI_EINVAL),
|
||||
};
|
||||
let new_path_cstr = match std::ffi::CString::new(new_path.as_bytes()) {
|
||||
Ok(new_path_cstr) => new_path_cstr,
|
||||
Err(_) => return Err(host::__WASI_EINVAL),
|
||||
};
|
||||
let res = unsafe { symlinkat(old_path_cstr.as_ptr(), dir, new_path_cstr.as_ptr()) };
|
||||
if res != 0 {
|
||||
Err(host_impl::errno_from_nix(nix::errno::Errno::last()))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn path_unlink_file(
|
||||
wasi_ctx: &WasiCtx,
|
||||
dirfd: host::__wasi_fd_t,
|
||||
path: &OsStr,
|
||||
rights: host::__wasi_rights_t,
|
||||
) -> Result<(), host::__wasi_errno_t> {
|
||||
use nix::errno;
|
||||
use nix::libc::unlinkat;
|
||||
|
||||
let (dir, path) = match path_get(wasi_ctx, dirfd, 0, path, rights, 0, false) {
|
||||
Ok((dir, path)) => (dir, path),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let path_cstr = match std::ffi::CString::new(path.as_os_str().as_bytes()) {
|
||||
Ok(path_cstr) => path_cstr,
|
||||
Err(_) => return Err(host::__WASI_EINVAL),
|
||||
};
|
||||
// nix doesn't expose unlinkat() yet
|
||||
match unsafe { unlinkat(dir, path_cstr.as_ptr(), 0) } {
|
||||
0 => Ok(()),
|
||||
_ => Err(host_impl::errno_from_nix(errno::Errno::last())),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn path_remove_directory(
|
||||
wasi_ctx: &WasiCtx,
|
||||
dirfd: host::__wasi_fd_t,
|
||||
path: &OsStr,
|
||||
rights: host::__wasi_rights_t,
|
||||
) -> Result<(), host::__wasi_errno_t> {
|
||||
use nix::errno;
|
||||
use nix::libc::{unlinkat, AT_REMOVEDIR};
|
||||
|
||||
let (dir, path) = match path_get(wasi_ctx, dirfd, 0, path, rights, 0, false) {
|
||||
Ok((dir, path)) => (dir, path),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let path_cstr = match std::ffi::CString::new(path.as_os_str().as_bytes()) {
|
||||
Ok(path_cstr) => path_cstr,
|
||||
Err(_) => return Err(host::__WASI_EINVAL),
|
||||
};
|
||||
// nix doesn't expose unlinkat() yet
|
||||
match unsafe { unlinkat(dir, path_cstr.as_ptr(), AT_REMOVEDIR) } {
|
||||
0 => Ok(()),
|
||||
_ => Err(host_impl::errno_from_nix(errno::Errno::last())),
|
||||
}
|
||||
}
|
||||
286
src/sys/unix/hostcalls_impl/fs_helpers.rs
Normal file
286
src/sys/unix/hostcalls_impl/fs_helpers.rs
Normal file
@@ -0,0 +1,286 @@
|
||||
#![allow(non_camel_case_types)]
|
||||
#![allow(unused_unsafe)]
|
||||
|
||||
use super::host_impl;
|
||||
use crate::ctx::WasiCtx;
|
||||
use crate::host;
|
||||
|
||||
use nix::libc::{self, c_long};
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::os::unix::prelude::{OsStrExt, OsStringExt, RawFd};
|
||||
|
||||
/// Normalizes a path to ensure that the target path is located under the directory provided.
|
||||
///
|
||||
/// This is a workaround for not having Capsicum support in the OS.
|
||||
pub fn path_get<P: AsRef<OsStr>>(
|
||||
wasi_ctx: &WasiCtx,
|
||||
dirfd: host::__wasi_fd_t,
|
||||
dirflags: host::__wasi_lookupflags_t,
|
||||
path: P,
|
||||
needed_base: host::__wasi_rights_t,
|
||||
needed_inheriting: host::__wasi_rights_t,
|
||||
needs_final_component: bool,
|
||||
) -> Result<(RawFd, OsString), host::__wasi_errno_t> {
|
||||
use nix::errno::Errno;
|
||||
use nix::fcntl::{openat, readlinkat, OFlag};
|
||||
use nix::sys::stat::Mode;
|
||||
|
||||
const MAX_SYMLINK_EXPANSIONS: usize = 128;
|
||||
|
||||
/// close all the intermediate file descriptors, but make sure not to drop either the original
|
||||
/// dirfd or the one we return (which may be the same dirfd)
|
||||
fn ret_dir_success(dir_stack: &mut Vec<RawFd>) -> RawFd {
|
||||
let ret_dir = dir_stack.pop().expect("there is always a dirfd to return");
|
||||
if let Some(dirfds) = dir_stack.get(1..) {
|
||||
for dirfd in dirfds {
|
||||
nix::unistd::close(*dirfd).unwrap_or_else(|e| {
|
||||
dbg!(e);
|
||||
});
|
||||
}
|
||||
}
|
||||
ret_dir
|
||||
}
|
||||
|
||||
/// close all file descriptors other than the base directory, and return the errno for
|
||||
/// convenience with `return`
|
||||
fn ret_error(
|
||||
dir_stack: &mut Vec<RawFd>,
|
||||
errno: host::__wasi_errno_t,
|
||||
) -> Result<(RawFd, OsString), host::__wasi_errno_t> {
|
||||
if let Some(dirfds) = dir_stack.get(1..) {
|
||||
for dirfd in dirfds {
|
||||
nix::unistd::close(*dirfd).unwrap_or_else(|e| {
|
||||
dbg!(e);
|
||||
});
|
||||
}
|
||||
}
|
||||
Err(errno)
|
||||
}
|
||||
|
||||
let dirfe = wasi_ctx.get_fd_entry(dirfd, needed_base, needed_inheriting)?;
|
||||
|
||||
// Stack of directory file descriptors. Index 0 always corresponds with the directory provided
|
||||
// to this function. Entering a directory causes a file descriptor to be pushed, while handling
|
||||
// ".." entries causes an entry to be popped. Index 0 cannot be popped, as this would imply
|
||||
// escaping the base directory.
|
||||
let mut dir_stack = vec![dirfe.fd_object.rawfd];
|
||||
|
||||
// Stack of paths left to process. This is initially the `path` argument to this function, but
|
||||
// any symlinks we encounter are processed by pushing them on the stack.
|
||||
let mut path_stack = vec![path.as_ref().to_owned().into_vec()];
|
||||
|
||||
// Track the number of symlinks we've expanded, so we can return `ELOOP` after too many.
|
||||
let mut symlink_expansions = 0;
|
||||
|
||||
// Buffer to read links into; defined outside of the loop so we don't reallocate it constantly.
|
||||
let mut readlink_buf = vec![0u8; libc::PATH_MAX as usize + 1];
|
||||
|
||||
// TODO: rewrite this using a custom posix path type, with a component iterator that respects
|
||||
// trailing slashes. This version does way too much allocation, and is way too fiddly.
|
||||
loop {
|
||||
let component = if let Some(cur_path) = path_stack.pop() {
|
||||
// eprintln!(
|
||||
// "cur_path = {:?}",
|
||||
// std::str::from_utf8(cur_path.as_slice()).unwrap()
|
||||
// );
|
||||
let mut split = cur_path.splitn(2, |&c| c == '/' as u8);
|
||||
let head = split.next();
|
||||
let tail = split.next();
|
||||
match (head, tail) {
|
||||
(None, _) => {
|
||||
// split always returns at least a singleton iterator with an empty slice
|
||||
panic!("unreachable");
|
||||
}
|
||||
// path is empty
|
||||
(Some([]), None) => {
|
||||
return ret_error(&mut dir_stack, host::__WASI_ENOENT);
|
||||
}
|
||||
// path starts with `/`, is absolute
|
||||
(Some([]), Some(_)) => {
|
||||
return ret_error(&mut dir_stack, host::__WASI_ENOTCAPABLE);
|
||||
}
|
||||
// the final component of the path with no trailing slash
|
||||
(Some(component), None) => component.to_vec(),
|
||||
(Some(component), Some(rest)) => {
|
||||
if rest.iter().all(|&c| c == '/' as u8) {
|
||||
// the final component of the path with trailing slashes; put one trailing
|
||||
// slash back on
|
||||
let mut component = component.to_vec();
|
||||
component.push('/' as u8);
|
||||
component
|
||||
} else {
|
||||
// non-final component; push the rest back on the stack
|
||||
path_stack.push(rest.to_vec());
|
||||
component.to_vec()
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// if the path stack is ever empty, we return rather than going through the loop again
|
||||
panic!("unreachable");
|
||||
};
|
||||
|
||||
// eprintln!(
|
||||
// "component = {:?}",
|
||||
// std::str::from_utf8(component.as_slice()).unwrap()
|
||||
// );
|
||||
|
||||
match component.as_slice() {
|
||||
b"." => {
|
||||
// skip component
|
||||
}
|
||||
b".." => {
|
||||
// pop a directory
|
||||
let dirfd = dir_stack.pop().expect("dir_stack is never empty");
|
||||
|
||||
// we're not allowed to pop past the original directory
|
||||
if dir_stack.is_empty() {
|
||||
return ret_error(&mut dir_stack, host::__WASI_ENOTCAPABLE);
|
||||
} else {
|
||||
nix::unistd::close(dirfd).unwrap_or_else(|e| {
|
||||
dbg!(e);
|
||||
});
|
||||
}
|
||||
}
|
||||
// should the component be a directory? it should if there is more path left to process, or
|
||||
// if it has a trailing slash and `needs_final_component` is not set
|
||||
component
|
||||
if !path_stack.is_empty()
|
||||
|| (component.ends_with(b"/") && !needs_final_component) =>
|
||||
{
|
||||
match openat(
|
||||
*dir_stack.last().expect("dir_stack is never empty"),
|
||||
component,
|
||||
OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW,
|
||||
Mode::empty(),
|
||||
) {
|
||||
Ok(new_dir) => {
|
||||
dir_stack.push(new_dir);
|
||||
continue;
|
||||
}
|
||||
Err(e)
|
||||
// Check to see if it was a symlink. Linux indicates
|
||||
// this with ENOTDIR because of the O_DIRECTORY flag.
|
||||
if e.as_errno() == Some(Errno::ELOOP)
|
||||
|| e.as_errno() == Some(Errno::EMLINK)
|
||||
|| e.as_errno() == Some(Errno::ENOTDIR) =>
|
||||
{
|
||||
// attempt symlink expansion
|
||||
match readlinkat(
|
||||
*dir_stack.last().expect("dir_stack is never empty"),
|
||||
component,
|
||||
readlink_buf.as_mut_slice(),
|
||||
) {
|
||||
Ok(link_path) => {
|
||||
symlink_expansions += 1;
|
||||
if symlink_expansions > MAX_SYMLINK_EXPANSIONS {
|
||||
return ret_error(&mut dir_stack, host::__WASI_ELOOP);
|
||||
}
|
||||
|
||||
let mut link_path = link_path.as_bytes().to_vec();
|
||||
|
||||
// append a trailing slash if the component leading to it has one, so
|
||||
// that we preserve any ENOTDIR that might come from trying to open a
|
||||
// non-directory
|
||||
if component.ends_with(b"/") {
|
||||
link_path.push('/' as u8);
|
||||
}
|
||||
|
||||
path_stack.push(link_path);
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
return ret_error(
|
||||
&mut dir_stack,
|
||||
host_impl::errno_from_nix(e.as_errno().unwrap()),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
return ret_error(
|
||||
&mut dir_stack,
|
||||
host_impl::errno_from_nix(e.as_errno().unwrap()),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
// the final component
|
||||
component => {
|
||||
// if there's a trailing slash, or if `LOOKUP_SYMLINK_FOLLOW` is set, attempt
|
||||
// symlink expansion
|
||||
if component.ends_with(b"/") || (dirflags & host::__WASI_LOOKUP_SYMLINK_FOLLOW) != 0
|
||||
{
|
||||
match readlinkat(
|
||||
*dir_stack.last().expect("dir_stack is never empty"),
|
||||
component,
|
||||
readlink_buf.as_mut_slice(),
|
||||
) {
|
||||
Ok(link_path) => {
|
||||
symlink_expansions += 1;
|
||||
if symlink_expansions > MAX_SYMLINK_EXPANSIONS {
|
||||
return ret_error(&mut dir_stack, host::__WASI_ELOOP);
|
||||
}
|
||||
|
||||
let mut link_path = link_path.as_bytes().to_vec();
|
||||
|
||||
// append a trailing slash if the component leading to it has one, so
|
||||
// that we preserve any ENOTDIR that might come from trying to open a
|
||||
// non-directory
|
||||
if component.ends_with(b"/") {
|
||||
link_path.push('/' as u8);
|
||||
}
|
||||
|
||||
path_stack.push(link_path);
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
let errno = e.as_errno().unwrap();
|
||||
if errno != Errno::EINVAL && errno != Errno::ENOENT {
|
||||
// only return an error if this path is not actually a symlink
|
||||
return ret_error(&mut dir_stack, host_impl::errno_from_nix(errno));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// not a symlink, so we're done;
|
||||
return Ok((
|
||||
ret_dir_success(&mut dir_stack),
|
||||
OsStr::from_bytes(component).to_os_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if path_stack.is_empty() {
|
||||
// no further components to process. means we've hit a case like "." or "a/..", or if the
|
||||
// input path has trailing slashes and `needs_final_component` is not set
|
||||
return Ok((
|
||||
ret_dir_success(&mut dir_stack),
|
||||
OsStr::new(".").to_os_string(),
|
||||
));
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub fn utime_now() -> c_long {
|
||||
libc::UTIME_NOW
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn utime_now() -> c_long {
|
||||
-1
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub fn utime_omit() -> c_long {
|
||||
libc::UTIME_OMIT
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn utime_omit() -> c_long {
|
||||
-2
|
||||
}
|
||||
284
src/sys/unix/hostcalls_impl/misc.rs
Normal file
284
src/sys/unix/hostcalls_impl/misc.rs
Normal file
@@ -0,0 +1,284 @@
|
||||
#![allow(non_camel_case_types)]
|
||||
#![allow(unused_unsafe)]
|
||||
use super::host_impl;
|
||||
|
||||
use crate::memory::*;
|
||||
use crate::{host, wasm32};
|
||||
|
||||
use nix::convert_ioctl_res;
|
||||
use nix::libc::{self, c_int};
|
||||
use std::cmp;
|
||||
use std::time::SystemTime;
|
||||
|
||||
pub(crate) fn clock_res_get(
|
||||
clock_id: host::__wasi_clockid_t,
|
||||
) -> Result<host::__wasi_timestamp_t, host::__wasi_errno_t> {
|
||||
// convert the supported clocks to the libc types, or return EINVAL
|
||||
let clock_id = match clock_id {
|
||||
host::__WASI_CLOCK_REALTIME => libc::CLOCK_REALTIME,
|
||||
host::__WASI_CLOCK_MONOTONIC => libc::CLOCK_MONOTONIC,
|
||||
host::__WASI_CLOCK_PROCESS_CPUTIME_ID => libc::CLOCK_PROCESS_CPUTIME_ID,
|
||||
host::__WASI_CLOCK_THREAD_CPUTIME_ID => libc::CLOCK_THREAD_CPUTIME_ID,
|
||||
_ => return Err(host::__WASI_EINVAL),
|
||||
};
|
||||
|
||||
// no `nix` wrapper for clock_getres, so we do it ourselves
|
||||
let mut timespec = unsafe { std::mem::uninitialized::<libc::timespec>() };
|
||||
let res = unsafe { libc::clock_getres(clock_id, &mut timespec as *mut libc::timespec) };
|
||||
if res != 0 {
|
||||
return Err(host_impl::errno_from_nix(nix::errno::Errno::last()));
|
||||
}
|
||||
|
||||
// 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
|
||||
(timespec.tv_sec as host::__wasi_timestamp_t)
|
||||
.checked_mul(1_000_000_000)
|
||||
.and_then(|sec_ns| sec_ns.checked_add(timespec.tv_nsec as host::__wasi_timestamp_t))
|
||||
.map_or(Err(host::__WASI_EOVERFLOW), |resolution| {
|
||||
// a supported clock can never return zero; this case will probably never get hit, but
|
||||
// make sure we follow the spec
|
||||
if resolution == 0 {
|
||||
Err(host::__WASI_EINVAL)
|
||||
} else {
|
||||
Ok(resolution)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn clock_time_get(
|
||||
clock_id: host::__wasi_clockid_t,
|
||||
) -> Result<host::__wasi_timestamp_t, host::__wasi_errno_t> {
|
||||
// convert the supported clocks to the libc types, or return EINVAL
|
||||
let clock_id = match clock_id {
|
||||
host::__WASI_CLOCK_REALTIME => libc::CLOCK_REALTIME,
|
||||
host::__WASI_CLOCK_MONOTONIC => libc::CLOCK_MONOTONIC,
|
||||
host::__WASI_CLOCK_PROCESS_CPUTIME_ID => libc::CLOCK_PROCESS_CPUTIME_ID,
|
||||
host::__WASI_CLOCK_THREAD_CPUTIME_ID => libc::CLOCK_THREAD_CPUTIME_ID,
|
||||
_ => return Err(host::__WASI_EINVAL),
|
||||
};
|
||||
|
||||
// no `nix` wrapper for clock_getres, so we do it ourselves
|
||||
let mut timespec = unsafe { std::mem::uninitialized::<libc::timespec>() };
|
||||
let res = unsafe { libc::clock_gettime(clock_id, &mut timespec as *mut libc::timespec) };
|
||||
if res != 0 {
|
||||
return Err(host_impl::errno_from_nix(nix::errno::Errno::last()));
|
||||
}
|
||||
|
||||
// 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
|
||||
(timespec.tv_sec as host::__wasi_timestamp_t)
|
||||
.checked_mul(1_000_000_000)
|
||||
.and_then(|sec_ns| sec_ns.checked_add(timespec.tv_nsec as host::__wasi_timestamp_t))
|
||||
.map_or(Err(host::__WASI_EOVERFLOW), |time| Ok(time))
|
||||
}
|
||||
|
||||
pub(crate) fn poll_oneoff(
|
||||
input: Vec<Result<host::__wasi_subscription_t, host::__wasi_errno_t>>,
|
||||
output_slice: &mut [wasm32::__wasi_event_t],
|
||||
) -> Result<wasm32::size_t, host::__wasi_errno_t> {
|
||||
let timeout = input
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
Ok(event) if event.type_ == wasm32::__WASI_EVENTTYPE_CLOCK => Some(ClockEventData {
|
||||
delay: wasi_clock_to_relative_ns_delay(unsafe { event.u.clock }) / 1_000_000,
|
||||
userdata: event.userdata,
|
||||
}),
|
||||
_ => None,
|
||||
})
|
||||
.min_by_key(|event| event.delay);
|
||||
let fd_events: Vec<_> = input
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
Ok(event)
|
||||
if event.type_ == wasm32::__WASI_EVENTTYPE_FD_READ
|
||||
|| event.type_ == wasm32::__WASI_EVENTTYPE_FD_WRITE =>
|
||||
{
|
||||
Some(FdEventData {
|
||||
fd: unsafe { event.u.fd_readwrite.fd } as c_int,
|
||||
type_: event.type_,
|
||||
userdata: event.userdata,
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if fd_events.is_empty() && timeout.is_none() {
|
||||
return Ok(0);
|
||||
}
|
||||
let mut poll_fds: Vec<_> = fd_events
|
||||
.iter()
|
||||
.map(|event| {
|
||||
let mut flags = nix::poll::EventFlags::empty();
|
||||
match event.type_ {
|
||||
wasm32::__WASI_EVENTTYPE_FD_READ => flags.insert(nix::poll::EventFlags::POLLIN),
|
||||
wasm32::__WASI_EVENTTYPE_FD_WRITE => flags.insert(nix::poll::EventFlags::POLLOUT),
|
||||
// An event on a file descriptor can currently only be of type FD_READ or FD_WRITE
|
||||
// Nothing else has been defined in the specification, and these are also the only two
|
||||
// events we filtered before. If we get something else here, the code has a serious bug.
|
||||
_ => unreachable!(),
|
||||
};
|
||||
nix::poll::PollFd::new(event.fd, flags)
|
||||
})
|
||||
.collect();
|
||||
let timeout = timeout.map(|ClockEventData { delay, userdata }| ClockEventData {
|
||||
delay: cmp::min(delay, c_int::max_value() as u128),
|
||||
userdata,
|
||||
});
|
||||
let poll_timeout = timeout.map_or(-1, |timeout| timeout.delay as c_int);
|
||||
let ready = loop {
|
||||
match nix::poll::poll(&mut poll_fds, poll_timeout) {
|
||||
Err(_) => {
|
||||
if nix::errno::Errno::last() == nix::errno::Errno::EINTR {
|
||||
continue;
|
||||
}
|
||||
return Err(host_impl::errno_from_nix(nix::errno::Errno::last()));
|
||||
}
|
||||
Ok(ready) => break ready as usize,
|
||||
}
|
||||
};
|
||||
let events_count = if ready == 0 {
|
||||
poll_oneoff_handle_timeout_event(output_slice, timeout)
|
||||
} else {
|
||||
let events = fd_events.iter().zip(poll_fds.iter()).take(ready);
|
||||
poll_oneoff_handle_fd_event(output_slice, events)
|
||||
};
|
||||
|
||||
Ok(events_count)
|
||||
}
|
||||
|
||||
pub(crate) fn sched_yield() -> Result<(), host::__wasi_errno_t> {
|
||||
unsafe { libc::sched_yield() };
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// define the `fionread()` function, equivalent to `ioctl(fd, FIONREAD, *bytes)`
|
||||
nix::ioctl_read_bad!(fionread, nix::libc::FIONREAD, c_int);
|
||||
|
||||
fn wasi_clock_to_relative_ns_delay(
|
||||
wasi_clock: host::__wasi_subscription_t___wasi_subscription_u___wasi_subscription_u_clock_t,
|
||||
) -> u128 {
|
||||
if wasi_clock.flags != wasm32::__WASI_SUBSCRIPTION_CLOCK_ABSTIME {
|
||||
return wasi_clock.timeout as u128;
|
||||
}
|
||||
let now: u128 = SystemTime::now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.expect("Current date is before the epoch")
|
||||
.as_nanos();
|
||||
let deadline = wasi_clock.timeout as u128;
|
||||
deadline.saturating_sub(now)
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
struct ClockEventData {
|
||||
delay: u128,
|
||||
userdata: host::__wasi_userdata_t,
|
||||
}
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
struct FdEventData {
|
||||
fd: c_int,
|
||||
type_: host::__wasi_eventtype_t,
|
||||
userdata: host::__wasi_userdata_t,
|
||||
}
|
||||
|
||||
fn poll_oneoff_handle_timeout_event(
|
||||
output_slice: &mut [wasm32::__wasi_event_t],
|
||||
timeout: Option<ClockEventData>,
|
||||
) -> wasm32::size_t {
|
||||
if let Some(ClockEventData { userdata, .. }) = timeout {
|
||||
let output_event = host::__wasi_event_t {
|
||||
userdata,
|
||||
type_: wasm32::__WASI_EVENTTYPE_CLOCK,
|
||||
error: wasm32::__WASI_ESUCCESS,
|
||||
u: host::__wasi_event_t___wasi_event_u {
|
||||
fd_readwrite: host::__wasi_event_t___wasi_event_u___wasi_event_u_fd_readwrite_t {
|
||||
nbytes: 0,
|
||||
flags: 0,
|
||||
},
|
||||
},
|
||||
};
|
||||
output_slice[0] = enc_event(output_event);
|
||||
1
|
||||
} else {
|
||||
// shouldn't happen
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_oneoff_handle_fd_event<'t>(
|
||||
output_slice: &mut [wasm32::__wasi_event_t],
|
||||
events: impl Iterator<Item = (&'t FdEventData, &'t nix::poll::PollFd)>,
|
||||
) -> wasm32::size_t {
|
||||
let mut output_slice_cur = output_slice.iter_mut();
|
||||
let mut revents_count = 0;
|
||||
for (fd_event, poll_fd) in events {
|
||||
let revents = match poll_fd.revents() {
|
||||
Some(revents) => revents,
|
||||
None => continue,
|
||||
};
|
||||
let mut nbytes = 0;
|
||||
if fd_event.type_ == wasm32::__WASI_EVENTTYPE_FD_READ {
|
||||
let _ = unsafe { fionread(fd_event.fd, &mut nbytes) };
|
||||
}
|
||||
let output_event = if revents.contains(nix::poll::EventFlags::POLLNVAL) {
|
||||
host::__wasi_event_t {
|
||||
userdata: fd_event.userdata,
|
||||
type_: fd_event.type_,
|
||||
error: wasm32::__WASI_EBADF,
|
||||
u: host::__wasi_event_t___wasi_event_u {
|
||||
fd_readwrite:
|
||||
host::__wasi_event_t___wasi_event_u___wasi_event_u_fd_readwrite_t {
|
||||
nbytes: 0,
|
||||
flags: wasm32::__WASI_EVENT_FD_READWRITE_HANGUP,
|
||||
},
|
||||
},
|
||||
}
|
||||
} else if revents.contains(nix::poll::EventFlags::POLLERR) {
|
||||
host::__wasi_event_t {
|
||||
userdata: fd_event.userdata,
|
||||
type_: fd_event.type_,
|
||||
error: wasm32::__WASI_EIO,
|
||||
u: host::__wasi_event_t___wasi_event_u {
|
||||
fd_readwrite:
|
||||
host::__wasi_event_t___wasi_event_u___wasi_event_u_fd_readwrite_t {
|
||||
nbytes: 0,
|
||||
flags: wasm32::__WASI_EVENT_FD_READWRITE_HANGUP,
|
||||
},
|
||||
},
|
||||
}
|
||||
} else if revents.contains(nix::poll::EventFlags::POLLHUP) {
|
||||
host::__wasi_event_t {
|
||||
userdata: fd_event.userdata,
|
||||
type_: fd_event.type_,
|
||||
error: wasm32::__WASI_ESUCCESS,
|
||||
u: host::__wasi_event_t___wasi_event_u {
|
||||
fd_readwrite:
|
||||
host::__wasi_event_t___wasi_event_u___wasi_event_u_fd_readwrite_t {
|
||||
nbytes: 0,
|
||||
flags: wasm32::__WASI_EVENT_FD_READWRITE_HANGUP,
|
||||
},
|
||||
},
|
||||
}
|
||||
} else if revents.contains(nix::poll::EventFlags::POLLIN)
|
||||
| revents.contains(nix::poll::EventFlags::POLLOUT)
|
||||
{
|
||||
host::__wasi_event_t {
|
||||
userdata: fd_event.userdata,
|
||||
type_: fd_event.type_,
|
||||
error: wasm32::__WASI_ESUCCESS,
|
||||
u: host::__wasi_event_t___wasi_event_u {
|
||||
fd_readwrite:
|
||||
host::__wasi_event_t___wasi_event_u___wasi_event_u_fd_readwrite_t {
|
||||
nbytes: nbytes as host::__wasi_filesize_t,
|
||||
flags: 0,
|
||||
},
|
||||
},
|
||||
}
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
*output_slice_cur.next().unwrap() = enc_event(output_event);
|
||||
revents_count += 1;
|
||||
}
|
||||
revents_count
|
||||
}
|
||||
11
src/sys/unix/hostcalls_impl/mod.rs
Normal file
11
src/sys/unix/hostcalls_impl/mod.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
//! Unix-specific hostcalls that implement
|
||||
//! [WASI](https://github.com/CraneStation/wasmtime-wasi/blob/wasi/docs/WASI-overview.md).
|
||||
mod fs;
|
||||
mod fs_helpers;
|
||||
mod misc;
|
||||
|
||||
use super::fdentry;
|
||||
use super::host_impl;
|
||||
|
||||
pub(crate) use self::fs::*;
|
||||
pub(crate) use self::misc::*;
|
||||
Reference in New Issue
Block a user