substrate_wasm_builder/lib.rs
1// This file is part of Substrate.
2
3// Copyright (C) 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
21//! project into the main `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 substrate_wasm_builder::WasmBuilder;
34//!
35//! fn main() {
36//! // Builds the WASM binary using the recommended defaults.
37//! // If you need more control, you can call `new` or `init_with_defaults`.
38//! WasmBuilder::build_using_defaults();
39//! }
40//! ```
41//!
42//! As the final step, you need to add the following to your project:
43//!
44//! ```ignore
45//! include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
46//! ```
47//!
48//! This will include the generated Wasm binary as two constants `WASM_BINARY` and
49//! `WASM_BINARY_BLOATY`. The former is a compact Wasm binary and the latter is the Wasm binary as
50//! being generated by the compiler. Both variables have `Option<&'static [u8]>` as type.
51//! Additionally it will create the `WASM_BINARY_PATH` which is the path to the WASM blob on the
52//! filesystem.
53//!
54//! ### Feature
55//!
56//! Wasm builder supports to enable cargo features while building the Wasm binary. By default it
57//! will enable all features in the wasm build that are enabled for the native build except the
58//! `default` and `std` features. Besides that, wasm builder supports the special `runtime-wasm`
59//! feature. This `runtime-wasm` feature will be enabled by the wasm builder when it compiles the
60//! Wasm binary. If this feature is not present, it will not be enabled.
61//!
62//! ## Environment variables
63//!
64//! By using environment variables, you can configure which Wasm binaries are built and how:
65//!
66//! - `SUBSTRATE_RUNTIME_TARGET` - Sets the target for building runtime. Supported values are `wasm`
67//! or `riscv` (experimental, do not use it in production!). By default the target is equal to
68//! `wasm`.
69//! - `SKIP_WASM_BUILD` - Skips building any Wasm binary. This is useful when only native should be
70//! recompiled. If this is the first run and there doesn't exist a Wasm binary, this will set both
71//! variables to `None`.
72//! - `WASM_BUILD_TYPE` - Sets the build type for building Wasm binaries. Supported values are
73//! `release` or `debug`. By default the build type is equal to the build type used by the main
74//! build.
75//! - `FORCE_WASM_BUILD` - Can be set to force a Wasm build. On subsequent calls the value of the
76//! variable needs to change. As wasm-builder instructs `cargo` to watch for file changes this
77//! environment variable should only be required in certain circumstances.
78//! - `WASM_BUILD_RUSTFLAGS` - Extend `RUSTFLAGS` given to `cargo build` while building the wasm
79//! binary.
80//! - `WASM_BUILD_NO_COLOR` - Disable color output of the wasm build.
81//! - `WASM_TARGET_DIRECTORY` - Will copy any build Wasm binary to the given directory. The path
82//! needs to be absolute.
83//! - `WASM_BUILD_TOOLCHAIN` - The toolchain that should be used to build the Wasm binaries. The
84//! format needs to be the same as used by cargo, e.g. `nightly-2024-12-26`.
85//! - `WASM_BUILD_WORKSPACE_HINT` - Hint the workspace that is being built. This is normally not
86//! required as we walk up from the target directory until we find a `Cargo.toml`. If the target
87//! directory is changed for the build, this environment variable can be used to point to the
88//! actual workspace.
89//! - `WASM_BUILD_STD` - Sets whether the Rust's standard library crates (`core` and `alloc`) will
90//! also be built. This is necessary to make sure the standard library crates only use the exact
91//! WASM feature set that our executor supports. Enabled by default for RISC-V target and WASM
92//! target (but only if Rust < 1.84). Disabled by default for WASM target and Rust >= 1.84.
93//! - `WASM_BUILD_CARGO_ARGS` - This can take a string as space separated list of `cargo` arguments.
94//! It was added specifically for the use case of enabling JSON diagnostic messages during the
95//! build phase, to be used by IDEs that parse them, but it might be useful for other cases too.
96//! - `CARGO_NET_OFFLINE` - If `true`, `--offline` will be passed to all processes launched to
97//! prevent network access. Useful in offline environments.
98//!
99//! Each project can be skipped individually by using the environment variable
100//! `SKIP_PROJECT_NAME_WASM_BUILD`. Where `PROJECT_NAME` needs to be replaced by the name of the
101//! cargo project, e.g. `kitchensink-runtime` will be `NODE_RUNTIME`.
102//!
103//! ## Prerequisites:
104//!
105//! Wasm builder requires the following prerequisites for building the Wasm binary:
106//! - Rust >= 1.68 and Rust < 1.84:
107//! - `wasm32-unknown-unknown` target
108//! - `rust-src` component
109//! - Rust >= 1.84:
110//! - `wasm32v1-none` target
111//!
112//! If a specific Rust is installed with `rustup`, it is important that the WASM
113//! target is installed as well. For example if installing the Rust from
114//! 26.12.2024 using `rustup install nightly-2024-12-26`, the WASM target
115//! (`wasm32-unknown-unknown` or `wasm32v1-none`) needs to be installed as well
116//! `rustup target add wasm32-unknown-unknown --toolchain nightly-2024-12-26`.
117//! To install the `rust-src` component, use `rustup component add rust-src
118//! --toolchain nightly-2024-12-26`.
119
120use prerequisites::DummyCrate;
121use std::{env, fs, io::BufRead, path::Path, process::Command};
122use version::Version;
123
124mod builder;
125#[cfg(feature = "metadata-hash")]
126mod metadata_hash;
127mod prerequisites;
128mod version;
129mod wasm_project;
130
131pub use builder::{WasmBuilder, WasmBuilderSelectProject};
132
133/// Environment variable that tells us to skip building the wasm binary.
134const SKIP_BUILD_ENV: &str = "SKIP_WASM_BUILD";
135
136/// Environment variable that tells us whether we should avoid network requests
137const OFFLINE: &str = "CARGO_NET_OFFLINE";
138
139/// Environment variable to force a certain build type when building the wasm binary.
140/// Expects "debug", "release" or "production" as value.
141///
142/// When unset the WASM binary uses the same build type as the main cargo build with
143/// the exception of a debug build: In this case the wasm build defaults to `release` in
144/// order to avoid a slowdown when not explicitly requested.
145const WASM_BUILD_TYPE_ENV: &str = "WASM_BUILD_TYPE";
146
147/// Environment variable to extend the `RUSTFLAGS` variable given to the wasm build.
148const WASM_BUILD_RUSTFLAGS_ENV: &str = "WASM_BUILD_RUSTFLAGS";
149
150/// Environment variable to set the target directory to copy the final wasm binary.
151///
152/// The directory needs to be an absolute path.
153const WASM_TARGET_DIRECTORY: &str = "WASM_TARGET_DIRECTORY";
154
155/// Environment variable to disable color output of the wasm build.
156const WASM_BUILD_NO_COLOR: &str = "WASM_BUILD_NO_COLOR";
157
158/// Environment variable to set the toolchain used to compile the wasm binary.
159const WASM_BUILD_TOOLCHAIN: &str = "WASM_BUILD_TOOLCHAIN";
160
161/// Environment variable that makes sure the WASM build is triggered.
162const FORCE_WASM_BUILD_ENV: &str = "FORCE_WASM_BUILD";
163
164/// Environment variable that hints the workspace we are building.
165const WASM_BUILD_WORKSPACE_HINT: &str = "WASM_BUILD_WORKSPACE_HINT";
166
167/// Environment variable to set whether we'll build `core`/`alloc`.
168const WASM_BUILD_STD: &str = "WASM_BUILD_STD";
169
170/// Environment variable to set additional cargo arguments that might be useful
171/// during the build phase.
172const WASM_BUILD_CARGO_ARGS: &str = "WASM_BUILD_CARGO_ARGS";
173
174/// The target to use for the runtime. Valid values are `wasm` (default) or `riscv`.
175const RUNTIME_TARGET: &str = "SUBSTRATE_RUNTIME_TARGET";
176
177/// Write to the given `file` if the `content` is different.
178fn write_file_if_changed(file: impl AsRef<Path>, content: impl AsRef<str>) {
179 if fs::read_to_string(file.as_ref()).ok().as_deref() != Some(content.as_ref()) {
180 fs::write(file.as_ref(), content.as_ref())
181 .unwrap_or_else(|_| panic!("Writing `{}` can not fail!", file.as_ref().display()));
182 }
183}
184
185/// Copy `src` to `dst` if the `dst` does not exist or is different.
186fn copy_file_if_changed(src: &Path, dst: &Path) -> bool {
187 let src_file = fs::read(src).ok();
188 let dst_file = fs::read(dst).ok();
189
190 if src_file != dst_file {
191 fs::copy(&src, &dst).unwrap_or_else(|_| {
192 panic!("Copying `{}` to `{}` can not fail; qed", src.display(), dst.display())
193 });
194
195 true
196 } else {
197 false
198 }
199}
200
201/// Get a cargo command that should be used to invoke the compilation.
202fn get_cargo_command(target: RuntimeTarget) -> CargoCommand {
203 let env_cargo =
204 CargoCommand::new(&env::var("CARGO").expect("`CARGO` env variable is always set by cargo"));
205 let default_cargo = CargoCommand::new("cargo");
206 let wasm_toolchain = env::var(WASM_BUILD_TOOLCHAIN).ok();
207
208 // First check if the user requested a specific toolchain
209 if let Some(cmd) =
210 wasm_toolchain.map(|t| CargoCommand::new_with_args("rustup", &["run", &t, "cargo"]))
211 {
212 cmd
213 } else if env_cargo.supports_substrate_runtime_env(target) {
214 env_cargo
215 } else if default_cargo.supports_substrate_runtime_env(target) {
216 default_cargo
217 } else {
218 // If no command before provided us with a cargo that supports our Substrate wasm env, we
219 // try to search one with rustup. If that fails as well, we return the default cargo and let
220 // the perquisites check fail.
221 get_rustup_command(target).unwrap_or(default_cargo)
222 }
223}
224
225/// Get the newest rustup command that supports compiling a runtime.
226///
227/// Stable versions are always favored over nightly versions even if the nightly versions are
228/// newer.
229fn get_rustup_command(target: RuntimeTarget) -> Option<CargoCommand> {
230 let output = Command::new("rustup").args(&["toolchain", "list"]).output().ok()?.stdout;
231 let lines = output.as_slice().lines();
232
233 let mut versions = Vec::new();
234 for line in lines.filter_map(|l| l.ok()) {
235 // Split by a space to get rid of e.g. " (default)" at the end.
236 let rustup_version = line.split(" ").next().unwrap();
237 let cmd = CargoCommand::new_with_args("rustup", &["run", &rustup_version, "cargo"]);
238
239 if !cmd.supports_substrate_runtime_env(target) {
240 continue
241 }
242
243 let Some(cargo_version) = cmd.version() else { continue };
244
245 versions.push((cargo_version, rustup_version.to_string()));
246 }
247
248 // Sort by the parsed version to get the latest version (greatest version) at the end of the
249 // vec.
250 versions.sort_by_key(|v| v.0);
251 let version = &versions.last()?.1;
252
253 Some(CargoCommand::new_with_args("rustup", &["run", &version, "cargo"]))
254}
255
256/// Wraps a specific command which represents a cargo invocation.
257#[derive(Debug, Clone)]
258struct CargoCommand {
259 program: String,
260 args: Vec<String>,
261 version: Option<Version>,
262}
263
264impl CargoCommand {
265 fn new(program: &str) -> Self {
266 let version = Self::extract_version(program, &[]);
267
268 CargoCommand { program: program.into(), args: Vec::new(), version }
269 }
270
271 fn new_with_args(program: &str, args: &[&str]) -> Self {
272 let version = Self::extract_version(program, args);
273
274 CargoCommand {
275 program: program.into(),
276 args: args.iter().map(ToString::to_string).collect(),
277 version,
278 }
279 }
280
281 fn command(&self) -> Command {
282 let mut cmd = Command::new(&self.program);
283 cmd.args(&self.args);
284 cmd
285 }
286
287 fn extract_version(program: &str, args: &[&str]) -> Option<Version> {
288 let version = Command::new(program)
289 .args(args)
290 .arg("--version")
291 .output()
292 .ok()
293 .and_then(|o| String::from_utf8(o.stdout).ok())?;
294
295 Version::extract(&version)
296 }
297
298 /// Returns the version of this cargo command or `None` if it failed to extract the version.
299 fn version(&self) -> Option<Version> {
300 self.version
301 }
302
303 /// Returns whether this version of the toolchain supports nightly features.
304 fn supports_nightly_features(&self) -> bool {
305 self.version.map_or(false, |version| version.is_nightly) ||
306 env::var("RUSTC_BOOTSTRAP").is_ok()
307 }
308
309 /// Check if the supplied cargo command supports our runtime environment.
310 fn supports_substrate_runtime_env(&self, target: RuntimeTarget) -> bool {
311 match target {
312 RuntimeTarget::Wasm => self.supports_substrate_runtime_env_wasm(),
313 RuntimeTarget::Riscv => true,
314 }
315 }
316
317 /// Check if the supplied cargo command supports our Substrate wasm environment.
318 ///
319 /// This means that either the cargo version is at minimum 1.68.0 or this is a nightly cargo.
320 ///
321 /// Assumes that cargo version matches the rustc version.
322 fn supports_substrate_runtime_env_wasm(&self) -> bool {
323 // `RUSTC_BOOTSTRAP` tells a stable compiler to behave like a nightly. So, when this env
324 // variable is set, we can assume that whatever rust compiler we have, it is a nightly
325 // compiler. For "more" information, see:
326 // https://github.com/rust-lang/rust/blob/fa0f7d0080d8e7e9eb20aa9cbf8013f96c81287f/src/libsyntax/feature_gate/check.rs#L891
327 if env::var("RUSTC_BOOTSTRAP").is_ok() {
328 return true
329 }
330
331 let Some(version) = self.version() else { return false };
332
333 // Check if major and minor are greater or equal than 1.68 or this is a nightly.
334 version.major > 1 || (version.major == 1 && version.minor >= 68) || version.is_nightly
335 }
336
337 /// Returns whether this version of the toolchain supports the `wasm32v1-none` target.
338 fn supports_wasm32v1_none_target(&self) -> bool {
339 self.version.map_or(false, |version| {
340 // Check if major and minor are greater or equal than 1.84.
341 version.major > 1 || (version.major == 1 && version.minor >= 84)
342 })
343 }
344
345 /// Returns whether the `wasm32v1-none` target is installed in this version of the toolchain.
346 fn is_wasm32v1_none_target_installed(&self) -> bool {
347 let dummy_crate = DummyCrate::new(self, RuntimeTarget::Wasm, true);
348 dummy_crate.is_target_installed("wasm32v1-none").unwrap_or(false)
349 }
350
351 /// Returns whether the `wasm32v1-none` target is available in this version of the toolchain.
352 fn is_wasm32v1_none_target_available(&self) -> bool {
353 // Check if major and minor are greater or equal than 1.84 and that the `wasm32v1-none`
354 // target is installed for this toolchain.
355 self.supports_wasm32v1_none_target() && self.is_wasm32v1_none_target_installed()
356 }
357}
358
359/// Wraps a [`CargoCommand`] and the version of `rustc` the cargo command uses.
360#[derive(Clone)]
361struct CargoCommandVersioned {
362 command: CargoCommand,
363 version: String,
364}
365
366impl CargoCommandVersioned {
367 fn new(command: CargoCommand, version: String) -> Self {
368 Self { command, version }
369 }
370
371 /// Returns the `rustc` version.
372 fn rustc_version(&self) -> &str {
373 &self.version
374 }
375}
376
377impl std::ops::Deref for CargoCommandVersioned {
378 type Target = CargoCommand;
379
380 fn deref(&self) -> &CargoCommand {
381 &self.command
382 }
383}
384
385/// Returns `true` when color output is enabled.
386fn color_output_enabled() -> bool {
387 env::var(crate::WASM_BUILD_NO_COLOR).is_err()
388}
389
390/// Fetches a boolean environment variable. Will exit the process if the value is invalid.
391fn get_bool_environment_variable(name: &str) -> Option<bool> {
392 let value = env::var_os(name)?;
393
394 // We're comparing `OsString`s here so we can't use a `match`.
395 if value == "1" {
396 Some(true)
397 } else if value == "0" {
398 Some(false)
399 } else {
400 build_helper::warning!(
401 "the '{name}' environment variable has an invalid value; it must be either '1' or '0'",
402 );
403 std::process::exit(1);
404 }
405}
406
407#[derive(Copy, Clone, PartialEq, Eq)]
408enum RuntimeTarget {
409 Wasm,
410 Riscv,
411}
412
413impl RuntimeTarget {
414 /// Creates a new instance.
415 fn new() -> Self {
416 let Some(value) = env::var_os(RUNTIME_TARGET) else {
417 return Self::Wasm;
418 };
419
420 if value == "wasm" {
421 Self::Wasm
422 } else if value == "riscv" {
423 Self::Riscv
424 } else {
425 build_helper::warning!(
426 "RUNTIME_TARGET environment variable must be set to either \"wasm\" or \"riscv\""
427 );
428 std::process::exit(1);
429 }
430 }
431
432 /// Figures out the target parameter value for rustc.
433 fn rustc_target(self, cargo_command: &CargoCommand) -> String {
434 match self {
435 RuntimeTarget::Wasm =>
436 if cargo_command.is_wasm32v1_none_target_available() {
437 "wasm32v1-none".into()
438 } else {
439 "wasm32-unknown-unknown".into()
440 },
441 RuntimeTarget::Riscv => {
442 let mut args = polkavm_linker::TargetJsonArgs::default();
443 args.is_64_bit = false;
444 let path = polkavm_linker::target_json_path(args).expect("riscv not found");
445 path.into_os_string().into_string().unwrap()
446 },
447 }
448 }
449
450 /// Figures out the target directory name used by cargo.
451 fn rustc_target_dir(self, cargo_command: &CargoCommand) -> &'static str {
452 match self {
453 RuntimeTarget::Wasm =>
454 if cargo_command.is_wasm32v1_none_target_available() {
455 "wasm32v1-none".into()
456 } else {
457 "wasm32-unknown-unknown".into()
458 },
459 RuntimeTarget::Riscv => "riscv32emac-unknown-none-polkavm",
460 }
461 }
462
463 /// Figures out the build-std argument.
464 fn rustc_target_build_std(self, cargo_command: &CargoCommand) -> Option<&'static str> {
465 if !crate::get_bool_environment_variable(crate::WASM_BUILD_STD).unwrap_or_else(
466 || match self {
467 RuntimeTarget::Wasm => !cargo_command.is_wasm32v1_none_target_available(),
468 RuntimeTarget::Riscv => true,
469 },
470 ) {
471 return None;
472 }
473
474 // This is a nightly-only flag.
475
476 // We only build `core` and `alloc` crates since wasm-builder disables `std` featue for
477 // runtime. Thus the runtime is `#![no_std]` crate.
478
479 Some("build-std=core,alloc")
480 }
481}