Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(sandbox): add -Zsandbox unstable flag #66

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/cargo/core/compiler/build_context/target_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -953,6 +953,16 @@ impl<'gctx> RustcTargetData<'gctx> {
res.merge_compile_kind(kind)?;
}

// TODO: Although `-Zsandbox need this target platform to exist,
// if there is no build script involved in the entire dependency tree,
// there is no need for doing this target pre-fetch.
if ws.gctx().cli_unstable().sandbox {
if let Some(target) = gctx.sandbox_config()?.target.as_ref() {
let kind = CompileKind::Target(CompileTarget::new(target)?);
res.merge_compile_kind(kind)?;
}
}

Ok(res)
}

Expand Down
24 changes: 17 additions & 7 deletions src/cargo/core/compiler/compilation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,13 +227,23 @@ impl<'gctx> Compilation<'gctx> {
cmd: T,
pkg: &Package,
) -> CargoResult<ProcessBuilder> {
self.fill_env(
ProcessBuilder::new(cmd),
pkg,
None,
CompileKind::Host,
ToolKind::HostProcess,
)
let builder = if self.gctx.cli_unstable().sandbox {
let sandbox = self.gctx.sandbox_config()?;
match &sandbox.runner {
Some(runner) => {
let program = runner.path.resolve_program(self.gctx);
let mut builder = ProcessBuilder::new(program);
builder.args(&runner.args);
builder.arg(cmd);
builder
}
None => ProcessBuilder::new(cmd),
}
} else {
ProcessBuilder::new(cmd)
};

self.fill_env(builder, pkg, None, CompileKind::Host, ToolKind::HostProcess)
}

pub fn target_runner(&self, kind: CompileKind) -> Option<&(PathBuf, Vec<String>)> {
Expand Down
17 changes: 14 additions & 3 deletions src/cargo/core/compiler/custom_build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@
//! [instructions]: https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script

use super::{fingerprint, BuildRunner, Job, Unit, Work};
use crate::core::compiler::artifact;
use crate::core::compiler::build_runner::Metadata;
use crate::core::compiler::fingerprint::DirtyReason;
use crate::core::compiler::job_queue::JobState;
use crate::core::compiler::{artifact, FileFlavor};
use crate::core::{profiles::ProfileRoot, PackageId, Target};
use crate::util::errors::CargoResult;
use crate::util::internal;
Expand Down Expand Up @@ -265,7 +265,19 @@ fn build_work(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) -> CargoResul
}

// Building the command to execute
let to_exec = script_dir.join(unit.target.name());
let to_exec = if build_runner.bcx.gctx.cli_unstable().sandbox {
// XXX: is the `expect` statement here really the truth?
let outputs = build_runner.outputs(build_script_unit)?;
let mut outputs = outputs
.iter()
.filter(|output| output.flavor == FileFlavor::Normal);
let (Some(output), None) = (outputs.next(), outputs.next()) else {
panic!("a build script to produce the one and only executable");
};
output.bin_dst().as_os_str().to_os_string()
} else {
script_dir.join(unit.target.name()).into_os_string()
};

