Add yanix crate and replace nix with yanix in wasi-common (#649)
* Add yanix crate This commit adds `yanix` crate as a Unix dependency for `wasi-common`. `yanix` stands for Yet Another Nix crate and is exactly what the name suggests: a crate in the spirit of the `nix` crate, but which takes a different approach, using lower-level interfaces with less abstraction, so that it fits better with its main use case, implementation of WASI syscalls. * Replace nix with yanix crate Having introduced `yanix` crate as an in-house replacement for the `nix` crate, this commit makes the necessary changes to `wasi-common` to depend _only_ on `yanix` crate. * Address review comments * make `fd_dup` unsafe * rename `get_fd` to `get_fd_flags`, etc. * reuse `io::Error::last_os_error()` to get the last errno value * Address more comments * make all `fcntl` fns unsafe * adjust `wasi-common` impl appropriately * Make all fns operating on RawFd unsafe * Fix linux build * Address more comments
This commit is contained in:
18
crates/wasi-common/yanix/Cargo.toml
Normal file
18
crates/wasi-common/yanix/Cargo.toml
Normal file
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "yanix"
|
||||
version = "0.1.0"
|
||||
authors = ["The Wasmtime Project Developers"]
|
||||
description = "Yet Another Nix crate: a Unix API helper library"
|
||||
license = "Apache-2.0 WITH LLVM-exception"
|
||||
repository = "https://github.com/bytecodealliance/wasmtime"
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
log = "0.4"
|
||||
libc = { version = "0.2", features = ["extra_traits"] }
|
||||
thiserror = "1.0"
|
||||
bitflags = "1.2"
|
||||
cfg-if = "0.1.9"
|
||||
|
||||
[badges]
|
||||
maintenance = { status = "actively-developed" }
|
||||
220
crates/wasi-common/yanix/LICENSE
Normal file
220
crates/wasi-common/yanix/LICENSE
Normal file
@@ -0,0 +1,220 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
|
||||
--- LLVM Exceptions to the Apache 2.0 License ----
|
||||
|
||||
As an exception, if, as a result of your compiling your source code, portions
|
||||
of this Software are embedded into an Object form of such source code, you
|
||||
may redistribute such embedded portions in such Object form without complying
|
||||
with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
|
||||
|
||||
In addition, if you combine or link compiled forms of this Software with
|
||||
software that is licensed under the GPLv2 ("Combined Software") and if a
|
||||
court of competent jurisdiction determines that the patent provision (Section
|
||||
3), the indemnity provision (Section 9) or other Section of the License
|
||||
conflicts with the conditions of the GPLv2, you may retroactively and
|
||||
prospectively choose to deem waived or otherwise exclude such Section(s) of
|
||||
the License, but only in their entirety and only with respect to the Combined
|
||||
Software.
|
||||
|
||||
29
crates/wasi-common/yanix/src/clock.rs
Normal file
29
crates/wasi-common/yanix/src/clock.rs
Normal file
@@ -0,0 +1,29 @@
|
||||
use crate::{Errno, Result};
|
||||
use std::mem::MaybeUninit;
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub enum ClockId {
|
||||
Realtime,
|
||||
Monotonic,
|
||||
ProcessCPUTime,
|
||||
ThreadCPUTime,
|
||||
}
|
||||
|
||||
impl ClockId {
|
||||
pub fn as_raw(&self) -> libc::clockid_t {
|
||||
match self {
|
||||
Self::Realtime => libc::CLOCK_REALTIME,
|
||||
Self::Monotonic => libc::CLOCK_MONOTONIC,
|
||||
Self::ProcessCPUTime => libc::CLOCK_PROCESS_CPUTIME_ID,
|
||||
Self::ThreadCPUTime => libc::CLOCK_THREAD_CPUTIME_ID,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clock_getres(clock_id: ClockId) -> Result<libc::timespec> {
|
||||
let mut timespec = MaybeUninit::<libc::timespec>::uninit();
|
||||
Errno::from_success_code(unsafe {
|
||||
libc::clock_getres(clock_id.as_raw(), timespec.as_mut_ptr())
|
||||
})?;
|
||||
Ok(unsafe { timespec.assume_init() })
|
||||
}
|
||||
162
crates/wasi-common/yanix/src/dir.rs
Normal file
162
crates/wasi-common/yanix/src/dir.rs
Normal file
@@ -0,0 +1,162 @@
|
||||
use crate::{
|
||||
sys::dir::{iter_impl, EntryImpl},
|
||||
Errno, Result,
|
||||
};
|
||||
use std::os::unix::io::{AsRawFd, IntoRawFd, RawFd};
|
||||
use std::{ffi::CStr, ops::Deref, ptr};
|
||||
|
||||
pub use crate::sys::EntryExt;
|
||||
|
||||
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||
pub struct Dir(pub(crate) ptr::NonNull<libc::DIR>);
|
||||
|
||||
impl Dir {
|
||||
/// Takes the ownership of the passed-in descriptor-based object,
|
||||
/// and creates a new instance of `Dir`.
|
||||
#[inline]
|
||||
pub fn from<F: IntoRawFd>(fd: F) -> Result<Self> {
|
||||
let fd = fd.into_raw_fd();
|
||||
unsafe { Self::from_fd(fd) }
|
||||
}
|
||||
|
||||
unsafe fn from_fd(fd: RawFd) -> Result<Self> {
|
||||
let d = libc::fdopendir(fd);
|
||||
if let Some(d) = ptr::NonNull::new(d) {
|
||||
Ok(Self(d))
|
||||
} else {
|
||||
let e = Errno::last();
|
||||
libc::close(fd);
|
||||
Err(e.into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the position of the directory stream, see `seekdir(3)`.
|
||||
#[cfg(not(target_os = "android"))]
|
||||
pub fn seek(&mut self, loc: SeekLoc) {
|
||||
unsafe { libc::seekdir(self.0.as_ptr(), loc.0) }
|
||||
}
|
||||
|
||||
/// Reset directory stream, see `rewinddir(3)`.
|
||||
pub fn rewind(&mut self) {
|
||||
unsafe { libc::rewinddir(self.0.as_ptr()) }
|
||||
}
|
||||
|
||||
/// Get the current position in the directory stream.
|
||||
///
|
||||
/// If this location is given to `Dir::seek`, the entries up to the previously returned
|
||||
/// will be omitted and the iteration will start from the currently pending directory entry.
|
||||
#[cfg(not(target_os = "android"))]
|
||||
#[allow(dead_code)]
|
||||
pub fn tell(&self) -> SeekLoc {
|
||||
let loc = unsafe { libc::telldir(self.0.as_ptr()) };
|
||||
SeekLoc(loc)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl Send for Dir {}
|
||||
|
||||
impl AsRawFd for Dir {
|
||||
fn as_raw_fd(&self) -> RawFd {
|
||||
unsafe { libc::dirfd(self.0.as_ptr()) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Dir {
|
||||
fn drop(&mut self) {
|
||||
unsafe { libc::closedir(self.0.as_ptr()) };
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub struct Entry(pub(crate) EntryImpl);
|
||||
|
||||
impl Entry {
|
||||
/// Returns the file name of this directory entry.
|
||||
pub fn file_name(&self) -> &CStr {
|
||||
unsafe { CStr::from_ptr(self.0.d_name.as_ptr()) }
|
||||
}
|
||||
|
||||
/// Returns the type of this directory entry.
|
||||
pub fn file_type(&self) -> FileType {
|
||||
unsafe { FileType::from_raw(self.0.d_type) }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "android"))]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct SeekLoc(libc::c_long);
|
||||
|
||||
#[cfg(not(target_os = "android"))]
|
||||
impl SeekLoc {
|
||||
pub unsafe fn from_raw(loc: i64) -> Self {
|
||||
Self(loc.into())
|
||||
}
|
||||
|
||||
pub fn to_raw(&self) -> i64 {
|
||||
self.0.into()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[repr(u8)]
|
||||
pub enum FileType {
|
||||
CharacterDevice = libc::DT_CHR,
|
||||
Directory = libc::DT_DIR,
|
||||
BlockDevice = libc::DT_BLK,
|
||||
RegularFile = libc::DT_REG,
|
||||
Symlink = libc::DT_LNK,
|
||||
Fifo = libc::DT_FIFO,
|
||||
Socket = libc::DT_SOCK,
|
||||
Unknown = libc::DT_UNKNOWN,
|
||||
}
|
||||
|
||||
impl FileType {
|
||||
pub unsafe fn from_raw(file_type: u8) -> Self {
|
||||
match file_type {
|
||||
libc::DT_CHR => Self::CharacterDevice,
|
||||
libc::DT_DIR => Self::Directory,
|
||||
libc::DT_BLK => Self::BlockDevice,
|
||||
libc::DT_REG => Self::RegularFile,
|
||||
libc::DT_LNK => Self::Symlink,
|
||||
libc::DT_SOCK => Self::Socket,
|
||||
libc::DT_FIFO => Self::Fifo,
|
||||
/* libc::DT_UNKNOWN */ _ => Self::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_raw(&self) -> u8 {
|
||||
match self {
|
||||
Self::CharacterDevice => libc::DT_CHR,
|
||||
Self::Directory => libc::DT_DIR,
|
||||
Self::BlockDevice => libc::DT_BLK,
|
||||
Self::RegularFile => libc::DT_REG,
|
||||
Self::Symlink => libc::DT_LNK,
|
||||
Self::Socket => libc::DT_SOCK,
|
||||
Self::Fifo => libc::DT_FIFO,
|
||||
Self::Unknown => libc::DT_UNKNOWN,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct DirIter<T: Deref<Target = Dir>>(T);
|
||||
|
||||
impl<T> DirIter<T>
|
||||
where
|
||||
T: Deref<Target = Dir>,
|
||||
{
|
||||
pub fn new(dir: T) -> Self {
|
||||
Self(dir)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Iterator for DirIter<T>
|
||||
where
|
||||
T: Deref<Target = Dir>,
|
||||
{
|
||||
type Item = Result<Entry>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
unsafe { iter_impl(&self.0).map(|x| x.map(Entry)) }
|
||||
}
|
||||
}
|
||||
227
crates/wasi-common/yanix/src/errno.rs
Normal file
227
crates/wasi-common/yanix/src/errno.rs
Normal file
@@ -0,0 +1,227 @@
|
||||
//! Errno-specific for different Unix platforms
|
||||
use crate::Result;
|
||||
use std::{fmt, io};
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Copy, Clone, Error, PartialEq, Eq, Hash)]
|
||||
#[repr(i32)]
|
||||
pub enum Errno {
|
||||
EPERM = libc::EPERM,
|
||||
ENOENT = libc::ENOENT,
|
||||
ESRCH = libc::ESRCH,
|
||||
EINTR = libc::EINTR,
|
||||
EIO = libc::EIO,
|
||||
ENXIO = libc::ENXIO,
|
||||
E2BIG = libc::E2BIG,
|
||||
ENOEXEC = libc::ENOEXEC,
|
||||
EBADF = libc::EBADF,
|
||||
ECHILD = libc::ECHILD,
|
||||
EAGAIN = libc::EAGAIN,
|
||||
ENOMEM = libc::ENOMEM,
|
||||
EACCES = libc::EACCES,
|
||||
EFAULT = libc::EFAULT,
|
||||
EBUSY = libc::EBUSY,
|
||||
EEXIST = libc::EEXIST,
|
||||
EXDEV = libc::EXDEV,
|
||||
ENODEV = libc::ENODEV,
|
||||
ENOTDIR = libc::ENOTDIR,
|
||||
EISDIR = libc::EISDIR,
|
||||
EINVAL = libc::EINVAL,
|
||||
ENFILE = libc::ENFILE,
|
||||
EMFILE = libc::EMFILE,
|
||||
ENOTTY = libc::ENOTTY,
|
||||
ETXTBSY = libc::ETXTBSY,
|
||||
EFBIG = libc::EFBIG,
|
||||
ENOSPC = libc::ENOSPC,
|
||||
ESPIPE = libc::ESPIPE,
|
||||
EROFS = libc::EROFS,
|
||||
EMLINK = libc::EMLINK,
|
||||
EPIPE = libc::EPIPE,
|
||||
EDOM = libc::EDOM,
|
||||
ERANGE = libc::ERANGE,
|
||||
EDEADLK = libc::EDEADLK,
|
||||
ENAMETOOLONG = libc::ENAMETOOLONG,
|
||||
ENOLCK = libc::ENOLCK,
|
||||
ENOSYS = libc::ENOSYS,
|
||||
ENOTEMPTY = libc::ENOTEMPTY,
|
||||
ELOOP = libc::ELOOP,
|
||||
ENOMSG = libc::ENOMSG,
|
||||
EIDRM = libc::EIDRM,
|
||||
ENOLINK = libc::ENOLINK,
|
||||
EPROTO = libc::EPROTO,
|
||||
EMULTIHOP = libc::EMULTIHOP,
|
||||
EBADMSG = libc::EBADMSG,
|
||||
EOVERFLOW = libc::EOVERFLOW,
|
||||
EILSEQ = libc::EILSEQ,
|
||||
ENOTSOCK = libc::ENOTSOCK,
|
||||
EDESTADDRREQ = libc::EDESTADDRREQ,
|
||||
EMSGSIZE = libc::EMSGSIZE,
|
||||
EPROTOTYPE = libc::EPROTOTYPE,
|
||||
ENOPROTOOPT = libc::ENOPROTOOPT,
|
||||
EPROTONOSUPPORT = libc::EPROTONOSUPPORT,
|
||||
EAFNOSUPPORT = libc::EAFNOSUPPORT,
|
||||
EADDRINUSE = libc::EADDRINUSE,
|
||||
EADDRNOTAVAIL = libc::EADDRNOTAVAIL,
|
||||
ENETDOWN = libc::ENETDOWN,
|
||||
ENETUNREACH = libc::ENETUNREACH,
|
||||
ENETRESET = libc::ENETRESET,
|
||||
ECONNABORTED = libc::ECONNABORTED,
|
||||
ECONNRESET = libc::ECONNRESET,
|
||||
ENOBUFS = libc::ENOBUFS,
|
||||
EISCONN = libc::EISCONN,
|
||||
ENOTCONN = libc::ENOTCONN,
|
||||
ETIMEDOUT = libc::ETIMEDOUT,
|
||||
ECONNREFUSED = libc::ECONNREFUSED,
|
||||
EHOSTUNREACH = libc::EHOSTUNREACH,
|
||||
EALREADY = libc::EALREADY,
|
||||
EINPROGRESS = libc::EINPROGRESS,
|
||||
ESTALE = libc::ESTALE,
|
||||
EDQUOT = libc::EDQUOT,
|
||||
ECANCELED = libc::ECANCELED,
|
||||
EOWNERDEAD = libc::EOWNERDEAD,
|
||||
ENOTRECOVERABLE = libc::ENOTRECOVERABLE,
|
||||
}
|
||||
|
||||
impl Errno {
|
||||
pub fn from_i32(err: i32) -> Self {
|
||||
match err {
|
||||
libc::EPERM => Self::EPERM,
|
||||
libc::ENOENT => Self::ENOENT,
|
||||
libc::ESRCH => Self::ESRCH,
|
||||
libc::EINTR => Self::EINTR,
|
||||
libc::EIO => Self::EIO,
|
||||
libc::ENXIO => Self::ENXIO,
|
||||
libc::E2BIG => Self::E2BIG,
|
||||
libc::ENOEXEC => Self::ENOEXEC,
|
||||
libc::EBADF => Self::EBADF,
|
||||
libc::ECHILD => Self::ECHILD,
|
||||
libc::EAGAIN => Self::EAGAIN,
|
||||
libc::ENOMEM => Self::ENOMEM,
|
||||
libc::EACCES => Self::EACCES,
|
||||
libc::EFAULT => Self::EFAULT,
|
||||
libc::EBUSY => Self::EBUSY,
|
||||
libc::EEXIST => Self::EEXIST,
|
||||
libc::EXDEV => Self::EXDEV,
|
||||
libc::ENODEV => Self::ENODEV,
|
||||
libc::ENOTDIR => Self::ENOTDIR,
|
||||
libc::EISDIR => Self::EISDIR,
|
||||
libc::EINVAL => Self::EINVAL,
|
||||
libc::ENFILE => Self::ENFILE,
|
||||
libc::EMFILE => Self::EMFILE,
|
||||
libc::ENOTTY => Self::ENOTTY,
|
||||
libc::ETXTBSY => Self::ETXTBSY,
|
||||
libc::EFBIG => Self::EFBIG,
|
||||
libc::ENOSPC => Self::ENOSPC,
|
||||
libc::ESPIPE => Self::ESPIPE,
|
||||
libc::EROFS => Self::EROFS,
|
||||
libc::EMLINK => Self::EMLINK,
|
||||
libc::EPIPE => Self::EPIPE,
|
||||
libc::EDOM => Self::EDOM,
|
||||
libc::ERANGE => Self::ERANGE,
|
||||
libc::EDEADLK => Self::EDEADLK,
|
||||
libc::ENAMETOOLONG => Self::ENAMETOOLONG,
|
||||
libc::ENOLCK => Self::ENOLCK,
|
||||
libc::ENOSYS => Self::ENOSYS,
|
||||
libc::ENOTEMPTY => Self::ENOTEMPTY,
|
||||
libc::ELOOP => Self::ELOOP,
|
||||
libc::ENOMSG => Self::ENOMSG,
|
||||
libc::EIDRM => Self::EIDRM,
|
||||
libc::ENOLINK => Self::ENOLINK,
|
||||
libc::EPROTO => Self::EPROTO,
|
||||
libc::EMULTIHOP => Self::EMULTIHOP,
|
||||
libc::EBADMSG => Self::EBADMSG,
|
||||
libc::EOVERFLOW => Self::EOVERFLOW,
|
||||
libc::EILSEQ => Self::EILSEQ,
|
||||
libc::ENOTSOCK => Self::ENOTSOCK,
|
||||
libc::EDESTADDRREQ => Self::EDESTADDRREQ,
|
||||
libc::EMSGSIZE => Self::EMSGSIZE,
|
||||
libc::EPROTOTYPE => Self::EPROTOTYPE,
|
||||
libc::ENOPROTOOPT => Self::ENOPROTOOPT,
|
||||
libc::EPROTONOSUPPORT => Self::EPROTONOSUPPORT,
|
||||
libc::EAFNOSUPPORT => Self::EAFNOSUPPORT,
|
||||
libc::EADDRINUSE => Self::EADDRINUSE,
|
||||
libc::EADDRNOTAVAIL => Self::EADDRNOTAVAIL,
|
||||
libc::ENETDOWN => Self::ENETDOWN,
|
||||
libc::ENETUNREACH => Self::ENETUNREACH,
|
||||
libc::ENETRESET => Self::ENETRESET,
|
||||
libc::ECONNABORTED => Self::ECONNABORTED,
|
||||
libc::ECONNRESET => Self::ECONNRESET,
|
||||
libc::ENOBUFS => Self::ENOBUFS,
|
||||
libc::EISCONN => Self::EISCONN,
|
||||
libc::ENOTCONN => Self::ENOTCONN,
|
||||
libc::ETIMEDOUT => Self::ETIMEDOUT,
|
||||
libc::ECONNREFUSED => Self::ECONNREFUSED,
|
||||
libc::EHOSTUNREACH => Self::EHOSTUNREACH,
|
||||
libc::EALREADY => Self::EALREADY,
|
||||
libc::EINPROGRESS => Self::EINPROGRESS,
|
||||
libc::ESTALE => Self::ESTALE,
|
||||
libc::EDQUOT => Self::EDQUOT,
|
||||
libc::ECANCELED => Self::ECANCELED,
|
||||
libc::EOWNERDEAD => Self::EOWNERDEAD,
|
||||
libc::ENOTRECOVERABLE => Self::ENOTRECOVERABLE,
|
||||
other => {
|
||||
log::warn!("Unknown errno: {}", other);
|
||||
Self::ENOSYS
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn last() -> Self {
|
||||
let errno = io::Error::last_os_error()
|
||||
.raw_os_error()
|
||||
.unwrap_or(libc::ENOSYS);
|
||||
Self::from_i32(errno)
|
||||
}
|
||||
|
||||
pub fn from_success_code<T: IsZero>(t: T) -> Result<()> {
|
||||
if t.is_zero() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Self::last().into())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_result<T: IsMinusOne>(t: T) -> Result<T> {
|
||||
if t.is_minus_one() {
|
||||
Err(Self::last().into())
|
||||
} else {
|
||||
Ok(t)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Errno {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "Errno code: {}", self)
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub trait IsZero {
|
||||
fn is_zero(&self) -> bool;
|
||||
}
|
||||
|
||||
macro_rules! impl_is_zero {
|
||||
($($t:ident)*) => ($(impl IsZero for $t {
|
||||
fn is_zero(&self) -> bool {
|
||||
*self == 0
|
||||
}
|
||||
})*)
|
||||
}
|
||||
|
||||
impl_is_zero! { i32 i64 isize }
|
||||
|
||||
#[doc(hidden)]
|
||||
pub trait IsMinusOne {
|
||||
fn is_minus_one(&self) -> bool;
|
||||
}
|
||||
|
||||
macro_rules! impl_is_minus_one {
|
||||
($($t:ident)*) => ($(impl IsMinusOne for $t {
|
||||
fn is_minus_one(&self) -> bool {
|
||||
*self == -1
|
||||
}
|
||||
})*)
|
||||
}
|
||||
|
||||
impl_is_minus_one! { i32 i64 isize }
|
||||
33
crates/wasi-common/yanix/src/fcntl.rs
Normal file
33
crates/wasi-common/yanix/src/fcntl.rs
Normal file
@@ -0,0 +1,33 @@
|
||||
use crate::{
|
||||
file::{FdFlag, OFlag},
|
||||
Errno, Result,
|
||||
};
|
||||
use std::os::unix::prelude::*;
|
||||
|
||||
pub unsafe fn dup_fd(fd: RawFd, close_on_exec: bool) -> Result<RawFd> {
|
||||
// Both fcntl commands expect a RawFd arg which will specify
|
||||
// the minimum duplicated RawFd number. In our case, I don't
|
||||
// think we have to worry about this that much, so passing in
|
||||
// the RawFd descriptor we want duplicated
|
||||
Errno::from_result(if close_on_exec {
|
||||
libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, fd)
|
||||
} else {
|
||||
libc::fcntl(fd, libc::F_DUPFD, fd)
|
||||
})
|
||||
}
|
||||
|
||||
pub unsafe fn get_fd_flags(fd: RawFd) -> Result<FdFlag> {
|
||||
Errno::from_result(libc::fcntl(fd, libc::F_GETFD)).map(FdFlag::from_bits_truncate)
|
||||
}
|
||||
|
||||
pub unsafe fn set_fd_flags(fd: RawFd, flags: FdFlag) -> Result<()> {
|
||||
Errno::from_success_code(libc::fcntl(fd, libc::F_SETFD, flags.bits()))
|
||||
}
|
||||
|
||||
pub unsafe fn get_status_flags(fd: RawFd) -> Result<OFlag> {
|
||||
Errno::from_result(libc::fcntl(fd, libc::F_GETFL)).map(OFlag::from_bits_truncate)
|
||||
}
|
||||
|
||||
pub unsafe fn set_status_flags(fd: RawFd, flags: OFlag) -> Result<()> {
|
||||
Errno::from_success_code(libc::fcntl(fd, libc::F_SETFL, flags.bits()))
|
||||
}
|
||||
198
crates/wasi-common/yanix/src/file.rs
Normal file
198
crates/wasi-common/yanix/src/file.rs
Normal file
@@ -0,0 +1,198 @@
|
||||
use crate::{Errno, Result};
|
||||
use bitflags::bitflags;
|
||||
use std::{
|
||||
convert::TryInto,
|
||||
ffi::{CString, OsStr, OsString},
|
||||
os::unix::prelude::*,
|
||||
};
|
||||
|
||||
pub use crate::sys::file::*;
|
||||
|
||||
bitflags! {
|
||||
pub struct FdFlag: libc::c_int {
|
||||
const CLOEXEC = libc::FD_CLOEXEC;
|
||||
}
|
||||
}
|
||||
|
||||
bitflags! {
|
||||
pub struct AtFlag: libc::c_int {
|
||||
const REMOVEDIR = libc::AT_REMOVEDIR;
|
||||
const SYMLINK_FOLLOW = libc::AT_SYMLINK_FOLLOW;
|
||||
const SYMLINK_NOFOLLOW = libc::AT_SYMLINK_NOFOLLOW;
|
||||
}
|
||||
}
|
||||
|
||||
bitflags! {
|
||||
pub struct Mode: libc::mode_t {
|
||||
const IRWXU = libc::S_IRWXU;
|
||||
const IRUSR = libc::S_IRUSR;
|
||||
const IWUSR = libc::S_IWUSR;
|
||||
const IXUSR = libc::S_IXUSR;
|
||||
const IRWXG = libc::S_IRWXG;
|
||||
const IRGRP = libc::S_IRGRP;
|
||||
const IWGRP = libc::S_IWGRP;
|
||||
const IXGRP = libc::S_IXGRP;
|
||||
const IRWXO = libc::S_IRWXO;
|
||||
const IROTH = libc::S_IROTH;
|
||||
const IWOTH = libc::S_IWOTH;
|
||||
const IXOTH = libc::S_IXOTH;
|
||||
const ISUID = libc::S_ISUID as libc::mode_t;
|
||||
const ISGID = libc::S_ISGID as libc::mode_t;
|
||||
const ISVTX = libc::S_ISVTX as libc::mode_t;
|
||||
}
|
||||
}
|
||||
|
||||
bitflags! {
|
||||
pub struct OFlag: libc::c_int {
|
||||
const ACCMODE = libc::O_ACCMODE;
|
||||
const APPEND = libc::O_APPEND;
|
||||
const CREAT = libc::O_CREAT;
|
||||
const DIRECTORY = libc::O_DIRECTORY;
|
||||
#[cfg(any(target_os = "android",
|
||||
target_os = "ios",
|
||||
target_os = "linux",
|
||||
target_os = "macos",
|
||||
target_os = "netbsd",
|
||||
target_os = "openbsd",
|
||||
target_os = "emscripten"))]
|
||||
const DSYNC = libc::O_DSYNC;
|
||||
const EXCL = libc::O_EXCL;
|
||||
#[cfg(any(target_os = "dragonfly",
|
||||
target_os = "freebsd",
|
||||
target_os = "ios",
|
||||
all(target_os = "linux", not(target_env = "musl")),
|
||||
target_os = "macos",
|
||||
target_os = "netbsd",
|
||||
target_os = "openbsd"))]
|
||||
const FSYNC = libc::O_FSYNC;
|
||||
const NOFOLLOW = libc::O_NOFOLLOW;
|
||||
const NONBLOCK = libc::O_NONBLOCK;
|
||||
const RDONLY = libc::O_RDONLY;
|
||||
const WRONLY = libc::O_WRONLY;
|
||||
const RDWR = libc::O_RDWR;
|
||||
#[cfg(any(target_os = "linux",
|
||||
target_os = "netbsd",
|
||||
target_os = "openbsd",
|
||||
target_os = "emscripten"))]
|
||||
const RSYNC = libc::O_RSYNC;
|
||||
const SYNC = libc::O_SYNC;
|
||||
const TRUNC = libc::O_TRUNC;
|
||||
}
|
||||
}
|
||||
|
||||
bitflags! {
|
||||
pub struct SFlag: libc::mode_t {
|
||||
const IFIFO = libc::S_IFIFO;
|
||||
const IFCHR = libc::S_IFCHR;
|
||||
const IFDIR = libc::S_IFDIR;
|
||||
const IFBLK = libc::S_IFBLK;
|
||||
const IFREG = libc::S_IFREG;
|
||||
const IFLNK = libc::S_IFLNK;
|
||||
const IFSOCK = libc::S_IFSOCK;
|
||||
const IFMT = libc::S_IFMT;
|
||||
}
|
||||
}
|
||||
|
||||
pub unsafe fn openat<P: AsRef<OsStr>>(
|
||||
dirfd: RawFd,
|
||||
path: P,
|
||||
oflag: OFlag,
|
||||
mode: Mode,
|
||||
) -> Result<RawFd> {
|
||||
let path = CString::new(path.as_ref().as_bytes())?;
|
||||
Errno::from_result(libc::openat(
|
||||
dirfd,
|
||||
path.as_ptr(),
|
||||
oflag.bits(),
|
||||
libc::c_uint::from(mode.bits()),
|
||||
))
|
||||
}
|
||||
|
||||
pub unsafe fn readlinkat<P: AsRef<OsStr>>(dirfd: RawFd, path: P) -> Result<OsString> {
|
||||
let path = CString::new(path.as_ref().as_bytes())?;
|
||||
let buffer = &mut [0u8; libc::PATH_MAX as usize + 1];
|
||||
Errno::from_result(libc::readlinkat(
|
||||
dirfd,
|
||||
path.as_ptr(),
|
||||
buffer.as_mut_ptr() as *mut _,
|
||||
buffer.len(),
|
||||
))
|
||||
.and_then(|nread| {
|
||||
let link = OsStr::from_bytes(&buffer[0..nread.try_into()?]);
|
||||
Ok(link.into())
|
||||
})
|
||||
}
|
||||
|
||||
pub unsafe fn mkdirat<P: AsRef<OsStr>>(dirfd: RawFd, path: P, mode: Mode) -> Result<()> {
|
||||
let path = CString::new(path.as_ref().as_bytes())?;
|
||||
Errno::from_success_code(libc::mkdirat(dirfd, path.as_ptr(), mode.bits()))
|
||||
}
|
||||
|
||||
pub unsafe fn linkat<P: AsRef<OsStr>>(
|
||||
old_dirfd: RawFd,
|
||||
old_path: P,
|
||||
new_dirfd: RawFd,
|
||||
new_path: P,
|
||||
flags: AtFlag,
|
||||
) -> Result<()> {
|
||||
let old_path = CString::new(old_path.as_ref().as_bytes())?;
|
||||
let new_path = CString::new(new_path.as_ref().as_bytes())?;
|
||||
Errno::from_success_code(libc::linkat(
|
||||
old_dirfd,
|
||||
old_path.as_ptr(),
|
||||
new_dirfd,
|
||||
new_path.as_ptr(),
|
||||
flags.bits(),
|
||||
))
|
||||
}
|
||||
|
||||
pub unsafe fn unlinkat<P: AsRef<OsStr>>(dirfd: RawFd, path: P, flags: AtFlag) -> Result<()> {
|
||||
let path = CString::new(path.as_ref().as_bytes())?;
|
||||
Errno::from_success_code(libc::unlinkat(dirfd, path.as_ptr(), flags.bits()))
|
||||
}
|
||||
|
||||
pub unsafe fn renameat<P: AsRef<OsStr>>(
|
||||
old_dirfd: RawFd,
|
||||
old_path: P,
|
||||
new_dirfd: RawFd,
|
||||
new_path: P,
|
||||
) -> Result<()> {
|
||||
let old_path = CString::new(old_path.as_ref().as_bytes())?;
|
||||
let new_path = CString::new(new_path.as_ref().as_bytes())?;
|
||||
Errno::from_success_code(libc::renameat(
|
||||
old_dirfd,
|
||||
old_path.as_ptr(),
|
||||
new_dirfd,
|
||||
new_path.as_ptr(),
|
||||
))
|
||||
}
|
||||
|
||||
pub unsafe fn symlinkat<P: AsRef<OsStr>>(old_path: P, new_dirfd: RawFd, new_path: P) -> Result<()> {
|
||||
let old_path = CString::new(old_path.as_ref().as_bytes())?;
|
||||
let new_path = CString::new(new_path.as_ref().as_bytes())?;
|
||||
Errno::from_success_code(libc::symlinkat(
|
||||
old_path.as_ptr(),
|
||||
new_dirfd,
|
||||
new_path.as_ptr(),
|
||||
))
|
||||
}
|
||||
|
||||
pub unsafe fn fstatat<P: AsRef<OsStr>>(dirfd: RawFd, path: P, flags: AtFlag) -> Result<libc::stat> {
|
||||
use std::mem::MaybeUninit;
|
||||
let path = CString::new(path.as_ref().as_bytes())?;
|
||||
let mut filestat = MaybeUninit::<libc::stat>::uninit();
|
||||
Errno::from_result(libc::fstatat(
|
||||
dirfd,
|
||||
path.as_ptr(),
|
||||
filestat.as_mut_ptr(),
|
||||
flags.bits(),
|
||||
))?;
|
||||
Ok(filestat.assume_init())
|
||||
}
|
||||
|
||||
/// `fionread()` function, equivalent to `ioctl(fd, FIONREAD, *bytes)`.
|
||||
pub unsafe fn fionread(fd: RawFd) -> Result<usize> {
|
||||
let mut nread: libc::c_int = 0;
|
||||
Errno::from_result(libc::ioctl(fd, libc::FIONREAD, &mut nread as *mut _))?;
|
||||
Ok(nread.try_into()?)
|
||||
}
|
||||
40
crates/wasi-common/yanix/src/lib.rs
Normal file
40
crates/wasi-common/yanix/src/lib.rs
Normal file
@@ -0,0 +1,40 @@
|
||||
//! `yanix` stands for Yet Another Nix crate, and, well, it is simply
|
||||
//! a yet another crate in the spirit of the [nix] crate. As such,
|
||||
//! this crate is inspired by the original `nix` crate, however,
|
||||
//! it takes a different approach, using lower-level interfaces with
|
||||
//! less abstraction, so that it fits better with its main use case
|
||||
//! which is our WASI implementation, [wasi-common].
|
||||
//!
|
||||
//! [nix]: https://github.com/nix-rust/nix
|
||||
//! [wasi-common]: https://github.com/bytecodealliance/wasmtime/tree/master/crates/wasi-common
|
||||
#![cfg(unix)]
|
||||
|
||||
pub mod clock;
|
||||
pub mod dir;
|
||||
pub mod fcntl;
|
||||
pub mod file;
|
||||
pub mod poll;
|
||||
pub mod socket;
|
||||
|
||||
mod errno;
|
||||
mod sys;
|
||||
|
||||
pub mod fadvise {
|
||||
pub use super::sys::fadvise::*;
|
||||
}
|
||||
|
||||
pub use errno::Errno;
|
||||
use std::{ffi, num};
|
||||
use thiserror::Error;
|
||||
|
||||
pub type Result<T> = std::result::Result<T, YanixError>;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum YanixError {
|
||||
#[error("raw os error {0}")]
|
||||
Errno(#[from] Errno),
|
||||
#[error("a nul byte was not found in the expected position")]
|
||||
NulError(#[from] ffi::NulError),
|
||||
#[error("integral type conversion failed")]
|
||||
TryFromIntError(#[from] num::TryFromIntError),
|
||||
}
|
||||
47
crates/wasi-common/yanix/src/poll.rs
Normal file
47
crates/wasi-common/yanix/src/poll.rs
Normal file
@@ -0,0 +1,47 @@
|
||||
use crate::{Errno, Result};
|
||||
use bitflags::bitflags;
|
||||
use std::{convert::TryInto, os::unix::prelude::*};
|
||||
|
||||
bitflags! {
|
||||
pub struct PollFlags: libc::c_short {
|
||||
const POLLIN = libc::POLLIN;
|
||||
const POLLPRI = libc::POLLPRI;
|
||||
const POLLOUT = libc::POLLOUT;
|
||||
const POLLRDNORM = libc::POLLRDNORM;
|
||||
const POLLWRNORM = libc::POLLWRNORM;
|
||||
const POLLRDBAND = libc::POLLRDBAND;
|
||||
const POLLWRBAND = libc::POLLWRBAND;
|
||||
const POLLERR = libc::POLLERR;
|
||||
const POLLHUP = libc::POLLHUP;
|
||||
const POLLNVAL = libc::POLLNVAL;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||
#[repr(C)]
|
||||
pub struct PollFd(libc::pollfd);
|
||||
|
||||
impl PollFd {
|
||||
pub unsafe fn new(fd: RawFd, events: PollFlags) -> Self {
|
||||
Self(libc::pollfd {
|
||||
fd,
|
||||
events: events.bits(),
|
||||
revents: PollFlags::empty().bits(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn revents(self) -> Option<PollFlags> {
|
||||
PollFlags::from_bits(self.0.revents)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn poll(fds: &mut [PollFd], timeout: i32) -> Result<usize> {
|
||||
Errno::from_result(unsafe {
|
||||
libc::poll(
|
||||
fds.as_mut_ptr() as *mut libc::pollfd,
|
||||
fds.len() as libc::nfds_t,
|
||||
timeout,
|
||||
)
|
||||
})
|
||||
.and_then(|nready| nready.try_into().map_err(Into::into))
|
||||
}
|
||||
31
crates/wasi-common/yanix/src/socket.rs
Normal file
31
crates/wasi-common/yanix/src/socket.rs
Normal file
@@ -0,0 +1,31 @@
|
||||
use crate::{Errno, Result};
|
||||
use std::os::unix::prelude::*;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
#[repr(i32)]
|
||||
pub enum SockType {
|
||||
Stream = libc::SOCK_STREAM,
|
||||
Datagram = libc::SOCK_DGRAM,
|
||||
SeqPacket = libc::SOCK_SEQPACKET,
|
||||
Raw = libc::SOCK_RAW,
|
||||
Rdm = libc::SOCK_RDM,
|
||||
}
|
||||
|
||||
pub unsafe fn get_socket_type(fd: RawFd) -> Result<SockType> {
|
||||
use std::mem::{self, MaybeUninit};
|
||||
let mut buffer = MaybeUninit::<SockType>::zeroed().assume_init();
|
||||
let mut out_len = mem::size_of::<SockType>() as libc::socklen_t;
|
||||
Errno::from_success_code(libc::getsockopt(
|
||||
fd,
|
||||
libc::SOL_SOCKET,
|
||||
libc::SO_TYPE,
|
||||
&mut buffer as *mut SockType as *mut _,
|
||||
&mut out_len,
|
||||
))?;
|
||||
assert_eq!(
|
||||
out_len as usize,
|
||||
mem::size_of::<SockType>(),
|
||||
"invalid SockType value"
|
||||
);
|
||||
Ok(buffer)
|
||||
}
|
||||
52
crates/wasi-common/yanix/src/sys/bsd/dir.rs
Normal file
52
crates/wasi-common/yanix/src/sys/bsd/dir.rs
Normal file
@@ -0,0 +1,52 @@
|
||||
use crate::{
|
||||
dir::{Dir, Entry, EntryExt, SeekLoc},
|
||||
Errno, Result,
|
||||
};
|
||||
use std::ops::Deref;
|
||||
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub(crate) struct EntryImpl {
|
||||
dirent: libc::dirent,
|
||||
loc: SeekLoc,
|
||||
}
|
||||
|
||||
impl Deref for EntryImpl {
|
||||
type Target = libc::dirent;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.dirent
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) unsafe fn iter_impl(dir: &Dir) -> Option<Result<EntryImpl>> {
|
||||
let errno = Errno::last();
|
||||
let dirent = libc::readdir(dir.0.as_ptr());
|
||||
if dirent.is_null() {
|
||||
if errno != Errno::last() {
|
||||
// TODO This should be verified on different BSD-flavours.
|
||||
//
|
||||
// According to 4.3BSD/POSIX.1-2001 man pages, there was an error
|
||||
// if the errno value has changed at some point during the sequence
|
||||
// of readdir calls.
|
||||
Some(Err(Errno::last().into()))
|
||||
} else {
|
||||
// Not an error. We've simply reached the end of the stream.
|
||||
None
|
||||
}
|
||||
} else {
|
||||
Some(Ok(EntryImpl {
|
||||
dirent: *dirent,
|
||||
loc: dir.tell(),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl EntryExt for Entry {
|
||||
fn ino(&self) -> u64 {
|
||||
self.0.d_ino.into()
|
||||
}
|
||||
|
||||
fn seek_loc(&self) -> SeekLoc {
|
||||
self.0.loc
|
||||
}
|
||||
}
|
||||
51
crates/wasi-common/yanix/src/sys/bsd/fadvise.rs
Normal file
51
crates/wasi-common/yanix/src/sys/bsd/fadvise.rs
Normal file
@@ -0,0 +1,51 @@
|
||||
use crate::{Errno, Result};
|
||||
use std::{convert::TryInto, os::unix::prelude::*};
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
#[repr(i32)]
|
||||
pub enum PosixFadviseAdvice {
|
||||
Normal,
|
||||
Sequential,
|
||||
Random,
|
||||
NoReuse,
|
||||
WillNeed,
|
||||
DontNeed,
|
||||
}
|
||||
|
||||
// There's no posix_fadvise on macOS but we can use fcntl with F_RDADVISE
|
||||
// command instead to achieve the same
|
||||
#[cfg(any(target_os = "macos", target_os = "ios"))]
|
||||
pub unsafe fn posix_fadvise(
|
||||
fd: RawFd,
|
||||
offset: libc::off_t,
|
||||
len: libc::off_t,
|
||||
_advice: PosixFadviseAdvice,
|
||||
) -> Result<()> {
|
||||
// From macOS man pages:
|
||||
// F_RDADVISE Issue an advisory read async with no copy to user.
|
||||
//
|
||||
// The F_RDADVISE command operates on the following structure which holds information passed from
|
||||
// the user to the system:
|
||||
//
|
||||
// struct radvisory {
|
||||
// off_t ra_offset; /* offset into the file */
|
||||
// int ra_count; /* size of the read */
|
||||
// };
|
||||
let advisory = libc::radvisory {
|
||||
ra_offset: offset,
|
||||
ra_count: len.try_into()?,
|
||||
};
|
||||
Errno::from_success_code(libc::fcntl(fd, libc::F_RDADVISE, &advisory))
|
||||
}
|
||||
|
||||
// TODO
|
||||
// On non-macOS BSD's we leave it as no-op for now
|
||||
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
|
||||
pub unsafe fn posix_fadvise(
|
||||
_fd: RawFd,
|
||||
_offset: libc::off_t,
|
||||
_len: libc::off_t,
|
||||
_advice: PosixFadviseAdvice,
|
||||
) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
18
crates/wasi-common/yanix/src/sys/bsd/file.rs
Normal file
18
crates/wasi-common/yanix/src/sys/bsd/file.rs
Normal file
@@ -0,0 +1,18 @@
|
||||
use crate::{Errno, Result};
|
||||
use std::os::unix::prelude::*;
|
||||
|
||||
pub unsafe fn isatty(fd: RawFd) -> Result<bool> {
|
||||
let res = libc::isatty(fd);
|
||||
if res == 1 {
|
||||
// isatty() returns 1 if fd is an open file descriptor referring to a terminal...
|
||||
Ok(true)
|
||||
} else {
|
||||
// ... otherwise 0 is returned, and errno is set to indicate the error.
|
||||
let errno = Errno::last();
|
||||
if errno == Errno::ENOTTY {
|
||||
Ok(false)
|
||||
} else {
|
||||
Err(errno.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
3
crates/wasi-common/yanix/src/sys/bsd/mod.rs
Normal file
3
crates/wasi-common/yanix/src/sys/bsd/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
pub(crate) mod dir;
|
||||
pub(crate) mod fadvise;
|
||||
pub(crate) mod file;
|
||||
46
crates/wasi-common/yanix/src/sys/linux/dir.rs
Normal file
46
crates/wasi-common/yanix/src/sys/linux/dir.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
use crate::{
|
||||
dir::{Dir, Entry, EntryExt, SeekLoc},
|
||||
Errno, Result,
|
||||
};
|
||||
use std::ops::Deref;
|
||||
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub(crate) struct EntryImpl(libc::dirent64);
|
||||
|
||||
impl Deref for EntryImpl {
|
||||
type Target = libc::dirent64;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl EntryExt for Entry {
|
||||
fn ino(&self) -> u64 {
|
||||
self.0.d_ino.into()
|
||||
}
|
||||
|
||||
fn seek_loc(&self) -> SeekLoc {
|
||||
unsafe { SeekLoc::from_raw(self.0.d_off) }
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) unsafe fn iter_impl(dir: &Dir) -> Option<Result<EntryImpl>> {
|
||||
let errno = Errno::last();
|
||||
let dirent = libc::readdir64(dir.0.as_ptr());
|
||||
if dirent.is_null() {
|
||||
if errno != Errno::last() {
|
||||
// TODO This should be verified on different BSD-flavours.
|
||||
//
|
||||
// According to 4.3BSD/POSIX.1-2001 man pages, there was an error
|
||||
// if the errno value has changed at some point during the sequence
|
||||
// of readdir calls.
|
||||
Some(Err(Errno::last().into()))
|
||||
} else {
|
||||
// Not an error. We've simply reached the end of the stream.
|
||||
None
|
||||
}
|
||||
} else {
|
||||
Some(Ok(EntryImpl(*dirent)))
|
||||
}
|
||||
}
|
||||
22
crates/wasi-common/yanix/src/sys/linux/fadvise.rs
Normal file
22
crates/wasi-common/yanix/src/sys/linux/fadvise.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
use crate::{Errno, Result};
|
||||
use std::os::unix::prelude::*;
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
#[repr(i32)]
|
||||
pub enum PosixFadviseAdvice {
|
||||
Normal = libc::POSIX_FADV_NORMAL,
|
||||
Sequential = libc::POSIX_FADV_SEQUENTIAL,
|
||||
Random = libc::POSIX_FADV_RANDOM,
|
||||
NoReuse = libc::POSIX_FADV_NOREUSE,
|
||||
WillNeed = libc::POSIX_FADV_WILLNEED,
|
||||
DontNeed = libc::POSIX_FADV_DONTNEED,
|
||||
}
|
||||
|
||||
pub unsafe fn posix_fadvise(
|
||||
fd: RawFd,
|
||||
offset: libc::off_t,
|
||||
len: libc::off_t,
|
||||
advice: PosixFadviseAdvice,
|
||||
) -> Result<()> {
|
||||
Errno::from_success_code(libc::posix_fadvise(fd, offset, len, advice as libc::c_int))
|
||||
}
|
||||
23
crates/wasi-common/yanix/src/sys/linux/file.rs
Normal file
23
crates/wasi-common/yanix/src/sys/linux/file.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
use crate::{Errno, Result};
|
||||
use std::os::unix::prelude::*;
|
||||
|
||||
pub unsafe fn isatty(fd: RawFd) -> Result<bool> {
|
||||
let res = libc::isatty(fd);
|
||||
if res == 1 {
|
||||
// isatty() returns 1 if fd is an open file descriptor referring to a terminal...
|
||||
Ok(true)
|
||||
} else {
|
||||
// ... otherwise 0 is returned, and errno is set to indicate the error.
|
||||
let errno = Errno::last();
|
||||
// While POSIX specifies ENOTTY if the passed
|
||||
// fd is *not* a tty, on Linux, some implementations
|
||||
// may return EINVAL instead.
|
||||
//
|
||||
// https://linux.die.net/man/3/isatty
|
||||
if errno == Errno::ENOTTY || errno == Errno::EINVAL {
|
||||
Ok(false)
|
||||
} else {
|
||||
Err(errno.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
3
crates/wasi-common/yanix/src/sys/linux/mod.rs
Normal file
3
crates/wasi-common/yanix/src/sys/linux/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
pub(crate) mod dir;
|
||||
pub(crate) mod fadvise;
|
||||
pub(crate) mod file;
|
||||
27
crates/wasi-common/yanix/src/sys/mod.rs
Normal file
27
crates/wasi-common/yanix/src/sys/mod.rs
Normal file
@@ -0,0 +1,27 @@
|
||||
use crate::dir::SeekLoc;
|
||||
use cfg_if::cfg_if;
|
||||
|
||||
cfg_if! {
|
||||
if #[cfg(any(target_os = "linux",
|
||||
target_os = "android",
|
||||
target_os = "emscripten"))] {
|
||||
mod linux;
|
||||
pub(crate) use self::linux::*;
|
||||
}
|
||||
else if #[cfg(any(target_os = "macos",
|
||||
target_os = "ios",
|
||||
target_os = "freebsd",
|
||||
target_os = "netbsd",
|
||||
target_os = "openbsd",
|
||||
target_os = "dragonfly"))] {
|
||||
mod bsd;
|
||||
pub(crate) use self::bsd::*;
|
||||
} else {
|
||||
compile_error!("yanix doesn't compile for this platform yet");
|
||||
}
|
||||
}
|
||||
|
||||
pub trait EntryExt {
|
||||
fn ino(&self) -> u64;
|
||||
fn seek_loc(&self) -> SeekLoc;
|
||||
}
|
||||
Reference in New Issue
Block a user