Skip to content

Commit ace7124

Browse files
committedMar 29, 2019
Add a new wasm32-unknown-wasi target
This commit adds a new wasm32-based target distributed through rustup, supported in the standard library, and implemented in the compiler. The `wasm32-unknown-wasi` target is intended to be a WebAssembly target which matches the [WASI proposal recently announced.][LINK]. In summary the WASI target is an effort to define a standard set of syscalls for WebAssembly modules, allowing WebAssembly modules to not only be portable across architectures but also be portable across environments implementing this standard set of system calls. The wasi target in libstd is still somewhat bare bones. This PR does not fill out the filesystem, networking, threads, etc. Instead it only provides the most basic of integration with the wasi syscalls, enabling features like: * `Instant::now` and `SystemTime::now` work * `env::args` is hooked up * `env::vars` will look up environment variables * `println!` will print to standard out * `process::{exit, abort}` should be hooked up appropriately None of these APIs can work natively on the `wasm32-unknown-unknown` target, but with the assumption of the WASI set of syscalls we're able to provide implementations of these syscalls that engines can implement. Currently the primary engine implementing wasi is [wasmtime], but more will surely emerge! In terms of future development of libstd, I think this is something we'll probably want to discuss. The purpose of the WASI target is to provide a standardized set of syscalls, but it's *also* to provide a standard C sysroot for compiling C/C++ programs. This means it's intended that functions like `read` and `write` are implemented for this target with a relatively standard definition and implementation. It's unclear, therefore, how we want to expose file descriptors and how we'll want to implement system primitives. For example should `std::fs::File` have a libc-based file descriptor underneath it? The raw wasi file descriptor? We'll see! Currently these details are all intentionally hidden and things we can change over time. A `WasiFd` sample struct was added to the standard library as part of this commit, but it's not currently used. It shows how all the wasi syscalls could be ergonomically bound in Rust, and they offer a possible implementation of primitives like `std::fs::File` if we bind wasi file descriptors exactly. Apart from the standard library, there's also the matter of how this target is integrated with respect to its C standard library. The reference sysroot, for example, provides managment of standard unix file descriptors and also standard APIs like `open` (as opposed to the relative `openat` inspiration for the wasi ssycalls). Currently the standard library relies on the C sysroot symbols for operations such as environment management, process exit, and `read`/`write` of stdio fds. We want these operations in Rust to be interoperable with C if they're used in the same process. Put another way, if Rust and C are linked into the same WebAssembly binary they should work together, but that requires that the same C standard library is used. We also, however, want the `wasm32-unknown-wasi` target to be usable-by-default with the Rust compiler without requiring a separate toolchain to get downloaded and configured. With that in mind, there's two modes of operation for the `wasm32-unknown-wasi` target: 1. By default the C standard library is statically provided inside of `liblibc.rlib` distributed as part of the sysroot. This means that you can `rustc foo.wasm --target wasm32-unknown-unknown` and you're good to go, a fully workable wasi binary pops out. This is incompatible with linking in C code, however, which may be compiled against a different sysroot than the Rust code was previously compiled against. In this mode the default of `rust-lld` is used to link binaries. 2. For linking with C code, the `-C target-feature=-crt-static` flag needs to be passed. This takes inspiration from the musl target for this flag, but the idea is that you're no longer using the provided static C runtime, but rather one will be provided externally. This flag is intended to also get coupled with an external `clang` compiler configured with its own sysroot. Therefore you'll typically use this flag with `-C linker=/path/to/clang-script-wrapper`. Using this mode the Rust code will continue to reference standard C symbols, but the definition will be pulled in by the linker configured. Alright so that's all the current state of this PR. I suspect we'll definitely want to discuss this before landing of course! This PR is coupled with libc changes as well which I'll be posting shortly. [LINK]: [wasmtime]:
1 parent e782d79 commit ace7124

33 files changed

+2226
-82
lines changed
 

‎Cargo.lock

+77-77
Large diffs are not rendered by default.

‎config.toml.example

+3
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,9 @@
477477
# linked binaries
478478
#musl-root = "..."
479479

480+
# The root location of the `wasm32-unknown-wasi` sysroot.
481+
#wasi-root = "..."
482+
480483
# Used in testing for configuring where the QEMU images are located, you
481484
# probably don't want to use this.
482485
#qemu-rootfs = "..."

‎src/bootstrap/bin/rustc.rs

+8-2
Original file line numberDiff line numberDiff line change
@@ -122,8 +122,8 @@ fn main() {
122122
cmd.arg("-Cprefer-dynamic");
123123
}
124124

125-
// Help the libc crate compile by assisting it in finding the MUSL
126-
// native libraries.
125+
// Help the libc crate compile by assisting it in finding various
126+
// sysroot native libraries.
127127
if let Some(s) = env::var_os("MUSL_ROOT") {
128128
if target.contains("musl") {
129129
let mut root = OsString::from("native=");
@@ -132,6 +132,12 @@ fn main() {
132132
cmd.arg("-L").arg(&root);
133133
}
134134
}
135+
if let Some(s) = env::var_os("WASI_ROOT") {
136+
let mut root = OsString::from("native=");
137+
root.push(&s);
138+
root.push("/lib/wasm32-wasi");
139+
cmd.arg("-L").arg(&root);
140+
}
135141

136142
// Override linker if necessary.
137143
if let Ok(target_linker) = env::var("RUSTC_TARGET_LINKER") {

‎src/bootstrap/compile.rs

+13
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,13 @@ fn copy_third_party_objects(builder: &Builder<'_>, compiler: &Compiler, target:
129129
&libdir.join(obj),
130130
);
131131
}
132+
} else if target.ends_with("-wasi") {
133+
for &obj in &["crt1.o"] {
134+
builder.copy(
135+
&builder.wasi_root(target).unwrap().join("lib/wasm32-wasi").join(obj),
136+
&libdir.join(obj),
137+
);
138+
}
132139
}
133140

134141
// Copies libunwind.a compiled to be linked wit x86_64-fortanix-unknown-sgx.
@@ -190,6 +197,12 @@ pub fn std_cargo(builder: &Builder<'_>,
190197
cargo.env("MUSL_ROOT", p);
191198
}
192199
}
200+
201+
if target.ends_with("-wasi") {
202+
if let Some(p) = builder.wasi_root(target) {
203+
cargo.env("WASI_ROOT", p);
204+
}
205+
}
193206
}
194207
}
195208

‎src/bootstrap/config.rs

+3
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,7 @@ pub struct Target {
169169
pub ndk: Option<PathBuf>,
170170
pub crt_static: Option<bool>,
171171
pub musl_root: Option<PathBuf>,
172+
pub wasi_root: Option<PathBuf>,
172173
pub qemu_rootfs: Option<PathBuf>,
173174
pub no_std: bool,
174175
}
@@ -344,6 +345,7 @@ struct TomlTarget {
344345
android_ndk: Option<String>,
345346
crt_static: Option<bool>,
346347
musl_root: Option<String>,
348+
wasi_root: Option<String>,
347349
qemu_rootfs: Option<String>,
348350
}
349351

