Skip to content

Commit 41e03c3

Browse files
committed
Auto merge of #45905 - alexcrichton:add-wasm-target, r=aturon
std: Add a new wasm32-unknown-unknown target This commit adds a new target to the compiler: wasm32-unknown-unknown. This target is a reimagining of what it looks like to generate WebAssembly code from Rust. Instead of using Emscripten which can bring with it a weighty runtime this instead is a target which uses only the LLVM backend for WebAssembly and a "custom linker" for now which will hopefully one day be direct calls to lld. Notable features of this target include: * There is zero runtime footprint. The target assumes nothing exists other than the wasm32 instruction set. * There is zero toolchain footprint beyond adding the target. No custom linker is needed, rustc contains everything. * Very small wasm modules can be generated directly from Rust code using this target. * Most of the standard library is stubbed out to return an error, but anything related to allocation works (aka `HashMap`, `Vec`, etc). * Naturally, any `#[no_std]` crate should be 100% compatible with this new target. This target is currently somewhat janky due to how linking works. The "linking" is currently unconditional whole program LTO (aka LLVM is being used as a linker). Naturally that means compiling programs is pretty slow! Eventually though this target should have a linker. This target is also intended to be quite experimental. I'm hoping that this can act as a catalyst for further experimentation in Rust with WebAssembly. Breaking changes are very likely to land to this target, so it's not recommended to rely on it in any critical capacity yet. We'll let you know when it's "production ready". ### Building yourself First you'll need to configure the build of LLVM and enable this target ``` $ ./configure --target=wasm32-unknown-unknown --set llvm.experimental-targets=WebAssembly ``` Next you'll want to remove any previously compiled LLVM as it needs to be rebuilt with WebAssembly support. You can do that with: ``` $ rm -rf build ``` And then you're good to go! A `./x.py build` should give you a rustc with the appropriate libstd target. ### Test support Currently testing-wise this target is looking pretty good but isn't complete. I've got almost the entire `run-pass` test suite working with this target (lots of tests ignored, but many passing as well). The `core` test suite is [still getting LLVM bugs fixed](https://reviews.llvm.org/D39866) to get that working and will take some time. Relatively simple programs all seem to work though! In general I've only tested this with a local fork that makes use of LLVM 5 rather than our current LLVM 4 on master. The LLVM 4 WebAssembly backend AFAIK isn't broken per se but is likely missing bug fixes available on LLVM 5. I'm hoping though that we can decouple the LLVM 5 upgrade and adding this wasm target! ### But the modules generated are huge! It's worth nothing that you may not immediately see the "smallest possible wasm module" for the input you feed to rustc. For various reasons it's very difficult to get rid of the final "bloat" in vanilla rustc (again, a real linker should fix all this). For now what you'll have to do is: cargo install --git https://github.com/alexcrichton/wasm-gc wasm-gc foo.wasm bar.wasm And then `bar.wasm` should be the smallest we can get it! --- In any case for now I'd love feedback on this, particularly on the various integration points if you've got better ideas of how to approach them!
2 parents 5802986 + 80ff0f7 commit 41e03c3

File tree

162 files changed

+3644
-440
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

162 files changed

+3644
-440
lines changed

Diff for: .gitmodules

+6
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,9 @@
4242
[submodule "src/tools/miri"]
4343
path = src/tools/miri
4444
url = https://github.com/solson/miri.git
45+
[submodule "src/dlmalloc"]
46+
path = src/dlmalloc
47+
url = https://github.com/alexcrichton/dlmalloc-rs.git
48+
[submodule "src/binaryen"]
49+
path = src/binaryen
50+
url = https://github.com/alexcrichton/binaryen.git

Diff for: src/Cargo.lock

+19-3
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Diff for: src/binaryen

Submodule binaryen added at 1c9bf65

