Skip to main content

ab_contracts_tooling/
build.rs

1//! Build an ELF `cdylib` with the contract
2
3use crate::target_specification::TARGET_SPECIFICATION_NAME;
4use anyhow::Context;
5use cargo_metadata::MetadataCommand;
6use std::env;
7use std::path::{Path, PathBuf};
8use std::process::Command;
9use tracing::debug;
10
11/// Options for building a contract
12#[derive(Debug)]
13pub struct BuildOptions<'a> {
14    /// Package to build.
15    ///
16    /// A package in the current directory is built if not specified explicitly.
17    pub package: Option<&'a str>,
18    /// Comma separated list of features to activate
19    pub features: Option<&'a str>,
20    /// Do not activate the `default` feature
21    pub no_default_features: bool,
22    /// Build artifacts with the specified profile
23    pub profile: &'a str,
24    /// Path to the target specification JSON file
25    pub target_specification_path: &'a Path,
26    /// Custom target directory to use instead of the default one
27    pub target_dir: Option<&'a Path>,
28    /// Extra flags for `rustc`, appended to `RUSTFLAGS` of the contract build.
29    ///
30    /// `RUSTFLAGS` of the host build are not used, since they don't apply to a contract built for
31    /// a different target.
32    pub extra_rustflags: Option<&'a str>,
33}
34
35/// Build a `cdylib` with the contract and return the path to the resulting ELF file
36pub fn build_cdylib(options: BuildOptions<'_>) -> anyhow::Result<PathBuf> {
37    let BuildOptions {
38        package,
39        features,
40        no_default_features,
41        profile,
42        target_specification_path,
43        target_dir,
44        extra_rustflags,
45    } = options;
46
47    // Hack for enabling RISC-V Zknh backend in `sha2` crate since it is a nightly-only feature,
48    // and they really don't like using normal features for it.
49    let mut rustflags =
50        String::from(r#"--cfg sha2_backend="riscv-zknh" --cfg sha2_backend_riscv_zknh="compact""#);
51    if let Some(extra_rustflags) = extra_rustflags {
52        rustflags.push(' ');
53        rustflags.push_str(extra_rustflags);
54    }
55
56    let mut command_builder = Command::new("cargo");
57    command_builder
58        .env_remove("RUSTFLAGS")
59        .env_remove("CARGO_ENCODED_RUSTFLAGS")
60        // Remove Clippy's wrapper in place that makes Cargo fingerprint contract artifacts
61        // differently under `cargo clippy` than under `cargo build`, rebuilding all of them on
62        // every switch between the two
63        .env_remove("RUSTC_WORKSPACE_WRAPPER")
64        .env("RUSTFLAGS", rustflags)
65        .args([
66            "rustc",
67            "-Zbuild-std=core",
68            "--crate-type",
69            "cdylib",
70            "-Zjson-target-spec",
71            "--target",
72            target_specification_path
73                .to_str()
74                .context("Path to target specification file is not valid UTF-8")?,
75        ]);
76
77    if env::var("MIRI_SYSROOT").is_ok() {
78        command_builder
79            .env_remove("RUSTC")
80            .env_remove("RUSTC_WRAPPER");
81    }
82
83    if let Some(package) = package {
84        command_builder.args([
85            "--package",
86            package,
87            "--features",
88            &format!("{package}/guest"),
89        ]);
90    } else {
91        command_builder.args(["--features", "guest"]);
92    }
93    if let Some(features) = features {
94        command_builder.args(["--features", features]);
95    }
96    if no_default_features {
97        command_builder.arg("--no-default-features");
98    }
99
100    command_builder.args(["--profile", profile]);
101
102    let metadata = MetadataCommand::new()
103        .exec()
104        .context("Failed to fetch cargo metadata")?;
105
106    let target_directory = if let Some(target_dir) = target_dir {
107        command_builder.args([
108            "--target-dir",
109            target_dir
110                .to_str()
111                .context("Path to target directory is not valid UTF-8")?,
112        ]);
113        target_dir
114    } else {
115        metadata.target_directory.as_std_path()
116    };
117
118    let cdylib_path = target_directory
119        .join(TARGET_SPECIFICATION_NAME)
120        .join(if profile == "dev" { "debug" } else { profile })
121        .join({
122            let package_name = if let Some(package) = package {
123                package
124            } else {
125                let current_dir = env::current_dir().context("Failed to get current directory")?;
126                let current_manifest = current_dir.join("Cargo.toml");
127                metadata
128                    .packages
129                    .iter()
130                    .find_map(|package| {
131                        if package.manifest_path == current_manifest {
132                            Some(&package.name)
133                        } else {
134                            None
135                        }
136                    })
137                    .context("Failed to find package name")?
138            };
139
140            format!("{}.contract.so", package_name.replace('-', "_"))
141        });
142
143    debug!(
144        ?package,
145        ?features,
146        ?profile,
147        ?target_specification_path,
148        cdylib_path = ?cdylib_path,
149        command = ?command_builder,
150        "Building ELF `cdylib` contract"
151    );
152
153    let status = command_builder
154        .status()
155        .context("Failed to build a contract")?;
156
157    if !status.success() {
158        return Err(anyhow::anyhow!("Failed to build a contract"));
159    }
160
161    Ok(cdylib_path)
162}