@@ -605,6 +607,7 @@ impl Config {
605607
target.linker = cfg.linker.clone().map(PathBuf::from);
606608
target.crt_static = cfg.crt_static.clone();
607609
target.musl_root = cfg.musl_root.clone().map(PathBuf::from);
610+
target.wasi_root = cfg.wasi_root.clone().map(PathBuf::from);
608611
target.qemu_rootfs = cfg.qemu_rootfs.clone().map(PathBuf::from);
609612

610613
config.target_config.insert(INTERNER.intern_string(triple.clone()), target);

‎src/bootstrap/lib.rs

+7
Original file line numberDiff line numberDiff line change
@@ -861,6 +861,13 @@ impl Build {
861861
.map(|p| &**p)
862862
}
863863

864+
/// Returns the sysroot for the wasi target, if defined
865+
fn wasi_root(&self, target: Interned<String>) -> Option<&Path> {
866+
self.config.target_config.get(&target)
867+
.and_then(|t| t.wasi_root.as_ref())
868+
.map(|p| &**p)
869+
}
870+
864871
/// Returns `true` if this is a no-std `target`, if defined
865872
fn no_std(&self, target: Interned<String>) -> Option<bool> {
866873
self.config.target_config.get(&target)

‎src/ci/docker/dist-various-2/Dockerfile

+6-1
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ COPY dist-various-2/build-x86_64-fortanix-unknown-sgx-toolchain.sh /tmp/
3434
# Any update to the commit id here, should cause the container image to be re-built from this point on.
3535
RUN /tmp/build-x86_64-fortanix-unknown-sgx-toolchain.sh "53b586346f2c7870e20b170decdc30729d97c42b"
3636

37+
COPY dist-various-2/build-wasi-toolchain.sh /tmp/
38+
RUN /tmp/build-wasi-toolchain.sh
39+
3740
COPY scripts/sccache.sh /scripts/
3841
RUN sh /scripts/sccache.sh
3942

@@ -66,6 +69,7 @@ ENV TARGETS=x86_64-fuchsia
6669
ENV TARGETS=$TARGETS,aarch64-fuchsia
6770
ENV TARGETS=$TARGETS,sparcv9-sun-solaris
6871
ENV TARGETS=$TARGETS,wasm32-unknown-unknown
72+
ENV TARGETS=$TARGETS,wasm32-unknown-wasi
6973
ENV TARGETS=$TARGETS,x86_64-sun-solaris
7074
ENV TARGETS=$TARGETS,x86_64-unknown-linux-gnux32
7175
ENV TARGETS=$TARGETS,x86_64-unknown-cloudabi
@@ -74,5 +78,6 @@ ENV TARGETS=$TARGETS,nvptx64-nvidia-cuda
7478

7579
ENV X86_FORTANIX_SGX_LIBS="/x86_64-fortanix-unknown-sgx/lib/"
7680

77-
ENV RUST_CONFIGURE_ARGS --enable-extended --enable-lld --disable-docs
81+
ENV RUST_CONFIGURE_ARGS --enable-extended --enable-lld --disable-docs \
82+
--set target.wasm32-unknown-wasi.wasi-root=/wasm32-unknown-wasi
7883
ENV SCRIPT python2.7 ../x.py dist --target $TARGETS
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
#!/bin/sh
2+
#
3+
# ignore-tidy-linelength
4+
5+
set -ex
6+
7+
# Originally from https://releases.llvm.org/8.0.0/clang+llvm-8.0.0-x86_64-linux-gnu-ubuntu-14.04.tar.xz
8+
curl https://s3-us-west-1.amazonaws.com/rust-lang-ci2/rust-ci-mirror/clang%2Bllvm-8.0.0-x86_64-linux-gnu-ubuntu-14.04.tar.xz | \
9+
tar xJf -
10+
export PATH=`pwd`/clang+llvm-8.0.0-x86_64-linux-gnu-ubuntu-14.04/bin:$PATH
11+
12+
git clone https://github.com/CraneStation/wasi-sysroot
13+
14+
cd wasi-sysroot
15+
git reset --hard 320054e84f8f2440def3b1c8700cedb8fd697bf8
16+
make -j$(nproc) INSTALL_DIR=/wasm32-unknown-wasi install
17+
18+
cd ..
19+
rm -rf reference-sysroot-wasi
20+
rm -rf clang+llvm*

‎src/librustc_target/spec/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,7 @@ supported_targets! {
444444
("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
445445
("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
446446
("wasm32-unknown-unknown", wasm32_unknown_unknown),
447+
("wasm32-unknown-wasi", wasm32_unknown_wasi),
447448
("wasm32-experimental-emscripten", wasm32_experimental_emscripten),
448449

449450
("thumbv6m-none-eabi", thumbv6m_none_eabi),
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
//! The `wasm32-unknown-wasi` target is a new and still (as of March 2019)
2+
//! experimental target. The definition in this file is likely to be tweaked
3+
//! over time and shouldn't be relied on too much.
4+
//!
5+
//! The `wasi` target is a proposal to define a standardized set of syscalls
6+
//! that WebAssembly files can interoperate with. This set of syscalls is
7+
//! intended to empower WebAssembly binaries with native capabilities such as
8+
//! filesystem access, network access, etc.
9+
//!
10+
//! You can see more about the proposal at https://wasi.dev
11+
//!
12+
//! The Rust target definition here is interesting in a few ways. We want to
13+
//! serve two use cases here with this target:
14+
//!
15+
//! * First, we want Rust usage of the target to be as hassle-free as possible,
16+
//! ideally avoiding the need to configure and install a local
17+
//! wasm32-unknown-wasi toolchain.
18+
//!
19+
//! * Second, one of the primary use cases of LLVM's new wasm backend and the
20+
//! wasm support in LLD is that any compiled language can interoperate with
21+
//! any other. To that the `wasm32-unknown-wasi` target is the first with a
22+
//! viable C standard library and sysroot common definition, so we want Rust
23+
//! and C/C++ code to interoperate when compiled to `wasm32-unknown-unknown`.
24+
//!
25+
//! You'll note, however, that the two goals above are somewhat at odds with one
26+
//! another. To attempt to solve both use cases in one go we define a target
27+
//! that (ab)uses the `crt-static` target feature to indicate which one you're
28+
//! in.
29+
//!
30+
//! ## No interop with C required
31+
//!
32+
//! By default the `crt-static` target feature is enabled, and when enabled
33+
//! this means that the the bundled version of `libc.a` found in `liblibc.rlib`
34+
//! is used. This isn't intended really for interoperation with a C because it
35+
//! may be the case that Rust's bundled C library is incompatible with a
36+
//! foreign-compiled C library. In this use case, though, we use `rust-lld` and
37+
//! some copied crt startup object files to ensure that you can download the
38+
//! wasi target for Rust and you're off to the races, no further configuration
39+
//! necessary.
40+
//!
41+
//! All in all, by default, no external dependencies are required. You can
42+
//! compile `wasm32-unknown-wasi` binaries straight out of the box. You can't,
43+
//! however, reliably interoperate with C code in this mode (yet).
44+
//!
45+
//! ## Interop with C required
46+
//!
47+
//! For the second goal we repurpose the `target-feature` flag, meaning that
48+
//! you'll need to do a few things to have C/Rust code interoperate.
49+
//!
50+
//! 1. All Rust code needs to be compiled with `-C target-feature=-crt-static`,
51+
//! indicating that the bundled C standard library in the Rust sysroot will
52+
//! not be used.
53+
//!
54+
//! 2. If you're using rustc to build a linked artifact then you'll need to
55+
//! specify `-C linker` to a `clang` binary that supports
56+
//! `wasm32-unknown-wasi` and is configured with the `wasm32-unknown-wasi`
57+
//! sysroot. This will cause Rust code to be linked against the libc.a that
58+
//! the specified `clang` provides.
59+
//!
60+
//! 3. If you're building a staticlib and integrating Rust code elsewhere, then
61+
//! compiling with `-C target-feature=-crt-static` is all you need to do.
62+
//!
63+
//! You can configure the linker via Cargo using the
64+
//! `CARGO_TARGET_WASM32_UNKNOWN_WASI_LINKER` env var. Be sure to also set
65+
//! `CC_wasm32-unknown-wasi` if any crates in the dependency graph are using
66+
//! the `cc` crate.
67+
//!
68+
//! ## Remember, this is all in flux
69+
//!
70+
//! The wasi target is **very** new in its specification. It's likely going to
71+
//! be a long effort to get it standardized and stable. We'll be following it as
72+
//! best we can with this target. Don't start relying on too much here unless
73+
//! you know what you're getting in to!
74+
75+
use super::wasm32_base;
76+
use super::{LinkerFlavor, LldFlavor, Target};
77+
78+
pub fn target() -> Result<Target, String> {
79+
let mut options = wasm32_base::options();
80+
81+
options
82+
.pre_link_args
83+
.entry(LinkerFlavor::Gcc)
84+
.or_insert(Vec::new())
85+
.push("--target=wasm32-unknown-wasi".to_string());
86+
87+
// When generating an executable be sure to put the startup object at the
88+
// front so the main function is correctly hooked up.
89+
options.pre_link_objects_exe_crt.push("crt1.o".to_string());
90+
91+
// Right now this is a bit of a workaround but we're currently saying that
92+
// the target by default has a static crt which we're taking as a signal
93+
// for "use the bundled crt". If that's turned off then the system's crt
94+
// will be used, but this means that default usage of this target doesn't
95+
// need an external compiler but it's still interoperable with an external
96+
// compiler if configured correctly.
97+
options.crt_static_default = true;
98+
options.crt_static_respected = true;
99+
100+
Ok(Target {
101+
llvm_target: "wasm32-unknown-wasi".to_string(),
102+
target_endian: "little".to_string(),
103+
target_pointer_width: "32".to_string(),
104+
target_c_int_width: "32".to_string(),
105+
target_os: "unknown".to_string(),
106+
target_env: "wasi".to_string(),
107+
target_vendor: "unknown".to_string(),
108+
data_layout: "e-m:e-p:32:32-i64:64-n32:64-S128".to_string(),
109+
arch: "wasm32".to_string(),
110+
linker_flavor: LinkerFlavor::Lld(LldFlavor::Wasm),
111+
options,
112+
})
113+
}

‎src/libstd/Cargo.toml

+2-2
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ alloc = { path = "../liballoc" }
1818
panic_unwind = { path = "../libpanic_unwind", optional = true }
1919
panic_abort = { path = "../libpanic_abort" }
2020
core = { path = "../libcore" }
21-
libc = { version = "0.2.44", default-features = false, features = ['rustc-dep-of-std'] }
22-
compiler_builtins = { version = "0.1.1" }
21+
libc = { version = "0.2.51", default-features = false, features = ['rustc-dep-of-std'] }
22+
compiler_builtins = { version = "0.1.8" }
2323
profiler_builtins = { path = "../libprofiler_builtins", optional = true }
2424
unwind = { path = "../libunwind" }
2525
rustc-demangle = { version = "0.1.10", features = ['rustc-dep-of-std'] }

‎src/libstd/os/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ cfg_if! {
5151
#[cfg(target_os = "emscripten")] pub mod emscripten;
5252
#[cfg(target_os = "fuchsia")] pub mod fuchsia;
5353
#[cfg(target_os = "hermit")] pub mod hermit;
54+
#[cfg(target_env = "wasi")] pub mod wasi;
5455
#[cfg(all(target_vendor = "fortanix", target_env = "sgx"))] pub mod fortanix_sgx;
5556

5657
pub mod raw;

‎src/libstd/os/wasi.rs

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
//! WASI-specific definitions
2+
3+
#![stable(feature = "raw_ext", since = "1.1.0")]
4+
5+
#[stable(feature = "rust1", since = "1.0.0")]
6+
pub use crate::sys::ext::*;

‎src/libstd/sys/mod.rs

+3
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@ cfg_if! {
3535
} else if #[cfg(target_os = "redox")] {
3636
mod redox;
3737
pub use self::redox::*;
38+
} else if #[cfg(target_env = "wasi")] {
39+
mod wasi;
40+
pub use self::wasi::*;
3841
} else if #[cfg(target_arch = "wasm32")] {
3942
mod wasm;
4043
pub use self::wasm::*;

‎src/libstd/sys/wasi/alloc.rs

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
use crate::alloc::{GlobalAlloc, Layout, System};
2+
use crate::ptr;
3+
use crate::sys_common::alloc::{MIN_ALIGN, realloc_fallback};
4+
use libc;
5+
6+
#[stable(feature = "alloc_system_type", since = "1.28.0")]
7+
unsafe impl GlobalAlloc for System {
8+
#[inline]
9+
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
10+
if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() {
11+
libc::malloc(layout.size()) as *mut u8
12+
} else {
13+
libc::aligned_alloc(layout.size(), layout.align()) as *mut u8
14+
}
15+
}
16+
17+
#[inline]
18+
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
19+
if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() {
20+
libc::calloc(layout.size(), 1) as *mut u8
21+
} else {
22+
let ptr = self.alloc(layout.clone());
23+
if !ptr.is_null() {
24+
ptr::write_bytes(ptr, 0, layout.size());
25+
}
26+
ptr
27+
}
28+
}
29+
30+
#[inline]
31+
unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
32+
libc::free(ptr as *mut libc::c_void)
33+
}
34+
35+
#[inline]
36+
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
37+
if layout.align() <= MIN_ALIGN && layout.align() <= new_size {
38+
libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8
39+
} else {
40+
realloc_fallback(self, ptr, layout, new_size)
41+
}
42+
}
43+
}

‎src/libstd/sys/wasi/args.rs

+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
use crate::any::Any;
2+
use crate::ffi::CStr;
3+
use crate::ffi::OsString;
4+
use crate::marker::PhantomData;
5+
use crate::os::wasi::ffi::OsStringExt;
6+
use crate::ptr;
7+
use crate::vec;
8+
9+
static mut ARGC: isize = 0;
10+
static mut ARGV: *const *const u8 = ptr::null();
11+
12+
#[cfg(not(target_feature = "atomics"))]
13+
pub unsafe fn args_lock() -> impl Any {
14+
// No need for a lock if we're single-threaded, but this function will need
15+
// to get implemented for multi-threaded scenarios
16+
}
17+
18+
pub unsafe fn init(argc: isize, argv: *const *const u8) {
19+
let _guard = args_lock();
20+
ARGC = argc;
21+
ARGV = argv;
22+
}
23+
24+
pub unsafe fn cleanup() {
25+
let _guard = args_lock();
26+
ARGC = 0;
27+
ARGV = ptr::null();
28+
}
29+
30+
pub struct Args {
31+
iter: vec::IntoIter<OsString>,
32+
_dont_send_or_sync_me: PhantomData<*mut ()>,
33+
}
34+
35+
/// Returns the command line arguments
36+
pub fn args() -> Args {
37+
unsafe {
38+
let _guard = args_lock();
39+
let args = (0..ARGC)
40+
.map(|i| {
41+
let cstr = CStr::from_ptr(*ARGV.offset(i) as *const libc::c_char);
42+
OsStringExt::from_vec(cstr.to_bytes().to_vec())
43+
})
44+
.collect::<Vec<_>>();
45+
Args {
46+
iter: args.into_iter(),
47+
_dont_send_or_sync_me: PhantomData,
48+
}
49+
}
50+
}
51+
52+
impl Args {
53+
pub fn inner_debug(&self) -> &[OsString] {
54+
self.iter.as_slice()
55+
}
56+
}
57+
58+
impl Iterator for Args {
59+
type Item = OsString;
60+
fn next(&mut self) -> Option<OsString> {
61+
self.iter.next()
62+
}
63+
fn size_hint(&self) -> (usize, Option<usize>) {
64+
self.iter.size_hint()
65+
}
66+
}
67+
68+
impl ExactSizeIterator for Args {
69+
fn len(&self) -> usize {
70+
self.iter.len()
71+
}
72+
}
73+
74+
impl DoubleEndedIterator for Args {
75+
fn next_back(&mut self) -> Option<OsString> {
76+
self.iter.next_back()
77+
}
78+
}

‎src/libstd/sys/wasi/backtrace.rs

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
use crate::io;
2+
use crate::sys::unsupported;
3+
use crate::sys_common::backtrace::Frame;
4+
5+
pub struct BacktraceContext;
6+
7+
pub fn unwind_backtrace(_frames: &mut [Frame])
8+
-> io::Result<(usize, BacktraceContext)>
9+
{
10+
unsupported()
11+
}
12+
13+
pub fn resolve_symname<F>(_frame: Frame,
14+
_callback: F,
15+
_: &BacktraceContext) -> io::Result<()>
16+
where F: FnOnce(Option<&str>) -> io::Result<()>
17+
{
18+
unsupported()
19+
}
20+
21+
pub fn foreach_symbol_fileline<F>(_: Frame,
22+
_: F,
23+
_: &BacktraceContext) -> io::Result<bool>
24+
where F: FnMut(&[u8], u32) -> io::Result<()>
25+
{
26+
unsupported()
27+
}

‎src/libstd/sys/wasi/env.rs

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
pub mod os {
2+
pub const FAMILY: &str = "";
3+
pub const OS: &str = "";
4+
pub const DLL_PREFIX: &str = "";
5+
pub const DLL_SUFFIX: &str = ".wasm";
6+
pub const DLL_EXTENSION: &str = "wasm";
7+
pub const EXE_SUFFIX: &str = ".wasm";
8+
pub const EXE_EXTENSION: &str = "wasm";
9+
}

‎src/libstd/sys/wasi/ext/ffi.rs

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
//! WASI-specific extension to the primitives in the `std::ffi` module
2+
3+
#![stable(feature = "rust1", since = "1.0.0")]
4+
5+
use crate::ffi::{OsStr, OsString};
6+
use crate::mem;
7+
use crate::sys::os_str::Buf;
8+
use crate::sys_common::{FromInner, IntoInner, AsInner};
9+
10+
/// WASI-specific extensions to [`OsString`].
11+
///
12+
/// [`OsString`]: ../../../../std/ffi/struct.OsString.html
13+
#[stable(feature = "rust1", since = "1.0.0")]
14+
pub trait OsStringExt {
15+
/// Creates an `OsString` from a byte vector.
16+
#[stable(feature = "rust1", since = "1.0.0")]
17+
fn from_vec(vec: Vec<u8>) -> Self;
18+
19+
/// Yields the underlying byte vector of this `OsString`.
20+
#[stable(feature = "rust1", since = "1.0.0")]
21+
fn into_vec(self) -> Vec<u8>;
22+
}
23+
24+
#[stable(feature = "rust1", since = "1.0.0")]
25+
impl OsStringExt for OsString {
26+
fn from_vec(vec: Vec<u8>) -> OsString {
27+
FromInner::from_inner(Buf { inner: vec })
28+
}
29+
fn into_vec(self) -> Vec<u8> {
30+
self.into_inner().inner
31+
}
32+
}
33+
34+
/// WASI-specific extensions to [`OsStr`].
35+
///
36+
/// [`OsStr`]: ../../../../std/ffi/struct.OsStr.html
37+
#[stable(feature = "rust1", since = "1.0.0")]
38+
pub trait OsStrExt {
39+
#[stable(feature = "rust1", since = "1.0.0")]
40+
/// Creates an [`OsStr`] from a byte slice.
41+
///
42+
/// [`OsStr`]: ../../../ffi/struct.OsStr.html
43+
fn from_bytes(slice: &[u8]) -> &Self;
44+
45+
/// Gets the underlying byte view of the [`OsStr`] slice.
46+
///
47+
/// [`OsStr`]: ../../../ffi/struct.OsStr.html
48+
#[stable(feature = "rust1", since = "1.0.0")]
49+
fn as_bytes(&self) -> &[u8];
50+
}
51+
52+
#[stable(feature = "rust1", since = "1.0.0")]
53+
impl OsStrExt for OsStr {
54+
fn from_bytes(slice: &[u8]) -> &OsStr {
55+
unsafe { mem::transmute(slice) }
56+
}
57+
fn as_bytes(&self) -> &[u8] {
58+
&self.as_inner().inner
59+
}
60+
}
61+

‎src/libstd/sys/wasi/ext/mod.rs

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
pub mod ffi;
2+
3+
/// A prelude for conveniently writing platform-specific code.
4+
///
5+
/// Includes all extension traits, and some important type definitions.
6+
#[stable(feature = "rust1", since = "1.0.0")]
7+
pub mod prelude {
8+
#[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")]
9+
pub use crate::sys::ext::ffi::{OsStringExt, OsStrExt};
10+
}

‎src/libstd/sys/wasi/fd.rs