// Start preparing the process to execute, starting out with some
// environment variables. Note that the profile-related environment
Expand All @@ -274,7 +286,6 @@ fn build_work(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) -> CargoResul
// NOTE: if you add any profile flags, be sure to update
// `Profiles::get_profile_run_custom_build` so that those flags get
// carried over.
let to_exec = to_exec.into_os_string();
let mut cmd = build_runner.compilation.host_process(to_exec, &unit.pkg)?;
let debug = unit.profile.debuginfo.is_turned_on();
cmd.env("OUT_DIR", &script_out_dir)
Expand Down
12 changes: 10 additions & 2 deletions src/cargo/core/compiler/unit_dependencies.rs
Original file line number Diff line number Diff line change
Expand Up @@ -481,8 +481,16 @@ fn compute_deps_custom_build(
&unit.pkg,
&unit.target,
script_unit_for,
// Build scripts always compiled for the host.
CompileKind::Host,
// Build scripts always compiled for the host,
// unless `sandbox.target` is set.
if state.gctx.cli_unstable().sandbox {
match state.gctx.sandbox_config()?.target.as_ref() {
Some(target) => CompileKind::Target(super::CompileTarget::new(target)?),
None => CompileKind::Host,
}
} else {
CompileKind::Host
},
CompileMode::Build,
IS_NO_ARTIFACT_DEP,
)?;
Expand Down
2 changes: 2 additions & 0 deletions src/cargo/core/features.rs
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,7 @@ unstable_cli_options!(
publish_timeout: bool = ("Enable the `publish.timeout` key in .cargo/config.toml file"),
rustdoc_map: bool = ("Allow passing external documentation mappings to rustdoc"),
rustdoc_scrape_examples: bool = ("Allows Rustdoc to scrape code examples from reverse-dependencies"),
sandbox: bool = ("Enable sandbox build"),
script: bool = ("Enable support for single-file, `.rs` packages"),
separate_nightlies: bool,
skip_rustdoc_fingerprint: bool,
Expand Down Expand Up @@ -1289,6 +1290,7 @@ impl CliUnstable {
"publish-timeout" => self.publish_timeout = parse_empty(k, v)?,
"rustdoc-map" => self.rustdoc_map = parse_empty(k, v)?,
"rustdoc-scrape-examples" => self.rustdoc_scrape_examples = parse_empty(k, v)?,
"sandbox" => self.sandbox = parse_empty(k, v)?,
"separate-nightlies" => self.separate_nightlies = parse_empty(k, v)?,
"checksum-freshness" => self.checksum_freshness = parse_empty(k, v)?,
"skip-rustdoc-fingerprint" => self.skip_rustdoc_fingerprint = parse_empty(k, v)?,
Expand Down
20 changes: 20 additions & 0 deletions src/cargo/util/context/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ pub struct GlobalContext {
doc_extern_map: LazyCell<RustdocExternMap>,
progress_config: ProgressConfig,
env_config: LazyCell<EnvConfig>,
sandbox_config: LazyCell<CargoSandboxConfig>,
/// This should be false if:
/// - this is an artifact of the rustc distribution process for "stable" or for "beta"
/// - this is an `#[test]` that does not opt in with `enable_nightly_features`
Expand Down Expand Up @@ -322,6 +323,7 @@ impl GlobalContext {
doc_extern_map: LazyCell::new(),
progress_config: ProgressConfig::default(),
env_config: LazyCell::new(),
sandbox_config: LazyCell::new(),
nightly_features_allowed: matches!(&*features::channel(), "nightly" | "dev"),
ws_roots: RefCell::new(HashMap::new()),
global_cache_tracker: LazyCell::new(),
Expand Down Expand Up @@ -1891,6 +1893,15 @@ impl GlobalContext {
.try_borrow_with(|| self.get::<RustdocExternMap>("doc.extern-map"))
}

/// Returns the config table of `[sandbox]` (unstable).
///
/// TODO: currently access `sandbox.runner` from config for convenience.
/// Need to find a better configuration design.
pub fn sandbox_config(&self) -> CargoResult<&CargoSandboxConfig> {
self.sandbox_config
.try_borrow_with(|| self.get::<CargoSandboxConfig>("sandbox"))
}

/// Returns true if the `[target]` table should be applied to host targets.
pub fn target_applies_to_host(&self) -> CargoResult<bool> {
target::get_target_applies_to_host(self)
Expand Down Expand Up @@ -2724,6 +2735,15 @@ pub enum ProgressWhen {
Always,
}

#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct CargoSandboxConfig {
/// Target platform sandboxed build scripts built for.
pub target: Option<String>,
/// Runner that executes artifacts of build scripts.
pub runner: Option<PathAndArgs>,
}

fn progress_or_string<'de, D>(deserializer: D) -> Result<Option<ProgressConfig>, D::Error>
where
D: serde::de::Deserializer<'de>,
Expand Down
22 changes: 12 additions & 10 deletions tests/testsuite/cargo/z_help/stdout.term.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading