use crate::TOOLCHAIN;
use anyhow::{Context, Result, bail, ensure};
use serde_json::Value;
use std::{
collections::BTreeSet,
env,
fs::{self, File, OpenOptions},
os::{fd::AsRawFd, unix::process::CommandExt},
path::{Path, PathBuf},
process::{Command, Output, Stdio},
};
pub const BUILD_STD: &str = "-Zbuild-std=std,panic_abort";
pub fn feature_flags(
features: impl IntoIterator<Item = String>,
all_features: bool,
no_default_features: bool,
) -> Vec<String> {
let mut flags = Vec::new();
for features in features {
flags.extend(["--features".into(), features]);
}
if all_features {
flags.push("--all-features".into());
}
if no_default_features {
flags.push("--no-default-features".into());
}
flags
}
pub fn refresh_lock(manifest: &Path, offline: bool) -> Result<()> {
let manifest = manifest
.canonicalize()
.with_context(|| format!("open {}", manifest.display()))?;
let compiler = Compiler::select(offline)?;
let mut cargo = compiler.for_manifest(&manifest, "update");
cargo.arg("--workspace");
if offline {
cargo.arg("--offline");
}
checked(&mut cargo, &[]).context("refresh the application workspace lockfile")?;
Ok(())
}
pub struct Compiler {
pub rustc: PathBuf,
pub cargo: PathBuf,
pub host: String,
pub version: String,
pub home: PathBuf,
pub sources: PathBuf,
target_directory: Option<PathBuf>,
}
impl Compiler {
pub fn select(offline: bool) -> Result<Self> {
let locate = || {
Command::new("rustup")
.args(["which", "--toolchain", TOOLCHAIN, "rustc"])
.output()
.context("Rustup is required to select the pinned canister compiler")
};
let result = locate()?;
let rustc = if result.status.success() {
PathBuf::from(String::from_utf8(result.stdout)?.trim()).canonicalize()?
} else {
ensure!(
!offline,
"install {TOOLCHAIN} and rust-src before building offline"
);
checked(
Command::new("rustup").args([
"toolchain",
"install",
TOOLCHAIN,
"--profile",
"minimal",
"--component",
"rust-src",
"--no-self-update",
]),
&[],
)?;
PathBuf::from(
String::from_utf8(checked(
Command::new("rustup").args(["which", "--toolchain", TOOLCHAIN, "rustc"]),
&[],
)?)?
.trim(),
)
.canonicalize()?
};
let version = String::from_utf8(checked(Command::new(&rustc).arg("-Vv"), &[])?)?;
let host = version
.lines()
.find_map(|line| line.strip_prefix("host: "))
.context("pinned rustc did not report its native host")?
.to_owned();
let sources = rustc
.parent()
.unwrap()
.parent()
.unwrap()
.join("lib/rustlib/src/rust");
if !sources.join("library/Cargo.toml").is_file() {
ensure!(
!offline,
"install rust-src for {TOOLCHAIN} before building offline"
);
checked(
Command::new("rustup").args([
"component",
"add",
"--toolchain",
TOOLCHAIN,
"rust-src",
]),
&[],
)?;
}
let home = env::var_os("CARGO_HOME")
.map(PathBuf::from)
.or_else(|| env::var_os("HOME").map(|path| PathBuf::from(path).join(".cargo")))
.context("set CARGO_HOME to a writable Cargo cache")?;
fs::create_dir_all(&home)?;
let target_directory = env::var_os("CARGO_TARGET_DIR")
.map(std::path::absolute)
.transpose()
.context("resolve CARGO_TARGET_DIR from the invocation directory")?;
Ok(Self {
cargo: rustc.with_file_name("cargo"),
rustc,
host,
version,
home: home.canonicalize()?,
sources: sources.canonicalize()?,
target_directory,
})
}
pub fn command(&self, executable: &Path, workspace: &Path) -> Command {
let mut command = Command::new(executable);
let path = env::join_paths(
std::iter::once(self.rustc.parent().unwrap().to_path_buf())
.chain(env::var_os("PATH").iter().flat_map(env::split_paths)),
);
if let Ok(path) = path {
command.env("PATH", path);
}
if let Some(target) = &self.target_directory {
command.env("CARGO_TARGET_DIR", target);
}
command
.current_dir(workspace)
.env("CARGO_HOME", &self.home)
.env("RUSTUP_TOOLCHAIN", TOOLCHAIN)
.env("RUSTC", &self.rustc)
.env("RUSTDOC", self.rustc.with_file_name("rustdoc"))
.env("CARGO_BUILD_TARGET", &self.host)
.env("CARGO_ENCODED_RUSTFLAGS", "")
.env_remove("RUSTFLAGS")
.env_remove("RUSTC_WRAPPER")
.env_remove("RUSTC_WORKSPACE_WRAPPER")
.env_remove("CDK_RSX_COMPAT_CONTEXT")
.env_remove("CDK_RSX_COMPAT_ALIASES")
.env_remove("CDK_RSX_COMPAT_TOOLING")
.env_remove("CDK_RSX_COMPAT_PACKAGE_ROOTS")
.env("CARGO_UNSTABLE_CHECKSUM_FRESHNESS", "true")
.env("CARGO_BUILD_FINGERPRINT", "content")
.env("CARGO_INCREMENTAL", "0");
command
}
pub fn for_manifest(&self, manifest: &Path, subcommand: &str) -> Command {
let mut command = self.command(&self.cargo, manifest.parent().unwrap());
command.arg(subcommand).arg("--manifest-path").arg(manifest);
command
}
pub fn prepare_lock(&self, manifest: &Path, locked: bool, offline: bool) -> Result<()> {
let workspace = checked(
self.for_manifest(manifest, "locate-project").args([
"--workspace",
"--message-format",
"plain",
]),
&[],
)?;
let lock = Path::new(std::str::from_utf8(&workspace)?.trim()).with_file_name("Cargo.lock");
if !lock.is_file() {
ensure!(
!locked && !offline,
"{} is missing; run cdk-rsx lock to create it",
lock.display()
);
checked(&mut self.for_manifest(manifest, "generate-lockfile"), &[])?;
}
Ok(())
}
pub fn fetch(&self, manifest: &Path, target: Option<&str>) -> Result<()> {
let mut fetch = self.for_manifest(manifest, "fetch");
fetch.arg("--locked").stdout(Stdio::inherit());
if let Some(target) = target {
fetch.args(["--target", target, BUILD_STD]);
}
checked(&mut fetch, &[])
.context("fetch locked dependencies (run cdk-rsx lock after dependency edits)")?;
Ok(())
}
pub fn workspace_metadata(&self, manifest: &Path) -> Result<Value> {
let output = checked(
self.for_manifest(manifest, "metadata").args([
"--format-version",
"1",
"--no-deps",
"--locked",
"--offline",
]),
&[],
)
.context("list app workspace packages")?;
serde_json::from_slice(&output).context("parse Cargo metadata")
}
pub fn metadata(
&self,
manifest: &Path,
features: &[String],
platform: Option<&str>,
offline: bool,
) -> Result<Value> {
let mut command = self.for_manifest(manifest, "metadata");
command.args(["--format-version", "1", "--locked"]).args(features);
if offline {
command.arg("--offline");
}
if let Some(platform) = platform {
command.args(["--filter-platform", platform]);
}
let output = checked(&mut command, &[]).context(
"resolve locked app dependencies (run cdk-rsx lock after dependency edits)",
)?;
serde_json::from_slice(&output).context("parse Cargo metadata")
}
}
pub fn project_metadata(path: &Path) -> Result<Value> {
let manifest = path
.canonicalize()
.with_context(|| format!("open {}", path.display()))?;
let compiler = Compiler::select(false)?;
compiler.prepare_lock(&manifest, false, false)?;
compiler.metadata(&manifest, &[], None, false)
}
fn execute(command: &mut Command, locks: &[&File]) -> Result<Output> {
if !locks.is_empty() {
let handles: Vec<_> = locks.iter().map(|file| file.as_raw_fd()).collect();
unsafe {
command.pre_exec(move || {
for &fd in &handles {
if libc::fcntl(fd, libc::F_SETFD, 0) < 0 {
return Err(std::io::Error::last_os_error());
}
}
Ok(())
});
}
}
command
.stderr(Stdio::inherit())
.output()
.with_context(|| format!("run {}", command.get_program().to_string_lossy()))
}
pub fn checked(command: &mut Command, locks: &[&File]) -> Result<Vec<u8>> {
let output = execute(command, locks)?;
ensure!(
output.status.success(),
"{} exited with {}",
command.get_program().to_string_lossy(),
output.status
);
Ok(output.stdout)
}
pub fn lock(directory: &Path, name: &str) -> Result<File> {
let root = directory.join(".cdk-rsx-build-locks");
fs::create_dir_all(&root)?;
let file = OpenOptions::new()
.create(true)
.truncate(false)
.append(true)
.open(root.join(name))?;
file.lock()
.with_context(|| format!("lock {}", root.join(name).display()))?;
Ok(file)
}
pub fn app_library<'a>(
metadata: &'a Value,
manifest: &Path,
requested: Option<&str>,
) -> Result<(&'a Value, &'a Value)> {
let packages = metadata["packages"]
.as_array()
.context("missing Cargo packages")?;
let members = metadata["workspace_members"]
.as_array()
.context("missing Cargo workspace members")?;
let available: Vec<_> = packages
.iter()
.filter(|package| members.contains(&package["id"]))
.collect();
let mut selected: Vec<_> = available
.iter()
.copied()
.filter(|package| match requested {
Some(name) => package["name"] == name,
None => package["manifest_path"]
.as_str()
.is_some_and(|path| Path::new(path) == manifest),
})
.collect();
if selected.is_empty() && requested.is_none() {
let defaults = metadata["workspace_default_members"]
.as_array()
.context("missing default workspace members")?;
selected = available
.iter()
.copied()
.filter(|package| defaults.contains(&package["id"]))
.collect();
}
let [package] = selected.as_slice() else {
let names = available
.iter()
.filter_map(|row| row["name"].as_str())
.collect::<Vec<_>>()
.join(", ");
bail!("select one canister with --package (workspace packages: {names})");
};
let library = package["targets"]
.as_array()
.and_then(|targets| {
targets.iter().find(|target| {
target["crate_types"].as_array().is_some_and(|types| {
types.iter().any(|kind| kind == "cdylib")
&& types.iter().any(|kind| kind == "rlib")
})
})
})
.context("the app needs [lib] crate-type = [\"cdylib\", \"rlib\"]")?;
Ok((package, library))
}
pub fn compile(command: Command, locks: &[&File]) -> Result<Vec<Value>> {
compile_with(command, locks, |_| false)
}
pub fn compile_with(
mut command: Command,
locks: &[&File],
format_failure: impl FnOnce(&[Value]) -> bool,
) -> Result<Vec<Value>> {
command.arg("--message-format=json");
let output = execute(&mut command, locks)?;
let messages: Vec<Value> = std::str::from_utf8(&output.stdout)?
.lines()
.filter(|line| line.starts_with('{'))
.map(serde_json::from_str)
.collect::<serde_json::Result<_>>()?;
if output.status.success() || !format_failure(&messages) {
for message in &messages {
if message["reason"] == "compiler-message" {
eprint!(
"{}",
message["message"]["rendered"].as_str().unwrap_or_default()
);
}
}
}
ensure!(
output.status.success(),
"Cargo build exited with {}",
output.status
);
Ok(messages)
}
pub fn artifact<'a>(
messages: &'a [Value],
package: &Value,
library: &Value,
suffix: &str,
) -> Result<(PathBuf, &'a Value)> {
let mut selected = messages
.iter()
.filter(|message| {
message["reason"] == "compiler-artifact"
&& message["package_id"] == *package
&& message["target"]["name"] == *library
})
.flat_map(|message| {
message["filenames"]
.as_array()
.into_iter()
.flatten()
.map(move |file| (file, message))
})
.filter_map(|(file, message)| {
file.as_str()
.filter(|name| name.ends_with(suffix))
.map(|name| (PathBuf::from(name), message))
});
let pair = selected
.next()
.with_context(|| format!("Cargo did not report a {suffix} for {library}"))?;
ensure!(
selected.next().is_none(),
"Cargo reported multiple {suffix} outputs for {library}"
);
Ok(pair)
}
pub fn native_interface(
compiler: &Compiler,
directory: &Path,
messages: &[Value],
package: &Value,
library: &Value,
output: &Path,
locks: &[&File],
) -> Result<()> {
let stage = output
.parent()
.context("missing Wire descriptor output directory")?;
let (rmeta, _) = artifact(messages, package, library, ".rmeta")?;
let (rlib, _) = artifact(messages, package, library, ".rlib")?;
let driver = stage.join("wire-descriptor.rs");
fs::write(
&driver,
r#"extern crate rsx_app;
unsafe extern "Rust" { fn __cdk_rsx_wire_interface() -> Result<String, String>; }
fn main() -> Result<(), Box<dyn std::error::Error>> {
// SAFETY: the linked application root exports this exact Rust signature.
println!("{}", unsafe { __cdk_rsx_wire_interface()? });
Ok(())
}
"#,
)?;
let binary = stage.join("wire-descriptor");
let mut link = compiler.command(&compiler.rustc, directory);
link.args(["--edition=2024", "--target", &compiler.host])
.arg(&driver)
.arg("--extern")
.arg(format!("rsx_app={}", rmeta.display()))
.arg("--extern")
.arg(format!("rsx_app={}", rlib.display()));
let mut search = BTreeSet::new();
for message in messages {
if message["reason"] == "build-script-executed" {
search.extend(
message["linked_paths"]
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(str::to_owned),
);
} else if message["reason"] == "compiler-artifact" {
search.extend(
message["filenames"]
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_str)
.filter_map(|file| Path::new(file).parent())
.map(|path| format!("dependency={}", path.display())),
);
}
}
for path in search {
link.arg("-L").arg(path);
}
checked(link.arg("-o").arg(&binary), locks).context("link the native IC Wire descriptor")?;
fs::write(
output,
checked(&mut compiler.command(&binary, directory), locks)?,
)?;
Ok(())
}