+322
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,322 @@
1+
#![allow(dead_code)]
2+
3+
use crate::io::{self, IoVec, IoVecMut, SeekFrom};
4+
use crate::mem;
5+
use crate::net::Shutdown;
6+
use crate::sys::cvt_wasi;
7+
use libc::{self, c_char, c_void};
8+
9+
pub struct WasiFd {
10+
fd: libc::__wasi_fd_t,
11+
}
12+
13+
// FIXME: these should probably all be fancier structs, builders, enums, etc
14+
pub type LookupFlags = u32;
15+
pub type FdFlags = u16;
16+
pub type Advice = u8;
17+
pub type Rights = u64;
18+
pub type Oflags = u16;
19+
pub type DirCookie = u64;
20+
pub type Timestamp = u64;
21+
pub type FstFlags = u16;
22+
pub type RiFlags = u16;
23+
pub type RoFlags = u16;
24+
pub type SiFlags = u16;
25+
26+
fn iovec(a: &mut [IoVecMut]) -> (*const libc::__wasi_iovec_t, usize) {
27+
assert_eq!(
28+
mem::size_of::<IoVecMut>(),
29+
mem::size_of::<libc::__wasi_iovec_t>()
30+
);
31+
assert_eq!(
32+
mem::align_of::<IoVecMut>(),
33+
mem::align_of::<libc::__wasi_iovec_t>()
34+
);
35+
(a.as_ptr() as *const libc::__wasi_iovec_t, a.len())
36+
}
37+
38+
fn ciovec(a: &[IoVec]) -> (*const libc::__wasi_ciovec_t, usize) {
39+
assert_eq!(
40+
mem::size_of::<IoVec>(),
41+
mem::size_of::<libc::__wasi_ciovec_t>()
42+
);
43+
assert_eq!(
44+
mem::align_of::<IoVec>(),
45+
mem::align_of::<libc::__wasi_ciovec_t>()
46+
);
47+
(a.as_ptr() as *const libc::__wasi_ciovec_t, a.len())
48+
}
49+
50+
impl WasiFd {
51+
pub unsafe fn from_raw(fd: libc::__wasi_fd_t) -> WasiFd {
52+
WasiFd { fd }
53+
}
54+
55+
pub fn datasync(&self) -> io::Result<()> {
56+
cvt_wasi(unsafe { libc::__wasi_fd_datasync(self.fd) })
57+
}
58+
59+
pub fn pread(&self, bufs: &mut [IoVecMut], offset: u64) -> io::Result<usize> {
60+
let mut read = 0;
61+
let (ptr, len) = iovec(bufs);
62+
cvt_wasi(unsafe { libc::__wasi_fd_pread(self.fd, ptr, len, offset, &mut read) })?;
63+
Ok(read)
64+
}
65+
66+
pub fn pwrite(&self, bufs: &[IoVec], offset: u64) -> io::Result<usize> {
67+
let mut read = 0;
68+
let (ptr, len) = ciovec(bufs);
69+
cvt_wasi(unsafe { libc::__wasi_fd_pwrite(self.fd, ptr, len, offset, &mut read) })?;
70+
Ok(read)
71+
}
72+
73+
pub fn read(&self, bufs: &mut [IoVecMut]) -> io::Result<usize> {
74+
let mut read = 0;
75+
let (ptr, len) = iovec(bufs);
76+
cvt_wasi(unsafe { libc::__wasi_fd_read(self.fd, ptr, len, &mut read) })?;
77+
Ok(read)
78+
}
79+
80+
pub fn write(&self, bufs: &[IoVec]) -> io::Result<usize> {
81+
let mut read = 0;
82+
let (ptr, len) = ciovec(bufs);
83+
cvt_wasi(unsafe { libc::__wasi_fd_write(self.fd, ptr, len, &mut read) })?;
84+
Ok(read)
85+
}
86+
87+
pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
88+
let (whence, offset) = match pos {
89+
SeekFrom::Start(pos) => (libc::__WASI_WHENCE_SET, pos as i64),
90+
SeekFrom::End(pos) => (libc::__WASI_WHENCE_END, pos),
91+
SeekFrom::Current(pos) => (libc::__WASI_WHENCE_CUR, pos),
92+
};
93+
let mut pos = 0;
94+
cvt_wasi(unsafe { libc::__wasi_fd_seek(self.fd, offset, whence, &mut pos) })?;
95+
Ok(pos)
96+
}
97+
98+
pub fn tell(&self) -> io::Result<u64> {
99+
let mut pos = 0;
100+
cvt_wasi(unsafe { libc::__wasi_fd_tell(self.fd, &mut pos) })?;
101+
Ok(pos)
102+
}
103+
104+
// FIXME: __wasi_fd_fdstat_get
105+
106+
pub fn set_flags(&self, flags: FdFlags) -> io::Result<()> {
107+
cvt_wasi(unsafe { libc::__wasi_fd_fdstat_set_flags(self.fd, flags) })
108+
}
109+
110+
pub fn set_rights(&self, base: Rights, inheriting: Rights) -> io::Result<()> {
111+
cvt_wasi(unsafe { libc::__wasi_fd_fdstat_set_rights(self.fd, base, inheriting) })
112+
}
113+
114+
pub fn sync(&self) -> io::Result<()> {
115+
cvt_wasi(unsafe { libc::__wasi_fd_sync(self.fd) })
116+
}
117+
118+
pub fn advise(&self, offset: u64, len: u64, advice: Advice) -> io::Result<()> {
119+
cvt_wasi(unsafe { libc::__wasi_fd_advise(self.fd, offset, len, advice as u8) })
120+
}
121+
122+
pub fn allocate(&self, offset: u64, len: u64) -> io::Result<()> {
123+
cvt_wasi(unsafe { libc::__wasi_fd_allocate(self.fd, offset, len) })
124+
}
125+
126+
pub fn crate_directory(&self, path: &[u8]) -> io::Result<()> {
127+
cvt_wasi(unsafe {
128+
libc::__wasi_path_create_directory(self.fd, path.as_ptr() as *const c_char, path.len())
129+
})
130+
}
131+
132+
pub fn link(
133+
&self,
134+
old_flags: LookupFlags,
135+
old_path: &[u8],
136+
new_fd: &WasiFd,
137+
new_path: &[u8],
138+
) -> io::Result<()> {
139+
cvt_wasi(unsafe {
140+
libc::__wasi_path_link(
141+
self.fd,
142+
old_flags,
143+
old_path.as_ptr() as *const c_char,
144+
old_path.len(),
145+
new_fd.fd,
146+
new_path.as_ptr() as *const c_char,
147+
new_path.len(),
148+
)
149+
})
150+
}
151+
152+
pub fn open(
153+
&self,
154+
dirflags: LookupFlags,
155+
path: &[u8],
156+
oflags: Oflags,
157+
fs_rights_base: Rights,
158+
fs_rights_inheriting: Rights,
159+
fs_flags: FdFlags,
160+
) -> io::Result<WasiFd> {
161+
unsafe {
162+
let mut fd = 0;
163+
cvt_wasi(libc::__wasi_path_open(
164+
self.fd,
165+
dirflags,
166+
path.as_ptr() as *const c_char,
167+
path.len(),
168+
oflags,
169+
fs_rights_base,
170+
fs_rights_inheriting,
171+
fs_flags,
172+
&mut fd,
173+
))?;
174+
Ok(WasiFd::from_raw(fd))
175+
}
176+
}
177+
178+
pub fn readdir(&self, buf: &mut [u8], cookie: DirCookie) -> io::Result<usize> {
179+
let mut used = 0;
180+
cvt_wasi(unsafe {
181+
libc::__wasi_fd_readdir(
182+
self.fd,
183+
buf.as_mut_ptr() as *mut c_void,
184+
buf.len(),
185+
cookie,
186+
&mut used,
187+
)
188+
})?;
189+
Ok(used)
190+
}
191+
192+
pub fn readlink(&self, path: &[u8], buf: &mut [u8]) -> io::Result<usize> {
193+
let mut used = 0;
194+
cvt_wasi(unsafe {
195+
libc::__wasi_path_readlink(
196+
self.fd,
197+
path.as_ptr() as *const c_char,
198+
path.len(),
199+
buf.as_mut_ptr() as *mut c_char,
200+
buf.len(),
201+
&mut used,
202+
)
203+
})?;
204+
Ok(used)
205+
}
206+
207+
pub fn rename(&self, old_path: &[u8], new_fd: &WasiFd, new_path: &[u8]) -> io::Result<()> {
208+
cvt_wasi(unsafe {
209+
libc::__wasi_path_rename(
210+
self.fd,
211+
old_path.as_ptr() as *const c_char,
212+
old_path.len(),
213+
new_fd.fd,
214+
new_path.as_ptr() as *const c_char,
215+
new_path.len(),
216+
)
217+
})
218+
}
219+
220+
// FIXME: __wasi_fd_filestat_get
221+
222+
pub fn filestat_set_times(
223+
&self,
224+
atim: Timestamp,
225+
mtim: Timestamp,
226+
fstflags: FstFlags,
227+
) -> io::Result<()> {
228+
cvt_wasi(unsafe { libc::__wasi_fd_filestat_set_times(self.fd, atim, mtim, fstflags) })
229+
}
230+
231+
pub fn filestat_set_size(&self, size: u64) -> io::Result<()> {
232+
cvt_wasi(unsafe { libc::__wasi_fd_filestat_set_size(self.fd, size) })
233+
}
234+
235+
// FIXME: __wasi_path_filestat_get
236+
237+
pub fn path_filestat_set_times(
238+
&self,
239+
flags: LookupFlags,
240+
path: &[u8],
241+
atim: Timestamp,
242+
mtim: Timestamp,
243+
fstflags: FstFlags,
244+
) -> io::Result<()> {
245+
cvt_wasi(unsafe {
246+
libc::__wasi_path_filestat_set_times(
247+
self.fd,
248+
flags,
249+
path.as_ptr() as *const c_char,
250+
path.len(),
251+
atim,
252+
mtim,
253+
fstflags,
254+
)
255+
})
256+
}
257+
258+
pub fn symlink(&self, old_path: &[u8], new_path: &[u8]) -> io::Result<()> {
259+
cvt_wasi(unsafe {
260+
libc::__wasi_path_symlink(
261+
old_path.as_ptr() as *const c_char,
262+
old_path.len(),
263+
self.fd,
264+
new_path.as_ptr() as *const c_char,
265+
new_path.len(),
266+
)
267+
})
268+
}
269+
270+
pub fn unlink_file(&self, path: &[u8]) -> io::Result<()> {
271+
cvt_wasi(unsafe {
272+
libc::__wasi_path_unlink_file(self.fd, path.as_ptr() as *const c_char, path.len())
273+
})
274+
}
275+
276+
pub fn remove_directory(&self, path: &[u8]) -> io::Result<()> {
277+
cvt_wasi(unsafe {
278+
libc::__wasi_path_remove_directory(self.fd, path.as_ptr() as *const c_char, path.len())
279+
})
280+
}
281+
282+
pub fn sock_recv(
283+
&self,
284+
ri_data: &mut [IoVecMut],
285+
ri_flags: RiFlags,
286+
) -> io::Result<(usize, RoFlags)> {
287+
let mut ro_datalen = 0;
288+
let mut ro_flags = 0;
289+
let (ptr, len) = iovec(ri_data);
290+
cvt_wasi(unsafe {
291+
libc::__wasi_sock_recv(self.fd, ptr, len, ri_flags, &mut ro_datalen, &mut ro_flags)
292+
})?;
293+
Ok((ro_datalen, ro_flags))
294+
}
295+
296+
pub fn sock_send(&self, si_data: &[IoVec], si_flags: SiFlags) -> io::Result<usize> {
297+
let mut so_datalen = 0;
298+
let (ptr, len) = ciovec(si_data);
299+
cvt_wasi(unsafe { libc::__wasi_sock_send(self.fd, ptr, len, si_flags, &mut so_datalen) })?;
300+
Ok(so_datalen)
301+
}
302+
303+
pub fn sock_shutdown(&self, how: Shutdown) -> io::Result<()> {
304+
let how = match how {
305+
Shutdown::Read => libc::__WASI_SHUT_RD,
306+
Shutdown::Write => libc::__WASI_SHUT_WR,
307+
Shutdown::Both => libc::__WASI_SHUT_WR | libc::__WASI_SHUT_RD,
308+
};
309+
cvt_wasi(unsafe { libc::__wasi_sock_shutdown(self.fd, how) })?;
310+
Ok(())
311+
}
312+
}
313+
314+
impl Drop for WasiFd {
315+
fn drop(&mut self) {
316+
unsafe {
317+
// FIXME: can we handle the return code here even though we can't on
318+
// unix?
319+
libc::__wasi_fd_close(self.fd);
320+
}
321+
}
322+
}

‎src/libstd/sys/wasi/fs.rs

