Skip to content

Commit ace7124

Browse files
committed
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+
}

0 commit comments

Comments
 (0)