wasm_builder/lib.rs
1// This file is part of Tetcore.
2
3// Copyright (C) 2019-2021 Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! # Wasm builder is a utility for building a project as a Wasm binary
19//!
20//! The Wasm builder is a tool that integrates the process of building the WASM binary of your project into the main
21//! `cargo` build process.
22//!
23//! ## Project setup
24//!
25//! A project that should be compiled as a Wasm binary needs to:
26//!
27//! 1. Add a `build.rs` file.
28//! 2. Add `wasm-builder` as dependency into `build-dependencies`.
29//!
30//! The `build.rs` file needs to contain the following code:
31//!
32//! ```no_run
33//! use wasm_builder::WasmBuilder;
34//!
35//! fn main() {
36//! WasmBuilder::new()
37//! // Tell the builder to build the project (crate) this `build.rs` is part of.
38//! .with_current_project()
39//! // Make sure to export the `heap_base` global, this is required by Tetcore
40//! .export_heap_base()
41//! // Build the Wasm file so that it imports the memory (need to be provided by at instantiation)
42//! .import_memory()
43//! // Build it.
44//! .build()
45//! }
46//! ```
47//!
48//! As the final step, you need to add the following to your project:
49//!
50//! ```ignore
51//! include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
52//! ```
53//!
54//! This will include the generated Wasm binary as two constants `WASM_BINARY` and `WASM_BINARY_BLOATY`.
55//! The former is a compact Wasm binary and the latter is the Wasm binary as being generated by the compiler.
56//! Both variables have `Option<&'static [u8]>` as type.
57//!
58//! ### Feature
59//!
60//! Wasm builder supports to enable cargo features while building the Wasm binary. By default it will
61//! enable all features in the wasm build that are enabled for the native build except the
62//! `default` and `std` features. Besides that, wasm builder supports the special `runtime-wasm`
63//! feature. This `runtime-wasm` feature will be enabled by the wasm builder when it compiles the
64//! Wasm binary. If this feature is not present, it will not be enabled.
65//!
66//! ## Environment variables
67//!
68//! By using environment variables, you can configure which Wasm binaries are built and how:
69//!
70//! - `SKIP_WASM_BUILD` - Skips building any Wasm binary. This is useful when only native should be recompiled.
71//! If this is the first run and there doesn't exist a Wasm binary, this will set both
72//! variables to `None`.
73//! - `WASM_BUILD_TYPE` - Sets the build type for building Wasm binaries. Supported values are `release` or `debug`.
74//! By default the build type is equal to the build type used by the main build.
75//! - `FORCE_WASM_BUILD` - Can be set to force a Wasm build. On subsequent calls the value of the variable
76//! needs to change. As wasm-builder instructs `cargo` to watch for file changes
77//! this environment variable should only be required in certain circumstances.
78//! - `WASM_BUILD_RUSTFLAGS` - Extend `RUSTFLAGS` given to `cargo build` while building the wasm binary.
79//! - `WASM_BUILD_NO_COLOR` - Disable color output of the wasm build.
80//! - `WASM_TARGET_DIRECTORY` - Will copy any build Wasm binary to the given directory. The path needs
81//! to be absolute.
82//! - `WASM_BUILD_TOOLCHAIN` - The toolchain that should be used to build the Wasm binaries. The
83//! format needs to be the same as used by cargo, e.g. `nightly-2020-02-20`.
84//!
85//! Each project can be skipped individually by using the environment variable `SKIP_PROJECT_NAME_WASM_BUILD`.
86//! Where `PROJECT_NAME` needs to be replaced by the name of the cargo project, e.g. `node-runtime` will
87//! be `NODE_RUNTIME`.
88//!
89//! ## Prerequisites:
90//!
91//! Wasm builder requires the following prerequisites for building the Wasm binary:
92//!
93//! - rust nightly + `wasm32-unknown-unknown` toolchain
94//!
95//! If a specific rust nightly is installed with `rustup`, it is important that the wasm target is installed
96//! as well. For example if installing the rust nightly from 20.02.2020 using `rustup install nightly-2020-02-20`,
97//! the wasm target needs to be installed as well `rustup target add wasm32-unknown-unknown --toolchain nightly-2020-02-20`.
98
99use std::{env, fs, path::{PathBuf, Path}, process::Command, io::BufRead};
100
101mod builder;
102mod prerequisites;
103mod wasm_project;
104
105pub use builder::{WasmBuilder, WasmBuilderSelectProject};
106
107/// Environment variable that tells us to skip building the wasm binary.
108const SKIP_BUILD_ENV: &str = "SKIP_WASM_BUILD";
109
110/// Environment variable to force a certain build type when building the wasm binary.
111/// Expects "debug" or "release" as value.
112///
113/// By default the WASM binary uses the same build type as the main cargo build.
114const WASM_BUILD_TYPE_ENV: &str = "WASM_BUILD_TYPE";
115
116/// Environment variable to extend the `RUSTFLAGS` variable given to the wasm build.
117const WASM_BUILD_RUSTFLAGS_ENV: &str = "WASM_BUILD_RUSTFLAGS";
118
119/// Environment variable to set the target directory to copy the final wasm binary.
120///
121/// The directory needs to be an absolute path.
122const WASM_TARGET_DIRECTORY: &str = "WASM_TARGET_DIRECTORY";
123
124/// Environment variable to disable color output of the wasm build.
125const WASM_BUILD_NO_COLOR: &str = "WASM_BUILD_NO_COLOR";
126
127/// Environment variable to set the toolchain used to compile the wasm binary.
128const WASM_BUILD_TOOLCHAIN: &str = "WASM_BUILD_TOOLCHAIN";
129
130/// Environment variable that makes sure the WASM build is triggered.
131const FORCE_WASM_BUILD_ENV: &str = "FORCE_WASM_BUILD";
132
133/// Write to the given `file` if the `content` is different.
134fn write_file_if_changed(file: impl AsRef<Path>, content: impl AsRef<str>) {
135 if fs::read_to_string(file.as_ref()).ok().as_deref() != Some(content.as_ref()) {
136 fs::write(file.as_ref(), content.as_ref())
137 .unwrap_or_else(|_| panic!("Writing `{}` can not fail!", file.as_ref().display()));
138 }
139}
140
141/// Copy `src` to `dst` if the `dst` does not exist or is different.
142fn copy_file_if_changed(src: PathBuf, dst: PathBuf) {
143 let src_file = fs::read_to_string(&src).ok();
144 let dst_file = fs::read_to_string(&dst).ok();
145
146 if src_file != dst_file {
147 fs::copy(&src, &dst)
148 .unwrap_or_else(
149 |_| panic!("Copying `{}` to `{}` can not fail; qed", src.display(), dst.display())
150 );
151 }
152}
153
154/// Get a cargo command that compiles with nightly
155fn get_nightly_cargo() -> CargoCommand {
156 let env_cargo = CargoCommand::new(
157 &env::var("CARGO").expect("`CARGO` env variable is always set by cargo"),
158 );
159 let default_cargo = CargoCommand::new("cargo");
160 let rustup_run_nightly = CargoCommand::new_with_args("rustup", &["run", "nightly", "cargo"]);
161 let wasm_toolchain = env::var(WASM_BUILD_TOOLCHAIN).ok();
162
163 // First check if the user requested a specific toolchain
164 if let Some(cmd) = wasm_toolchain.and_then(|t| get_rustup_nightly(Some(t))) {
165 cmd
166 } else if env_cargo.is_nightly() {
167 env_cargo
168 } else if default_cargo.is_nightly() {
169 default_cargo
170 } else if rustup_run_nightly.is_nightly() {
171 rustup_run_nightly
172 } else {
173 // If no command before provided us with a nightly compiler, we try to search one
174 // with rustup. If that fails as well, we return the default cargo and let the prequisities
175 // check fail.
176 get_rustup_nightly(None).unwrap_or(default_cargo)
177 }
178}
179
180/// Get a nightly from rustup. If `selected` is `Some(_)`, a `CargoCommand` using the given
181/// nightly is returned.
182fn get_rustup_nightly(selected: Option<String>) -> Option<CargoCommand> {
183 let host = format!("-{}", env::var("HOST").expect("`HOST` is always set by cargo"));
184
185 let version = match selected {
186 Some(selected) => selected,
187 None => {
188 let output = Command::new("rustup").args(&["toolchain", "list"]).output().ok()?.stdout;
189 let lines = output.as_slice().lines();
190
191 let mut latest_nightly = None;
192 for line in lines.filter_map(|l| l.ok()) {
193 if line.starts_with("nightly-") && line.ends_with(&host) {
194 // Rustup prints them sorted
195 latest_nightly = Some(line.clone());
196 }
197 }
198
199 latest_nightly?.trim_end_matches(&host).into()
200 }
201 };
202
203 Some(CargoCommand::new_with_args("rustup", &["run", &version, "cargo"]))
204}
205
206/// Wraps a specific command which represents a cargo invocation.
207#[derive(Debug)]
208struct CargoCommand {
209 program: String,
210 args: Vec<String>,
211}
212
213impl CargoCommand {
214 fn new(program: &str) -> Self {
215 CargoCommand { program: program.into(), args: Vec::new() }
216 }
217
218 fn new_with_args(program: &str, args: &[&str]) -> Self {
219 CargoCommand {
220 program: program.into(),
221 args: args.iter().map(ToString::to_string).collect(),
222 }
223 }
224
225 fn command(&self) -> Command {
226 let mut cmd = Command::new(&self.program);
227 cmd.args(&self.args);
228 cmd
229 }
230
231 /// Check if the supplied cargo command is a nightly version
232 fn is_nightly(&self) -> bool {
233 // `RUSTC_BOOTSTRAP` tells a stable compiler to behave like a nightly. So, when this env
234 // variable is set, we can assume that whatever rust compiler we have, it is a nightly compiler.
235 // For "more" information, see:
236 // https://github.com/rust-lang/rust/blob/fa0f7d0080d8e7e9eb20aa9cbf8013f96c81287f/src/libsyntax/feature_gate/check.rs#L891
237 env::var("RUSTC_BOOTSTRAP").is_ok() ||
238 self.command()
239 .arg("--version")
240 .output()
241 .map_err(|_| ())
242 .and_then(|o| String::from_utf8(o.stdout).map_err(|_| ()))
243 .unwrap_or_default()
244 .contains("-nightly")
245 }
246}
247
248/// Wraps a [`CargoCommand`] and the version of `rustc` the cargo command uses.
249struct CargoCommandVersioned {
250 command: CargoCommand,
251 version: String,
252}
253
254impl CargoCommandVersioned {
255 fn new(command: CargoCommand, version: String) -> Self {
256 Self {
257 command,
258 version,
259 }
260 }
261
262 /// Returns the `rustc` version.
263 fn rustc_version(&self) -> &str {
264 &self.version
265 }
266}
267
268impl std::ops::Deref for CargoCommandVersioned {
269 type Target = CargoCommand;
270
271 fn deref(&self) -> &CargoCommand {
272 &self.command
273 }
274}
275
276/// Returns `true` when color output is enabled.
277fn color_output_enabled() -> bool {
278 env::var(crate::WASM_BUILD_NO_COLOR).is_err()
279}