Diff for: src/bootstrap/check.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1211,7 +1211,8 @@ impl Step for Crate {
12111211
// ends up messing with various mtime calculations and such.
12121212
if !name.contains("jemalloc") &&
12131213
*name != *"build_helper" &&
1214-
!(name.starts_with("rustc_") && name.ends_with("san")) {
1214+
!(name.starts_with("rustc_") && name.ends_with("san")) &&
1215+
name != "dlmalloc" {
12151216
cargo.arg("-p").arg(&format!("{}:0.0.0", name));
12161217
}
12171218
for dep in build.crates[&name].deps.iter() {

Diff for: src/bootstrap/dist.rs

+5
Original file line numberDiff line numberDiff line change
@@ -672,6 +672,9 @@ fn copy_src_dirs(build: &Build, src_dirs: &[&str], exclude_dirs: &[&str], dst_di
672672
spath.ends_with(".s")) {
673673
return false
674674
}
675+
if spath.contains("test/emscripten") || spath.contains("test\\emscripten") {
676+
return false
677+
}
675678

676679
let full_path = Path::new(dir).join(path);
677680
if exclude_dirs.iter().any(|excl| full_path == Path::new(excl)) {
@@ -736,6 +739,7 @@ impl Step for Src {
736739
// (essentially libstd and all of its path dependencies)
737740
let std_src_dirs = [
738741
"src/build_helper",
742+
"src/dlmalloc",
739743
"src/liballoc",
740744
"src/liballoc_jemalloc",
741745
"src/liballoc_system",
@@ -754,6 +758,7 @@ impl Step for Src {
754758
"src/libunwind",
755759
"src/rustc/compiler_builtins_shim",
756760
"src/rustc/libc_shim",
761+
"src/rustc/dlmalloc_shim",
757762
"src/libtest",
758763
"src/libterm",
759764
"src/jemalloc",

Diff for: src/dlmalloc

Submodule dlmalloc added at d3812c3

Diff for: src/etc/wasm32-shim.js

+119
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
// This is a small "shim" program which is used when wasm32 unit tests are run
12+
// in this repository. This program is intended to be run in node.js and will
13+
// load a wasm module into memory, instantiate it with a set of imports, and
14+
// then run it.
15+
//
16+
// There's a bunch of helper functions defined here in `imports.env`, but note
17+
// that most of them aren't actually needed to execute most programs. Many of
18+
// these are just intended for completeness or debugging. Hopefully over time
19+
// nothing here is needed for completeness.
20+
21+
const fs = require('fs');
22+
const process = require('process');
23+
const buffer = fs.readFileSync(process.argv[2]);
24+
25+
Error.stackTraceLimit = 20;
26+
27+
let m = new WebAssembly.Module(buffer);
28+
29+
let memory = null;
30+
31+
function copystr(a, b) {
32+
if (memory === null) {
33+
return null
34+
}
35+
let view = new Uint8Array(memory.buffer).slice(a, a + b);
36+
return String.fromCharCode.apply(null, view);
37+
}
38+
39+
let imports = {};
40+
imports.env = {
41+
// These are generated by LLVM itself for various intrinsic calls. Hopefully
42+
// one day this is not necessary and something will automatically do this.
43+
fmod: function(x, y) { return x % y; },
44+
exp2: function(x) { return Math.pow(2, x); },
45+
exp2f: function(x) { return Math.pow(2, x); },
46+
ldexp: function(x, y) { return x * Math.pow(2, y); },
47+
ldexpf: function(x, y) { return x * Math.pow(2, y); },
48+
log10: function(x) { return Math.log10(x); },
49+
log10f: function(x) { return Math.log10(x); },
50+
51+
// These are called in src/libstd/sys/wasm/stdio.rs and are used when
52+
// debugging is enabled.
53+
rust_wasm_write_stdout: function(a, b) {
54+
let s = copystr(a, b);
55+
if (s !== null) {
56+
process.stdout.write(s);
57+
}
58+
},
59+
rust_wasm_write_stderr: function(a, b) {
60+
let s = copystr(a, b);
61+
if (s !== null) {
62+
process.stderr.write(s);
63+
}
64+
},
65+
66+
// These are called in src/libstd/sys/wasm/args.rs and are used when
67+
// debugging is enabled.
68+
rust_wasm_args_count: function() {
69+
if (memory === null)
70+
return 0;
71+
return process.argv.length - 2;
72+
},
73+
rust_wasm_args_arg_size: function(i) {
74+
return process.argv[i + 2].length;
75+
},
76+
rust_wasm_args_arg_fill: function(idx, ptr) {
77+
let arg = process.argv[idx + 2];
78+
let view = new Uint8Array(memory.buffer);
79+
for (var i = 0; i < arg.length; i++) {
80+
view[ptr + i] = arg.charCodeAt(i);
81+
}
82+
},
83+
84+
// These are called in src/libstd/sys/wasm/os.rs and are used when
85+
// debugging is enabled.
86+
rust_wasm_getenv_len: function(a, b) {
87+
let key = copystr(a, b);
88+
if (key === null) {
89+
return -1;
90+
}
91+
if (!(key in process.env)) {
92+
return -1;
93+
}
94+
return process.env[key].length;
95+
},
96+
rust_wasm_getenv_data: function(a, b, ptr) {
97+
let key = copystr(a, b);
98+
let value = process.env[key];
99+
let view = new Uint8Array(memory.buffer);
100+
for (var i = 0; i < value.length; i++) {
101+
view[ptr + i] = value.charCodeAt(i);
102+
}
103+
},
104+
};
105+
106+
let module_imports = WebAssembly.Module.imports(m);
107+
108+
for (var i = 0; i < module_imports.length; i++) {
109+
let imp = module_imports[i];
110+
if (imp.module != 'env') {
111+
continue
112+
}
113+
if (imp.name == 'memory' && imp.kind == 'memory') {
114+
memory = new WebAssembly.Memory({initial: 20});
115+
imports.env.memory = memory;
116+
}
117+
}
118+
119+
let instance = new WebAssembly.Instance(m, imports);

Diff for: src/liballoc_jemalloc/build.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ fn main() {
3131
let host = env::var("HOST").expect("HOST was not set");
3232
if target.contains("rumprun") || target.contains("bitrig") || target.contains("openbsd") ||
3333
target.contains("msvc") || target.contains("emscripten") || target.contains("fuchsia") ||
34-
target.contains("redox") {
34+
target.contains("redox") || target.contains("wasm32") {
3535
println!("cargo:rustc-cfg=dummy_jemalloc");
3636
return;
3737
}

Diff for: src/liballoc_system/Cargo.toml

+4
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,7 @@ doc = false
1313
alloc = { path = "../liballoc" }
1414
core = { path = "../libcore" }
1515
libc = { path = "../rustc/libc_shim" }
16+
17+
# See comments in the source for what this dependency is
18+
[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))'.dependencies]
19+
dlmalloc = { path = "../rustc/dlmalloc_shim" }

Diff for: src/liballoc_system/lib.rs

+90
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,14 @@
3434
target_arch = "powerpc64",
3535
target_arch = "asmjs",
3636
target_arch = "wasm32")))]
37+
#[allow(dead_code)]
3738
const MIN_ALIGN: usize = 8;
3839
#[cfg(all(any(target_arch = "x86_64",
3940
target_arch = "aarch64",
4041
target_arch = "mips64",
4142
target_arch = "s390x",
4243
target_arch = "sparc64")))]
44+
#[allow(dead_code)]
4345
const MIN_ALIGN: usize = 16;
4446