+294
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,294 @@
1+
use crate::ffi::OsString;
2+
use crate::fmt;
3+
use crate::hash::{Hash, Hasher};
4+
use crate::io::{self, SeekFrom};
5+
use crate::path::{Path, PathBuf};
6+
use crate::sys::time::SystemTime;
7+
use crate::sys::{unsupported, Void};
8+
9+
pub struct File(Void);
10+
11+
pub struct FileAttr(Void);
12+
13+
pub struct ReadDir(Void);
14+
15+
pub struct DirEntry(Void);
16+
17+
#[derive(Clone, Debug)]
18+
pub struct OpenOptions { }
19+
20+
pub struct FilePermissions(Void);
21+
22+
pub struct FileType(Void);
23+
24+
#[derive(Debug)]
25+
pub struct DirBuilder { }
26+
27+
impl FileAttr {
28+
pub fn size(&self) -> u64 {
29+
match self.0 {}
30+
}
31+
32+
pub fn perm(&self) -> FilePermissions {
33+
match self.0 {}
34+
}
35+
36+
pub fn file_type(&self) -> FileType {
37+
match self.0 {}
38+
}
39+
40+
pub fn modified(&self) -> io::Result<SystemTime> {
41+
match self.0 {}
42+
}
43+
44+
pub fn accessed(&self) -> io::Result<SystemTime> {
45+
match self.0 {}
46+
}
47+
48+
pub fn created(&self) -> io::Result<SystemTime> {
49+
match self.0 {}
50+
}
51+
}
52+
53+
impl Clone for FileAttr {
54+
fn clone(&self) -> FileAttr {
55+
match self.0 {}
56+
}
57+
}
58+
59+
impl FilePermissions {
60+
pub fn readonly(&self) -> bool {
61+
match self.0 {}
62+
}
63+
64+
pub fn set_readonly(&mut self, _readonly: bool) {
65+
match self.0 {}
66+
}
67+
}
68+
69+
impl Clone for FilePermissions {
70+
fn clone(&self) -> FilePermissions {
71+
match self.0 {}
72+
}
73+
}
74+
75+
impl PartialEq for FilePermissions {
76+
fn eq(&self, _other: &FilePermissions) -> bool {
77+
match self.0 {}
78+
}
79+
}
80+
81+
impl Eq for FilePermissions {
82+
}
83+
84+
impl fmt::Debug for FilePermissions {
85+
fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
86+
match self.0 {}
87+
}
88+
}
89+
90+
impl FileType {
91+
pub fn is_dir(&self) -> bool {
92+
match self.0 {}
93+
}
94+
95+
pub fn is_file(&self) -> bool {
96+
match self.0 {}
97+
}
98+
99+
pub fn is_symlink(&self) -> bool {
100+
match self.0 {}
101+
}
102+
}
103+
104+
impl Clone for FileType {
105+
fn clone(&self) -> FileType {
106+
match self.0 {}
107+
}
108+
}
109+
110+
impl Copy for FileType {}
111+
112+
impl PartialEq for FileType {
113+
fn eq(&self, _other: &FileType) -> bool {
114+
match self.0 {}
115+
}
116+
}
117+
118+
impl Eq for FileType {
119+
}
120+
121+
impl Hash for FileType {
122+
fn hash<H: Hasher>(&self, _h: &mut H) {
123+
match self.0 {}
124+
}
125+
}
126+
127+
impl fmt::Debug for FileType {
128+
fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
129+
match self.0 {}
130+
}
131+
}
132+
133+
impl fmt::Debug for ReadDir {
134+
fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
135+
match self.0 {}
136+
}
137+
}
138+
139+
impl Iterator for ReadDir {
140+
type Item = io::Result<DirEntry>;
141+
142+
fn next(&mut self) -> Option<io::Result<DirEntry>> {
143+
match self.0 {}
144+
}
145+
}
146+
147+
impl DirEntry {
148+
pub fn path(&self) -> PathBuf {
149+
match self.0 {}
150+
}
151+
152+
pub fn file_name(&self) -> OsString {
153+
match self.0 {}
154+
}
155+
156+
pub fn metadata(&self) -> io::Result<FileAttr> {
157+
match self.0 {}
158+
}
159+
160+
pub fn file_type(&self) -> io::Result<FileType> {
161+
match self.0 {}
162+
}
163+
}
164+
165+
impl OpenOptions {
166+
pub fn new() -> OpenOptions {
167+
OpenOptions { }
168+
}
169+
170+
pub fn read(&mut self, _read: bool) { }
171+
pub fn write(&mut self, _write: bool) { }
172+
pub fn append(&mut self, _append: bool) { }
173+
pub fn truncate(&mut self, _truncate: bool) { }
174+
pub fn create(&mut self, _create: bool) { }
175+
pub fn create_new(&mut self, _create_new: bool) { }
176+
}
177+
178+
impl File {
179+
pub fn open(_path: &Path, _opts: &OpenOptions) -> io::Result<File> {
180+
unsupported()
181+
}
182+
183+
pub fn file_attr(&self) -> io::Result<FileAttr> {
184+
match self.0 {}
185+
}
186+
187+
pub fn fsync(&self) -> io::Result<()> {
188+
match self.0 {}
189+
}
190+
191+
pub fn datasync(&self) -> io::Result<()> {
192+
match self.0 {}
193+
}
194+
195+
pub fn truncate(&self, _size: u64) -> io::Result<()> {
196+
match self.0 {}
197+
}
198+
199+
pub fn read(&self, _buf: &mut [u8]) -> io::Result<usize> {
200+
match self.0 {}
201+
}
202+
203+
pub fn write(&self, _buf: &[u8]) -> io::Result<usize> {
204+
match self.0 {}
205+
}
206+
207+
pub fn flush(&self) -> io::Result<()> {
208+
match self.0 {}
209+
}
210+
211+
pub fn seek(&self, _pos: SeekFrom) -> io::Result<u64> {
212+
match self.0 {}
213+
}
214+
215+
pub fn duplicate(&self) -> io::Result<File> {
216+
match self.0 {}
217+
}
218+
219+
pub fn set_permissions(&self, _perm: FilePermissions) -> io::Result<()> {
220+
match self.0 {}
221+
}
222+
223+
pub fn diverge(&self) -> ! {
224+
match self.0 {}
225+
}
226+
}
227+
228+
impl DirBuilder {
229+
pub fn new() -> DirBuilder {
230+
DirBuilder { }
231+
}
232+
233+
pub fn mkdir(&self, _p: &Path) -> io::Result<()> {
234+
unsupported()
235+
}
236+
}
237+
238+
impl fmt::Debug for File {
239+
fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
240+
match self.0 {}
241+
}
242+
}
243+
244+
pub fn readdir(_p: &Path) -> io::Result<ReadDir> {
245+
unsupported()
246+
}
247+
248+
pub fn unlink(_p: &Path) -> io::Result<()> {
249+
unsupported()
250+
}
251+
252+
pub fn rename(_old: &Path, _new: &Path) -> io::Result<()> {
253+
unsupported()
254+
}
255+
256+
pub fn set_perm(_p: &Path, perm: FilePermissions) -> io::Result<()> {
257+
match perm.0 {}
258+
}
259+
260+
pub fn rmdir(_p: &Path) -> io::Result<()> {
261+
unsupported()
262+
}
263+
264+
pub fn remove_dir_all(_path: &Path) -> io::Result<()> {
265+
unsupported()
266+
}
267+
268+
pub fn readlink(_p: &Path) -> io::Result<PathBuf> {
269+
unsupported()
270+
}
271+
272+
pub fn symlink(_src: &Path, _dst: &Path) -> io::Result<()> {
273+
unsupported()
274+
}
275+
276+
pub fn link(_src: &Path, _dst: &Path) -> io::Result<()> {
277+
unsupported()
278+
}
279+
280+
pub fn stat(_p: &Path) -> io::Result<FileAttr> {
281+
unsupported()
282+
}
283+
284+
pub fn lstat(_p: &Path) -> io::Result<FileAttr> {
285+
unsupported()
286+
}
287+
288+
pub fn canonicalize(_p: &Path) -> io::Result<PathBuf> {
289+
unsupported()
290+
}
291+
292+
pub fn copy(_from: &Path, _to: &Path) -> io::Result<u64> {
293+
unsupported()
294+
}

