Skip to main content

rustc_target/spec/base/
wasm.rs

1use std::borrow::Cow;
2
3use crate::spec::{
4    BinaryFormat, Cc, LinkArgs, LinkSelfContainedDefault, LinkerFlavor, Os, PanicStrategy,
5    RelocModel, TargetOptions, TlsModel, add_link_args, cvs,
6};
7
8pub(crate) fn options() -> TargetOptions {
9    macro_rules! args {
10        ($prefix:literal) => {
11            &[
12                // By default LLD only gives us one page of stack (64k) which is a
13                // little small. Default to a larger stack closer to other PC platforms
14                // (1MB) and users can always inject their own link-args to override this.
15                concat!($prefix, "-z"),
16                concat!($prefix, "stack-size=1048576"),
17                // By default LLD's memory layout is:
18                //
19                // 1. First, a blank page
20                // 2. Next, all static data
21                // 3. Finally, the main stack (which grows down)
22                //
23                // This has the unfortunate consequence that on stack overflows you
24                // corrupt static data and can cause some exceedingly weird bugs. To
25                // help detect this a little sooner we instead request that the stack is
26                // placed before static data.
27                //
28                // This means that we'll generate slightly larger binaries as references
29                // to static data will take more bytes in the ULEB128 encoding, but
30                // stack overflow will be guaranteed to trap as it underflows instead of
31                // corrupting static data.
32                concat!($prefix, "--stack-first"),
33                // LLD only implements C++-like demangling, which doesn't match our own
34                // mangling scheme. Tell LLD to not demangle anything and leave it up to
35                // us to demangle these symbols later. Currently rustc does not perform
36                // further demangling, but tools like twiggy and wasm-bindgen are intended
37                // to do so.
38                concat!($prefix, "--no-demangle"),
39            ]
40        };
41    }
42
43    let mut pre_link_args = TargetOptions::link_args(LinkerFlavor::WasmLld(Cc::No), &["-z", "stack-size=1048576", "--stack-first", "--no-demangle"]args!(""));
44    add_link_args(&mut pre_link_args, LinkerFlavor::WasmLld(Cc::Yes), &["-Wl,-z", "-Wl,stack-size=1048576", "-Wl,--stack-first",
            "-Wl,--no-demangle"]args!("-Wl,"));
45
46    TargetOptions {
47        is_like_wasm: true,
48        binary_format: BinaryFormat::Wasm,
49        families: ::std::borrow::Cow::Borrowed(&[::std::borrow::Cow::Borrowed("wasm")])cvs!["wasm"],
50
51        // we allow dynamic linking, but only cdylibs. Basically we allow a
52        // final library artifact that exports some symbols (a wasm module) but
53        // we don't allow intermediate `dylib` crate types
54        dynamic_linking: true,
55        only_cdylib: true,
56
57        // relatively self-explanatory!
58        exe_suffix: ".wasm".into(),
59        dll_prefix: "".into(),
60        dll_suffix: ".wasm".into(),
61        eh_frame_header: false,
62
63        max_atomic_width: Some(64),
64
65        // WebAssembly targets all started out originally as `-Cpanic=abort`
66        // since that was all that worked. Since then, however, the WebAssembly
67        // exception-handling proposal has been finalized/implemented and is now
68        // supported in both LLVM & rustc & libstd & co. The default still
69        // remains at `-Cpanic=abort` for now for historical compatibility,
70        // but `bootstrap.toml` can be used to configure a local build to
71        // use `-Cpanic=unwind` instead. This is used in CI, for example, to
72        // test wasm targets with `-Cpanic=unwind`.
73        //
74        // In the future this might change where preexisting targets migrate,
75        // but that's not going to be as easy as just changing this, so for now
76        // this is just a local build configuration option.
77        panic_strategy: if ::core::option::Option::None::<&'static str>option_env!("CFG_WASM_PANIC_UNWIND_DEFAULT") == Some("1") {
78            PanicStrategy::Unwind
79        } else {
80            PanicStrategy::Abort
81        },
82
83        // Wasm doesn't have atomics yet, so tell LLVM that we're in a single
84        // threaded model which will legalize atomics to normal operations.
85        singlethread: true,
86
87        // we use the LLD shipped with the Rust toolchain by default
88        linker: Some("rust-lld".into()),
89        linker_flavor: LinkerFlavor::WasmLld(Cc::No),
90
91        pre_link_args,
92
93        // FIXME: Figure out cases in which WASM needs to link with a native toolchain.
94        //
95        // rust-lang/rust#104137: cannot blindly remove this without putting in
96        // some other way to compensate for lack of `-nostartfiles` in linker
97        // invocation.
98        link_self_contained: LinkSelfContainedDefault::True,
99
100        // This has no effect in LLVM 8 or prior, but in LLVM 9 and later when
101        // PIC code is implemented this has quite a drastic effect if it stays
102        // at the default, `pic`. In an effort to keep wasm binaries as minimal
103        // as possible we're defaulting to `static` for now, but the hope is
104        // that eventually we can ship a `pic`-compatible standard library which
105        // works with `static` as well (or works with some method of generating
106        // non-relative calls and such later on).
107        relocation_model: RelocModel::Static,
108
109        // When the atomics feature is activated then these two keys matter,
110        // otherwise they're basically ignored by the standard library. In this
111        // mode, however, the `#[thread_local]` attribute works (i.e.
112        // `has_thread_local`) and we need to get it to work by specifying
113        // `local-exec` as that's all that's implemented in LLVM today for wasm.
114        has_thread_local: true,
115        tls_model: TlsModel::LocalExec,
116
117        // gdb scripts don't work on wasm blobs
118        emit_debug_gdb_scripts: false,
119
120        // There's more discussion of this at
121        // https://bugs.llvm.org/show_bug.cgi?id=52442 but the general result is
122        // that this isn't useful for wasm and has tricky issues with
123        // representation, so this is disabled.
124        generate_arange_section: false,
125
126        // Differ from LLVM's default to use the legacy exception-handling
127        // proposal instructions and use the standard exception-handling
128        // instructions. Note that this is only applicable when unwinding is
129        // actually turned on, which it's not by default on this target. For
130        // `-Zbuild-std` builds, however, this affects when rebuilding libstd
131        // with unwinding.
132        llvm_args: ::std::borrow::Cow::Borrowed(&[::std::borrow::Cow::Borrowed("-wasm-use-legacy-eh=false")])cvs!["-wasm-use-legacy-eh=false"],
133
134        // WASI's `sys::args::init` function ignores its arguments; instead,
135        // `args::args()` makes the WASI API calls itself.
136        //
137        // Other Wasm targets make no use of `std::env` entirely.
138        // Emscripten enables it explicitly.
139        main_needs_argc_argv: false,
140
141        ..Default::default()
142    }
143}
144
145pub(crate) fn emscripten_options() -> TargetOptions {
146    TargetOptions {
147        os: Os::Emscripten,
148        linker_flavor: LinkerFlavor::EmCc,
149        // emcc emits two files - a .js file to instantiate the wasm and supply platform
150        // functionality, and a .wasm file.
151        exe_suffix: ".js".into(),
152        linker: None,
153        // Reset flags for non-Em flavors back to empty to satisfy sanity checking tests.
154        pre_link_args: LinkArgs::new(),
155        post_link_args: TargetOptions::link_args(LinkerFlavor::EmCc, &["-sABORTING_MALLOC=0"]),
156        relocation_model: RelocModel::Pic,
157        // crt_static should always be true for an executable and always false
158        // for a shared library. There is no easy way to indicate this and it
159        // doesn't seem to matter much so we set crt_static_allows_dylibs to
160        // true and leave crt_static as true when linking dynamic libraries.
161        // wasi also sets crt_static_allows_dylibs: true so this is at least
162        // aligned between wasm targets.
163        crt_static_respected: true,
164        crt_static_default: true,
165        crt_static_allows_dylibs: true,
166        main_needs_argc_argv: true,
167        // Use the wasm C-ABI entry name from the tool-conventions BasicCABI
168        // spec rather than a raw `main`, as referenced by emscripten's crt/libc.
169        // Required for entry paths like `-sPROXY_TO_PTHREAD`, whose
170        // `crt1_proxy_main` links against `__main_argc_argv`.
171        entry_name: "__main_argc_argv".into(),
172        panic_strategy: PanicStrategy::Unwind,
173        no_default_libraries: false,
174        families: ::std::borrow::Cow::Borrowed(&[::std::borrow::Cow::Borrowed("unix"),
                ::std::borrow::Cow::Borrowed("wasm")])cvs!["unix", "wasm"],
175        // Explicitly override the `base::wasm`'s `llvm_args` back to empty. The
176        // base is to force using the most standard exception-handling
177        // instructions, when enabled, but this target is intended to follow
178        // Emscripten, which is whatever LLVM defaults to.
179        llvm_args: ::std::borrow::Cow::Borrowed(&[])cvs![],
180        ..options()
181    }
182}
183
184pub(crate) fn default_wasm64_features() -> Cow<'static, str> {
185    // Any engine that implements wasm64 will surely implement the rest of
186    // these features since they were all merged into the official spec by the
187    // time wasm64 was designed.
188    "+bulk-memory,+mutable-globals,+sign-ext,+nontrapping-fptoint".into()
189}