#![allow(non_camel_case_types)]
#![allow(unused)]
use super::fs_helpers::*;
use crate::old::snapshot_0::ctx::WasiCtx;
use crate::old::snapshot_0::fdentry::FdEntry;
use crate::old::snapshot_0::host::{Dirent, FileType};
use crate::old::snapshot_0::hostcalls_impl::{fd_filestat_set_times_impl, PathGet};
use crate::old::snapshot_0::sys::fdentry_impl::determine_type_rights;
use crate::old::snapshot_0::sys::host_impl::{self, path_from_host};
use crate::old::snapshot_0::sys::hostcalls_impl::fs_helpers::PathGetExt;
use crate::old::snapshot_0::{wasi, Error, Result};
use log::{debug, trace};
use std::convert::TryInto;
use std::fs::{File, Metadata, OpenOptions};
use std::io::{self, Seek, SeekFrom};
use std::os::windows::fs::{FileExt, OpenOptionsExt};
use std::os::windows::prelude::{AsRawHandle, FromRawHandle};
use std::path::{Path, PathBuf};
use winx::file::{AccessMode, CreationDisposition, FileModeInformation, Flags};
fn read_at(mut file: &File, buf: &mut [u8], offset: u64) -> io::Result<usize> {
let cur_pos = file.seek(SeekFrom::Current(0))?;
let nread = file.seek_read(buf, offset)?;
file.seek(SeekFrom::Start(cur_pos))?;
Ok(nread)
}
fn write_at(mut file: &File, buf: &[u8], offset: u64) -> io::Result<usize> {
let cur_pos = file.seek(SeekFrom::Current(0))?;
let nwritten = file.seek_write(buf, offset)?;
file.seek(SeekFrom::Start(cur_pos))?;
Ok(nwritten)
}
pub(crate) fn fd_pread(
file: &File,
buf: &mut [u8],
offset: wasi::__wasi_filesize_t,
) -> Result<usize> {
read_at(file, buf, offset).map_err(Into::into)
}
pub(crate) fn fd_pwrite(file: &File, buf: &[u8], offset: wasi::__wasi_filesize_t) -> Result<usize> {
write_at(file, buf, offset).map_err(Into::into)
}
pub(crate) fn fd_fdstat_get(fd: &File) -> Result<wasi::__wasi_fdflags_t> {
let mut fdflags = 0;
let handle = unsafe { fd.as_raw_handle() };
let access_mode = winx::file::query_access_information(handle)?;
let mode = winx::file::query_mode_information(handle)?;
if access_mode.contains(AccessMode::FILE_APPEND_DATA)
&& !access_mode.contains(AccessMode::FILE_WRITE_DATA)
{
fdflags |= wasi::__WASI_FDFLAGS_APPEND;
}
if mode.contains(FileModeInformation::FILE_WRITE_THROUGH) {
fdflags |= wasi::__WASI_FDFLAGS_SYNC;
}
Ok(fdflags)
}
pub(crate) fn fd_fdstat_set_flags(fd: &File, fdflags: wasi::__wasi_fdflags_t) -> Result<()> {
unimplemented!("fd_fdstat_set_flags")
}
pub(crate) fn fd_advise(
_file: &File,
advice: wasi::__wasi_advice_t,
_offset: wasi::__wasi_filesize_t,
_len: wasi::__wasi_filesize_t,
) -> Result<()> {
match advice {
wasi::__WASI_ADVICE_DONTNEED
| wasi::__WASI_ADVICE_SEQUENTIAL
| wasi::__WASI_ADVICE_WILLNEED
| wasi::__WASI_ADVICE_NOREUSE
| wasi::__WASI_ADVICE_RANDOM
| wasi::__WASI_ADVICE_NORMAL => {}
_ => return Err(Error::EINVAL),
}
Ok(())
}
pub(crate) fn path_create_directory(resolved: PathGet) -> Result<()> {
let path = resolved.concatenate()?;
std::fs::create_dir(&path).map_err(Into::into)
}
pub(crate) fn path_link(resolved_old: PathGet, resolved_new: PathGet) -> Result<()> {
unimplemented!("path_link")
}
pub(crate) fn path_open(
resolved: PathGet,
read: bool,
write: bool,
oflags: wasi::__wasi_oflags_t,
fdflags: wasi::__wasi_fdflags_t,
) -> Result<File> {
use winx::file::{AccessMode, CreationDisposition, Flags};
let mut opts = OpenOptions::new();
match creation_disposition_from_oflags(oflags) {
CreationDisposition::CREATE_ALWAYS => {
opts.create(true).write(true);
}
CreationDisposition::CREATE_NEW => {
opts.create_new(true).write(true);
}
CreationDisposition::TRUNCATE_EXISTING => {
opts.truncate(true).write(true);
}
_ => {}
}
let path = resolved.concatenate()?;
match path.symlink_metadata().map(|metadata| metadata.file_type()) {
Ok(file_type) => {
if file_type.is_symlink() {
return Err(Error::ELOOP);
}
if file_type.is_file() && oflags & wasi::__WASI_OFLAGS_DIRECTORY != 0 {
return Err(Error::ENOTDIR);
}
}
Err(e) => match e.raw_os_error() {
Some(e) => {
use winx::winerror::WinError;
log::debug!("path_open at symlink_metadata error code={:?}", e);
let e = WinError::from_u32(e as u32);
if e != WinError::ERROR_FILE_NOT_FOUND {
return Err(e.into());
}
}
None => {
log::debug!("Inconvertible OS error: {}", e);
return Err(Error::EIO);
}
},
}
opts.access_mode(file_access_mode_from_fdflags(fdflags, read, write).bits())
.custom_flags(file_flags_from_fdflags(fdflags).bits())
.open(&path)
.map_err(Into::into)
}
fn creation_disposition_from_oflags(oflags: wasi::__wasi_oflags_t) -> CreationDisposition {
if oflags & wasi::__WASI_OFLAGS_CREAT != 0 {
if oflags & wasi::__WASI_OFLAGS_EXCL != 0 {
CreationDisposition::CREATE_NEW
} else {
CreationDisposition::CREATE_ALWAYS
}
} else if oflags & wasi::__WASI_OFLAGS_TRUNC != 0 {
CreationDisposition::TRUNCATE_EXISTING
} else {
CreationDisposition::OPEN_EXISTING
}
}
fn file_access_mode_from_fdflags(
fdflags: wasi::__wasi_fdflags_t,
read: bool,
write: bool,
) -> AccessMode {
let mut access_mode = AccessMode::READ_CONTROL;
if read {
access_mode.insert(AccessMode::GENERIC_READ);
}
if write {
access_mode.insert(AccessMode::GENERIC_WRITE);
}
if fdflags & wasi::__WASI_FDFLAGS_APPEND != 0 {
access_mode.insert(AccessMode::FILE_APPEND_DATA);
access_mode.remove(AccessMode::FILE_WRITE_DATA);
}
access_mode
}
fn file_flags_from_fdflags(fdflags: wasi::__wasi_fdflags_t) -> Flags {
let mut flags = Flags::FILE_FLAG_BACKUP_SEMANTICS;
if fdflags & wasi::__WASI_FDFLAGS_DSYNC != 0
|| fdflags & wasi::__WASI_FDFLAGS_RSYNC != 0
|| fdflags & wasi::__WASI_FDFLAGS_SYNC != 0
{
flags.insert(Flags::FILE_FLAG_WRITE_THROUGH);
}
flags
}
fn dirent_from_path<P: AsRef<Path>>(
path: P,
name: &str,
cookie: wasi::__wasi_dircookie_t,
) -> Result<Dirent> {
let path = path.as_ref();
trace!("dirent_from_path: opening {}", path.to_string_lossy());
let file = OpenOptions::new()
.custom_flags(Flags::FILE_FLAG_BACKUP_SEMANTICS.bits())
.read(true)
.open(path)?;
let ty = file.metadata()?.file_type();
Ok(Dirent {
ftype: host_impl::filetype_from_std(&ty),
name: name.to_owned(),
cookie,
ino: host_impl::file_serial_no(&file)?,
})
}
pub(crate) fn fd_readdir(
fd: &File,
cookie: wasi::__wasi_dircookie_t,
) -> Result<impl Iterator<Item = Result<Dirent>>> {
use winx::file::get_file_path;
let cookie = cookie.try_into()?;
let path = get_file_path(fd)?;
let path = Path::new(&path);
let parent = path.parent().unwrap_or(path);
let dot = dirent_from_path(path, ".", 1)?;
let dotdot = dirent_from_path(parent, "..", 2)?;
trace!(" | fd_readdir impl: executing std::fs::ReadDir");
let iter = path.read_dir()?.zip(3..).map(|(dir, no)| {
let dir: std::fs::DirEntry = dir?;
Ok(Dirent {
name: path_from_host(dir.file_name())?,
ftype: host_impl::filetype_from_std(&dir.file_type()?),
ino: File::open(dir.path()).and_then(|f| host_impl::file_serial_no(&f))?,
cookie: no,
})
});
let iter = vec![dot, dotdot].into_iter().map(Ok).chain(iter);
Ok(iter.skip(cookie))
}
pub(crate) fn path_readlink(resolved: PathGet, buf: &mut [u8]) -> Result<usize> {
use winx::file::get_file_path;
let path = resolved.concatenate()?;
let target_path = path.read_link()?;
let dir_path = get_file_path(resolved.dirfd())?;
let dir_path = PathBuf::from(strip_extended_prefix(dir_path));
let target_path = target_path
.strip_prefix(dir_path)
.map_err(|_| Error::ENOTCAPABLE)
.and_then(|path| path.to_str().map(String::from).ok_or(Error::EILSEQ))?;
if buf.len() > 0 {
let mut chars = target_path.chars();
let mut nread = 0usize;
for i in 0..buf.len() {
match chars.next() {
Some(ch) => {
buf[i] = ch as u8;
nread += 1;
}
None => break,
}
}
Ok(nread)
} else {
Ok(0)
}
}
fn strip_trailing_slashes_and_concatenate(resolved: &PathGet) -> Result<Option<PathBuf>> {
if resolved.path().ends_with('/') {
let suffix = resolved.path().trim_end_matches('/');
concatenate(resolved.dirfd(), Path::new(suffix)).map(Some)
} else {
Ok(None)
}
}
pub(crate) fn path_rename(resolved_old: PathGet, resolved_new: PathGet) -> Result<()> {
use std::fs;
let old_path = resolved_old.concatenate()?;
let new_path = resolved_new.concatenate()?;
if old_path.is_dir() && new_path.is_file() {
return Err(Error::ENOTDIR);
}
if old_path.is_file() && resolved_new.path().ends_with('/') {
return Err(Error::ENOTDIR);
}
fs::rename(&old_path, &new_path).or_else(|e| match e.raw_os_error() {
Some(e) => {
use winx::winerror::WinError;
log::debug!("path_rename at rename error code={:?}", e);
match WinError::from_u32(e as u32) {
WinError::ERROR_ACCESS_DENIED => {
if old_path.is_file() {
Err(Error::EISDIR)
} else {
fs::remove_dir(&new_path)
.and_then(|()| fs::rename(old_path, new_path))
.map_err(Into::into)
}
}
WinError::ERROR_INVALID_NAME => {
if let Some(path) = strip_trailing_slashes_and_concatenate(&resolved_old)? {
if path.is_file() {
return Err(Error::ENOTDIR);
}
}
Err(WinError::ERROR_INVALID_NAME.into())
}
e => Err(e.into()),
}
}
None => {
log::debug!("Inconvertible OS error: {}", e);
Err(Error::EIO)
}
})
}
pub(crate) fn fd_filestat_get(file: &std::fs::File) -> Result<wasi::__wasi_filestat_t> {
host_impl::filestat_from_win(file)
}
pub(crate) fn path_filestat_get(
resolved: PathGet,
dirflags: wasi::__wasi_lookupflags_t,
) -> Result<wasi::__wasi_filestat_t> {
let path = resolved.concatenate()?;
let file = File::open(path)?;
host_impl::filestat_from_win(&file)
}
pub(crate) fn path_filestat_set_times(
resolved: PathGet,
dirflags: wasi::__wasi_lookupflags_t,
st_atim: wasi::__wasi_timestamp_t,
mut st_mtim: wasi::__wasi_timestamp_t,
fst_flags: wasi::__wasi_fstflags_t,
) -> Result<()> {
use winx::file::AccessMode;
let path = resolved.concatenate()?;
let file = OpenOptions::new()
.access_mode(AccessMode::FILE_WRITE_ATTRIBUTES.bits())
.open(path)?;
fd_filestat_set_times_impl(&file, st_atim, st_mtim, fst_flags)
}
pub(crate) fn path_symlink(old_path: &str, resolved: PathGet) -> Result<()> {
use std::os::windows::fs::{symlink_dir, symlink_file};
use winx::winerror::WinError;
let old_path = concatenate(resolved.dirfd(), Path::new(old_path))?;
let new_path = resolved.concatenate()?;
symlink_file(&old_path, &new_path).or_else(|e| {
match e.raw_os_error() {
Some(e) => {
log::debug!("path_symlink at symlink_file error code={:?}", e);
match WinError::from_u32(e as u32) {
WinError::ERROR_NOT_A_REPARSE_POINT => {
symlink_dir(old_path, new_path).map_err(Into::into)
}
WinError::ERROR_ACCESS_DENIED => {
if new_path.exists() {
Err(Error::EEXIST)
} else {
Err(WinError::ERROR_ACCESS_DENIED.into())
}
}
WinError::ERROR_INVALID_NAME => {
if let Some(path) = strip_trailing_slashes_and_concatenate(&resolved)? {
if path.exists() {
return Err(Error::EEXIST);
}
}
Err(WinError::ERROR_INVALID_NAME.into())
}
e => Err(e.into()),
}
}
None => {
log::debug!("Inconvertible OS error: {}", e);
Err(Error::EIO)
}
}
})
}
pub(crate) fn path_unlink_file(resolved: PathGet) -> Result<()> {
use std::fs;
use winx::winerror::WinError;
let path = resolved.concatenate()?;
let file_type = path
.symlink_metadata()
.map(|metadata| metadata.file_type())?;
if file_type.is_symlink() {
fs::remove_file(&path).or_else(|e| {
match e.raw_os_error() {
Some(e) => {
log::debug!("path_unlink_file at symlink_file error code={:?}", e);
match WinError::from_u32(e as u32) {
WinError::ERROR_ACCESS_DENIED => {
fs::remove_dir(path).map_err(Into::into)
}
e => Err(e.into()),
}
}
None => {
log::debug!("Inconvertible OS error: {}", e);
Err(Error::EIO)
}
}
})
} else if file_type.is_dir() {
Err(Error::EISDIR)
} else if file_type.is_file() {
fs::remove_file(path).map_err(Into::into)
} else {
Err(Error::EINVAL)
}
}
pub(crate) fn path_remove_directory(resolved: PathGet) -> Result<()> {
let path = resolved.concatenate()?;
std::fs::remove_dir(&path).map_err(Into::into)
}