‎src/libstd/sys/wasi/io.rs

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
use crate::marker::PhantomData;
2+
use crate::slice;
3+
4+
use libc::{__wasi_ciovec_t, __wasi_iovec_t, c_void};
5+
6+
#[repr(transparent)]
7+
pub struct IoVec<'a> {
8+
vec: __wasi_ciovec_t,
9+
_p: PhantomData<&'a [u8]>,
10+
}
11+
12+
impl<'a> IoVec<'a> {
13+
#[inline]
14+
pub fn new(buf: &'a [u8]) -> IoVec<'a> {
15+
IoVec {
16+
vec: __wasi_ciovec_t {
17+
buf: buf.as_ptr() as *const c_void,
18+
buf_len: buf.len(),
19+
},
20+
_p: PhantomData,
21+
}
22+
}
23+
24+
#[inline]
25+
pub fn as_slice(&self) -> &[u8] {
26+
unsafe {
27+
slice::from_raw_parts(self.vec.buf as *const u8, self.vec.buf_len)
28+
}
29+
}
30+
}
31+
32+
pub struct IoVecMut<'a> {
33+
vec: __wasi_iovec_t,
34+
_p: PhantomData<&'a mut [u8]>,
35+
}
36+
37+
impl<'a> IoVecMut<'a> {
38+
#[inline]
39+
pub fn new(buf: &'a mut [u8]) -> IoVecMut<'a> {
40+
IoVecMut {
41+
vec: __wasi_iovec_t {
42+
buf: buf.as_mut_ptr() as *mut c_void,
43+
buf_len: buf.len()
44+
},
45+
_p: PhantomData,
46+
}
47+
}
48+
49+
#[inline]
50+
pub fn as_slice(&self) -> &[u8] {
51+
unsafe {
52+
slice::from_raw_parts(self.vec.buf as *const u8, self.vec.buf_len)
53+
}
54+
}
55+
56+
#[inline]
57+
pub fn as_mut_slice(&mut self) -> &mut [u8] {
58+
unsafe {
59+
slice::from_raw_parts_mut(self.vec.buf as *mut u8, self.vec.buf_len)
60+
}
61+
}
62+
}

‎src/libstd/sys/wasi/mod.rs

+128
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
//! System bindings for the wasm/web platform
2+
//!
3+
//! This module contains the facade (aka platform-specific) implementations of
4+
//! OS level functionality for wasm. Note that this wasm is *not* the emscripten
5+
//! wasm, so we have no runtime here.
6+
//!
7+
//! This is all super highly experimental and not actually intended for
8+
//! wide/production use yet, it's still all in the experimental category. This
9+
//! will likely change over time.
10+
//!
11+
//! Currently all functions here are basically stubs that immediately return
12+
//! errors. The hope is that with a portability lint we can turn actually just
13+
//! remove all this and just omit parts of the standard library if we're
14+
//! compiling for wasm. That way it's a compile time error for something that's
15+
//! guaranteed to be a runtime error!
16+
17+
use libc;
18+
use crate::io::{Error, ErrorKind};
19+
use crate::mem;
20+
use crate::os::raw::c_char;
21+
22+
pub mod alloc;
23+
pub mod args;
24+
#[cfg(feature = "backtrace")]
25+
pub mod backtrace;
26+
#[path = "../wasm/cmath.rs"]
27+
pub mod cmath;
28+
#[path = "../wasm/condvar.rs"]
29+
pub mod condvar;
30+
pub mod env;
31+
pub mod fd;
32+
pub mod fs;
33+
#[path = "../wasm/memchr.rs"]
34+
pub mod memchr;
35+
#[path = "../wasm/mutex.rs"]
36+
pub mod mutex;
37+
pub mod net;
38+
pub mod io;
39+
pub mod os;
40+
pub use crate::sys_common::os_str_bytes as os_str;
41+
pub mod path;
42+
pub mod pipe;
43+
pub mod process;
44+
#[path = "../wasm/rwlock.rs"]
45+
pub mod rwlock;
46+
#[path = "../wasm/stack_overflow.rs"]
47+
pub mod stack_overflow;
48+
pub mod stdio;
49+
pub mod thread;
50+
#[path = "../wasm/thread_local.rs"]
51+
pub mod thread_local;
52+
pub mod time;
53+
pub mod ext;
54+
55+
#[cfg(not(test))]
56+
pub fn init() {
57+
}
58+
59+
pub fn unsupported<T>() -> crate::io::Result<T> {
60+
Err(unsupported_err())
61+
}
62+
63+
pub fn unsupported_err() -> Error {
64+
Error::new(ErrorKind::Other, "operation not supported on wasm yet")
65+
}
66+
67+
pub fn decode_error_kind(_code: i32) -> ErrorKind {
68+
ErrorKind::Other
69+
}
70+
71+
// This enum is used as the storage for a bunch of types which can't actually
72+
// exist.
73+
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
74+
pub enum Void {}
75+
76+
pub unsafe fn strlen(mut s: *const c_char) -> usize {
77+
let mut n = 0;
78+
while *s != 0 {
79+
n += 1;
80+
s = s.offset(1);
81+
}
82+
return n
83+
}
84+
85+
pub unsafe fn abort_internal() -> ! {
86+
libc::abort()
87+
}
88+
89+
pub fn hashmap_random_keys() -> (u64, u64) {
90+
let mut ret = (0u64, 0u64);
91+
unsafe {
92+
let base = &mut ret as *mut (u64, u64) as *mut libc::c_void;
93+
let len = mem::size_of_val(&ret);
94+
cvt_wasi(libc::__wasi_random_get(base, len)).unwrap();
95+
}
96+
return ret
97+
}
98+
99+
#[doc(hidden)]
100+
pub trait IsMinusOne {
101+
fn is_minus_one(&self) -> bool;
102+
}
103+
104+
macro_rules! impl_is_minus_one {
105+
($($t:ident)*) => ($(impl IsMinusOne for $t {
106+
fn is_minus_one(&self) -> bool {
107+
*self == -1
108+
}
109+
})*)
110+
}
111+
112+
impl_is_minus_one! { i8 i16 i32 i64 isize }
113+
114+
pub fn cvt<T: IsMinusOne>(t: T) -> crate::io::Result<T> {
115+
if t.is_minus_one() {
116+
Err(Error::last_os_error())
117+
} else {
118+
Ok(t)
119+
}
120+
}
121+
122+
pub fn cvt_wasi(r: u16) -> crate::io::Result<()> {
123+
if r != libc::__WASI_ESUCCESS {
124+
Err(Error::from_raw_os_error(r as i32))
125+
} else {
126+
Ok(())
127+
}
128+
}

‎src/libstd/sys/wasi/net.rs

+358
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,358 @@
1+
use crate::fmt;
2+
use crate::io::{self, IoVec, IoVecMut};
3+
use crate::net::{SocketAddr, Shutdown, Ipv4Addr, Ipv6Addr};
4+
use crate::time::Duration;
5+
use crate::sys::{unsupported, Void};
6+
use crate::convert::TryFrom;
7+
8+
pub struct TcpStream(Void);
9+
10+
impl TcpStream {
11+
pub fn connect(_: io::Result<&SocketAddr>) -> io::Result<TcpStream> {
12+
unsupported()
13+
}
14+
15+
pub fn connect_timeout(_: &SocketAddr, _: Duration) -> io::Result<TcpStream> {
16+
unsupported()
17+
}
18+
19+
pub fn set_read_timeout(&self, _: Option<Duration>) -> io::Result<()> {
20+
match self.0 {}
21+
}
22+
23+
pub fn set_write_timeout(&self, _: Option<Duration>) -> io::Result<()> {
24+
match self.0 {}
25+
}
26+
27+
pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
28+
match self.0 {}
29+
}
30+
31+
pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
32+
match self.0 {}
33+
}
34+
35+
pub fn peek(&self, _: &mut [u8]) -> io::Result<usize> {
36+
match self.0 {}
37+
}
38+
39+
pub fn read(&self, _: &mut [u8]) -> io::Result<usize> {
40+
match self.0 {}
41+
}
42+
43+
pub fn read_vectored(&self, _: &mut [IoVecMut<'_>]) -> io::Result<usize> {
44+
match self.0 {}
45+
}
46+
47+
pub fn write(&self, _: &[u8]) -> io::Result<usize> {
48+
match self.0 {}
49+
}
50+
51+
pub fn write_vectored(&self, _: &[IoVec<'_>]) -> io::Result<usize> {
52+
match self.0 {}
53+
}
54+
55+
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
56+
match self.0 {}
57+
}
58+
59+
pub fn socket_addr(&self) -> io::Result<SocketAddr> {
60+
match self.0 {}
61+
}
62+
63+
pub fn shutdown(&self, _: Shutdown) -> io::Result<()> {
64+
match self.0 {}
65+
}
66+
67+
pub fn duplicate(&self) -> io::Result<TcpStream> {
68+
match self.0 {}
69+
}
70+
71+
pub fn set_nodelay(&self, _: bool) -> io::Result<()> {
72+
match self.0 {}
73+
}
74+
75+
pub fn nodelay(&self) -> io::Result<bool> {
76+
match self.0 {}
77+
}
78+
79+
pub fn set_ttl(&self, _: u32) -> io::Result<()> {
80+
match self.0 {}
81+
}
82+
83+
pub fn ttl(&self) -> io::Result<u32> {
84+
match self.0 {}
85+
}
86+
87+
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
88+
match self.0 {}
89+
}
90+
91+
pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
92+
match self.0 {}
93+
}
94+
}
95+
96+
impl fmt::Debug for TcpStream {
97+
fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
98+
match self.0 {}
99+
}
100+
}
101+
102+
pub struct TcpListener(Void);
103+
104+
impl TcpListener {
105+
pub fn bind(_: io::Result<&SocketAddr>) -> io::Result<TcpListener> {
106+
unsupported()
107+
}
108+
109+
pub fn socket_addr(&self) -> io::Result<SocketAddr> {
110+
match self.0 {}
111+
}
112+
113+
pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
114+
match self.0 {}
115+
}
116+
117+
pub fn duplicate(&self) -> io::Result<TcpListener> {
118+
match self.0 {}
119+
}
120+
121+
pub fn set_ttl(&self, _: u32) -> io::Result<()> {
122+
match self.0 {}
123+
}
124+
125+
pub fn ttl(&self) -> io::Result<u32> {
126+
match self.0 {}
127+
}
128+
129+
pub fn set_only_v6(&self, _: bool) -> io::Result<()> {
130+
match self.0 {}
131+
}
132+
133+
pub fn only_v6(&self) -> io::Result<bool> {
134+
match self.0 {}
135+
}
136+
137+
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
138+
match self.0 {}
139+
}
140+
141+
pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
142+
match self.0 {}
143+
}
144+
}
145+
146+
impl fmt::Debug for TcpListener {
147+
fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
148+
match self.0 {}
149+
}
150+
}
151+
152+
pub struct UdpSocket(Void);
153+
154+
impl UdpSocket {
155+
pub fn bind(_: io::Result<&SocketAddr>) -> io::Result<UdpSocket> {
156+
unsupported()
157+
}
158+
159+
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
160+
match self.0 {}
161+
}
162+
163+
pub fn socket_addr(&self) -> io::Result<SocketAddr> {
164+
match self.0 {}
165+
}
166+
167+
pub fn recv_from(&self, _: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
168+
match self.0 {}
169+
}
170+
171+
pub fn peek_from(&self, _: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
172+
match self.0 {}
173+
}
174+
175+
pub fn send_to(&self, _: &[u8], _: &SocketAddr) -> io::Result<usize> {
176+
match self.0 {}
177+
}
178+
179+
pub fn duplicate(&self) -> io::Result<UdpSocket> {
180+
match self.0 {}
181+
}
182+
183+
pub fn set_read_timeout(&self, _: Option<Duration>) -> io::Result<()> {
184+
match self.0 {}
185+
}
186+
187+
pub fn set_write_timeout(&self, _: Option<Duration>) -> io::Result<()> {
188+
match self.0 {}
189+
}
190+
191+
pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
192+
match self.0 {}
193+
}
194+
195+
pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
196+
match self.0 {}
197+
}
198+
199+
pub fn set_broadcast(&self, _: bool) -> io::Result<()> {
200+
match self.0 {}
201+
}
202+
203+
pub fn broadcast(&self) -> io::Result<bool> {
204+
match self.0 {}
205+
}
206+
207+
pub fn set_multicast_loop_v4(&self, _: bool) -> io::Result<()> {
208+
match self.0 {}
209+
}
210+
211+
pub fn multicast_loop_v4(&self) -> io::Result<bool> {
212+
match self.0 {}
213+
}
214+
215+
pub fn set_multicast_ttl_v4(&self, _: u32) -> io::Result<()> {
216+
match self.0 {}
217+
}
218+
219+
pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
220+
match self.0 {}
221+
}
222+
223+
pub fn set_multicast_loop_v6(&self, _: bool) -> io::Result<()> {
224+
match self.0 {}
225+
}
226+
227+
pub fn multicast_loop_v6(&self) -> io::Result<bool> {
228+
match self.0 {}
229+
}
230+
231+
pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr)
232+
-> io::Result<()> {
233+
match self.0 {}
234+
}
235+
236+
pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32)
237+
-> io::Result<()> {
238+
match self.0 {}
239+
}
240+
241+
pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr)
242+
-> io::Result<()> {
243+
match self.0 {}
244+
}
245+
246+
pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32)
247+
-> io::Result<()> {
248+
match self.0 {}
249+
}
250+
251+
pub fn set_ttl(&self, _: u32) -> io::Result<()> {
252+
match self.0 {}
253+
}
254+
255+
pub fn ttl(&self) -> io::Result<u32> {
256+
match self.0 {}
257+
}
258+
259+
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
260+
match self.0 {}
261+
}
262+
263+
pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
264+
match self.0 {}
265+
}
266+
267+
pub fn recv(&self, _: &mut [u8]) -> io::Result<usize> {
268+
match self.0 {}
269+
}
270+
271+
pub fn peek(&self, _: &mut [u8]) -> io::Result<usize> {
272+
match self.0 {}
273+
}
274+
275+
pub fn send(&self, _: &[u8]) -> io::Result<usize> {
276+
match self.0 {}
277+
}
278+
279+
pub fn connect(&self, _: io::Result<&SocketAddr>) -> io::Result<()> {
280+
match self.0 {}
281+
}
282+
}
283+
284+
impl fmt::Debug for UdpSocket {
285+
fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
286+
match self.0 {}
287+
}
288+
}
289+
290+
pub struct LookupHost(Void);
291+
292+
impl LookupHost {
293+
pub fn port(&self) -> u16 {
294+
match self.0 {}
295+
}
296+
}
297+
298+
impl Iterator for LookupHost {
299+
type Item = SocketAddr;
300+
fn next(&mut self) -> Option<SocketAddr> {
301+
match self.0 {}
302+
}
303+
}
304+
305+
impl<'a> TryFrom<&'a str> for LookupHost {
306+
type Error = io::Error;
307+
308+
fn try_from(_v: &'a str) -> io::Result<LookupHost> {
309+
unsupported()
310+
}
311+
}
312+
313+
impl<'a> TryFrom<(&'a str, u16)> for LookupHost {
314+
type Error = io::Error;
315+
316+
fn try_from(_v: (&'a str, u16)) -> io::Result<LookupHost> {
317+
unsupported()
318+
}
319+
}
320+
321+
#[allow(nonstandard_style)]
322+
pub mod netc {
323+
pub const AF_INET: u8 = 0;
324+
pub const AF_INET6: u8 = 1;
325+
pub type sa_family_t = u8;
326+
327+
#[derive(Copy, Clone)]
328+
pub struct in_addr {
329+
pub s_addr: u32,
330+
}
331+
332+
#[derive(Copy, Clone)]
333+
pub struct sockaddr_in {
334+
pub sin_family: sa_family_t,
335+
pub sin_port: u16,
336+
pub sin_addr: in_addr,
337+
}
338+
339+
#[derive(Copy, Clone)]
340+
pub struct in6_addr {
341+
pub s6_addr: [u8; 16],
342+
}
343+
344+
#[derive(Copy, Clone)]
345+
pub struct sockaddr_in6 {
346+
pub sin6_family: sa_family_t,
347+
pub sin6_port: u16,
348+
pub sin6_addr: in6_addr,
349+
pub sin6_flowinfo: u32,
350+
pub sin6_scope_id: u32,
351+
}
352+
353+
#[derive(Copy, Clone)]
354+
pub struct sockaddr {
355+
}
356+
357+
pub type socklen_t = usize;
358+
}

‎src/libstd/sys/wasi/os.rs

+171
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
use crate::any::Any;
2+
use crate::error::Error as StdError;
3+
use crate::ffi::{OsString, OsStr, CString, CStr};
4+
use crate::fmt;
5+
use crate::io;
6+
use crate::marker::PhantomData;
7+
use crate::os::wasi::prelude::*;
8+
use crate::path::{self, PathBuf};
9+
use crate::ptr;
10+
use crate::str;
11+
use crate::sys::memchr;
12+
use crate::sys::{cvt, unsupported, Void};
13+
use crate::vec;
14+
15+
#[cfg(not(target_feature = "atomics"))]
16+
pub unsafe fn env_lock() -> impl Any {
17+
// No need for a lock if we're single-threaded, but this function will need
18+
// to get implemented for multi-threaded scenarios
19+
}
20+
21+
pub fn errno() -> i32 {
22+
extern {
23+
#[thread_local]
24+
static errno: libc::c_int;
25+
}
26+
27+
unsafe { errno as i32 }
28+
}
29+
30+
pub fn error_string(_errno: i32) -> String {
31+
"operation failed".to_string()
32+
}
33+
34+
pub fn getcwd() -> io::Result<PathBuf> {
35+
unsupported()
36+
}
37+
38+
pub fn chdir(_: &path::Path) -> io::Result<()> {
39+
unsupported()
40+
}
41+
42+
pub struct SplitPaths<'a>(&'a Void);
43+
44+
pub fn split_paths(_unparsed: &OsStr) -> SplitPaths {
45+
panic!("unsupported")
46+
}
47+
48+
impl<'a> Iterator for SplitPaths<'a> {
49+
type Item = PathBuf;
50+
fn next(&mut self) -> Option<PathBuf> {
51+
match *self.0 {}
52+
}
53+
}
54+
55+
#[derive(Debug)]
56+
pub struct JoinPathsError;
57+
58+
pub fn join_paths<I, T>(_paths: I) -> Result<OsString, JoinPathsError>
59+
where I: Iterator<Item=T>, T: AsRef<OsStr>
60+
{
61+
Err(JoinPathsError)
62+
}
63+
64+
impl fmt::Display for JoinPathsError {
65+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
66+
"not supported on wasm yet".fmt(f)
67+
}
68+
}
69+
70+
impl StdError for JoinPathsError {
71+
fn description(&self) -> &str {
72+
"not supported on wasm yet"
73+
}
74+
}
75+
76+
pub fn current_exe() -> io::Result<PathBuf> {
77+
unsupported()
78+
}
79+
80+
pub struct Env {
81+
iter: vec::IntoIter<(OsString, OsString)>,
82+
_dont_send_or_sync_me: PhantomData<*mut ()>,
83+
}
84+
85+
impl Iterator for Env {
86+
type Item = (OsString, OsString);
87+
fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() }
88+
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
89+
}
90+
91+
92+
pub fn env() -> Env {
93+
unsafe {
94+
let _guard = env_lock();
95+
let mut environ = libc::environ;
96+
let mut result = Vec::new();
97+
while environ != ptr::null_mut() && *environ != ptr::null_mut() {
98+
if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) {
99+
result.push(key_value);
100+
}
101+
environ = environ.offset(1);
102+
}
103+
return Env {
104+
iter: result.into_iter(),
105+
_dont_send_or_sync_me: PhantomData,
106+
}
107+
}
108+
109+
// See src/libstd/sys/unix/os.rs, same as that
110+
fn parse(input: &[u8]) -> Option<(OsString, OsString)> {
111+
if input.is_empty() {
112+
return None;
113+
}
114+
let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
115+
pos.map(|p| (
116+
OsStringExt::from_vec(input[..p].to_vec()),
117+
OsStringExt::from_vec(input[p+1..].to_vec()),
118+
))
119+
}
120+
}
121+
122+
pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
123+
let k = CString::new(k.as_bytes())?;
124+
unsafe {
125+
let _guard = env_lock();
126+
let s = libc::getenv(k.as_ptr()) as *const libc::c_char;
127+
let ret = if s.is_null() {
128+
None
129+
} else {
130+
Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
131+
};
132+
Ok(ret)
133+
}
134+
}
135+
136+
pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
137+
let k = CString::new(k.as_bytes())?;
138+
let v = CString::new(v.as_bytes())?;
139+
140+
unsafe {
141+
let _guard = env_lock();
142+
cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(|_| ())
143+
}
144+
}
145+
146+
pub fn unsetenv(n: &OsStr) -> io::Result<()> {
147+
let nbuf = CString::new(n.as_bytes())?;
148+
149+
unsafe {
150+
let _guard = env_lock();
151+
cvt(libc::unsetenv(nbuf.as_ptr())).map(|_| ())
152+
}
153+
}
154+
155+
pub fn temp_dir() -> PathBuf {
156+
panic!("no filesystem on wasm")
157+
}
158+
159+
pub fn home_dir() -> Option<PathBuf> {
160+
None
161+
}
162+
163+
pub fn exit(code: i32) -> ! {
164+
unsafe {
165+
libc::exit(code)
166+
}
167+
}
168+
169+
pub fn getpid() -> u32 {
170+
panic!("unsupported");
171+
}

