summaryrefslogtreecommitdiff
path: root/src/libstd/sys/wasi
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2020-07-27 17:39:01 +0000
committerbors <bors@rust-lang.org>2020-07-27 17:39:01 +0000
commit54e000891ffccd4cbfb92146b92736c83085df63 (patch)
tree1200bb13eb9ae22def4c43bc657bc56da8faedc6 /src/libstd/sys/wasi
parent4a90e36c85336d1d4b209556c1a9733210bbff19 (diff)
parent6d9705220fec4553d693a7c19d99496e14c89edf (diff)
downloadrust-tmp-nightly.tar.gz
Auto merge of #73265 - mark-i-m:mv-std, r=<try>tmp-nightly
mv std libs to library/ This is the first step in refactoring the directory layout of this repository, with further followup steps planned (but not done yet). Background: currently, all crates are under src/, without nested src directories and with the unconventional `lib*` prefixes (e.g., `src/libcore/lib.rs`). This directory structures is not idiomatic and makes the `src/` directory rather overwhelming. To improve contributor experience and make things a bit more approachable, we are reorganizing the repo a bit. In this PR, we move the standard libs (basically anything that is "runtime", as opposed to part of the compiler, build system, or one of the tools, etc). The new layout moves these libraries to a new `library/` directory in the root of the repo. Additionally, we remove the `lib*` prefixes and add nested `src/` directories. The other crates/tools in this repo are not touched. So in summary: ``` library/<crate>/src/*.rs src/<all the rest> // unchanged ``` where `<crate>` is: - core - alloc - std - test - proc_macro - panic_abort - panic_unwind - profiler_builtins - term - unwind - rtstartup - backtrace - rustc-std-workspace-* There was a lot of discussion about this and a few rounds of compiler team approvals, FCPs, MCPs, and nominations. The original MCP is https://github.com/rust-lang/compiler-team/issues/298. The final approval of the compiler team was given here: https://github.com/rust-lang/rust/pull/73265#issuecomment-659498446. The name `library` was chosen to complement a later move of the compiler crates to a `compiler/` directory. There was a lot of discussion around adding the nested `src/` directories. Note that this does increase the nesting depth (plausibly important for manual traversal of the tree, e.g., through GitHub's UI or `cd`), but this is deemed to be better as it fits the standard layout of Rust crates throughout most of the ecosystem, though there is some debate about how much this should apply to multi-crate projects. Overall, there seem to be more people in favor of nested `src/` than against. After this PR, there are no dependencies out of the `library/` directory except on the `build_helper` (or crates.io crates).
Diffstat (limited to 'src/libstd/sys/wasi')
-rw-r--r--src/libstd/sys/wasi/alloc.rs42
-rw-r--r--src/libstd/sys/wasi/args.rs65
-rw-r--r--src/libstd/sys/wasi/env.rs9
-rw-r--r--src/libstd/sys/wasi/ext/ffi.rs6
-rw-r--r--src/libstd/sys/wasi/ext/fs.rs538
-rw-r--r--src/libstd/sys/wasi/ext/io.rs142
-rw-r--r--src/libstd/sys/wasi/ext/mod.rs22
-rw-r--r--src/libstd/sys/wasi/fd.rs228
-rw-r--r--src/libstd/sys/wasi/fs.rs667
-rw-r--r--src/libstd/sys/wasi/io.rs71
-rw-r--r--src/libstd/sys/wasi/mod.rs96
-rw-r--r--src/libstd/sys/wasi/net.rs411
-rw-r--r--src/libstd/sys/wasi/os.rs201
-rw-r--r--src/libstd/sys/wasi/path.rs19
-rw-r--r--src/libstd/sys/wasi/pipe.rs38
-rw-r--r--src/libstd/sys/wasi/process.rs149
-rw-r--r--src/libstd/sys/wasi/stdio.rs102
-rw-r--r--src/libstd/sys/wasi/thread.rs72
-rw-r--r--src/libstd/sys/wasi/time.rs67
19 files changed, 0 insertions, 2945 deletions
diff --git a/src/libstd/sys/wasi/alloc.rs b/src/libstd/sys/wasi/alloc.rs
deleted file mode 100644
index 57187851a14..00000000000
--- a/src/libstd/sys/wasi/alloc.rs
+++ /dev/null
@@ -1,42 +0,0 @@
-use crate::alloc::{GlobalAlloc, Layout, System};
-use crate::ptr;
-use crate::sys_common::alloc::{realloc_fallback, MIN_ALIGN};
-
-#[stable(feature = "alloc_system_type", since = "1.28.0")]
-unsafe impl GlobalAlloc for System {
- #[inline]
- unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
- if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() {
- libc::malloc(layout.size()) as *mut u8
- } else {
- libc::aligned_alloc(layout.align(), layout.size()) as *mut u8
- }
- }
-
- #[inline]
- unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
- if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() {
- libc::calloc(layout.size(), 1) as *mut u8
- } else {
- let ptr = self.alloc(layout.clone());
- if !ptr.is_null() {
- ptr::write_bytes(ptr, 0, layout.size());
- }
- ptr
- }
- }
-
- #[inline]
- unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
- libc::free(ptr as *mut libc::c_void)
- }
-
- #[inline]
- unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
- if layout.align() <= MIN_ALIGN && layout.align() <= new_size {
- libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8
- } else {
- realloc_fallback(self, ptr, layout, new_size)
- }
- }
-}
diff --git a/src/libstd/sys/wasi/args.rs b/src/libstd/sys/wasi/args.rs
deleted file mode 100644
index 02aa68d6f3a..00000000000
--- a/src/libstd/sys/wasi/args.rs
+++ /dev/null
@@ -1,65 +0,0 @@
-use crate::ffi::{CStr, OsStr, OsString};
-use crate::marker::PhantomData;
-use crate::os::wasi::ffi::OsStrExt;
-use crate::vec;
-
-pub unsafe fn init(_argc: isize, _argv: *const *const u8) {}
-
-pub unsafe fn cleanup() {}
-
-pub struct Args {
- iter: vec::IntoIter<OsString>,
- _dont_send_or_sync_me: PhantomData<*mut ()>,
-}
-
-/// Returns the command line arguments
-pub fn args() -> Args {
- Args {
- iter: maybe_args().unwrap_or(Vec::new()).into_iter(),
- _dont_send_or_sync_me: PhantomData,
- }
-}
-
-fn maybe_args() -> Option<Vec<OsString>> {
- unsafe {
- let (argc, buf_size) = wasi::args_sizes_get().ok()?;
- let mut argv = Vec::with_capacity(argc);
- let mut buf = Vec::with_capacity(buf_size);
- wasi::args_get(argv.as_mut_ptr(), buf.as_mut_ptr()).ok()?;
- argv.set_len(argc);
- let mut ret = Vec::with_capacity(argc);
- for ptr in argv {
- let s = CStr::from_ptr(ptr.cast());
- ret.push(OsStr::from_bytes(s.to_bytes()).to_owned());
- }
- Some(ret)
- }
-}
-
-impl Args {
- pub fn inner_debug(&self) -> &[OsString] {
- self.iter.as_slice()
- }
-}
-
-impl Iterator for Args {
- type Item = OsString;
- fn next(&mut self) -> Option<OsString> {
- self.iter.next()
- }
- fn size_hint(&self) -> (usize, Option<usize>) {
- self.iter.size_hint()
- }
-}
-
-impl ExactSizeIterator for Args {
- fn len(&self) -> usize {
- self.iter.len()
- }
-}
-
-impl DoubleEndedIterator for Args {
- fn next_back(&mut self) -> Option<OsString> {
- self.iter.next_back()
- }
-}
diff --git a/src/libstd/sys/wasi/env.rs b/src/libstd/sys/wasi/env.rs
deleted file mode 100644
index 730e356d7fe..00000000000
--- a/src/libstd/sys/wasi/env.rs
+++ /dev/null
@@ -1,9 +0,0 @@
-pub mod os {
- pub const FAMILY: &str = "";
- pub const OS: &str = "";
- pub const DLL_PREFIX: &str = "";
- pub const DLL_SUFFIX: &str = ".wasm";
- pub const DLL_EXTENSION: &str = "wasm";
- pub const EXE_SUFFIX: &str = ".wasm";
- pub const EXE_EXTENSION: &str = "wasm";
-}
diff --git a/src/libstd/sys/wasi/ext/ffi.rs b/src/libstd/sys/wasi/ext/ffi.rs
deleted file mode 100644
index f71f316d1ba..00000000000
--- a/src/libstd/sys/wasi/ext/ffi.rs
+++ /dev/null
@@ -1,6 +0,0 @@
-//! WASI-specific extension to the primitives in the `std::ffi` module
-
-#![stable(feature = "rust1", since = "1.0.0")]
-
-#[stable(feature = "rust1", since = "1.0.0")]
-pub use crate::sys_common::os_str_bytes::*;
diff --git a/src/libstd/sys/wasi/ext/fs.rs b/src/libstd/sys/wasi/ext/fs.rs
deleted file mode 100644
index f41c6626ccf..00000000000
--- a/src/libstd/sys/wasi/ext/fs.rs
+++ /dev/null
@@ -1,538 +0,0 @@
-//! WASI-specific extensions to primitives in the `std::fs` module.
-
-#![unstable(feature = "wasi_ext", issue = "none")]
-
-use crate::fs::{self, File, Metadata, OpenOptions};
-use crate::io::{self, IoSlice, IoSliceMut};
-use crate::path::{Path, PathBuf};
-use crate::sys::fs::osstr2str;
-use crate::sys_common::{AsInner, AsInnerMut, FromInner};
-
-/// WASI-specific extensions to [`File`].
-///
-/// [`File`]: ../../../../std/fs/struct.File.html
-pub trait FileExt {
- /// Reads a number of bytes starting from a given offset.
- ///
- /// Returns the number of bytes read.
- ///
- /// The offset is relative to the start of the file and thus independent
- /// from the current cursor.
- ///
- /// The current file cursor is not affected by this function.
- ///
- /// Note that similar to [`File::read`], it is not an error to return with a
- /// short read.
- ///
- /// [`File::read`]: ../../../../std/fs/struct.File.html#method.read
- fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
- let bufs = &mut [IoSliceMut::new(buf)];
- self.read_vectored_at(bufs, offset)
- }
-
- /// Reads a number of bytes starting from a given offset.
- ///
- /// Returns the number of bytes read.
- ///
- /// The offset is relative to the start of the file and thus independent
- /// from the current cursor.
- ///
- /// The current file cursor is not affected by this function.
- ///
- /// Note that similar to [`File::read_vectored`], it is not an error to
- /// return with a short read.
- ///
- /// [`File::read`]: ../../../../std/fs/struct.File.html#method.read_vectored
- fn read_vectored_at(&self, bufs: &mut [IoSliceMut<'_>], offset: u64) -> io::Result<usize>;
-
- /// Reads the exact number of byte required to fill `buf` from the given offset.
- ///
- /// The offset is relative to the start of the file and thus independent
- /// from the current cursor.
- ///
- /// The current file cursor is not affected by this function.
- ///
- /// Similar to [`Read::read_exact`] but uses [`read_at`] instead of `read`.
- ///
- /// [`Read::read_exact`]: ../../../../std/io/trait.Read.html#method.read_exact
- /// [`read_at`]: #tymethod.read_at
- ///
- /// # Errors
- ///
- /// If this function encounters an error of the kind
- /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
- /// will continue.
- ///
- /// If this function encounters an "end of file" before completely filling
- /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
- /// The contents of `buf` are unspecified in this case.
- ///
- /// If any other read error is encountered then this function immediately
- /// returns. The contents of `buf` are unspecified in this case.
- ///
- /// If this function returns an error, it is unspecified how many bytes it
- /// has read, but it will never read more than would be necessary to
- /// completely fill the buffer.
- ///
- /// [`ErrorKind::Interrupted`]: ../../../../std/io/enum.ErrorKind.html#variant.Interrupted
- /// [`ErrorKind::UnexpectedEof`]: ../../../../std/io/enum.ErrorKind.html#variant.UnexpectedEof
- #[stable(feature = "rw_exact_all_at", since = "1.33.0")]
- fn read_exact_at(&self, mut buf: &mut [u8], mut offset: u64) -> io::Result<()> {
- while !buf.is_empty() {
- match self.read_at(buf, offset) {
- Ok(0) => break,
- Ok(n) => {
- let tmp = buf;
- buf = &mut tmp[n..];
- offset += n as u64;
- }
- Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
- Err(e) => return Err(e),
- }
- }
- if !buf.is_empty() {
- Err(io::Error::new(io::ErrorKind::UnexpectedEof, "failed to fill whole buffer"))
- } else {
- Ok(())
- }
- }
-
- /// Writes a number of bytes starting from a given offset.
- ///
- /// Returns the number of bytes written.
- ///
- /// The offset is relative to the start of the file and thus independent
- /// from the current cursor.
- ///
- /// The current file cursor is not affected by this function.
- ///
- /// When writing beyond the end of the file, the file is appropriately
- /// extended and the intermediate bytes are initialized with the value 0.
- ///
- /// Note that similar to [`File::write`], it is not an error to return a
- /// short write.
- ///
- /// [`File::write`]: ../../../../std/fs/struct.File.html#write.v
- fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
- let bufs = &[IoSlice::new(buf)];
- self.write_vectored_at(bufs, offset)
- }
-
- /// Writes a number of bytes starting from a given offset.
- ///
- /// Returns the number of bytes written.
- ///
- /// The offset is relative to the start of the file and thus independent
- /// from the current cursor.
- ///
- /// The current file cursor is not affected by this function.
- ///
- /// When writing beyond the end of the file, the file is appropriately
- /// extended and the intermediate bytes are initialized with the value 0.
- ///
- /// Note that similar to [`File::write_vectored`], it is not an error to return a
- /// short write.
- ///
- /// [`File::write`]: ../../../../std/fs/struct.File.html#method.write_vectored
- fn write_vectored_at(&self, bufs: &[IoSlice<'_>], offset: u64) -> io::Result<usize>;
-
- /// Attempts to write an entire buffer starting from a given offset.
- ///
- /// The offset is relative to the start of the file and thus independent
- /// from the current cursor.
- ///
- /// The current file cursor is not affected by this function.
- ///
- /// This method will continuously call [`write_at`] until there is no more data
- /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
- /// returned. This method will not return until the entire buffer has been
- /// successfully written or such an error occurs. The first error that is
- /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
- /// returned.
- ///
- /// # Errors
- ///
- /// This function will return the first error of
- /// non-[`ErrorKind::Interrupted`] kind that [`write_at`] returns.
- ///
- /// [`ErrorKind::Interrupted`]: ../../../../std/io/enum.ErrorKind.html#variant.Interrupted
- /// [`write_at`]: #tymethod.write_at
- #[stable(feature = "rw_exact_all_at", since = "1.33.0")]
- fn write_all_at(&self, mut buf: &[u8], mut offset: u64) -> io::Result<()> {
- while !buf.is_empty() {
- match self.write_at(buf, offset) {
- Ok(0) => {
- return Err(io::Error::new(
- io::ErrorKind::WriteZero,
- "failed to write whole buffer",
- ));
- }
- Ok(n) => {
- buf = &buf[n..];
- offset += n as u64
- }
- Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
- Err(e) => return Err(e),
- }
- }
- Ok(())
- }
-
- /// Returns the current position within the file.
- ///
- /// This corresponds to the `fd_tell` syscall and is similar to
- /// `seek` where you offset 0 bytes from the current position.
- fn tell(&self) -> io::Result<u64>;
-
- /// Adjust the flags associated with this file.
- ///
- /// This corresponds to the `fd_fdstat_set_flags` syscall.
- fn fdstat_set_flags(&self, flags: u16) -> io::Result<()>;
-
- /// Adjust the rights associated with this file.
- ///
- /// This corresponds to the `fd_fdstat_set_rights` syscall.
- fn fdstat_set_rights(&self, rights: u64, inheriting: u64) -> io::Result<()>;
-
- /// Provide file advisory information on a file descriptor.
- ///
- /// This corresponds to the `fd_advise` syscall.
- fn advise(&self, offset: u64, len: u64, advice: u8) -> io::Result<()>;
-
- /// Force the allocation of space in a file.
- ///
- /// This corresponds to the `fd_allocate` syscall.
- fn allocate(&self, offset: u64, len: u64) -> io::Result<()>;
-
- /// Create a directory.
- ///
- /// This corresponds to the `path_create_directory` syscall.
- fn create_directory<P: AsRef<Path>>(&self, dir: P) -> io::Result<()>;
-
- /// Read the contents of a symbolic link.
- ///
- /// This corresponds to the `path_readlink` syscall.
- fn read_link<P: AsRef<Path>>(&self, path: P) -> io::Result<PathBuf>;
-
- /// Return the attributes of a file or directory.
- ///
- /// This corresponds to the `path_filestat_get` syscall.
- fn metadata_at<P: AsRef<Path>>(&self, lookup_flags: u32, path: P) -> io::Result<Metadata>;
-
- /// Unlink a file.
- ///
- /// This corresponds to the `path_unlink_file` syscall.
- fn remove_file<P: AsRef<Path>>(&self, path: P) -> io::Result<()>;
-
- /// Remove a directory.
- ///
- /// This corresponds to the `path_remove_directory` syscall.
- fn remove_directory<P: AsRef<Path>>(&self, path: P) -> io::Result<()>;
-}
-
-// FIXME: bind fd_fdstat_get - need to define a custom return type
-// FIXME: bind fd_readdir - can't return `ReadDir` since we only have entry name
-// FIXME: bind fd_filestat_set_times maybe? - on crates.io for unix
-// FIXME: bind path_filestat_set_times maybe? - on crates.io for unix
-// FIXME: bind poll_oneoff maybe? - probably should wait for I/O to settle
-// FIXME: bind random_get maybe? - on crates.io for unix
-
-impl FileExt for fs::File {
- fn read_vectored_at(&self, bufs: &mut [IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
- self.as_inner().fd().pread(bufs, offset)
- }
-
- fn write_vectored_at(&self, bufs: &[IoSlice<'_>], offset: u64) -> io::Result<usize> {
- self.as_inner().fd().pwrite(bufs, offset)
- }
-
- fn tell(&self) -> io::Result<u64> {
- self.as_inner().fd().tell()
- }
-
- fn fdstat_set_flags(&self, flags: u16) -> io::Result<()> {
- self.as_inner().fd().set_flags(flags)
- }
-
- fn fdstat_set_rights(&self, rights: u64, inheriting: u64) -> io::Result<()> {
- self.as_inner().fd().set_rights(rights, inheriting)
- }
-
- fn advise(&self, offset: u64, len: u64, advice: u8) -> io::Result<()> {
- self.as_inner().fd().advise(offset, len, advice)
- }
-
- fn allocate(&self, offset: u64, len: u64) -> io::Result<()> {
- self.as_inner().fd().allocate(offset, len)
- }
-
- fn create_directory<P: AsRef<Path>>(&self, dir: P) -> io::Result<()> {
- self.as_inner().fd().create_directory(osstr2str(dir.as_ref().as_ref())?)
- }
-
- fn read_link<P: AsRef<Path>>(&self, path: P) -> io::Result<PathBuf> {
- self.as_inner().read_link(path.as_ref())
- }
-
- fn metadata_at<P: AsRef<Path>>(&self, lookup_flags: u32, path: P) -> io::Result<Metadata> {
- let m = self.as_inner().metadata_at(lookup_flags, path.as_ref())?;
- Ok(FromInner::from_inner(m))
- }
-
- fn remove_file<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
- self.as_inner().fd().unlink_file(osstr2str(path.as_ref().as_ref())?)
- }
-
- fn remove_directory<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
- self.as_inner().fd().remove_directory(osstr2str(path.as_ref().as_ref())?)
- }
-}
-
-/// WASI-specific extensions to [`fs::OpenOptions`].
-///
-/// [`fs::OpenOptions`]: ../../../../std/fs/struct.OpenOptions.html
-pub trait OpenOptionsExt {
- /// Pass custom `dirflags` argument to `path_open`.
- ///
- /// This option configures the `dirflags` argument to the
- /// `path_open` syscall which `OpenOptions` will eventually call. The
- /// `dirflags` argument configures how the file is looked up, currently
- /// primarily affecting whether symlinks are followed or not.
- ///
- /// By default this value is `__WASI_LOOKUP_SYMLINK_FOLLOW`, or symlinks are
- /// followed. You can call this method with 0 to disable following symlinks
- fn lookup_flags(&mut self, flags: u32) -> &mut Self;
-
- /// Indicates whether `OpenOptions` must open a directory or not.
- ///
- /// This method will configure whether the `__WASI_O_DIRECTORY` flag is
- /// passed when opening a file. When passed it will require that the opened
- /// path is a directory.
- ///
- /// This option is by default `false`
- fn directory(&mut self, dir: bool) -> &mut Self;
-
- /// Indicates whether `__WASI_FDFLAG_DSYNC` is passed in the `fs_flags`
- /// field of `path_open`.
- ///
- /// This option is by default `false`
- fn dsync(&mut self, dsync: bool) -> &mut Self;
-
- /// Indicates whether `__WASI_FDFLAG_NONBLOCK` is passed in the `fs_flags`
- /// field of `path_open`.
- ///
- /// This option is by default `false`
- fn nonblock(&mut self, nonblock: bool) -> &mut Self;
-
- /// Indicates whether `__WASI_FDFLAG_RSYNC` is passed in the `fs_flags`
- /// field of `path_open`.
- ///
- /// This option is by default `false`
- fn rsync(&mut self, rsync: bool) -> &mut Self;
-
- /// Indicates whether `__WASI_FDFLAG_SYNC` is passed in the `fs_flags`
- /// field of `path_open`.
- ///
- /// This option is by default `false`
- fn sync(&mut self, sync: bool) -> &mut Self;
-
- /// Indicates the value that should be passed in for the `fs_rights_base`
- /// parameter of `path_open`.
- ///
- /// This option defaults based on the `read` and `write` configuration of
- /// this `OpenOptions` builder. If this method is called, however, the
- /// exact mask passed in will be used instead.
- fn fs_rights_base(&mut self, rights: u64) -> &mut Self;
-
- /// Indicates the value that should be passed in for the
- /// `fs_rights_inheriting` parameter of `path_open`.
- ///
- /// The default for this option is the same value as what will be passed
- /// for the `fs_rights_base` parameter but if this method is called then
- /// the specified value will be used instead.
- fn fs_rights_inheriting(&mut self, rights: u64) -> &mut Self;
-
- /// Open a file or directory.
- ///
- /// This corresponds to the `path_open` syscall.
- fn open_at<P: AsRef<Path>>(&self, file: &File, path: P) -> io::Result<File>;
-}
-
-impl OpenOptionsExt for OpenOptions {
- fn lookup_flags(&mut self, flags: u32) -> &mut OpenOptions {
- self.as_inner_mut().lookup_flags(flags);
- self
- }
-
- fn directory(&mut self, dir: bool) -> &mut OpenOptions {
- self.as_inner_mut().directory(dir);
- self
- }
-
- fn dsync(&mut self, enabled: bool) -> &mut OpenOptions {
- self.as_inner_mut().dsync(enabled);
- self
- }
-
- fn nonblock(&mut self, enabled: bool) -> &mut OpenOptions {
- self.as_inner_mut().nonblock(enabled);
- self
- }
-
- fn rsync(&mut self, enabled: bool) -> &mut OpenOptions {
- self.as_inner_mut().rsync(enabled);
- self
- }
-
- fn sync(&mut self, enabled: bool) -> &mut OpenOptions {
- self.as_inner_mut().sync(enabled);
- self
- }
-
- fn fs_rights_base(&mut self, rights: u64) -> &mut OpenOptions {
- self.as_inner_mut().fs_rights_base(rights);
- self
- }
-
- fn fs_rights_inheriting(&mut self, rights: u64) -> &mut OpenOptions {
- self.as_inner_mut().fs_rights_inheriting(rights);
- self
- }
-
- fn open_at<P: AsRef<Path>>(&self, file: &File, path: P) -> io::Result<File> {
- let inner = file.as_inner().open_at(path.as_ref(), self.as_inner())?;
- Ok(File::from_inner(inner))
- }
-}
-
-/// WASI-specific extensions to [`fs::Metadata`].
-///
-/// [`fs::Metadata`]: ../../../../std/fs/struct.Metadata.html
-pub trait MetadataExt {
- /// Returns the `st_dev` field of the internal `filestat_t`
- fn dev(&self) -> u64;
- /// Returns the `st_ino` field of the internal `filestat_t`
- fn ino(&self) -> u64;
- /// Returns the `st_nlink` field of the internal `filestat_t`
- fn nlink(&self) -> u64;
- /// Returns the `st_atim` field of the internal `filestat_t`
- fn atim(&self) -> u64;
- /// Returns the `st_mtim` field of the internal `filestat_t`
- fn mtim(&self) -> u64;
- /// Returns the `st_ctim` field of the internal `filestat_t`
- fn ctim(&self) -> u64;
-}
-
-impl MetadataExt for fs::Metadata {
- fn dev(&self) -> u64 {
- self.as_inner().as_wasi().dev
- }
- fn ino(&self) -> u64 {
- self.as_inner().as_wasi().ino
- }
- fn nlink(&self) -> u64 {
- self.as_inner().as_wasi().nlink
- }
- fn atim(&self) -> u64 {
- self.as_inner().as_wasi().atim
- }
- fn mtim(&self) -> u64 {
- self.as_inner().as_wasi().mtim
- }
- fn ctim(&self) -> u64 {
- self.as_inner().as_wasi().ctim
- }
-}
-
-/// WASI-specific extensions for [`FileType`].
-///
-/// Adds support for special WASI file types such as block/character devices,
-/// pipes, and sockets.
-///
-/// [`FileType`]: ../../../../std/fs/struct.FileType.html
-pub trait FileTypeExt {
- /// Returns `true` if this file type is a block device.
- fn is_block_device(&self) -> bool;
- /// Returns `true` if this file type is a character device.
- fn is_character_device(&self) -> bool;
- /// Returns `true` if this file type is a socket datagram.
- fn is_socket_dgram(&self) -> bool;
- /// Returns `true` if this file type is a socket stream.
- fn is_socket_stream(&self) -> bool;
-}
-
-impl FileTypeExt for fs::FileType {
- fn is_block_device(&self) -> bool {
- self.as_inner().bits() == wasi::FILETYPE_BLOCK_DEVICE
- }
- fn is_character_device(&self) -> bool {
- self.as_inner().bits() == wasi::FILETYPE_CHARACTER_DEVICE
- }
- fn is_socket_dgram(&self) -> bool {
- self.as_inner().bits() == wasi::FILETYPE_SOCKET_DGRAM
- }
- fn is_socket_stream(&self) -> bool {
- self.as_inner().bits() == wasi::FILETYPE_SOCKET_STREAM
- }
-}
-
-/// WASI-specific extension methods for [`fs::DirEntry`].
-///
-/// [`fs::DirEntry`]: ../../../../std/fs/struct.DirEntry.html
-pub trait DirEntryExt {
- /// Returns the underlying `d_ino` field of the `dirent_t`
- fn ino(&self) -> u64;
-}
-
-impl DirEntryExt for fs::DirEntry {
- fn ino(&self) -> u64 {
- self.as_inner().ino()
- }
-}
-
-/// Create a hard link.
-///
-/// This corresponds to the `path_link` syscall.
-pub fn link<P: AsRef<Path>, U: AsRef<Path>>(
- old_fd: &File,
- old_flags: u32,
- old_path: P,
- new_fd: &File,
- new_path: U,
-) -> io::Result<()> {
- old_fd.as_inner().fd().link(
- old_flags,
- osstr2str(old_path.as_ref().as_ref())?,
- new_fd.as_inner().fd(),
- osstr2str(new_path.as_ref().as_ref())?,
- )
-}
-
-/// Rename a file or directory.
-///
-/// This corresponds to the `path_rename` syscall.
-pub fn rename<P: AsRef<Path>, U: AsRef<Path>>(
- old_fd: &File,
- old_path: P,
- new_fd: &File,
- new_path: U,
-) -> io::Result<()> {
- old_fd.as_inner().fd().rename(
- osstr2str(old_path.as_ref().as_ref())?,
- new_fd.as_inner().fd(),
- osstr2str(new_path.as_ref().as_ref())?,
- )
-}
-
-/// Create a symbolic link.
-///
-/// This corresponds to the `path_symlink` syscall.
-pub fn symlink<P: AsRef<Path>, U: AsRef<Path>>(
- old_path: P,
- fd: &File,
- new_path: U,
-) -> io::Result<()> {
- fd.as_inner()
- .fd()
- .symlink(osstr2str(old_path.as_ref().as_ref())?, osstr2str(new_path.as_ref().as_ref())?)
-}
diff --git a/src/libstd/sys/wasi/ext/io.rs b/src/libstd/sys/wasi/ext/io.rs
deleted file mode 100644
index e849400d67e..00000000000
--- a/src/libstd/sys/wasi/ext/io.rs
+++ /dev/null
@@ -1,142 +0,0 @@
-//! WASI-specific extensions to general I/O primitives
-
-#![unstable(feature = "wasi_ext", issue = "none")]
-
-use crate::fs;
-use crate::io;
-use crate::net;
-use crate::sys;
-use crate::sys_common::{AsInner, FromInner, IntoInner};
-
-/// Raw file descriptors.
-pub type RawFd = u32;
-
-/// A trait to extract the raw WASI file descriptor from an underlying
-/// object.
-pub trait AsRawFd {
- /// Extracts the raw file descriptor.
- ///
- /// This method does **not** pass ownership of the raw file descriptor
- /// to the caller. The descriptor is only guaranteed to be valid while
- /// the original object has not yet been destroyed.
- fn as_raw_fd(&self) -> RawFd;
-}
-
-/// A trait to express the ability to construct an object from a raw file
-/// descriptor.
-pub trait FromRawFd {
- /// Constructs a new instance of `Self` from the given raw file
- /// descriptor.
- ///
- /// This function **consumes ownership** of the specified file
- /// descriptor. The returned object will take responsibility for closing
- /// it when the object goes out of scope.
- ///
- /// This function is also unsafe as the primitives currently returned
- /// have the contract that they are the sole owner of the file
- /// descriptor they are wrapping. Usage of this function could
- /// accidentally allow violating this contract which can cause memory
- /// unsafety in code that relies on it being true.
- unsafe fn from_raw_fd(fd: RawFd) -> Self;
-}
-
-/// A trait to express the ability to consume an object and acquire ownership of
-/// its raw file descriptor.
-pub trait IntoRawFd {
- /// Consumes this object, returning the raw underlying file descriptor.
- ///
- /// This function **transfers ownership** of the underlying file descriptor
- /// to the caller. Callers are then the unique owners of the file descriptor
- /// and must close the descriptor once it's no longer needed.
- fn into_raw_fd(self) -> RawFd;
-}
-
-impl AsRawFd for net::TcpStream {
- fn as_raw_fd(&self) -> RawFd {
- self.as_inner().fd().as_raw()
- }
-}
-
-impl FromRawFd for net::TcpStream {
- unsafe fn from_raw_fd(fd: RawFd) -> net::TcpStream {
- net::TcpStream::from_inner(sys::net::TcpStream::from_inner(fd))
- }
-}
-
-impl IntoRawFd for net::TcpStream {
- fn into_raw_fd(self) -> RawFd {
- self.into_inner().into_fd().into_raw()
- }
-}
-
-impl AsRawFd for net::TcpListener {
- fn as_raw_fd(&self) -> RawFd {
- self.as_inner().fd().as_raw()
- }
-}
-
-impl FromRawFd for net::TcpListener {
- unsafe fn from_raw_fd(fd: RawFd) -> net::TcpListener {
- net::TcpListener::from_inner(sys::net::TcpListener::from_inner(fd))
- }
-}
-
-impl IntoRawFd for net::TcpListener {
- fn into_raw_fd(self) -> RawFd {
- self.into_inner().into_fd().into_raw()
- }
-}
-
-impl AsRawFd for net::UdpSocket {
- fn as_raw_fd(&self) -> RawFd {
- self.as_inner().fd().as_raw()
- }
-}
-
-impl FromRawFd for net::UdpSocket {
- unsafe fn from_raw_fd(fd: RawFd) -> net::UdpSocket {
- net::UdpSocket::from_inner(sys::net::UdpSocket::from_inner(fd))
- }
-}
-
-impl IntoRawFd for net::UdpSocket {
- fn into_raw_fd(self) -> RawFd {
- self.into_inner().into_fd().into_raw()
- }
-}
-
-impl AsRawFd for fs::File {
- fn as_raw_fd(&self) -> RawFd {
- self.as_inner().fd().as_raw()
- }
-}
-
-impl FromRawFd for fs::File {
- unsafe fn from_raw_fd(fd: RawFd) -> fs::File {
- fs::File::from_inner(sys::fs::File::from_inner(fd))
- }
-}
-
-impl IntoRawFd for fs::File {
- fn into_raw_fd(self) -> RawFd {
- self.into_inner().into_fd().into_raw()
- }
-}
-
-impl AsRawFd for io::Stdin {
- fn as_raw_fd(&self) -> RawFd {
- sys::stdio::Stdin.as_raw_fd()
- }
-}
-
-impl AsRawFd for io::Stdout {
- fn as_raw_fd(&self) -> RawFd {
- sys::stdio::Stdout.as_raw_fd()
- }
-}
-
-impl AsRawFd for io::Stderr {
- fn as_raw_fd(&self) -> RawFd {
- sys::stdio::Stderr.as_raw_fd()
- }
-}
diff --git a/src/libstd/sys/wasi/ext/mod.rs b/src/libstd/sys/wasi/ext/mod.rs
deleted file mode 100644
index 58c8c46c969..00000000000
--- a/src/libstd/sys/wasi/ext/mod.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-pub mod ffi;
-pub mod fs;
-pub mod io;
-
-/// A prelude for conveniently writing platform-specific code.
-///
-/// Includes all extension traits, and some important type definitions.
-#[stable(feature = "rust1", since = "1.0.0")]
-pub mod prelude {
- #[doc(no_inline)]
- #[stable(feature = "rust1", since = "1.0.0")]
- pub use crate::sys::ext::ffi::{OsStrExt, OsStringExt};
- #[doc(no_inline)]
- #[stable(feature = "rust1", since = "1.0.0")]
- pub use crate::sys::ext::fs::FileTypeExt;
- #[doc(no_inline)]
- #[stable(feature = "rust1", since = "1.0.0")]
- pub use crate::sys::ext::fs::{DirEntryExt, FileExt, MetadataExt, OpenOptionsExt};
- #[doc(no_inline)]
- #[stable(feature = "rust1", since = "1.0.0")]
- pub use crate::sys::ext::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
-}
diff --git a/src/libstd/sys/wasi/fd.rs b/src/libstd/sys/wasi/fd.rs
deleted file mode 100644
index 8458ded5db0..00000000000
--- a/src/libstd/sys/wasi/fd.rs
+++ /dev/null
@@ -1,228 +0,0 @@
-#![allow(dead_code)]
-
-use super::err2io;
-use crate::io::{self, IoSlice, IoSliceMut, SeekFrom};
-use crate::mem;
-use crate::net::Shutdown;
-
-#[derive(Debug)]
-pub struct WasiFd {
- fd: wasi::Fd,
-}
-
-fn iovec<'a>(a: &'a mut [IoSliceMut<'_>]) -> &'a [wasi::Iovec] {
- assert_eq!(mem::size_of::<IoSliceMut<'_>>(), mem::size_of::<wasi::Iovec>());
- assert_eq!(mem::align_of::<IoSliceMut<'_>>(), mem::align_of::<wasi::Iovec>());
- // SAFETY: `IoSliceMut` and `IoVec` have exactly the same memory layout
- unsafe { mem::transmute(a) }
-}
-
-fn ciovec<'a>(a: &'a [IoSlice<'_>]) -> &'a [wasi::Ciovec] {
- assert_eq!(mem::size_of::<IoSlice<'_>>(), mem::size_of::<wasi::Ciovec>());
- assert_eq!(mem::align_of::<IoSlice<'_>>(), mem::align_of::<wasi::Ciovec>());
- // SAFETY: `IoSlice` and `CIoVec` have exactly the same memory layout
- unsafe { mem::transmute(a) }
-}
-
-impl WasiFd {
- pub unsafe fn from_raw(fd: wasi::Fd) -> WasiFd {
- WasiFd { fd }
- }
-
- pub fn into_raw(self) -> wasi::Fd {
- let ret = self.fd;
- mem::forget(self);
- ret
- }
-
- pub fn as_raw(&self) -> wasi::Fd {
- self.fd
- }
-
- pub fn datasync(&self) -> io::Result<()> {
- unsafe { wasi::fd_datasync(self.fd).map_err(err2io) }
- }
-
- pub fn pread(&self, bufs: &mut [IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
- unsafe { wasi::fd_pread(self.fd, iovec(bufs), offset).map_err(err2io) }
- }
-
- pub fn pwrite(&self, bufs: &[IoSlice<'_>], offset: u64) -> io::Result<usize> {
- unsafe { wasi::fd_pwrite(self.fd, ciovec(bufs), offset).map_err(err2io) }
- }
-
- pub fn read(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
- unsafe { wasi::fd_read(self.fd, iovec(bufs)).map_err(err2io) }
- }
-
- pub fn write(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
- unsafe { wasi::fd_write(self.fd, ciovec(bufs)).map_err(err2io) }
- }
-
- pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
- let (whence, offset) = match pos {
- SeekFrom::Start(pos) => (wasi::WHENCE_SET, pos as i64),
- SeekFrom::End(pos) => (wasi::WHENCE_END, pos),
- SeekFrom::Current(pos) => (wasi::WHENCE_CUR, pos),
- };
- unsafe { wasi::fd_seek(self.fd, offset, whence).map_err(err2io) }
- }
-
- pub fn tell(&self) -> io::Result<u64> {
- unsafe { wasi::fd_tell(self.fd).map_err(err2io) }
- }
-
- // FIXME: __wasi_fd_fdstat_get
-
- pub fn set_flags(&self, flags: wasi::Fdflags) -> io::Result<()> {
- unsafe { wasi::fd_fdstat_set_flags(self.fd, flags).map_err(err2io) }
- }
-
- pub fn set_rights(&self, base: wasi::Rights, inheriting: wasi::Rights) -> io::Result<()> {
- unsafe { wasi::fd_fdstat_set_rights(self.fd, base, inheriting).map_err(err2io) }
- }
-
- pub fn sync(&self) -> io::Result<()> {
- unsafe { wasi::fd_sync(self.fd).map_err(err2io) }
- }
-
- pub fn advise(&self, offset: u64, len: u64, advice: wasi::Advice) -> io::Result<()> {
- unsafe { wasi::fd_advise(self.fd, offset, len, advice).map_err(err2io) }
- }
-
- pub fn allocate(&self, offset: u64, len: u64) -> io::Result<()> {
- unsafe { wasi::fd_allocate(self.fd, offset, len).map_err(err2io) }
- }
-
- pub fn create_directory(&self, path: &str) -> io::Result<()> {
- unsafe { wasi::path_create_directory(self.fd, path).map_err(err2io) }
- }
-
- pub fn link(
- &self,
- old_flags: wasi::Lookupflags,
- old_path: &str,
- new_fd: &WasiFd,
- new_path: &str,
- ) -> io::Result<()> {
- unsafe {
- wasi::path_link(self.fd, old_flags, old_path, new_fd.fd, new_path).map_err(err2io)
- }
- }
-
- pub fn open(
- &self,
- dirflags: wasi::Lookupflags,
- path: &str,
- oflags: wasi::Oflags,
- fs_rights_base: wasi::Rights,
- fs_rights_inheriting: wasi::Rights,
- fs_flags: wasi::Fdflags,
- ) -> io::Result<WasiFd> {
- unsafe {
- wasi::path_open(
- self.fd,
- dirflags,
- path,
- oflags,
- fs_rights_base,
- fs_rights_inheriting,
- fs_flags,
- )
- .map(|fd| WasiFd::from_raw(fd))
- .map_err(err2io)
- }
- }
-
- pub fn readdir(&self, buf: &mut [u8], cookie: wasi::Dircookie) -> io::Result<usize> {
- unsafe { wasi::fd_readdir(self.fd, buf.as_mut_ptr(), buf.len(), cookie).map_err(err2io) }
- }
-
- pub fn readlink(&self, path: &str, buf: &mut [u8]) -> io::Result<usize> {
- unsafe { wasi::path_readlink(self.fd, path, buf.as_mut_ptr(), buf.len()).map_err(err2io) }
- }
-
- pub fn rename(&self, old_path: &str, new_fd: &WasiFd, new_path: &str) -> io::Result<()> {
- unsafe { wasi::path_rename(self.fd, old_path, new_fd.fd, new_path).map_err(err2io) }
- }
-
- pub fn filestat_get(&self) -> io::Result<wasi::Filestat> {
- unsafe { wasi::fd_filestat_get(self.fd).map_err(err2io) }
- }
-
- pub fn filestat_set_times(
- &self,
- atim: wasi::Timestamp,
- mtim: wasi::Timestamp,
- fstflags: wasi::Fstflags,
- ) -> io::Result<()> {
- unsafe { wasi::fd_filestat_set_times(self.fd, atim, mtim, fstflags).map_err(err2io) }
- }
-
- pub fn filestat_set_size(&self, size: u64) -> io::Result<()> {
- unsafe { wasi::fd_filestat_set_size(self.fd, size).map_err(err2io) }
- }
-
- pub fn path_filestat_get(
- &self,
- flags: wasi::Lookupflags,
- path: &str,
- ) -> io::Result<wasi::Filestat> {
- unsafe { wasi::path_filestat_get(self.fd, flags, path).map_err(err2io) }
- }
-
- pub fn path_filestat_set_times(
- &self,
- flags: wasi::Lookupflags,
- path: &str,
- atim: wasi::Timestamp,
- mtim: wasi::Timestamp,
- fstflags: wasi::Fstflags,
- ) -> io::Result<()> {
- unsafe {
- wasi::path_filestat_set_times(self.fd, flags, path, atim, mtim, fstflags)
- .map_err(err2io)
- }
- }
-
- pub fn symlink(&self, old_path: &str, new_path: &str) -> io::Result<()> {
- unsafe { wasi::path_symlink(old_path, self.fd, new_path).map_err(err2io) }
- }
-
- pub fn unlink_file(&self, path: &str) -> io::Result<()> {
- unsafe { wasi::path_unlink_file(self.fd, path).map_err(err2io) }
- }
-
- pub fn remove_directory(&self, path: &str) -> io::Result<()> {
- unsafe { wasi::path_remove_directory(self.fd, path).map_err(err2io) }
- }
-
- pub fn sock_recv(
- &self,
- ri_data: &mut [IoSliceMut<'_>],
- ri_flags: wasi::Riflags,
- ) -> io::Result<(usize, wasi::Roflags)> {
- unsafe { wasi::sock_recv(self.fd, iovec(ri_data), ri_flags).map_err(err2io) }
- }
-
- pub fn sock_send(&self, si_data: &[IoSlice<'_>], si_flags: wasi::Siflags) -> io::Result<usize> {
- unsafe { wasi::sock_send(self.fd, ciovec(si_data), si_flags).map_err(err2io) }
- }
-
- pub fn sock_shutdown(&self, how: Shutdown) -> io::Result<()> {
- let how = match how {
- Shutdown::Read => wasi::SDFLAGS_RD,
- Shutdown::Write => wasi::SDFLAGS_WR,
- Shutdown::Both => wasi::SDFLAGS_WR | wasi::SDFLAGS_RD,
- };
- unsafe { wasi::sock_shutdown(self.fd, how).map_err(err2io) }
- }
-}
-
-impl Drop for WasiFd {
- fn drop(&mut self) {
- // FIXME: can we handle the return code here even though we can't on
- // unix?
- let _ = unsafe { wasi::fd_close(self.fd) };
- }
-}
diff --git a/src/libstd/sys/wasi/fs.rs b/src/libstd/sys/wasi/fs.rs
deleted file mode 100644
index 2eed9e436a9..00000000000
--- a/src/libstd/sys/wasi/fs.rs
+++ /dev/null
@@ -1,667 +0,0 @@
-use crate::ffi::{CStr, CString, OsStr, OsString};
-use crate::fmt;
-use crate::io::{self, IoSlice, IoSliceMut, SeekFrom};
-use crate::iter;
-use crate::mem::{self, ManuallyDrop};
-use crate::os::wasi::ffi::{OsStrExt, OsStringExt};
-use crate::path::{Path, PathBuf};
-use crate::ptr;
-use crate::sync::Arc;
-use crate::sys::fd::WasiFd;
-use crate::sys::time::SystemTime;
-use crate::sys::unsupported;
-use crate::sys_common::FromInner;
-
-pub use crate::sys_common::fs::remove_dir_all;
-
-pub struct File {
- fd: WasiFd,
-}
-
-#[derive(Clone)]
-pub struct FileAttr {
- meta: wasi::Filestat,
-}
-
-pub struct ReadDir {
- inner: Arc<ReadDirInner>,
- cookie: Option<wasi::Dircookie>,
- buf: Vec<u8>,
- offset: usize,
- cap: usize,
-}
-
-struct ReadDirInner {
- root: PathBuf,
- dir: File,
-}
-
-pub struct DirEntry {
- meta: wasi::Dirent,
- name: Vec<u8>,
- inner: Arc<ReadDirInner>,
-}
-
-#[derive(Clone, Debug, Default)]
-pub struct OpenOptions {
- read: bool,
- write: bool,
- dirflags: wasi::Lookupflags,
- fdflags: wasi::Fdflags,
- oflags: wasi::Oflags,
- rights_base: Option<wasi::Rights>,
- rights_inheriting: Option<wasi::Rights>,
-}
-
-#[derive(Clone, PartialEq, Eq, Debug)]
-pub struct FilePermissions {
- readonly: bool,
-}
-
-#[derive(PartialEq, Eq, Hash, Debug, Copy, Clone)]
-pub struct FileType {
- bits: wasi::Filetype,
-}
-
-#[derive(Debug)]
-pub struct DirBuilder {}
-
-impl FileAttr {
- pub fn size(&self) -> u64 {
- self.meta.size
- }
-
- pub fn perm(&self) -> FilePermissions {
- // not currently implemented in wasi yet
- FilePermissions { readonly: false }
- }
-
- pub fn file_type(&self) -> FileType {
- FileType { bits: self.meta.filetype }
- }
-
- pub fn modified(&self) -> io::Result<SystemTime> {
- Ok(SystemTime::from_wasi_timestamp(self.meta.mtim))
- }
-
- pub fn accessed(&self) -> io::Result<SystemTime> {
- Ok(SystemTime::from_wasi_timestamp(self.meta.atim))
- }
-
- pub fn created(&self) -> io::Result<SystemTime> {
- Ok(SystemTime::from_wasi_timestamp(self.meta.ctim))
- }
-
- pub fn as_wasi(&self) -> &wasi::Filestat {
- &self.meta
- }
-}
-
-impl FilePermissions {
- pub fn readonly(&self) -> bool {
- self.readonly
- }
-
- pub fn set_readonly(&mut self, readonly: bool) {
- self.readonly = readonly;
- }
-}
-
-impl FileType {
- pub fn is_dir(&self) -> bool {
- self.bits == wasi::FILETYPE_DIRECTORY
- }
-
- pub fn is_file(&self) -> bool {
- self.bits == wasi::FILETYPE_REGULAR_FILE
- }
-
- pub fn is_symlink(&self) -> bool {
- self.bits == wasi::FILETYPE_SYMBOLIC_LINK
- }
-
- pub fn bits(&self) -> wasi::Filetype {
- self.bits
- }
-}
-
-impl fmt::Debug for ReadDir {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("ReadDir").finish()
- }
-}
-
-impl Iterator for ReadDir {
- type Item = io::Result<DirEntry>;
-
- fn next(&mut self) -> Option<io::Result<DirEntry>> {
- loop {
- // If we've reached the capacity of our buffer then we need to read
- // some more from the OS, otherwise we pick up at our old offset.
- let offset = if self.offset == self.cap {
- let cookie = self.cookie.take()?;
- match self.inner.dir.fd.readdir(&mut self.buf, cookie) {
- Ok(bytes) => self.cap = bytes,
- Err(e) => return Some(Err(e)),
- }
- self.offset = 0;
- self.cookie = Some(cookie);
-
- // If we didn't actually read anything, this is in theory the
- // end of the directory.
- if self.cap == 0 {
- self.cookie = None;
- return None;
- }
-
- 0
- } else {
- self.offset
- };
- let data = &self.buf[offset..self.cap];
-
- // If we're not able to read a directory entry then that means it
- // must have been truncated at the end of the buffer, so reset our
- // offset so we can go back and reread into the buffer, picking up
- // where we last left off.
- let dirent_size = mem::size_of::<wasi::Dirent>();
- if data.len() < dirent_size {
- assert!(self.cookie.is_some());
- assert!(self.buf.len() >= dirent_size);
- self.offset = self.cap;
- continue;
- }
- let (dirent, data) = data.split_at(dirent_size);
- let dirent = unsafe { ptr::read_unaligned(dirent.as_ptr() as *const wasi::Dirent) };
-
- // If the file name was truncated, then we need to reinvoke
- // `readdir` so we truncate our buffer to start over and reread this
- // descriptor. Note that if our offset is 0 that means the file name
- // is massive and we need a bigger buffer.
- if data.len() < dirent.d_namlen as usize {
- if offset == 0 {
- let amt_to_add = self.buf.capacity();
- self.buf.extend(iter::repeat(0).take(amt_to_add));
- }
- assert!(self.cookie.is_some());
- self.offset = self.cap;
- continue;
- }
- self.cookie = Some(dirent.d_next);
- self.offset = offset + dirent_size + dirent.d_namlen as usize;
-
- let name = &data[..(dirent.d_namlen as usize)];
-
- // These names are skipped on all other platforms, so let's skip
- // them here too
- if name == b"." || name == b".." {
- continue;
- }
-
- return Some(Ok(DirEntry {
- meta: dirent,
- name: name.to_vec(),
- inner: self.inner.clone(),
- }));
- }
- }
-}
-
-impl DirEntry {
- pub fn path(&self) -> PathBuf {
- let name = OsStr::from_bytes(&self.name);
- self.inner.root.join(name)
- }
-
- pub fn file_name(&self) -> OsString {
- OsString::from_vec(self.name.clone())
- }
-
- pub fn metadata(&self) -> io::Result<FileAttr> {
- metadata_at(&self.inner.dir.fd, 0, OsStr::from_bytes(&self.name).as_ref())
- }
-
- pub fn file_type(&self) -> io::Result<FileType> {
- Ok(FileType { bits: self.meta.d_type })
- }
-
- pub fn ino(&self) -> wasi::Inode {
- self.meta.d_ino
- }
-}
-
-impl OpenOptions {
- pub fn new() -> OpenOptions {
- let mut base = OpenOptions::default();
- base.dirflags = wasi::LOOKUPFLAGS_SYMLINK_FOLLOW;
- return base;
- }
-
- pub fn read(&mut self, read: bool) {
- self.read = read;
- }
-
- pub fn write(&mut self, write: bool) {
- self.write = write;
- }
-
- pub fn truncate(&mut self, truncate: bool) {
- self.oflag(wasi::OFLAGS_TRUNC, truncate);
- }
-
- pub fn create(&mut self, create: bool) {
- self.oflag(wasi::OFLAGS_CREAT, create);
- }
-
- pub fn create_new(&mut self, create_new: bool) {
- self.oflag(wasi::OFLAGS_EXCL, create_new);
- self.oflag(wasi::OFLAGS_CREAT, create_new);
- }
-
- pub fn directory(&mut self, directory: bool) {
- self.oflag(wasi::OFLAGS_DIRECTORY, directory);
- }
-
- fn oflag(&mut self, bit: wasi::Oflags, set: bool) {
- if set {
- self.oflags |= bit;
- } else {
- self.oflags &= !bit;
- }
- }
-
- pub fn append(&mut self, set: bool) {
- self.fdflag(wasi::FDFLAGS_APPEND, set);
- }
-
- pub fn dsync(&mut self, set: bool) {
- self.fdflag(wasi::FDFLAGS_DSYNC, set);
- }
-
- pub fn nonblock(&mut self, set: bool) {
- self.fdflag(wasi::FDFLAGS_NONBLOCK, set);
- }
-
- pub fn rsync(&mut self, set: bool) {
- self.fdflag(wasi::FDFLAGS_RSYNC, set);
- }
-
- pub fn sync(&mut self, set: bool) {
- self.fdflag(wasi::FDFLAGS_SYNC, set);
- }
-
- fn fdflag(&mut self, bit: wasi::Fdflags, set: bool) {
- if set {
- self.fdflags |= bit;
- } else {
- self.fdflags &= !bit;
- }
- }
-
- pub fn fs_rights_base(&mut self, rights: wasi::Rights) {
- self.rights_base = Some(rights);
- }
-
- pub fn fs_rights_inheriting(&mut self, rights: wasi::Rights) {
- self.rights_inheriting = Some(rights);
- }
-
- fn rights_base(&self) -> wasi::Rights {
- if let Some(rights) = self.rights_base {
- return rights;
- }
-
- // If rights haven't otherwise been specified try to pick a reasonable
- // set. This can always be overridden by users via extension traits, and
- // implementations may give us fewer rights silently than we ask for. So
- // given that, just look at `read` and `write` and bucket permissions
- // based on that.
- let mut base = 0;
- if self.read {
- base |= wasi::RIGHTS_FD_READ;
- base |= wasi::RIGHTS_FD_READDIR;
- }
- if self.write {
- base |= wasi::RIGHTS_FD_WRITE;
- base |= wasi::RIGHTS_FD_DATASYNC;
- base |= wasi::RIGHTS_FD_ALLOCATE;
- base |= wasi::RIGHTS_FD_FILESTAT_SET_SIZE;
- }
-
- // FIXME: some of these should probably be read-only or write-only...
- base |= wasi::RIGHTS_FD_ADVISE;
- base |= wasi::RIGHTS_FD_FDSTAT_SET_FLAGS;
- base |= wasi::RIGHTS_FD_FILESTAT_SET_TIMES;
- base |= wasi::RIGHTS_FD_SEEK;
- base |= wasi::RIGHTS_FD_SYNC;
- base |= wasi::RIGHTS_FD_TELL;
- base |= wasi::RIGHTS_PATH_CREATE_DIRECTORY;
- base |= wasi::RIGHTS_PATH_CREATE_FILE;
- base |= wasi::RIGHTS_PATH_FILESTAT_GET;
- base |= wasi::RIGHTS_PATH_LINK_SOURCE;
- base |= wasi::RIGHTS_PATH_LINK_TARGET;
- base |= wasi::RIGHTS_PATH_OPEN;
- base |= wasi::RIGHTS_PATH_READLINK;
- base |= wasi::RIGHTS_PATH_REMOVE_DIRECTORY;
- base |= wasi::RIGHTS_PATH_RENAME_SOURCE;
- base |= wasi::RIGHTS_PATH_RENAME_TARGET;
- base |= wasi::RIGHTS_PATH_SYMLINK;
- base |= wasi::RIGHTS_PATH_UNLINK_FILE;
- base |= wasi::RIGHTS_POLL_FD_READWRITE;
-
- return base;
- }
-
- fn rights_inheriting(&self) -> wasi::Rights {
- self.rights_inheriting.unwrap_or_else(|| self.rights_base())
- }
-
- pub fn lookup_flags(&mut self, flags: wasi::Lookupflags) {
- self.dirflags = flags;
- }
-}
-
-impl File {
- pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
- let (dir, file) = open_parent(path)?;
- open_at(&dir, &file, opts)
- }
-
- pub fn open_at(&self, path: &Path, opts: &OpenOptions) -> io::Result<File> {
- open_at(&self.fd, path, opts)
- }
-
- pub fn file_attr(&self) -> io::Result<FileAttr> {
- self.fd.filestat_get().map(|meta| FileAttr { meta })
- }
-
- pub fn metadata_at(&self, flags: wasi::Lookupflags, path: &Path) -> io::Result<FileAttr> {
- metadata_at(&self.fd, flags, path)
- }
-
- pub fn fsync(&self) -> io::Result<()> {
- self.fd.sync()
- }
-
- pub fn datasync(&self) -> io::Result<()> {
- self.fd.datasync()
- }
-
- pub fn truncate(&self, size: u64) -> io::Result<()> {
- self.fd.filestat_set_size(size)
- }
-
- pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
- self.read_vectored(&mut [IoSliceMut::new(buf)])
- }
-
- pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
- self.fd.read(bufs)
- }
-
- #[inline]
- pub fn is_read_vectored(&self) -> bool {
- true
- }
-
- pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
- self.write_vectored(&[IoSlice::new(buf)])
- }
-
- pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
- self.fd.write(bufs)
- }
-
- #[inline]
- pub fn is_write_vectored(&self) -> bool {
- true
- }
-
- pub fn flush(&self) -> io::Result<()> {
- Ok(())
- }
-
- pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
- self.fd.seek(pos)
- }
-
- pub fn duplicate(&self) -> io::Result<File> {
- // https://github.com/CraneStation/wasmtime/blob/master/docs/WASI-rationale.md#why-no-dup
- unsupported()
- }
-
- pub fn set_permissions(&self, _perm: FilePermissions) -> io::Result<()> {
- // Permissions haven't been fully figured out in wasi yet, so this is
- // likely temporary
- unsupported()
- }
-
- pub fn fd(&self) -> &WasiFd {
- &self.fd
- }
-
- pub fn into_fd(self) -> WasiFd {
- self.fd
- }
-
- pub fn read_link(&self, file: &Path) -> io::Result<PathBuf> {
- read_link(&self.fd, file)
- }
-}
-
-impl FromInner<u32> for File {
- fn from_inner(fd: u32) -> File {
- unsafe { File { fd: WasiFd::from_raw(fd) } }
- }
-}
-
-impl DirBuilder {
- pub fn new() -> DirBuilder {
- DirBuilder {}
- }
-
- pub fn mkdir(&self, p: &Path) -> io::Result<()> {
- let (dir, file) = open_parent(p)?;
- dir.create_directory(osstr2str(file.as_ref())?)
- }
-}
-
-impl fmt::Debug for File {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("File").field("fd", &self.fd.as_raw()).finish()
- }
-}
-
-pub fn readdir(p: &Path) -> io::Result<ReadDir> {
- let mut opts = OpenOptions::new();
- opts.directory(true);
- opts.read(true);
- let dir = File::open(p, &opts)?;
- Ok(ReadDir {
- cookie: Some(0),
- buf: vec![0; 128],
- offset: 0,
- cap: 0,
- inner: Arc::new(ReadDirInner { dir, root: p.to_path_buf() }),
- })
-}
-
-pub fn unlink(p: &Path) -> io::Result<()> {
- let (dir, file) = open_parent(p)?;
- dir.unlink_file(osstr2str(file.as_ref())?)
-}
-
-pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
- let (old, old_file) = open_parent(old)?;
- let (new, new_file) = open_parent(new)?;
- old.rename(osstr2str(old_file.as_ref())?, &new, osstr2str(new_file.as_ref())?)
-}
-
-pub fn set_perm(_p: &Path, _perm: FilePermissions) -> io::Result<()> {
- // Permissions haven't been fully figured out in wasi yet, so this is
- // likely temporary
- unsupported()
-}
-
-pub fn rmdir(p: &Path) -> io::Result<()> {
- let (dir, file) = open_parent(p)?;
- dir.remove_directory(osstr2str(file.as_ref())?)
-}
-
-pub fn readlink(p: &Path) -> io::Result<PathBuf> {
- let (dir, file) = open_parent(p)?;
- read_link(&dir, &file)
-}
-
-fn read_link(fd: &WasiFd, file: &Path) -> io::Result<PathBuf> {
- // Try to get a best effort initial capacity for the vector we're going to
- // fill. Note that if it's not a symlink we don't use a file to avoid
- // allocating gigabytes if you read_link a huge movie file by accident.
- // Additionally we add 1 to the initial size so if it doesn't change until
- // when we call `readlink` the returned length will be less than the
- // capacity, guaranteeing that we got all the data.
- let meta = metadata_at(fd, 0, file)?;
- let initial_size = if meta.file_type().is_symlink() {
- (meta.size() as usize).saturating_add(1)
- } else {
- 1 // this'll fail in just a moment
- };
-
- // Now that we have an initial guess of how big to make our buffer, call
- // `readlink` in a loop until it fails or reports it filled fewer bytes than
- // we asked for, indicating we got everything.
- let file = osstr2str(file.as_ref())?;
- let mut destination = vec![0u8; initial_size];
- loop {
- let len = fd.readlink(file, &mut destination)?;
- if len < destination.len() {
- destination.truncate(len);
- destination.shrink_to_fit();
- return Ok(PathBuf::from(OsString::from_vec(destination)));
- }
- let amt_to_add = destination.len();
- destination.extend(iter::repeat(0).take(amt_to_add));
- }
-}
-
-pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
- let (dst, dst_file) = open_parent(dst)?;
- dst.symlink(osstr2str(src.as_ref())?, osstr2str(dst_file.as_ref())?)
-}
-
-pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
- let (src, src_file) = open_parent(src)?;
- let (dst, dst_file) = open_parent(dst)?;
- src.link(
- wasi::LOOKUPFLAGS_SYMLINK_FOLLOW,
- osstr2str(src_file.as_ref())?,
- &dst,
- osstr2str(dst_file.as_ref())?,
- )
-}
-
-pub fn stat(p: &Path) -> io::Result<FileAttr> {
- let (dir, file) = open_parent(p)?;
- metadata_at(&dir, wasi::LOOKUPFLAGS_SYMLINK_FOLLOW, &file)
-}
-
-pub fn lstat(p: &Path) -> io::Result<FileAttr> {
- let (dir, file) = open_parent(p)?;
- metadata_at(&dir, 0, &file)
-}
-
-fn metadata_at(fd: &WasiFd, flags: wasi::Lookupflags, path: &Path) -> io::Result<FileAttr> {
- let meta = fd.path_filestat_get(flags, osstr2str(path.as_ref())?)?;
- Ok(FileAttr { meta })
-}
-
-pub fn canonicalize(_p: &Path) -> io::Result<PathBuf> {
- // This seems to not be in wasi's API yet, and we may need to end up
- // emulating it ourselves. For now just return an error.
- unsupported()
-}
-
-fn open_at(fd: &WasiFd, path: &Path, opts: &OpenOptions) -> io::Result<File> {
- let fd = fd.open(
- opts.dirflags,
- osstr2str(path.as_ref())?,
- opts.oflags,
- opts.rights_base(),
- opts.rights_inheriting(),
- opts.fdflags,
- )?;
- Ok(File { fd })
-}
-
-/// Attempts to open a bare path `p`.
-///
-/// WASI has no fundamental capability to do this. All syscalls and operations
-/// are relative to already-open file descriptors. The C library, however,
-/// manages a map of pre-opened file descriptors to their path, and then the C
-/// library provides an API to look at this. In other words, when you want to
-/// open a path `p`, you have to find a previously opened file descriptor in a
-/// global table and then see if `p` is relative to that file descriptor.
-///
-/// This function, if successful, will return two items:
-///
-/// * The first is a `ManuallyDrop<WasiFd>`. This represents a pre-opened file
-/// descriptor which we don't have ownership of, but we can use. You shouldn't
-/// actually drop the `fd`.
-///
-/// * The second is a path that should be a part of `p` and represents a
-/// relative traversal from the file descriptor specified to the desired
-/// location `p`.
-///
-/// If successful you can use the returned file descriptor to perform
-/// file-descriptor-relative operations on the path returned as well. The
-/// `rights` argument indicates what operations are desired on the returned file
-/// descriptor, and if successful the returned file descriptor should have the
-/// appropriate rights for performing `rights` actions.
-///
-/// Note that this can fail if `p` doesn't look like it can be opened relative
-/// to any pre-opened file descriptor.
-fn open_parent(p: &Path) -> io::Result<(ManuallyDrop<WasiFd>, PathBuf)> {
- let p = CString::new(p.as_os_str().as_bytes())?;
- unsafe {
- let mut ret = ptr::null();
- let fd = __wasilibc_find_relpath(p.as_ptr(), &mut ret);
- if fd == -1 {
- let msg = format!(
- "failed to find a pre-opened file descriptor \
- through which {:?} could be opened",
- p
- );
- return Err(io::Error::new(io::ErrorKind::Other, msg));
- }
- let path = Path::new(OsStr::from_bytes(CStr::from_ptr(ret).to_bytes()));
-
- // FIXME: right now `path` is a pointer into `p`, the `CString` above.
- // When we return `p` is deallocated and we can't use it, so we need to
- // currently separately allocate `path`. If this becomes an issue though
- // we should probably turn this into a closure-taking interface or take
- // `&CString` and then pass off `&Path` tied to the same lifetime.
- let path = path.to_path_buf();
-
- return Ok((ManuallyDrop::new(WasiFd::from_raw(fd as u32)), path));
- }
-
- extern "C" {
- pub fn __wasilibc_find_relpath(
- path: *const libc::c_char,
- relative_path: *mut *const libc::c_char,
- ) -> libc::c_int;
- }
-}
-
-pub fn osstr2str(f: &OsStr) -> io::Result<&str> {
- f.to_str().ok_or_else(|| io::Error::new(io::ErrorKind::Other, "input must be utf-8"))
-}
-
-pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
- use crate::fs::File;
-
- let mut reader = File::open(from)?;
- let mut writer = File::create(to)?;
-
- io::copy(&mut reader, &mut writer)
-}
diff --git a/src/libstd/sys/wasi/io.rs b/src/libstd/sys/wasi/io.rs
deleted file mode 100644
index 0ad2e152855..00000000000
--- a/src/libstd/sys/wasi/io.rs
+++ /dev/null
@@ -1,71 +0,0 @@
-use crate::marker::PhantomData;
-use crate::slice;
-
-#[derive(Copy, Clone)]
-#[repr(transparent)]
-pub struct IoSlice<'a> {
- vec: wasi::Ciovec,
- _p: PhantomData<&'a [u8]>,
-}
-
-impl<'a> IoSlice<'a> {
- #[inline]
- pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
- IoSlice { vec: wasi::Ciovec { buf: buf.as_ptr(), buf_len: buf.len() }, _p: PhantomData }
- }
-
- #[inline]
- pub fn advance(&mut self, n: usize) {
- if self.vec.buf_len < n {
- panic!("advancing IoSlice beyond its length");
- }
-
- unsafe {
- self.vec.buf_len -= n;
- self.vec.buf = self.vec.buf.add(n);
- }
- }
-
- #[inline]
- pub fn as_slice(&self) -> &[u8] {
- unsafe { slice::from_raw_parts(self.vec.buf as *const u8, self.vec.buf_len) }
- }
-}
-
-#[repr(transparent)]
-pub struct IoSliceMut<'a> {
- vec: wasi::Iovec,
- _p: PhantomData<&'a mut [u8]>,
-}
-
-impl<'a> IoSliceMut<'a> {
- #[inline]
- pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
- IoSliceMut {
- vec: wasi::Iovec { buf: buf.as_mut_ptr(), buf_len: buf.len() },
- _p: PhantomData,
- }
- }
-
- #[inline]
- pub fn advance(&mut self, n: usize) {
- if self.vec.buf_len < n {
- panic!("advancing IoSlice beyond its length");
- }
-
- unsafe {
- self.vec.buf_len -= n;
- self.vec.buf = self.vec.buf.add(n);
- }
- }
-
- #[inline]
- pub fn as_slice(&self) -> &[u8] {
- unsafe { slice::from_raw_parts(self.vec.buf as *const u8, self.vec.buf_len) }
- }
-
- #[inline]
- pub fn as_mut_slice(&mut self) -> &mut [u8] {
- unsafe { slice::from_raw_parts_mut(self.vec.buf as *mut u8, self.vec.buf_len) }
- }
-}
diff --git a/src/libstd/sys/wasi/mod.rs b/src/libstd/sys/wasi/mod.rs
deleted file mode 100644
index 2704ff484f9..00000000000
--- a/src/libstd/sys/wasi/mod.rs
+++ /dev/null
@@ -1,96 +0,0 @@
-//! System bindings for the wasm/web platform
-//!
-//! This module contains the facade (aka platform-specific) implementations of
-//! OS level functionality for wasm. Note that this wasm is *not* the emscripten
-//! wasm, so we have no runtime here.
-//!
-//! This is all super highly experimental and not actually intended for
-//! wide/production use yet, it's still all in the experimental category. This
-//! will likely change over time.
-//!
-//! Currently all functions here are basically stubs that immediately return
-//! errors. The hope is that with a portability lint we can turn actually just
-//! remove all this and just omit parts of the standard library if we're
-//! compiling for wasm. That way it's a compile time error for something that's
-//! guaranteed to be a runtime error!
-
-use crate::io as std_io;
-use crate::mem;
-
-pub mod alloc;
-pub mod args;
-#[path = "../unsupported/cmath.rs"]
-pub mod cmath;
-#[path = "../unsupported/condvar.rs"]
-pub mod condvar;
-pub mod env;
-pub mod fd;
-pub mod fs;
-pub mod io;
-#[path = "../unsupported/mutex.rs"]
-pub mod mutex;
-pub mod net;
-pub mod os;
-pub use crate::sys_common::os_str_bytes as os_str;
-pub mod ext;
-pub mod path;
-pub mod pipe;
-pub mod process;
-#[path = "../unsupported/rwlock.rs"]
-pub mod rwlock;
-#[path = "../unsupported/stack_overflow.rs"]
-pub mod stack_overflow;
-pub mod stdio;
-pub mod thread;
-#[path = "../unsupported/thread_local_dtor.rs"]
-pub mod thread_local_dtor;
-#[path = "../unsupported/thread_local_key.rs"]
-pub mod thread_local_key;
-pub mod time;
-
-#[path = "../unsupported/common.rs"]
-#[allow(unused)]
-mod common;
-pub use common::*;
-
-pub fn decode_error_kind(errno: i32) -> std_io::ErrorKind {
- use std_io::ErrorKind::*;
- if errno > u16::MAX as i32 || errno < 0 {
- return Other;
- }
- match errno as u16 {
- wasi::ERRNO_CONNREFUSED => ConnectionRefused,
- wasi::ERRNO_CONNRESET => ConnectionReset,
- wasi::ERRNO_PERM | wasi::ERRNO_ACCES => PermissionDenied,
- wasi::ERRNO_PIPE => BrokenPipe,
- wasi::ERRNO_NOTCONN => NotConnected,
- wasi::ERRNO_CONNABORTED => ConnectionAborted,
- wasi::ERRNO_ADDRNOTAVAIL => AddrNotAvailable,
- wasi::ERRNO_ADDRINUSE => AddrInUse,
- wasi::ERRNO_NOENT => NotFound,
- wasi::ERRNO_INTR => Interrupted,
- wasi::ERRNO_INVAL => InvalidInput,
- wasi::ERRNO_TIMEDOUT => TimedOut,
- wasi::ERRNO_EXIST => AlreadyExists,
- wasi::ERRNO_AGAIN => WouldBlock,
- _ => Other,
- }
-}
-
-pub fn abort_internal() -> ! {
- unsafe { libc::abort() }
-}
-
-pub fn hashmap_random_keys() -> (u64, u64) {
- let mut ret = (0u64, 0u64);
- unsafe {
- let base = &mut ret as *mut (u64, u64) as *mut u8;
- let len = mem::size_of_val(&ret);
- wasi::random_get(base, len).expect("random_get failure");
- }
- return ret;
-}
-
-fn err2io(err: wasi::Error) -> std_io::Error {
- std_io::Error::from_raw_os_error(err.raw_error().into())
-}
diff --git a/src/libstd/sys/wasi/net.rs b/src/libstd/sys/wasi/net.rs
deleted file mode 100644
index e186453588d..00000000000
--- a/src/libstd/sys/wasi/net.rs
+++ /dev/null
@@ -1,411 +0,0 @@
-use crate::convert::TryFrom;
-use crate::fmt;
-use crate::io::{self, IoSlice, IoSliceMut};
-use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr};
-use crate::sys::fd::WasiFd;
-use crate::sys::{unsupported, Void};
-use crate::sys_common::FromInner;
-use crate::time::Duration;
-
-pub struct TcpStream {
- fd: WasiFd,
-}
-
-impl TcpStream {
- pub fn connect(_: io::Result<&SocketAddr>) -> io::Result<TcpStream> {
- unsupported()
- }
-
- pub fn connect_timeout(_: &SocketAddr, _: Duration) -> io::Result<TcpStream> {
- unsupported()
- }
-
- pub fn set_read_timeout(&self, _: Option<Duration>) -> io::Result<()> {
- unsupported()
- }
-
- pub fn set_write_timeout(&self, _: Option<Duration>) -> io::Result<()> {
- unsupported()
- }
-
- pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
- unsupported()
- }
-
- pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
- unsupported()
- }
-
- pub fn peek(&self, _: &mut [u8]) -> io::Result<usize> {
- unsupported()
- }
-
- pub fn read(&self, _: &mut [u8]) -> io::Result<usize> {
- unsupported()
- }
-
- pub fn read_vectored(&self, _: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
- unsupported()
- }
-
- pub fn is_read_vectored(&self) -> bool {
- true
- }
-
- pub fn write(&self, _: &[u8]) -> io::Result<usize> {
- unsupported()
- }
-
- pub fn write_vectored(&self, _: &[IoSlice<'_>]) -> io::Result<usize> {
- unsupported()
- }
-
- pub fn is_write_vectored(&self) -> bool {
- true
- }
-
- pub fn peer_addr(&self) -> io::Result<SocketAddr> {
- unsupported()
- }
-
- pub fn socket_addr(&self) -> io::Result<SocketAddr> {
- unsupported()
- }
-
- pub fn shutdown(&self, _: Shutdown) -> io::Result<()> {
- unsupported()
- }
-
- pub fn duplicate(&self) -> io::Result<TcpStream> {
- unsupported()
- }
-
- pub fn set_nodelay(&self, _: bool) -> io::Result<()> {
- unsupported()
- }
-
- pub fn nodelay(&self) -> io::Result<bool> {
- unsupported()
- }
-
- pub fn set_ttl(&self, _: u32) -> io::Result<()> {
- unsupported()
- }
-
- pub fn ttl(&self) -> io::Result<u32> {
- unsupported()
- }
-
- pub fn take_error(&self) -> io::Result<Option<io::Error>> {
- unsupported()
- }
-
- pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
- unsupported()
- }
-
- pub fn fd(&self) -> &WasiFd {
- &self.fd
- }
-
- pub fn into_fd(self) -> WasiFd {
- self.fd
- }
-}
-
-impl FromInner<u32> for TcpStream {
- fn from_inner(fd: u32) -> TcpStream {
- unsafe { TcpStream { fd: WasiFd::from_raw(fd) } }
- }
-}
-
-impl fmt::Debug for TcpStream {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("TcpStream").field("fd", &self.fd.as_raw()).finish()
- }
-}
-
-pub struct TcpListener {
- fd: WasiFd,
-}
-
-impl TcpListener {
- pub fn bind(_: io::Result<&SocketAddr>) -> io::Result<TcpListener> {
- unsupported()
- }
-
- pub fn socket_addr(&self) -> io::Result<SocketAddr> {
- unsupported()
- }
-
- pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
- unsupported()
- }
-
- pub fn duplicate(&self) -> io::Result<TcpListener> {
- unsupported()
- }
-
- pub fn set_ttl(&self, _: u32) -> io::Result<()> {
- unsupported()
- }
-
- pub fn ttl(&self) -> io::Result<u32> {
- unsupported()
- }
-
- pub fn set_only_v6(&self, _: bool) -> io::Result<()> {
- unsupported()
- }
-
- pub fn only_v6(&self) -> io::Result<bool> {
- unsupported()
- }
-
- pub fn take_error(&self) -> io::Result<Option<io::Error>> {
- unsupported()
- }
-
- pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
- unsupported()
- }
-
- pub fn fd(&self) -> &WasiFd {
- &self.fd
- }
-
- pub fn into_fd(self) -> WasiFd {
- self.fd
- }
-}
-
-impl FromInner<u32> for TcpListener {
- fn from_inner(fd: u32) -> TcpListener {
- unsafe { TcpListener { fd: WasiFd::from_raw(fd) } }
- }
-}
-
-impl fmt::Debug for TcpListener {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("TcpListener").field("fd", &self.fd.as_raw()).finish()
- }
-}
-
-pub struct UdpSocket {
- fd: WasiFd,
-}
-
-impl UdpSocket {
- pub fn bind(_: io::Result<&SocketAddr>) -> io::Result<UdpSocket> {
- unsupported()
- }
-
- pub fn peer_addr(&self) -> io::Result<SocketAddr> {
- unsupported()
- }
-
- pub fn socket_addr(&self) -> io::Result<SocketAddr> {
- unsupported()
- }
-
- pub fn recv_from(&self, _: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
- unsupported()
- }
-
- pub fn peek_from(&self, _: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
- unsupported()
- }
-
- pub fn send_to(&self, _: &[u8], _: &SocketAddr) -> io::Result<usize> {
- unsupported()
- }
-
- pub fn duplicate(&self) -> io::Result<UdpSocket> {
- unsupported()
- }
-
- pub fn set_read_timeout(&self, _: Option<Duration>) -> io::Result<()> {
- unsupported()
- }
-
- pub fn set_write_timeout(&self, _: Option<Duration>) -> io::Result<()> {
- unsupported()
- }
-
- pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
- unsupported()
- }
-
- pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
- unsupported()
- }
-
- pub fn set_broadcast(&self, _: bool) -> io::Result<()> {
- unsupported()
- }
-
- pub fn broadcast(&self) -> io::Result<bool> {
- unsupported()
- }
-
- pub fn set_multicast_loop_v4(&self, _: bool) -> io::Result<()> {
- unsupported()
- }
-
- pub fn multicast_loop_v4(&self) -> io::Result<bool> {
- unsupported()
- }
-
- pub fn set_multicast_ttl_v4(&self, _: u32) -> io::Result<()> {
- unsupported()
- }
-
- pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
- unsupported()
- }
-
- pub fn set_multicast_loop_v6(&self, _: bool) -> io::Result<()> {
- unsupported()
- }
-
- pub fn multicast_loop_v6(&self) -> io::Result<bool> {
- unsupported()
- }
-
- pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> {
- unsupported()
- }
-
- pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> {
- unsupported()
- }
-
- pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> {
- unsupported()
- }
-
- pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> {
- unsupported()
- }
-
- pub fn set_ttl(&self, _: u32) -> io::Result<()> {
- unsupported()
- }
-
- pub fn ttl(&self) -> io::Result<u32> {
- unsupported()
- }
-
- pub fn take_error(&self) -> io::Result<Option<io::Error>> {
- unsupported()
- }
-
- pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
- unsupported()
- }
-
- pub fn recv(&self, _: &mut [u8]) -> io::Result<usize> {
- unsupported()
- }
-
- pub fn peek(&self, _: &mut [u8]) -> io::Result<usize> {
- unsupported()
- }
-
- pub fn send(&self, _: &[u8]) -> io::Result<usize> {
- unsupported()
- }
-
- pub fn connect(&self, _: io::Result<&SocketAddr>) -> io::Result<()> {
- unsupported()
- }
-
- pub fn fd(&self) -> &WasiFd {
- &self.fd
- }
-
- pub fn into_fd(self) -> WasiFd {
- self.fd
- }
-}
-
-impl FromInner<u32> for UdpSocket {
- fn from_inner(fd: u32) -> UdpSocket {
- unsafe { UdpSocket { fd: WasiFd::from_raw(fd) } }
- }
-}
-
-impl fmt::Debug for UdpSocket {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("UdpSocket").field("fd", &self.fd.as_raw()).finish()
- }
-}
-
-pub struct LookupHost(Void);
-
-impl LookupHost {
- pub fn port(&self) -> u16 {
- match self.0 {}
- }
-}
-
-impl Iterator for LookupHost {
- type Item = SocketAddr;
- fn next(&mut self) -> Option<SocketAddr> {
- match self.0 {}
- }
-}
-
-impl<'a> TryFrom<&'a str> for LookupHost {
- type Error = io::Error;
-
- fn try_from(_v: &'a str) -> io::Result<LookupHost> {
- unsupported()
- }
-}
-
-impl<'a> TryFrom<(&'a str, u16)> for LookupHost {
- type Error = io::Error;
-
- fn try_from(_v: (&'a str, u16)) -> io::Result<LookupHost> {
- unsupported()
- }
-}
-
-#[allow(nonstandard_style)]
-pub mod netc {
- pub const AF_INET: u8 = 0;
- pub const AF_INET6: u8 = 1;
- pub type sa_family_t = u8;
-
- #[derive(Copy, Clone)]
- pub struct in_addr {
- pub s_addr: u32,
- }
-
- #[derive(Copy, Clone)]
- pub struct sockaddr_in {
- pub sin_family: sa_family_t,
- pub sin_port: u16,
- pub sin_addr: in_addr,
- }
-
- #[derive(Copy, Clone)]
- pub struct in6_addr {
- pub s6_addr: [u8; 16],
- }
-
- #[derive(Copy, Clone)]
- pub struct sockaddr_in6 {
- pub sin6_family: sa_family_t,
- pub sin6_port: u16,
- pub sin6_addr: in6_addr,
- pub sin6_flowinfo: u32,
- pub sin6_scope_id: u32,
- }
-
- #[derive(Copy, Clone)]
- pub struct sockaddr {}
-
- pub type socklen_t = usize;
-}
diff --git a/src/libstd/sys/wasi/os.rs b/src/libstd/sys/wasi/os.rs
deleted file mode 100644
index 8052c0aa8a8..00000000000
--- a/src/libstd/sys/wasi/os.rs
+++ /dev/null
@@ -1,201 +0,0 @@
-use crate::any::Any;
-use crate::error::Error as StdError;
-use crate::ffi::{CStr, CString, OsStr, OsString};
-use crate::fmt;
-use crate::io;
-use crate::marker::PhantomData;
-use crate::os::wasi::prelude::*;
-use crate::path::{self, PathBuf};
-use crate::str;
-use crate::sys::memchr;
-use crate::sys::{unsupported, Void};
-use crate::vec;
-
-#[cfg(not(target_feature = "atomics"))]
-pub unsafe fn env_lock() -> impl Any {
- // No need for a lock if we're single-threaded, but this function will need
- // to get implemented for multi-threaded scenarios
-}
-
-pub fn errno() -> i32 {
- extern "C" {
- #[thread_local]
- static errno: libc::c_int;
- }
-
- unsafe { errno as i32 }
-}
-
-pub fn error_string(errno: i32) -> String {
- let mut buf = [0 as libc::c_char; 1024];
-
- let p = buf.as_mut_ptr();
- unsafe {
- if libc::strerror_r(errno as libc::c_int, p, buf.len()) < 0 {
- panic!("strerror_r failure");
- }
- str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_owned()
- }
-}
-
-pub fn getcwd() -> io::Result<PathBuf> {
- unsupported()
-}
-
-pub fn chdir(_: &path::Path) -> io::Result<()> {
- unsupported()
-}
-
-pub struct SplitPaths<'a>(&'a Void);
-
-pub fn split_paths(_unparsed: &OsStr) -> SplitPaths<'_> {
- panic!("unsupported")
-}
-
-impl<'a> Iterator for SplitPaths<'a> {
- type Item = PathBuf;
- fn next(&mut self) -> Option<PathBuf> {
- match *self.0 {}
- }
-}
-
-#[derive(Debug)]
-pub struct JoinPathsError;
-
-pub fn join_paths<I, T>(_paths: I) -> Result<OsString, JoinPathsError>
-where
- I: Iterator<Item = T>,
- T: AsRef<OsStr>,
-{
- Err(JoinPathsError)
-}
-
-impl fmt::Display for JoinPathsError {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- "not supported on wasm yet".fmt(f)
- }
-}
-
-impl StdError for JoinPathsError {
- #[allow(deprecated)]
- fn description(&self) -> &str {
- "not supported on wasm yet"
- }
-}
-
-pub fn current_exe() -> io::Result<PathBuf> {
- unsupported()
-}
-pub struct Env {
- iter: vec::IntoIter<(OsString, OsString)>,
- _dont_send_or_sync_me: PhantomData<*mut ()>,
-}
-
-impl Iterator for Env {
- type Item = (OsString, OsString);
- fn next(&mut self) -> Option<(OsString, OsString)> {
- self.iter.next()
- }
- fn size_hint(&self) -> (usize, Option<usize>) {
- self.iter.size_hint()
- }
-}
-
-pub fn env() -> Env {
- unsafe {
- let _guard = env_lock();
- let mut environ = libc::environ;
- let mut result = Vec::new();
- if !environ.is_null() {
- while !(*environ).is_null() {
- if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) {
- result.push(key_value);
- }
- environ = environ.add(1);
- }
- }
- return Env { iter: result.into_iter(), _dont_send_or_sync_me: PhantomData };
- }
-
- // See src/libstd/sys/unix/os.rs, same as that
- fn parse(input: &[u8]) -> Option<(OsString, OsString)> {
- if input.is_empty() {
- return None;
- }
- let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
- pos.map(|p| {
- (
- OsStringExt::from_vec(input[..p].to_vec()),
- OsStringExt::from_vec(input[p + 1..].to_vec()),
- )
- })
- }
-}
-
-pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
- let k = CString::new(k.as_bytes())?;
- unsafe {
- let _guard = env_lock();
- let s = libc::getenv(k.as_ptr()) as *const libc::c_char;
- let ret = if s.is_null() {
- None
- } else {
- Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
- };
- Ok(ret)
- }
-}
-
-pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
- let k = CString::new(k.as_bytes())?;
- let v = CString::new(v.as_bytes())?;
-
- unsafe {
- let _guard = env_lock();
- cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(drop)
- }
-}
-
-pub fn unsetenv(n: &OsStr) -> io::Result<()> {
- let nbuf = CString::new(n.as_bytes())?;
-
- unsafe {
- let _guard = env_lock();
- cvt(libc::unsetenv(nbuf.as_ptr())).map(drop)
- }
-}
-
-pub fn temp_dir() -> PathBuf {
- panic!("no filesystem on wasm")
-}
-
-pub fn home_dir() -> Option<PathBuf> {
- None
-}
-
-pub fn exit(code: i32) -> ! {
- unsafe { libc::exit(code) }
-}
-
-pub fn getpid() -> u32 {
- panic!("unsupported");
-}
-
-#[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! { i8 i16 i32 i64 isize }
-
-fn cvt<T: IsMinusOne>(t: T) -> io::Result<T> {
- if t.is_minus_one() { Err(io::Error::last_os_error()) } else { Ok(t) }
-}
diff --git a/src/libstd/sys/wasi/path.rs b/src/libstd/sys/wasi/path.rs
deleted file mode 100644
index 840a7ae0426..00000000000
--- a/src/libstd/sys/wasi/path.rs
+++ /dev/null
@@ -1,19 +0,0 @@
-use crate::ffi::OsStr;
-use crate::path::Prefix;
-
-#[inline]
-pub fn is_sep_byte(b: u8) -> bool {
- b == b'/'
-}
-
-#[inline]
-pub fn is_verbatim_sep(b: u8) -> bool {
- b == b'/'
-}
-
-pub fn parse_prefix(_: &OsStr) -> Option<Prefix<'_>> {
- None
-}
-
-pub const MAIN_SEP_STR: &str = "/";
-pub const MAIN_SEP: char = '/';
diff --git a/src/libstd/sys/wasi/pipe.rs b/src/libstd/sys/wasi/pipe.rs
deleted file mode 100644
index 10d0925823e..00000000000
--- a/src/libstd/sys/wasi/pipe.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-use crate::io::{self, IoSlice, IoSliceMut};
-use crate::sys::Void;
-
-pub struct AnonPipe(Void);
-
-impl AnonPipe {
- pub fn read(&self, _buf: &mut [u8]) -> io::Result<usize> {
- match self.0 {}
- }
-
- pub fn read_vectored(&self, _bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
- match self.0 {}
- }
-
- pub fn is_read_vectored(&self) -> bool {
- match self.0 {}
- }
-
- pub fn write(&self, _buf: &[u8]) -> io::Result<usize> {
- match self.0 {}
- }
-
- pub fn write_vectored(&self, _bufs: &[IoSlice<'_>]) -> io::Result<usize> {
- match self.0 {}
- }
-
- pub fn is_write_vectored(&self) -> bool {
- match self.0 {}
- }
-
- pub fn diverge(&self) -> ! {
- match self.0 {}
- }
-}
-
-pub fn read2(p1: AnonPipe, _v1: &mut Vec<u8>, _p2: AnonPipe, _v2: &mut Vec<u8>) -> io::Result<()> {
- match p1.0 {}
-}
diff --git a/src/libstd/sys/wasi/process.rs b/src/libstd/sys/wasi/process.rs
deleted file mode 100644
index 7156c9ab92f..00000000000
--- a/src/libstd/sys/wasi/process.rs
+++ /dev/null
@@ -1,149 +0,0 @@
-use crate::ffi::OsStr;
-use crate::fmt;
-use crate::io;
-use crate::sys::fs::File;
-use crate::sys::pipe::AnonPipe;
-use crate::sys::{unsupported, Void};
-use crate::sys_common::process::CommandEnv;
-
-pub use crate::ffi::OsString as EnvKey;
-
-////////////////////////////////////////////////////////////////////////////////
-// Command
-////////////////////////////////////////////////////////////////////////////////
-
-pub struct Command {
- env: CommandEnv,
-}
-
-// passed back to std::process with the pipes connected to the child, if any
-// were requested
-pub struct StdioPipes {
- pub stdin: Option<AnonPipe>,
- pub stdout: Option<AnonPipe>,
- pub stderr: Option<AnonPipe>,
-}
-
-pub enum Stdio {
- Inherit,
- Null,
- MakePipe,
-}
-
-impl Command {
- pub fn new(_program: &OsStr) -> Command {
- Command { env: Default::default() }
- }
-
- pub fn arg(&mut self, _arg: &OsStr) {}
-
- pub fn env_mut(&mut self) -> &mut CommandEnv {
- &mut self.env
- }
-
- pub fn cwd(&mut self, _dir: &OsStr) {}
-
- pub fn stdin(&mut self, _stdin: Stdio) {}
-
- pub fn stdout(&mut self, _stdout: Stdio) {}
-
- pub fn stderr(&mut self, _stderr: Stdio) {}
-
- pub fn spawn(
- &mut self,
- _default: Stdio,
- _needs_stdin: bool,
- ) -> io::Result<(Process, StdioPipes)> {
- unsupported()
- }
-}
-
-impl From<AnonPipe> for Stdio {
- fn from(pipe: AnonPipe) -> Stdio {
- pipe.diverge()
- }
-}
-
-impl From<File> for Stdio {
- fn from(_file: File) -> Stdio {
- panic!("unsupported")
- }
-}
-
-impl fmt::Debug for Command {
- fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
- Ok(())
- }
-}
-
-pub struct ExitStatus(Void);
-
-impl ExitStatus {
- pub fn success(&self) -> bool {
- match self.0 {}
- }
-
- pub fn code(&self) -> Option<i32> {
- match self.0 {}
- }
-}
-
-impl Clone for ExitStatus {
- fn clone(&self) -> ExitStatus {
- match self.0 {}
- }
-}
-
-impl Copy for ExitStatus {}
-
-impl PartialEq for ExitStatus {
- fn eq(&self, _other: &ExitStatus) -> bool {
- match self.0 {}
- }
-}
-
-impl Eq for ExitStatus {}
-
-impl fmt::Debug for ExitStatus {
- fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
- match self.0 {}
- }
-}
-
-impl fmt::Display for ExitStatus {
- fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
- match self.0 {}
- }
-}
-
-#[derive(PartialEq, Eq, Clone, Copy, Debug)]
-pub struct ExitCode(bool);
-
-impl ExitCode {
- pub const SUCCESS: ExitCode = ExitCode(false);
- pub const FAILURE: ExitCode = ExitCode(true);
-
- pub fn as_i32(&self) -> i32 {
- self.0 as i32
- }
-}
-
-pub struct Process(Void);
-
-impl Process {
- pub fn id(&self) -> u32 {
- match self.0 {}
- }
-
- pub fn kill(&mut self) -> io::Result<()> {
- match self.0 {}
- }
-
- pub fn wait(&mut self) -> io::Result<ExitStatus> {
- match self.0 {}
- }
-
- pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
- match self.0 {}
- }
-}
diff --git a/src/libstd/sys/wasi/stdio.rs b/src/libstd/sys/wasi/stdio.rs
deleted file mode 100644
index 78e3911dc4e..00000000000
--- a/src/libstd/sys/wasi/stdio.rs
+++ /dev/null
@@ -1,102 +0,0 @@
-use crate::io::{self, IoSlice, IoSliceMut};
-use crate::mem::ManuallyDrop;
-use crate::sys::fd::WasiFd;
-
-pub struct Stdin;
-pub struct Stdout;
-pub struct Stderr;
-
-impl Stdin {
- pub fn new() -> io::Result<Stdin> {
- Ok(Stdin)
- }
-
- #[inline]
- pub fn as_raw_fd(&self) -> u32 {
- 0
- }
-}
-
-impl io::Read for Stdin {
- fn read(&mut self, data: &mut [u8]) -> io::Result<usize> {
- self.read_vectored(&mut [IoSliceMut::new(data)])
- }
-
- fn read_vectored(&mut self, data: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
- ManuallyDrop::new(unsafe { WasiFd::from_raw(self.as_raw_fd()) }).read(data)
- }
-
- #[inline]
- fn is_read_vectored(&self) -> bool {
- true
- }
-}
-
-impl Stdout {
- pub fn new() -> io::Result<Stdout> {
- Ok(Stdout)
- }
-
- #[inline]
- pub fn as_raw_fd(&self) -> u32 {
- 1
- }
-}
-
-impl io::Write for Stdout {
- fn write(&mut self, data: &[u8]) -> io::Result<usize> {
- self.write_vectored(&[IoSlice::new(data)])
- }
-
- fn write_vectored(&mut self, data: &[IoSlice<'_>]) -> io::Result<usize> {
- ManuallyDrop::new(unsafe { WasiFd::from_raw(self.as_raw_fd()) }).write(data)
- }
-
- #[inline]
- fn is_write_vectored(&self) -> bool {
- true
- }
- fn flush(&mut self) -> io::Result<()> {
- Ok(())
- }
-}
-
-impl Stderr {
- pub fn new() -> io::Result<Stderr> {
- Ok(Stderr)
- }
-
- #[inline]
- pub fn as_raw_fd(&self) -> u32 {
- 2
- }
-}
-
-impl io::Write for Stderr {
- fn write(&mut self, data: &[u8]) -> io::Result<usize> {
- self.write_vectored(&[IoSlice::new(data)])
- }
-
- fn write_vectored(&mut self, data: &[IoSlice<'_>]) -> io::Result<usize> {
- ManuallyDrop::new(unsafe { WasiFd::from_raw(self.as_raw_fd()) }).write(data)
- }
-
- #[inline]
- fn is_write_vectored(&self) -> bool {
- true
- }
-
- fn flush(&mut self) -> io::Result<()> {
- Ok(())
- }
-}
-
-pub const STDIN_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE;
-
-pub fn is_ebadf(err: &io::Error) -> bool {
- err.raw_os_error() == Some(wasi::ERRNO_BADF.into())
-}
-
-pub fn panic_output() -> Option<impl io::Write> {
- Stderr::new().ok()
-}
diff --git a/src/libstd/sys/wasi/thread.rs b/src/libstd/sys/wasi/thread.rs
deleted file mode 100644
index 0d39b1cec32..00000000000
--- a/src/libstd/sys/wasi/thread.rs
+++ /dev/null
@@ -1,72 +0,0 @@
-use crate::ffi::CStr;
-use crate::io;
-use crate::mem;
-use crate::sys::{unsupported, Void};
-use crate::time::Duration;
-
-pub struct Thread(Void);
-
-pub const DEFAULT_MIN_STACK_SIZE: usize = 4096;
-
-impl Thread {
- // unsafe: see thread::Builder::spawn_unchecked for safety requirements
- pub unsafe fn new(_stack: usize, _p: Box<dyn FnOnce()>) -> io::Result<Thread> {
- unsupported()
- }
-
- pub fn yield_now() {
- let ret = unsafe { wasi::sched_yield() };
- debug_assert_eq!(ret, Ok(()));
- }
-
- pub fn set_name(_name: &CStr) {
- // nope
- }
-
- pub fn sleep(dur: Duration) {
- let nanos = dur.as_nanos();
- assert!(nanos <= u64::MAX as u128);
-
- const USERDATA: wasi::Userdata = 0x0123_45678;
-
- let clock = wasi::SubscriptionClock {
- id: wasi::CLOCKID_MONOTONIC,
- timeout: nanos as u64,
- precision: 0,
- flags: 0,
- };
-
- let in_ = wasi::Subscription {
- userdata: USERDATA,
- r#type: wasi::EVENTTYPE_CLOCK,
- u: wasi::SubscriptionU { clock },
- };
- unsafe {
- let mut event: wasi::Event = mem::zeroed();
- let res = wasi::poll_oneoff(&in_, &mut event, 1);
- match (res, event) {
- (
- Ok(1),
- wasi::Event {
- userdata: USERDATA, error: 0, r#type: wasi::EVENTTYPE_CLOCK, ..
- },
- ) => {}
- _ => panic!("thread::sleep(): unexpected result of poll_oneoff"),
- }
- }
- }
-
- pub fn join(self) {
- match self.0 {}
- }
-}
-
-pub mod guard {
- pub type Guard = !;
- pub unsafe fn current() -> Option<Guard> {
- None
- }
- pub unsafe fn init() -> Option<Guard> {
- None
- }
-}
diff --git a/src/libstd/sys/wasi/time.rs b/src/libstd/sys/wasi/time.rs
deleted file mode 100644
index 80ec317b5a2..00000000000
--- a/src/libstd/sys/wasi/time.rs
+++ /dev/null
@@ -1,67 +0,0 @@
-use crate::time::Duration;
-
-#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
-pub struct Instant(Duration);
-
-#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
-pub struct SystemTime(Duration);
-
-pub const UNIX_EPOCH: SystemTime = SystemTime(Duration::from_secs(0));
-
-fn current_time(clock: u32) -> Duration {
- let ts = unsafe {
- wasi::clock_time_get(
- clock, 1, // precision... seems ignored though?
- )
- .unwrap()
- };
- Duration::new((ts / 1_000_000_000) as u64, (ts % 1_000_000_000) as u32)
-}
-
-impl Instant {
- pub fn now() -> Instant {
- Instant(current_time(wasi::CLOCKID_MONOTONIC))
- }
-
- pub const fn zero() -> Instant {
- Instant(Duration::from_secs(0))
- }
-
- pub fn actually_monotonic() -> bool {
- true
- }
-
- pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
- self.0.checked_sub(other.0)
- }
-
- pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
- Some(Instant(self.0.checked_add(*other)?))
- }
-
- pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
- Some(Instant(self.0.checked_sub(*other)?))
- }
-}
-
-impl SystemTime {
- pub fn now() -> SystemTime {
- SystemTime(current_time(wasi::CLOCKID_REALTIME))
- }
-
- pub fn from_wasi_timestamp(ts: wasi::Timestamp) -> SystemTime {
- SystemTime(Duration::from_nanos(ts))
- }
-
- pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
- self.0.checked_sub(other.0).ok_or_else(|| other.0 - self.0)
- }
-
- pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
- Some(SystemTime(self.0.checked_add(*other)?))
- }
-
- pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
- Some(SystemTime(self.0.checked_sub(*other)?))
- }
-}