4547
extern crate alloc;
@@ -458,3 +460,91 @@ mod platform {
458460
}
459461
}
460462
}
463+
464+
// This is an implementation of a global allocator on the wasm32 platform when
465+
// emscripten is not in use. In that situation there's no actual runtime for us
466+
// to lean on for allocation, so instead we provide our own!
467+
//
468+
// The wasm32 instruction set has two instructions for getting the current
469+
// amount of memory and growing the amount of memory. These instructions are the
470+
// foundation on which we're able to build an allocator, so we do so! Note that
471+
// the instructions are also pretty "global" and this is the "global" allocator
472+
// after all!
473+
//
474+
// The current allocator here is the `dlmalloc` crate which we've got included
475+
// in the rust-lang/rust repository as a submodule. The crate is a port of
476+
// dlmalloc.c from C to Rust and is basically just so we can have "pure Rust"
477+
// for now which is currently technically required (can't link with C yet).
478+
//
479+
// The crate itself provides a global allocator which on wasm has no
480+
// synchronization as there are no threads!
481+
#[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))]
482+
mod platform {
483+
extern crate dlmalloc;
484+
485+
use alloc::heap::{Alloc, AllocErr, Layout, Excess, CannotReallocInPlace};
486+
use System;
487+
use self::dlmalloc::GlobalDlmalloc;
488+
489+
#[unstable(feature = "allocator_api", issue = "32838")]
490+
unsafe impl<'a> Alloc for &'a System {
491+
#[inline]
492+
unsafe fn alloc(&mut self, layout: Layout) -> Result<*mut u8, AllocErr> {
493+
GlobalDlmalloc.alloc(layout)
494+
}
495+
496+
#[inline]
497+
unsafe fn alloc_zeroed(&mut self, layout: Layout)
498+
-> Result<*mut u8, AllocErr>
499+
{
500+
GlobalDlmalloc.alloc_zeroed(layout)
501+
}
502+
503+
#[inline]
504+
unsafe fn dealloc(&mut self, ptr: *mut u8, layout: Layout) {
505+
GlobalDlmalloc.dealloc(ptr, layout)
506+
}
507+
508+
#[inline]
509+
unsafe fn realloc(&mut self,
510+
ptr: *mut u8,
511+
old_layout: Layout,
512+
new_layout: Layout) -> Result<*mut u8, AllocErr> {
513+
GlobalDlmalloc.realloc(ptr, old_layout, new_layout)
514+
}
515+
516+
#[inline]
517+
fn usable_size(&self, layout: &Layout) -> (usize, usize) {
518+
GlobalDlmalloc.usable_size(layout)
519+
}
520+
521+
#[inline]
522+
unsafe fn alloc_excess(&mut self, layout: Layout) -> Result<Excess, AllocErr> {
523+
GlobalDlmalloc.alloc_excess(layout)
524+
}
525+
526+
#[inline]
527+
unsafe fn realloc_excess(&mut self,
528+
ptr: *mut u8,
529+
layout: Layout,
530+
new_layout: Layout) -> Result<Excess, AllocErr> {
531+
GlobalDlmalloc.realloc_excess(ptr, layout, new_layout)
532+
}
533+
534+
#[inline]
535+
unsafe fn grow_in_place(&mut self,
536+
ptr: *mut u8,
537+
layout: Layout,
538+
new_layout: Layout) -> Result<(), CannotReallocInPlace> {
539+
GlobalDlmalloc.grow_in_place(ptr, layout, new_layout)
540+
}
541+
542+
#[inline]
543+
unsafe fn shrink_in_place(&mut self,
544+
ptr: *mut u8,
545+
layout: Layout,
546+
new_layout: Layout) -> Result<(), CannotReallocInPlace> {
547+
GlobalDlmalloc.shrink_in_place(ptr, layout, new_layout)
548+
}
549+
}
550+
}

Diff for: src/libcore/Cargo.toml

-3
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,6 @@ path = "lib.rs"
99
test = false
1010
bench = false
1111

12-
[dev-dependencies]
13-
rand = "0.3"
14-
1512
[[test]]
1613
name = "coretests"
1714
path = "../libcore/tests/lib.rs"

Diff for: src/libcore/tests/lib.rs

-2
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@
2828
#![feature(iter_rfind)]
2929
#![feature(iter_rfold)]
3030
#![feature(nonzero)]
31-
#![feature(rand)]
3231
#![feature(raw)]
3332
#![feature(refcell_replace_swap)]
3433
#![feature(sip_hash_13)]
@@ -49,7 +48,6 @@
4948

5049
extern crate core;
5150
extern crate test;
52-
extern crate rand;
5351

5452
mod any;
5553
mod array;

0 commit comments

Comments
 (0)