‎src/libstd/sys/wasi/path.rs

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
use crate::path::Prefix;
2+
use crate::ffi::OsStr;
3+
4+
#[inline]
5+
pub fn is_sep_byte(b: u8) -> bool {
6+
b == b'/'
7+
}
8+
9+
#[inline]
10+
pub fn is_verbatim_sep(b: u8) -> bool {
11+
b == b'/'
12+
}
13+
14+
pub fn parse_prefix(_: &OsStr) -> Option<Prefix> {
15+
None
16+
}
17+
18+
pub const MAIN_SEP_STR: &str = "/";
19+
pub const MAIN_SEP: char = '/';

‎src/libstd/sys/wasi/pipe.rs

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
use crate::io;
2+
use crate::sys::Void;
3+
4+
pub struct AnonPipe(Void);
5+
6+
impl AnonPipe {
7+
pub fn read(&self, _buf: &mut [u8]) -> io::Result<usize> {
8+
match self.0 {}
9+
}
10+
11+
pub fn write(&self, _buf: &[u8]) -> io::Result<usize> {
12+
match self.0 {}
13+
}
14+
15+
pub fn diverge(&self) -> ! {
16+
match self.0 {}
17+
}
18+
}
19+
20+
pub fn read2(p1: AnonPipe,
21+
_v1: &mut Vec<u8>,
22+
_p2: AnonPipe,
23+
_v2: &mut Vec<u8>) -> io::Result<()> {
24+
match p1.0 {}
25+
}

‎src/libstd/sys/wasi/process.rs

