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    /// Build artifacts with the specified profile
21    pub profile: &'a str,
22    /// Path to the target specification JSON file
23    pub target_specification_path: &'a Path,
24    /// Custom target directory to use instead of the default one
25    pub target_dir: Option<&'a Path>,
26}
27
28/// Build a `cdylib` with the contract and return the path to the resulting ELF file
29pub fn build_cdylib(options: BuildOptions<'_>) -> anyhow::Result<PathBuf> {
30    let BuildOptions {
31        package,
32        features,
33        profile,
34        target_specification_path,
35        target_dir,
36    } = options;
37
38    let mut command_builder = Command::new("cargo");
39    command_builder
40        .env_remove("RUSTFLAGS")
41        .env_remove("CARGO_ENCODED_RUSTFLAGS")
42        // Hack for enabling RISC-V Zknh backend in `sha2` crate since it is a nightly-only feature,
43        // and they really don't like using normal features for it.
44        // `-Znext-solver=globally` is needed for `generic_const_args` in various crates.
45        .env(
46            "RUSTFLAGS",
47            r#"--cfg sha2_backend="riscv-zknh" --cfg sha2_backend_riscv_zknh="compact"
48            -Znext-solver=globally"#,
49        )
50        .args([
51            "rustc",
52            "-Zbuild-std=core",
53            "--crate-type",
54            "cdylib",
55            "-Zjson-target-spec",
56            "--target",
57            target_specification_path
58                .to_str()
59                .context("Path to target specification file is not valid UTF-8")?,
60        ])
61        // `-Znext-solver=globally` is needed for `generic_const_args` in various crates, it is not
62        // propagated to the target's build script by default, hence such hacks
63        .args([
64            "-Ztarget-applies-to-host",
65            "-Zhost-config",
66            "--config",
67            r#"host.rustflags=["-Znext-solver=globally"]"#,
68        ]);
69
70    if env::var("MIRI_SYSROOT").is_ok() {
71        command_builder
72            .env_remove("RUSTC")
73            .env_remove("RUSTC_WRAPPER");
74    }
75
76    if let Some(package) = package {
77        command_builder.args([
78            "--package",
79            package,
80            "--features",
81            &format!("{package}/guest"),
82        ]);
83    } else {
84        command_builder.args(["--features", "guest"]);
85    }
86    if let Some(features) = features {
87        command_builder.args(["--features", features]);
88    }
89
90    command_builder.args(["--profile", profile]);
91
92    let metadata = MetadataCommand::new()
93        .exec()
94        .context("Failed to fetch cargo metadata")?;
95
96    let target_directory = if let Some(target_dir) = target_dir {
97        command_builder.args([
98            "--target-dir",
99            target_dir
100                .to_str()
101                .context("Path to target directory is not valid UTF-8")?,
102        ]);
103        target_dir
104    } else {
105        metadata.target_directory.as_std_path()
106    };
107
108    let cdylib_path = target_directory
109        .join(TARGET_SPECIFICATION_NAME)
110        .join(if profile == "dev" { "debug" } else { profile })
111        .join({
112            let package_name = if let Some(package) = package {
113                package
114            } else {
115                let current_dir = env::current_dir().context("Failed to get current directory")?;
116                let current_manifest = current_dir.join("Cargo.toml");
117                metadata
118                    .packages
119                    .iter()
120                    .find_map(|package| {
121                        if package.manifest_path == current_manifest {
122                            Some(&package.name)
123                        } else {
124                            None
125                        }
126                    })
127                    .context("Failed to find package name")?
128            };
129
130            format!("{}.contract.so", package_name.replace('-', "_"))
131        });
132
133    debug!(
134        ?package,
135        ?features,
136        ?profile,
137        ?target_specification_path,
138        cdylib_path = ?cdylib_path,
139        command = ?command_builder,
140        "Building ELF `cdylib` contract"
141    );
142
143    let status = command_builder
144        .status()
145        .context("Failed to build a contract")?;
146
147    if !status.success() {
148        return Err(anyhow::anyhow!("Failed to build a contract"));
149    }
150
151    Ok(cdylib_path)
152}