+152
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
use crate::ffi::OsStr;
2+
use crate::fmt;
3+
use crate::io;
4+
use crate::sys::fs::File;
5+
use crate::sys::pipe::AnonPipe;
6+
use crate::sys::{unsupported, Void};
7+
use crate::sys_common::process::{CommandEnv, DefaultEnvKey};
8+
9+
////////////////////////////////////////////////////////////////////////////////
10+
// Command
11+
////////////////////////////////////////////////////////////////////////////////
12+
13+
pub struct Command {
14+
env: CommandEnv<DefaultEnvKey>
15+
}
16+
17+
// passed back to std::process with the pipes connected to the child, if any
18+
// were requested
19+
pub struct StdioPipes {
20+
pub stdin: Option<AnonPipe>,
21+
pub stdout: Option<AnonPipe>,
22+
pub stderr: Option<AnonPipe>,
23+
}
24+
25+
pub enum Stdio {
26+
Inherit,
27+
Null,
28+
MakePipe,
29+
}
30+
31+
impl Command {
32+
pub fn new(_program: &OsStr) -> Command {
33+
Command {
34+
env: Default::default()
35+
}
36+
}
37+
38+
pub fn arg(&mut self, _arg: &OsStr) {
39+
}
40+
41+
pub fn env_mut(&mut self) -> &mut CommandEnv<DefaultEnvKey> {
42+
&mut self.env
43+
}
44+
45+
pub fn cwd(&mut self, _dir: &OsStr) {
46+
}
47+
48+
pub fn stdin(&mut self, _stdin: Stdio) {
49+
}
50+
51+
pub fn stdout(&mut self, _stdout: Stdio) {
52+
}
53+
54+
pub fn stderr(&mut self, _stderr: Stdio) {
55+
}
56+
57+
pub fn spawn(&mut self, _default: Stdio, _needs_stdin: bool)
58+
-> io::Result<(Process, StdioPipes)> {
59+
unsupported()
60+
}
61+
}
62+
63+
impl From<AnonPipe> for Stdio {
64+
fn from(pipe: AnonPipe) -> Stdio {
65+
pipe.diverge()
66+
}
67+
}
68+
69+
impl From<File> for Stdio {
70+
fn from(file: File) -> Stdio {
71+
file.diverge()
72+
}
73+
}
74+
75+
impl fmt::Debug for Command {
76+
fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
77+
Ok(())
78+
}
79+
}
80+
81+
pub struct ExitStatus(Void);
82+
83+
impl ExitStatus {
84+
pub fn success(&self) -> bool {
85+
match self.0 {}
86+
}
87+
88+
pub fn code(&self) -> Option<i32> {
89+
match self.0 {}
90+
}
91+
}
92+
93+
impl Clone for ExitStatus {
94+
fn clone(&self) -> ExitStatus {
95+
match self.0 {}
96+
}
97+
}
98+
99+
impl Copy for ExitStatus {}
100+
101+
impl PartialEq for ExitStatus {
102+
fn eq(&self, _other: &ExitStatus) -> bool {
103+
match self.0 {}
104+
}
105+
}
106+
107+
impl Eq for ExitStatus {
108+
}
109+
110+
impl fmt::Debug for ExitStatus {
111+
fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
112+
match self.0 {}
113+
}
114+
}
115+
116+
impl fmt::Display for ExitStatus {
117+
fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
118+
match self.0 {}
119+
}
120+
}
121+
122+
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
123+
pub struct ExitCode(bool);
124+
125+
impl ExitCode {
126+
pub const SUCCESS: ExitCode = ExitCode(false);
127+
pub const FAILURE: ExitCode = ExitCode(true);
128+
129+
pub fn as_i32(&self) -> i32 {
130+
self.0 as i32
131+
}
132+
}
133+
134+
pub struct Process(Void);
135+
136+
impl Process {
137+
pub fn id(&self) -> u32 {
138+
match self.0 {}
139+
}
140+
141+
pub fn kill(&mut self) -> io::Result<()> {
142+
match self.0 {}
143+
}
144+
145+
pub fn wait(&mut self) -> io::Result<ExitStatus> {
146+
match self.0 {}
147+
}
148+
149+
pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
150+
match self.0 {}
151+
}
152+
}

‎src/libstd/sys/wasi/stdio.rs

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
use crate::io;
2+
use crate::libc;
3+
use crate::sys::cvt;
4+
5+
pub struct Stdin;
6+
pub struct Stdout;
7+
pub struct Stderr;
8+
9+
impl Stdin {
10+
pub fn new() -> io::Result<Stdin> {
11+
Ok(Stdin)
12+
}
13+
14+
pub fn read(&self, data: &mut [u8]) -> io::Result<usize> {
15+
let amt = cvt(unsafe {
16+
libc::read(libc::STDIN_FILENO, data.as_mut_ptr() as *mut _, data.len())
17+
})?;
18+
Ok(amt as usize)
19+
}
20+
}
21+
22+
impl Stdout {
23+
pub fn new() -> io::Result<Stdout> {
24+
Ok(Stdout)
25+
}
26+
27+
pub fn write(&self, data: &[u8]) -> io::Result<usize> {
28+
let amt = cvt(unsafe {
29+
libc::write(libc::STDOUT_FILENO, data.as_ptr() as *const _, data.len())
30+
})?;
31+
Ok(amt as usize)
32+
}
33+
34+
pub fn flush(&self) -> io::Result<()> {
35+
Ok(())
36+
}
37+
}
38+
39+
impl Stderr {
40+
pub fn new() -> io::Result<Stderr> {
41+
Ok(Stderr)
42+
}
43+
44+
pub fn write(&self, data: &[u8]) -> io::Result<usize> {
45+
let amt = cvt(unsafe {
46+
libc::write(libc::STDERR_FILENO, data.as_ptr() as *const _, data.len())
47+
})?;
48+
Ok(amt as usize)
49+
}
50+
51+
pub fn flush(&self) -> io::Result<()> {
52+
Ok(())
53+
}
54+
}
55+
56+
impl io::Write for Stderr {
57+
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
58+
(&*self).write(data)
59+
}
60+
61+
fn flush(&mut self) -> io::Result<()> {
62+
(&*self).flush()
63+
}
64+
}
65+
66+
pub const STDIN_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE;
67+
68+
pub fn is_ebadf(err: &io::Error) -> bool {
69+
err.raw_os_error() == Some(libc::__WASI_EBADF as i32)
70+
}
71+
72+
pub fn panic_output() -> Option<impl io::Write> {
73+
Stderr::new().ok()
74+
}

‎src/libstd/sys/wasi/thread.rs

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
use crate::boxed::FnBox;
2+
use crate::cmp;
3+
use crate::ffi::CStr;
4+
use crate::io;
5+
use crate::sys::cvt;
6+
use crate::sys::{unsupported, Void};
7+
use crate::time::Duration;
8+
use libc;
9+
10+
pub struct Thread(Void);
11+
12+
pub const DEFAULT_MIN_STACK_SIZE: usize = 4096;
13+
14+
impl Thread {
15+
// unsafe: see thread::Builder::spawn_unchecked for safety requirements
16+
pub unsafe fn new(_stack: usize, _p: Box<dyn FnBox()>)
17+
-> io::Result<Thread>
18+
{
19+
unsupported()
20+
}
21+
22+
pub fn yield_now() {
23+
let ret = unsafe { libc::__wasi_sched_yield() };
24+
debug_assert_eq!(ret, 0);
25+
}
26+
27+
pub fn set_name(_name: &CStr) {
28+
// nope
29+
}
30+
31+
pub fn sleep(dur: Duration) {
32+
let mut secs = dur.as_secs();
33+
let mut nsecs = dur.subsec_nanos() as i32;
34+
35+
unsafe {
36+
while secs > 0 || nsecs > 0 {
37+
let mut ts = libc::timespec {
38+
tv_sec: cmp::min(libc::time_t::max_value() as u64, secs) as libc::time_t,
39+
tv_nsec: nsecs,
40+
};
41+
secs -= ts.tv_sec as u64;
42+
cvt(libc::nanosleep(&ts, &mut ts)).unwrap();
43+
nsecs = 0;
44+
}
45+
}
46+
}
47+
48+
pub fn join(self) {
49+
match self.0 {}
50+
}
51+
}
52+
53+
pub mod guard {
54+
pub type Guard = !;
55+
pub unsafe fn current() -> Option<Guard> { None }
56+
pub unsafe fn init() -> Option<Guard> { None }
57+
}

‎src/libstd/sys/wasi/time.rs

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
use crate::time::Duration;
2+
use crate::mem;
3+
use crate::sys::cvt_wasi;
4+
use libc;
5+
6+
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
7+
pub struct Instant(Duration);
8+
9+
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
10+
pub struct SystemTime(Duration);
11+
12+
pub const UNIX_EPOCH: SystemTime = SystemTime(Duration::from_secs(0));
13+
14+
fn current_time(clock: u32) -> Duration {
15+
unsafe {
16+
let mut ts = mem::zeroed();
17+
cvt_wasi(libc::__wasi_clock_time_get(
18+
clock,
19+
1, // precision... seems ignored though?
20+
&mut ts,
21+
)).unwrap();
22+
Duration::new(
23+
(ts / 1_000_000_000) as u64,
24+
(ts % 1_000_000_000) as u32,
25+
)
26+
}
27+
}
28+
29+
impl Instant {
30+
pub fn now() -> Instant {
31+
Instant(current_time(libc::__WASI_CLOCK_MONOTONIC))
32+
}
33+
34+
pub const fn zero() -> Instant {
35+
Instant(Duration::from_secs(0))
36+
}
37+
38+
pub fn actually_monotonic() -> bool {
39+
true
40+
}
41+
42+
pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
43+
self.0.checked_sub(other.0)
44+
}
45+
46+
pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
47+
Some(Instant(self.0.checked_add(*other)?))
48+
}
49+
50+
pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
51+
Some(Instant(self.0.checked_sub(*other)?))
52+
}
53+
}
54+
55+
impl SystemTime {
56+
pub fn now() -> SystemTime {
57+
SystemTime(current_time(libc::__WASI_CLOCK_REALTIME))
58+
}
59+
60+
pub fn sub_time(&self, other: &SystemTime)
61+
-> Result<Duration, Duration> {
62+
self.0.checked_sub(other.0).ok_or_else(|| other.0 - self.0)
63+
}
64+
65+
pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
66+
Some(SystemTime(self.0.checked_add(*other)?))
67+
}
68+
69+
pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
70+
Some(SystemTime(self.0.checked_sub(*other)?))
71+
}
72+
}

‎src/tools/build-manifest/src/main.rs

+1
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ static TARGETS: &[&str] = &[
106106
"thumbv8m.main-none-eabi",
107107
"wasm32-unknown-emscripten",
108108
"wasm32-unknown-unknown",
109+
"wasm32-unknown-wasi",
109110
"x86_64-apple-darwin",
110111
"x86_64-apple-ios",
111112
"x86_64-fortanix-unknown-sgx",

0 commit comments

Comments
 (0)
Please sign in to comment.