Skip to main content

cargo/compiler/
custom_build.rs

1//! How to execute a build script and parse its output.
2//!
3//! ## Preparing a build script run
4//!
5//! A [build script] is an optional Rust script Cargo will run before building
6//! your package. As of this writing, two kinds of special [`Unit`]s will be
7//! constructed when there is a build script in a package.
8//!
9//! * Build script compilation --- This unit is generally the same as units
10//!   that would compile other Cargo targets. It will recursively creates units
11//!   of its dependencies. One biggest difference is that the [`Unit`] of
12//!   compiling a build script is flagged as [`TargetKind::CustomBuild`].
13//! * Build script execution --- During the construction of the [`UnitGraph`],
14//!   Cargo inserts a [`Unit`] with [`CompileMode::RunCustomBuild`]. This unit
15//!   depends on the unit of compiling the associated build script, to ensure
16//!   the executable is available before running. The [`Work`] of running the
17//!   build script is prepared in the function [`prepare`].
18//!
19//! ## Running a build script
20//!
21//! When running a build script, Cargo is aware of the progress and the result
22//! of a build script. Standard output is the chosen interprocess communication
23//! between Cargo and build script processes. A set of strings is defined for
24//! that purpose. These strings, a.k.a. instructions, are interpreted by
25//! [`BuildOutput::parse`] and stored in [`BuildRunner::build_script_outputs`].
26//! The entire execution work is constructed by [`build_work`].
27//!
28//! [build script]: https://doc.rust-lang.org/nightly/cargo/reference/build-scripts.html
29//! [`TargetKind::CustomBuild`]: crate::workspace::manifest::TargetKind::CustomBuild
30//! [`UnitGraph`]: super::unit_graph::UnitGraph
31//! [`CompileMode::RunCustomBuild`]: crate::compiler::CompileMode::RunCustomBuild
32//! [instructions]: https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script
33
34use super::{BuildRunner, Job, Unit, Work, fingerprint, get_dynamic_search_path};
35use crate::compiler::CompileMode;
36use crate::compiler::artifact;
37use crate::compiler::build_runner::UnitHash;
38use crate::compiler::job_queue::JobState;
39use crate::util::errors::CargoResult;
40use crate::util::internal;
41use crate::util::machine_message::{self, Message};
42use crate::workspace::{PackageId, Target, profiles::ProfileRoot};
43use anyhow::{Context as _, bail};
44use cargo_platform::Cfg;
45use cargo_util::collections::HashMap;
46use cargo_util::collections::HashSet;
47use cargo_util::paths;
48use cargo_util_schemas::manifest::RustVersion;
49use std::collections::BTreeSet;
50use std::collections::hash_map::Entry;
51use std::path::{Path, PathBuf};
52use std::str;
53use std::sync::{Arc, Mutex};
54
55/// A build script instruction that tells Cargo to display an error after the
56/// build script has finished running. Read [the doc] for more.
57///
58/// [the doc]: https://doc.rust-lang.org/nightly/cargo/reference/build-scripts.html#cargo-error
59const CARGO_ERROR_SYNTAX: &str = "cargo::error=";
60/// Deprecated: A build script instruction that tells Cargo to display a warning after the
61/// build script has finished running. Read [the doc] for more.
62///
63/// [the doc]: https://doc.rust-lang.org/nightly/cargo/reference/build-scripts.html#cargo-warning
64const OLD_CARGO_WARNING_SYNTAX: &str = "cargo:warning=";
65/// A build script instruction that tells Cargo to display a warning after the
66/// build script has finished running. Read [the doc] for more.
67///
68/// [the doc]: https://doc.rust-lang.org/nightly/cargo/reference/build-scripts.html#cargo-warning
69const NEW_CARGO_WARNING_SYNTAX: &str = "cargo::warning=";
70
71#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
72pub enum Severity {
73    Error,
74    Warning,
75}
76
77pub type LogMessage = (Severity, String);
78
79/// Represents a path added to the library search path.
80///
81/// We need to keep track of requests to add search paths within the cargo build directory
82/// separately from paths outside of Cargo. The reason is that we want to give precedence to linking
83/// against libraries within the Cargo build directory even if a similar library exists in the
84/// system (e.g. crate A adds `/usr/lib` to the search path and then a later build of crate B adds
85/// `target/debug/...` to satisfy its request to link against the library B that it built, but B is
86/// also found in `/usr/lib`).
87///
88/// There's some nuance here because we want to preserve relative order of paths of the same type.
89/// For example, if the build process would in declaration order emit the following linker line:
90/// ```bash
91/// -L/usr/lib -Ltarget/debug/build/crate1/libs -L/lib -Ltarget/debug/build/crate2/libs)
92/// ```
93///
94/// we want the linker to actually receive:
95/// ```bash
96/// -Ltarget/debug/build/crate1/libs -Ltarget/debug/build/crate2/libs) -L/usr/lib -L/lib
97/// ```
98///
99/// so that the library search paths within the crate artifacts directory come first but retain
100/// relative ordering while the system library paths come after while still retaining relative
101/// ordering among them; ordering is the order they are emitted within the build process,
102/// not lexicographic order.
103///
104/// WARNING: Even though this type implements PartialOrd + Ord, this is a lexicographic ordering.
105/// The linker line will require an explicit sorting algorithm. PartialOrd + Ord is derived because
106/// BuildOutput requires it but that ordering is different from the one for the linker search path,
107/// at least today. It may be worth reconsidering & perhaps it's ok if BuildOutput doesn't have
108/// a lexicographic ordering for the library_paths? I'm not sure the consequence of that.
109#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
110pub enum LibraryPath {
111    /// The path is pointing within the output folder of the crate and takes priority over
112    /// external paths when passed to the linker.
113    CargoArtifact(PathBuf),
114    /// The path is pointing outside of the crate's build location. The linker will always
115    /// receive such paths after `CargoArtifact`.
116    External(PathBuf),
117}
118
119impl LibraryPath {
120    fn new(p: PathBuf, script_out_dir: &Path) -> Self {
121        let search_path = get_dynamic_search_path(&p);
122        if search_path.starts_with(script_out_dir) {
123            Self::CargoArtifact(p)
124        } else {
125            Self::External(p)
126        }
127    }
128
129    pub fn into_path_buf(self) -> PathBuf {
130        match self {
131            LibraryPath::CargoArtifact(p) | LibraryPath::External(p) => p,
132        }
133    }
134}
135
136impl AsRef<PathBuf> for LibraryPath {
137    fn as_ref(&self) -> &PathBuf {
138        match self {
139            LibraryPath::CargoArtifact(p) | LibraryPath::External(p) => p,
140        }
141    }
142}
143
144/// Contains the parsed output of a custom build script.
145#[derive(Clone, Debug, Hash, Default, PartialEq, Eq, PartialOrd, Ord)]
146pub struct BuildOutput {
147    /// Paths to pass to rustc with the `-L` flag.
148    pub library_paths: Vec<LibraryPath>,
149    /// Names and link kinds of libraries, suitable for the `-l` flag.
150    pub library_links: Vec<String>,
151    /// Linker arguments suitable to be passed to `-C link-arg=<args>`
152    pub linker_args: Vec<(LinkArgTarget, String)>,
153    /// Various `--cfg` flags to pass to the compiler.
154    pub cfgs: Vec<String>,
155    /// Various `--check-cfg` flags to pass to the compiler.
156    pub check_cfgs: Vec<String>,
157    /// Additional environment variables to run the compiler with.
158    pub env: Vec<(String, String)>,
159    /// Metadata to pass to the immediate dependencies.
160    pub metadata: Vec<(String, String)>,
161    /// Paths to trigger a rerun of this build script.
162    /// May be absolute or relative paths (relative to package root).
163    pub rerun_if_changed: Vec<PathBuf>,
164    /// Environment variables which, when changed, will cause a rebuild.
165    pub rerun_if_env_changed: Vec<String>,
166    /// Errors and warnings generated by this build.
167    ///
168    /// These are only displayed if this is a "local" package, `-vv` is used, or
169    /// there is a build error for any target in this package. Note that any log
170    /// message of severity `Error` will by itself cause a build error, and will
171    /// cause all log messages to be displayed.
172    pub log_messages: Vec<LogMessage>,
173}
174
175/// Map of packages to build script output.
176///
177/// This initially starts out as empty. Overridden build scripts get
178/// inserted during `build_map`. The rest of the entries are added
179/// immediately after each build script runs.
180///
181/// The [`UnitHash`] is the unique metadata hash for the `RunCustomBuild` Unit of
182/// the package. It needs a unique key, since the build script can be run
183/// multiple times with different profiles or features. We can't embed a
184/// `Unit` because this structure needs to be shareable between threads.
185#[derive(Default)]
186pub struct BuildScriptOutputs {
187    outputs: HashMap<UnitHash, BuildOutput>,
188}
189
190/// Linking information for a `Unit`.
191///
192/// See [`build_map`] for more details.
193#[derive(Default)]
194pub struct BuildScripts {
195    /// List of build script outputs this Unit needs to include for linking. Each
196    /// element is an index into `BuildScriptOutputs`.
197    ///
198    /// Cargo will use this `to_link` vector to add `-L` flags to compiles as we
199    /// propagate them upwards towards the final build. Note, however, that we
200    /// need to preserve the ordering of `to_link` to be topologically sorted.
201    /// This will ensure that build scripts which print their paths properly will
202    /// correctly pick up the files they generated (if there are duplicates
203    /// elsewhere).
204    ///
205    /// To preserve this ordering, the (id, metadata) is stored in two places, once
206    /// in the `Vec` and once in `seen_to_link` for a fast lookup. We maintain
207    /// this as we're building interactively below to ensure that the memory
208    /// usage here doesn't blow up too much.
209    ///
210    /// For more information, see #2354.
211    pub to_link: Vec<(PackageId, UnitHash)>,
212    /// This is only used while constructing `to_link` to avoid duplicates.
213    seen_to_link: HashSet<(PackageId, UnitHash)>,
214    /// Host-only dependencies that have build scripts. Each element is an
215    /// index into `BuildScriptOutputs`.
216    ///
217    /// This is the set of transitive dependencies that are host-only
218    /// (proc-macro, plugin, build-dependency) that contain a build script.
219    /// Any `BuildOutput::library_paths` path relative to `target` will be
220    /// added to `LD_LIBRARY_PATH` so that the compiler can find any dynamic
221    /// libraries a build script may have generated.
222    pub plugins: BTreeSet<(PackageId, UnitHash)>,
223}
224
225/// Dependency information as declared by a build script that might trigger
226/// a recompile of itself.
227#[derive(Debug)]
228pub struct BuildDeps {
229    /// Absolute path to the file in the target directory that stores the
230    /// output of the build script.
231    pub build_script_output: PathBuf,
232    /// Files that trigger a rebuild if they change.
233    pub rerun_if_changed: Vec<PathBuf>,
234    /// Environment variables that trigger a rebuild if they change.
235    pub rerun_if_env_changed: Vec<String>,
236}
237
238/// Represents one of the instructions from `cargo::rustc-link-arg-*` build
239/// script instruction family.
240///
241/// In other words, indicates targets that custom linker arguments applies to.
242///
243/// See the [build script documentation][1] for more.
244///
245/// [1]: https://doc.rust-lang.org/nightly/cargo/reference/build-scripts.html#cargorustc-link-argflag
246#[derive(Clone, Hash, Debug, PartialEq, Eq, PartialOrd, Ord)]
247pub enum LinkArgTarget {
248    /// Represents `cargo::rustc-link-arg=FLAG`.
249    All,
250    /// Represents `cargo::rustc-cdylib-link-arg=FLAG`.
251    Cdylib,
252    /// Represents `cargo::rustc-link-arg-bins=FLAG`.
253    Bin,
254    /// Represents `cargo::rustc-link-arg-bin=BIN=FLAG`.
255    SingleBin(String),
256    /// Represents `cargo::rustc-link-arg-tests=FLAG`.
257    Test,
258    /// Represents `cargo::rustc-link-arg-benches=FLAG`.
259    Bench,
260    /// Represents `cargo::rustc-link-arg-examples=FLAG`.
261    Example,
262}
263
264impl LinkArgTarget {
265    /// Checks if this link type applies to a given [`Target`].
266    pub fn applies_to(&self, target: &Target, mode: CompileMode) -> bool {
267        let is_test = mode.is_any_test();
268        match self {
269            LinkArgTarget::All => true,
270            LinkArgTarget::Cdylib => !is_test && target.is_cdylib(),
271            LinkArgTarget::Bin => target.is_bin(),
272            LinkArgTarget::SingleBin(name) => target.is_bin() && target.name() == name,
273            LinkArgTarget::Test => target.is_test(),
274            LinkArgTarget::Bench => target.is_bench(),
275            LinkArgTarget::Example => target.is_exe_example(),
276        }
277    }
278}
279
280/// Prepares a `Work` that executes the target as a custom build script.
281#[tracing::instrument(skip_all)]
282pub fn prepare(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<Job> {
283    let metadata = build_runner.get_run_build_script_metadata(unit);
284    if build_runner
285        .build_script_outputs
286        .lock()
287        .unwrap()
288        .contains_key(metadata)
289    {
290        // The output is already set, thus the build script is overridden.
291        fingerprint::prepare_target(build_runner, unit, false)
292    } else {
293        build_work(build_runner, unit)
294    }
295}
296
297/// Emits the output of a build script as a [`machine_message::BuildScript`]
298/// JSON string to standard output.
299fn emit_build_output(
300    state: &JobState<'_, '_>,
301    output: &BuildOutput,
302    out_dir: &Path,
303    package_id: PackageId,
304) -> CargoResult<()> {
305    let library_paths = output
306        .library_paths
307        .iter()
308        .map(|l| l.as_ref().display().to_string())
309        .collect::<Vec<_>>();
310
311    let msg = machine_message::BuildScript {
312        package_id: package_id.to_spec(),
313        linked_libs: &output.library_links,
314        linked_paths: &library_paths,
315        cfgs: &output.cfgs,
316        env: &output.env,
317        out_dir,
318    }
319    .to_json_string();
320    state.stdout(msg)?;
321    Ok(())
322}
323
324/// Constructs the unit of work of running a build script.
325///
326/// The construction includes:
327///
328/// * Set environment variables for the build script run.
329/// * Create the output dir (`OUT_DIR`) for the build script output.
330/// * Determine if the build script needs a re-run.
331/// * Run the build script and store its output.
332fn build_work(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<Job> {
333    assert!(unit.mode.is_run_custom_build());
334    let bcx = &build_runner.bcx;
335    let dependencies = build_runner.unit_deps(unit);
336    let build_script_unit = dependencies
337        .iter()
338        .find(|d| !d.unit.mode.is_run_custom_build() && d.unit.target.is_custom_build())
339        .map(|d| &d.unit)
340        .expect("running a script not depending on an actual script");
341    let script_dir = build_runner.files().build_script_dir(build_script_unit);
342
343    let script_out_dir = if bcx.gctx.cli_unstable().build_dir_new_layout {
344        build_runner.files().out_dir_new_layout(unit)
345    } else {
346        build_runner.files().build_script_out_dir(unit)
347    };
348
349    if let Some(deps) = unit.pkg.manifest().metabuild() {
350        prepare_metabuild(build_runner, build_script_unit, deps)?;
351    }
352
353    // Building the command to execute
354    let bin_name = if bcx.gctx.cli_unstable().build_dir_new_layout {
355        unit.target.crate_name()
356    } else {
357        unit.target.name().to_string()
358    };
359    let to_exec = script_dir.join(bin_name);
360
361    // Start preparing the process to execute, starting out with some
362    // environment variables. Note that the profile-related environment
363    // variables are not set with this the build script's profile but rather the
364    // package's library profile.
365    // NOTE: if you add any profile flags, be sure to update
366    // `Profiles::get_profile_run_custom_build` so that those flags get
367    // carried over.
368    let to_exec = to_exec.into_os_string();
369    let mut cmd = build_runner.compilation.host_process(to_exec, &unit.pkg)?;
370    let debug = unit.profile.debuginfo.is_turned_on();
371    cmd.env("OUT_DIR", &script_out_dir)
372        .env("CARGO_MANIFEST_DIR", unit.pkg.root())
373        .env("CARGO_MANIFEST_PATH", unit.pkg.manifest_path())
374        .env("NUM_JOBS", &bcx.jobs().to_string())
375        .env("TARGET", bcx.target_data.short_name(&unit.kind))
376        .env("DEBUG", debug.to_string())
377        .env("OPT_LEVEL", &unit.profile.opt_level)
378        .env(
379            "PROFILE",
380            match unit.profile.root {
381                ProfileRoot::Release => "release",
382                ProfileRoot::Debug => "debug",
383            },
384        )
385        .env("HOST", &bcx.host_triple())
386        .env("RUSTC", &bcx.rustc().path)
387        .env("RUSTDOC", &*bcx.gctx.rustdoc()?)
388        .inherit_jobserver(&build_runner.jobserver);
389
390    // Find all artifact dependencies and make their file and containing directory discoverable using environment variables.
391    for (var, value) in artifact::get_env(build_runner, unit, dependencies)? {
392        cmd.env(&var, value);
393    }
394
395    if let Some(linker) = &build_runner.compilation.target_linker(unit.kind) {
396        cmd.env("RUSTC_LINKER", linker);
397    }
398
399    if let Some(links) = unit.pkg.manifest().links() {
400        cmd.env("CARGO_MANIFEST_LINKS", links);
401    }
402
403    let trim_paths = &unit.profile.trim_paths;
404    cmd.env("CARGO_TRIM_PATHS_SCOPE", trim_paths.to_string());
405    let pairs = if trim_paths.is_none() {
406        Vec::new()
407    } else {
408        super::trim_paths::trim_paths_remap(build_runner, unit)
409    };
410    cmd.env(
411        "CARGO_TRIM_PATHS_REMAP",
412        paths::join_paths(&pairs, "CARGO_TRIM_PATHS_REMAP")?,
413    );
414
415    // Be sure to pass along all enabled features for this package, this is the
416    // last piece of statically known information that we have.
417    for feat in &unit.features {
418        cmd.env(&format!("CARGO_FEATURE_{}", super::envify(feat)), "1");
419    }
420
421    let mut cfg_map = HashMap::default();
422    cfg_map.insert(
423        "feature",
424        unit.features.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
425    );
426    // Manually inject debug_assertions based on the profile setting.
427    // The cfg query from rustc doesn't include profile settings and would always be true,
428    // so we override it with the actual profile setting.
429    if unit.profile.debug_assertions {
430        cfg_map.insert("debug_assertions", Vec::new());
431    }
432    for cfg in bcx.target_data.cfg(unit.kind) {
433        match *cfg {
434            Cfg::Name(ref n) => {
435                // Skip debug_assertions from rustc query; we use the profile setting instead
436                if n.as_str() == "debug_assertions" {
437                    continue;
438                }
439                cfg_map.insert(n.as_str(), Vec::new());
440            }
441            Cfg::KeyPair(ref k, ref v) => {
442                let values = cfg_map.entry(k.as_str()).or_default();
443                values.push(v.as_str());
444            }
445        }
446    }
447    for (k, v) in cfg_map {
448        // FIXME: We should handle raw-idents somehow instead of pretending they
449        // don't exist here
450        let k = format!("CARGO_CFG_{}", super::envify(k));
451        cmd.env(&k, v.join(","));
452    }
453
454    // Also inform the build script of the rustc compiler context.
455    if let Some(wrapper) = bcx.rustc().wrapper.as_ref() {
456        cmd.env("RUSTC_WRAPPER", wrapper);
457    } else {
458        cmd.env_remove("RUSTC_WRAPPER");
459    }
460    cmd.env_remove("RUSTC_WORKSPACE_WRAPPER");
461    if build_runner.bcx.ws.is_member(&unit.pkg) {
462        if let Some(wrapper) = bcx.rustc().workspace_wrapper.as_ref() {
463            cmd.env("RUSTC_WORKSPACE_WRAPPER", wrapper);
464        }
465    }
466    cmd.env("CARGO_ENCODED_RUSTFLAGS", unit.rustflags.join("\x1f"));
467    cmd.env_remove("RUSTFLAGS");
468
469    if build_runner.bcx.ws.gctx().extra_verbose() {
470        cmd.display_env_vars();
471    }
472
473    let any_build_script_metadata = bcx.gctx.cli_unstable().any_build_script_metadata;
474
475    // Gather the set of native dependencies that this package has along with
476    // some other variables to close over.
477    //
478    // This information will be used at build-time later on to figure out which
479    // sorts of variables need to be discovered at that time.
480    let lib_deps = dependencies
481        .iter()
482        .filter_map(|dep| {
483            if dep.unit.mode.is_run_custom_build() {
484                let dep_metadata = build_runner.get_run_build_script_metadata(&dep.unit);
485
486                let dep_name = dep.dep_name.unwrap_or(dep.unit.pkg.name());
487
488                Some((
489                    dep_name,
490                    dep.unit
491                        .pkg
492                        .manifest()
493                        .links()
494                        .map(|links| links.to_string()),
495                    dep.unit.pkg.package_id(),
496                    dep_metadata,
497                ))
498            } else {
499                None
500            }
501        })
502        .collect::<Vec<_>>();
503    let library_name = unit.pkg.library().map(|t| t.crate_name());
504    let pkg_descr = unit.pkg.to_string();
505    let build_script_outputs = Arc::clone(&build_runner.build_script_outputs);
506    let id = unit.pkg.package_id();
507    let run_files = BuildScriptRunFiles::for_unit(build_runner, unit);
508    let timestamp_file = build_runner.files().timestamp_file(unit);
509    let host_target_root = build_runner.files().host_dest().map(|v| v.to_path_buf());
510    let all = (
511        id,
512        library_name.clone(),
513        pkg_descr.clone(),
514        Arc::clone(&build_script_outputs),
515        run_files.stdout.clone(),
516        script_out_dir.clone(),
517    );
518    let build_scripts = build_runner.build_scripts.get(unit).cloned();
519    let json_messages = bcx.build_config.emit_json();
520    let extra_verbose = bcx.gctx.extra_verbose();
521    let capture_rusage = bcx.capture_rusage();
522    let (prev_output, prev_script_out_dir) = prev_build_output(build_runner, unit);
523    let metadata_hash = build_runner.get_run_build_script_metadata(unit);
524
525    paths::create_dir_all(&script_dir)?;
526    paths::create_dir_all(&script_out_dir)?;
527    paths::create_dir_all(&run_files.root)?;
528
529    let nightly_features_allowed = build_runner.bcx.gctx.nightly_features_allowed;
530    let targets: Vec<Target> = unit.pkg.targets().to_vec();
531    let msrv = unit.pkg.rust_version().cloned();
532    // Need a separate copy for the fresh closure.
533    let targets_fresh = targets.clone();
534    let msrv_fresh = msrv.clone();
535
536    let env_profile_name = unit.profile.name.to_uppercase();
537    let built_with_debuginfo = build_runner
538        .bcx
539        .unit_graph
540        .get(unit)
541        .and_then(|deps| deps.iter().find(|dep| dep.unit.target == unit.target))
542        .map(|dep| dep.unit.profile.debuginfo.is_turned_on())
543        .unwrap_or(false);
544
545    // Prepare the unit of "dirty work" which will actually run the custom build
546    // command.
547    //
548    // Note that this has to do some extra work just before running the command
549    // to determine extra environment variables and such.
550    let dirty = Work::new(move |state| {
551        // Make sure that OUT_DIR exists.
552        //
553        // If we have an old build directory, then just move it into place,
554        // otherwise create it!
555        paths::create_dir_all(&script_out_dir)
556            .context("failed to create script output directory for build command")?;
557
558        // For all our native lib dependencies, pick up their metadata to pass
559        // along to this custom build command. We're also careful to augment our
560        // dynamic library search path in case the build script depended on any
561        // native dynamic libraries.
562        {
563            let build_script_outputs = build_script_outputs.lock().unwrap();
564            for (name, links, dep_id, dep_metadata) in lib_deps {
565                let script_output = build_script_outputs.get(dep_metadata).ok_or_else(|| {
566                    internal(format!(
567                        "failed to locate build state for env vars: {}/{}",
568                        dep_id, dep_metadata
569                    ))
570                })?;
571                let data = &script_output.metadata;
572                for (key, value) in data.iter() {
573                    if let Some(ref links) = links {
574                        cmd.env(
575                            &format!("DEP_{}_{}", super::envify(&links), super::envify(key)),
576                            value,
577                        );
578                    }
579                    if any_build_script_metadata {
580                        cmd.env(
581                            &format!("CARGO_DEP_{}_{}", super::envify(&name), super::envify(key)),
582                            value,
583                        );
584                    }
585                }
586            }
587            if let Some(build_scripts) = build_scripts
588                && let Some(ref host_target_root) = host_target_root
589            {
590                super::add_plugin_deps(
591                    &mut cmd,
592                    &build_script_outputs,
593                    &build_scripts,
594                    host_target_root,
595                )?;
596            }
597        }
598
599        // And now finally, run the build command itself!
600        state.running(&cmd);
601        let timestamp = paths::set_invocation_time(&timestamp_file)?;
602        let prefix = format!("[{} {}] ", id.name(), id.version());
603        let mut log_messages_in_case_of_panic = Vec::new();
604        let span = tracing::debug_span!("build_script", process = cmd.to_string());
605        let (stats, output) = span.in_scope(|| {
606            let (stats, result) = cmd.exec_with_streaming(
607                &mut |stdout| {
608                    if let Some(error) = stdout.strip_prefix(CARGO_ERROR_SYNTAX) {
609                        log_messages_in_case_of_panic.push((Severity::Error, error.to_owned()));
610                    }
611                    if let Some(warning) = stdout
612                        .strip_prefix(OLD_CARGO_WARNING_SYNTAX)
613                        .or(stdout.strip_prefix(NEW_CARGO_WARNING_SYNTAX))
614                    {
615                        log_messages_in_case_of_panic.push((Severity::Warning, warning.to_owned()));
616                    }
617                    if extra_verbose {
618                        state.stdout(format!("{}{}", prefix, stdout))?;
619                    }
620                    Ok(())
621                },
622                &mut |stderr| {
623                    if extra_verbose {
624                        state.stderr(format!("{}{}", prefix, stderr))?;
625                    }
626                    Ok(())
627                },
628                true,
629                capture_rusage,
630            );
631            let result = result.with_context(|| {
632                let mut build_error_context =
633                    format!("failed to run custom build command for `{}`", pkg_descr);
634
635                // If we're opting into backtraces, mention that build dependencies' backtraces can
636                // be improved by requesting debuginfo to be built, if we're not building with
637                // debuginfo already.
638                #[expect(clippy::disallowed_methods, reason = "consistency with rustc")]
639                if let Ok(show_backtraces) = std::env::var("RUST_BACKTRACE") {
640                    if !built_with_debuginfo && show_backtraces != "0" {
641                        build_error_context.push_str(&format!(
642                            "\n\
643                            note: To improve backtraces for build dependencies, set the \
644                            CARGO_PROFILE_{env_profile_name}_BUILD_OVERRIDE_DEBUG=true environment \
645                            variable to enable debug information generation.",
646                        ));
647                    }
648                }
649
650                build_error_context
651            });
652            (stats, result)
653        });
654
655        if let Some(peak_memory) = stats.peak_rss {
656            state.peak_memory(peak_memory);
657        }
658
659        // If the build failed
660        if let Err(error) = output {
661            insert_log_messages_in_build_outputs(
662                build_script_outputs,
663                id,
664                metadata_hash,
665                log_messages_in_case_of_panic,
666            );
667            return Err(error);
668        }
669        // ... or it logged any errors
670        else if log_messages_in_case_of_panic
671            .iter()
672            .any(|(severity, _)| *severity == Severity::Error)
673        {
674            insert_log_messages_in_build_outputs(
675                build_script_outputs,
676                id,
677                metadata_hash,
678                log_messages_in_case_of_panic,
679            );
680            anyhow::bail!("build script logged errors");
681        }
682
683        let output = output.unwrap();
684
685        // After the build command has finished running, we need to be sure to
686        // remember all of its output so we can later discover precisely what it
687        // was, even if we don't run the build command again (due to freshness).
688        //
689        // This is also the location where we provide feedback into the build
690        // state informing what variables were discovered via our script as
691        // well.
692        paths::write(&run_files.stdout, &output.stdout)?;
693        // This mtime shift allows Cargo to detect if a source file was
694        // modified in the middle of the build.
695        paths::set_file_time_no_err(run_files.stdout, timestamp);
696        paths::write(&run_files.stderr, &output.stderr)?;
697        paths::write(&run_files.root_output, paths::path2bytes(&script_out_dir)?)?;
698        let parsed_output = BuildOutput::parse(
699            &output.stdout,
700            library_name,
701            &pkg_descr,
702            &script_out_dir,
703            &script_out_dir,
704            nightly_features_allowed,
705            &targets,
706            &msrv,
707        )?;
708
709        if json_messages {
710            emit_build_output(state, &parsed_output, script_out_dir.as_path(), id)?;
711        }
712        build_script_outputs
713            .lock()
714            .unwrap()
715            .insert(id, metadata_hash, parsed_output);
716        Ok(())
717    });
718
719    // Now that we've prepared our work-to-do, we need to prepare the fresh work
720    // itself to run when we actually end up just discarding what we calculated
721    // above.
722    let fresh = Work::new(move |state| {
723        let (id, library_name, pkg_descr, build_script_outputs, output_file, script_out_dir) = all;
724        let output = match prev_output {
725            Some(output) => output,
726            None => BuildOutput::parse_file(
727                &output_file,
728                library_name,
729                &pkg_descr,
730                &prev_script_out_dir,
731                &script_out_dir,
732                nightly_features_allowed,
733                &targets_fresh,
734                &msrv_fresh,
735            )?,
736        };
737
738        if json_messages {
739            emit_build_output(state, &output, script_out_dir.as_path(), id)?;
740        }
741
742        build_script_outputs
743            .lock()
744            .unwrap()
745            .insert(id, metadata_hash, output);
746        Ok(())
747    });
748
749    let mut job = fingerprint::prepare_target(build_runner, unit, false)?;
750    if job.freshness().is_dirty() {
751        job.before(dirty);
752    } else {
753        job.before(fresh);
754    }
755    Ok(job)
756}
757
758/// When a build script run fails, store only log messages, and nuke other
759/// outputs, as they are likely broken.
760fn insert_log_messages_in_build_outputs(
761    build_script_outputs: Arc<Mutex<BuildScriptOutputs>>,
762    id: PackageId,
763    metadata_hash: UnitHash,
764    log_messages: Vec<LogMessage>,
765) {
766    let build_output_with_only_log_messages = BuildOutput {
767        log_messages,
768        ..BuildOutput::default()
769    };
770    build_script_outputs.lock().unwrap().insert(
771        id,
772        metadata_hash,
773        build_output_with_only_log_messages,
774    );
775}
776
777impl BuildOutput {
778    /// Like [`BuildOutput::parse`] but from a file path.
779    pub fn parse_file(
780        path: &Path,
781        library_name: Option<String>,
782        pkg_descr: &str,
783        script_out_dir_when_generated: &Path,
784        script_out_dir: &Path,
785        nightly_features_allowed: bool,
786        targets: &[Target],
787        msrv: &Option<RustVersion>,
788    ) -> CargoResult<BuildOutput> {
789        let contents = paths::read_bytes(path)?;
790        BuildOutput::parse(
791            &contents,
792            library_name,
793            pkg_descr,
794            script_out_dir_when_generated,
795            script_out_dir,
796            nightly_features_allowed,
797            targets,
798            msrv,
799        )
800    }
801
802    /// Parses the output instructions of a build script.
803    ///
804    /// * `pkg_descr` --- for error messages
805    /// * `library_name` --- for determining if `RUSTC_BOOTSTRAP` should be allowed
806    pub fn parse(
807        input: &[u8],
808        // Takes String instead of InternedString so passing `unit.pkg.name()` will give a compile error.
809        library_name: Option<String>,
810        pkg_descr: &str,
811        script_out_dir_when_generated: &Path,
812        script_out_dir: &Path,
813        nightly_features_allowed: bool,
814        targets: &[Target],
815        msrv: &Option<RustVersion>,
816    ) -> CargoResult<BuildOutput> {
817        let mut library_paths = Vec::new();
818        let mut library_links = Vec::new();
819        let mut linker_args = Vec::new();
820        let mut cfgs = Vec::new();
821        let mut check_cfgs = Vec::new();
822        let mut env = Vec::new();
823        let mut metadata = Vec::new();
824        let mut rerun_if_changed = Vec::new();
825        let mut rerun_if_env_changed = Vec::new();
826        let mut log_messages = Vec::new();
827        let whence = format!("build script of `{}`", pkg_descr);
828        // Old syntax:
829        //    cargo:rustc-flags=VALUE
830        //    cargo:KEY=VALUE (for other unreserved keys)
831        // New syntax:
832        //    cargo::rustc-flags=VALUE
833        //    cargo::metadata=KEY=VALUE (for other unreserved keys)
834        // Due to backwards compatibility, no new keys can be added to this old format.
835        const RESERVED_PREFIXES: &[&str] = &[
836            "rustc-flags=",
837            "rustc-link-lib=",
838            "rustc-link-search=",
839            "rustc-link-arg-cdylib=",
840            "rustc-cdylib-link-arg=",
841            "rustc-link-arg-bins=",
842            "rustc-link-arg-bin=",
843            "rustc-link-arg-tests=",
844            "rustc-link-arg-benches=",
845            "rustc-link-arg-examples=",
846            "rustc-link-arg=",
847            "rustc-cfg=",
848            "rustc-check-cfg=",
849            "rustc-env=",
850            "warning=",
851            "rerun-if-changed=",
852            "rerun-if-env-changed=",
853        ];
854        const DOCS_LINK_SUGGESTION: &str = "See https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script \
855                for more information about build script outputs.";
856
857        fn has_reserved_prefix(flag: &str) -> bool {
858            RESERVED_PREFIXES
859                .iter()
860                .any(|reserved_prefix| flag.starts_with(reserved_prefix))
861        }
862
863        fn check_minimum_supported_rust_version_for_new_syntax(
864            pkg_descr: &str,
865            msrv: &Option<RustVersion>,
866            flag: &str,
867        ) -> CargoResult<()> {
868            if let Some(msrv) = msrv {
869                let new_syntax_added_in = RustVersion::new(1, 77, 0);
870                if !new_syntax_added_in.is_compatible_with(&msrv.to_partial()) {
871                    let old_syntax_suggestion = if has_reserved_prefix(flag) {
872                        format!(
873                            "Switch to the old `cargo:{flag}` syntax (note the single colon).\n"
874                        )
875                    } else if flag.starts_with("metadata=") {
876                        let old_format_flag = flag.strip_prefix("metadata=").unwrap();
877                        format!(
878                            "Switch to the old `cargo:{old_format_flag}` syntax instead of `cargo::{flag}` (note the single colon).\n"
879                        )
880                    } else {
881                        String::new()
882                    };
883
884                    bail!(
885                        "the `cargo::` syntax for build script output instructions was added in \
886                        Rust 1.77.0, but the minimum supported Rust version of `{pkg_descr}` is {msrv}.\n\
887                        {old_syntax_suggestion}\
888                        {DOCS_LINK_SUGGESTION}"
889                    );
890                }
891            }
892
893            Ok(())
894        }
895
896        fn parse_directive<'a>(
897            whence: &str,
898            line: &str,
899            data: &'a str,
900            old_syntax: bool,
901        ) -> CargoResult<(&'a str, &'a str)> {
902            let mut iter = data.splitn(2, "=");
903            let key = iter.next();
904            let value = iter.next();
905            match (key, value) {
906                (Some(a), Some(b)) => Ok((a, b.trim_end())),
907                _ => bail!(
908                    "invalid output in {whence}: `{line}`\n\
909                    Expected a line with `{syntax}KEY=VALUE` with an `=` character, \
910                    but none was found.\n\
911                    {DOCS_LINK_SUGGESTION}",
912                    syntax = if old_syntax { "cargo:" } else { "cargo::" },
913                ),
914            }
915        }
916
917        fn parse_metadata<'a>(
918            whence: &str,
919            line: &str,
920            data: &'a str,
921            old_syntax: bool,
922        ) -> CargoResult<(&'a str, &'a str)> {
923            let mut iter = data.splitn(2, "=");
924            let key = iter.next();
925            let value = iter.next();
926            match (key, value) {
927                (Some(a), Some(b)) => Ok((a, b.trim_end())),
928                _ => bail!(
929                    "invalid output in {whence}: `{line}`\n\
930                    Expected a line with `{syntax}KEY=VALUE` with an `=` character, \
931                    but none was found.\n\
932                    {DOCS_LINK_SUGGESTION}",
933                    syntax = if old_syntax {
934                        "cargo:"
935                    } else {
936                        "cargo::metadata="
937                    },
938                ),
939            }
940        }
941
942        for line in input.split(|b| *b == b'\n') {
943            let line = match str::from_utf8(line) {
944                Ok(line) => line.trim(),
945                Err(..) => continue,
946            };
947            let mut old_syntax = false;
948            let (key, value) = if let Some(data) = line.strip_prefix("cargo::") {
949                check_minimum_supported_rust_version_for_new_syntax(pkg_descr, msrv, data)?;
950                // For instance, `cargo::rustc-flags=foo` or `cargo::metadata=foo=bar`.
951                parse_directive(whence.as_str(), line, data, old_syntax)?
952            } else if let Some(data) = line.strip_prefix("cargo:") {
953                old_syntax = true;
954                // For instance, `cargo:rustc-flags=foo`.
955                if has_reserved_prefix(data) {
956                    parse_directive(whence.as_str(), line, data, old_syntax)?
957                } else {
958                    // For instance, `cargo:foo=bar`.
959                    ("metadata", data)
960                }
961            } else {
962                // Skip this line since it doesn't start with "cargo:" or "cargo::".
963                continue;
964            };
965            // This will rewrite paths if the target directory has been moved.
966            let value = value.replace(
967                script_out_dir_when_generated.to_str().unwrap(),
968                script_out_dir.to_str().unwrap(),
969            );
970
971            let syntax_prefix = if old_syntax { "cargo:" } else { "cargo::" };
972            macro_rules! check_and_add_target {
973                ($target_kind: expr, $is_target_kind: expr, $link_type: expr) => {
974                    if !targets.iter().any(|target| $is_target_kind(target)) {
975                        bail!(
976                            "invalid instruction `{}{}` from {}\n\
977                                The package {} does not have a {} target.",
978                            syntax_prefix,
979                            key,
980                            whence,
981                            pkg_descr,
982                            $target_kind
983                        );
984                    }
985                    linker_args.push(($link_type, value));
986                };
987            }
988
989            // Keep in sync with TargetConfig::parse_links_overrides.
990            match key {
991                "rustc-flags" => {
992                    let (paths, links) = BuildOutput::parse_rustc_flags(&value, &whence)?;
993                    library_links.extend(links.into_iter());
994                    library_paths.extend(
995                        paths
996                            .into_iter()
997                            .map(|p| LibraryPath::new(p, script_out_dir)),
998                    );
999                }
1000                "rustc-link-lib" => library_links.push(value.to_string()),
1001                "rustc-link-search" => {
1002                    library_paths.push(LibraryPath::new(PathBuf::from(value), script_out_dir))
1003                }
1004                "rustc-link-arg-cdylib" | "rustc-cdylib-link-arg" => {
1005                    if !targets.iter().any(|target| target.is_cdylib()) {
1006                        log_messages.push((
1007                            Severity::Warning,
1008                            format!(
1009                                "{}{} was specified in the build script of {}, \
1010                             but that package does not contain a cdylib target\n\
1011                             \n\
1012                             Allowing this was an unintended change in the 1.50 \
1013                             release, and may become an error in the future. \
1014                             For more information, see \
1015                             <https://github.com/rust-lang/cargo/issues/9562>.",
1016                                syntax_prefix, key, pkg_descr
1017                            ),
1018                        ));
1019                    }
1020                    linker_args.push((LinkArgTarget::Cdylib, value))
1021                }
1022                "rustc-link-arg-bins" => {
1023                    check_and_add_target!("bin", Target::is_bin, LinkArgTarget::Bin);
1024                }
1025                "rustc-link-arg-bin" => {
1026                    let (bin_name, arg) = value.split_once('=').ok_or_else(|| {
1027                        anyhow::format_err!(
1028                            "invalid instruction `{}{}={}` from {}\n\
1029                                The instruction should have the form {}{}=BIN=ARG",
1030                            syntax_prefix,
1031                            key,
1032                            value,
1033                            whence,
1034                            syntax_prefix,
1035                            key
1036                        )
1037                    })?;
1038                    if !targets
1039                        .iter()
1040                        .any(|target| target.is_bin() && target.name() == bin_name)
1041                    {
1042                        bail!(
1043                            "invalid instruction `{}{}` from {}\n\
1044                                The package {} does not have a bin target with the name `{}`.",
1045                            syntax_prefix,
1046                            key,
1047                            whence,
1048                            pkg_descr,
1049                            bin_name
1050                        );
1051                    }
1052                    linker_args.push((
1053                        LinkArgTarget::SingleBin(bin_name.to_owned()),
1054                        arg.to_string(),
1055                    ));
1056                }
1057                "rustc-link-arg-tests" => {
1058                    check_and_add_target!("test", Target::is_test, LinkArgTarget::Test);
1059                }
1060                "rustc-link-arg-benches" => {
1061                    check_and_add_target!("benchmark", Target::is_bench, LinkArgTarget::Bench);
1062                }
1063                "rustc-link-arg-examples" => {
1064                    check_and_add_target!("example", Target::is_example, LinkArgTarget::Example);
1065                }
1066                "rustc-link-arg" => {
1067                    linker_args.push((LinkArgTarget::All, value));
1068                }
1069                "rustc-cfg" => cfgs.push(value.to_string()),
1070                "rustc-check-cfg" => check_cfgs.push(value.to_string()),
1071                "rustc-env" => {
1072                    let (key, val) = BuildOutput::parse_rustc_env(&value, &whence)?;
1073                    // Build scripts aren't allowed to set RUSTC_BOOTSTRAP.
1074                    // See https://github.com/rust-lang/cargo/issues/7088.
1075                    if key == "RUSTC_BOOTSTRAP" {
1076                        // If RUSTC_BOOTSTRAP is already set, the user of Cargo knows about
1077                        // bootstrap and still wants to override the channel. Give them a way to do
1078                        // so, but still emit a warning that the current crate shouldn't be trying
1079                        // to set RUSTC_BOOTSTRAP.
1080                        // If this is a nightly build, setting RUSTC_BOOTSTRAP wouldn't affect the
1081                        // behavior, so still only give a warning.
1082                        // NOTE: cargo only allows nightly features on RUSTC_BOOTSTRAP=1, but we
1083                        // want setting any value of RUSTC_BOOTSTRAP to downgrade this to a warning
1084                        // (so that `RUSTC_BOOTSTRAP=library_name` will work)
1085                        let rustc_bootstrap_allows = |name: Option<&str>| {
1086                            let name = match name {
1087                                // as of 2021, no binaries on crates.io use RUSTC_BOOTSTRAP, so
1088                                // fine-grained opt-outs aren't needed. end-users can always use
1089                                // RUSTC_BOOTSTRAP=1 from the top-level if it's really a problem.
1090                                None => return false,
1091                                Some(n) => n,
1092                            };
1093                            #[expect(
1094                                clippy::disallowed_methods,
1095                                reason = "consistency with rustc, not specified behavior"
1096                            )]
1097                            std::env::var("RUSTC_BOOTSTRAP")
1098                                .map_or(false, |var| var.split(',').any(|s| s == name))
1099                        };
1100                        if nightly_features_allowed
1101                            || rustc_bootstrap_allows(library_name.as_deref())
1102                        {
1103                            log_messages.push((Severity::Warning, format!("cannot set `RUSTC_BOOTSTRAP={}` from {}.\n\
1104                                note: crates cannot set `RUSTC_BOOTSTRAP` themselves, as doing so would subvert the stability guarantees of Rust for your project.",
1105                                val, whence
1106                            )));
1107                        } else {
1108                            // Setting RUSTC_BOOTSTRAP would change the behavior of the crate.
1109                            // Abort with an error.
1110                            bail!(
1111                                "cannot set `RUSTC_BOOTSTRAP={}` from {}.\n\
1112                                note: crates cannot set `RUSTC_BOOTSTRAP` themselves, as doing so would subvert the stability guarantees of Rust for your project.\n\
1113                                help: If you're sure you want to do this in your project, set the environment variable `RUSTC_BOOTSTRAP={}` before running cargo instead.",
1114                                val,
1115                                whence,
1116                                library_name.as_deref().unwrap_or("1"),
1117                            );
1118                        }
1119                    } else {
1120                        env.push((key, val));
1121                    }
1122                }
1123                "error" => log_messages.push((Severity::Error, value.to_string())),
1124                "warning" => log_messages.push((Severity::Warning, value.to_string())),
1125                "rerun-if-changed" => rerun_if_changed.push(PathBuf::from(value)),
1126                "rerun-if-env-changed" => rerun_if_env_changed.push(value.to_string()),
1127                "metadata" => {
1128                    let (key, value) = parse_metadata(whence.as_str(), line, &value, old_syntax)?;
1129                    metadata.push((key.to_owned(), value.to_owned()));
1130                }
1131                _ => bail!(
1132                    "invalid output in {whence}: `{line}`\n\
1133                    Unknown key: `{key}`.\n\
1134                    {DOCS_LINK_SUGGESTION}",
1135                ),
1136            }
1137        }
1138
1139        Ok(BuildOutput {
1140            library_paths,
1141            library_links,
1142            linker_args,
1143            cfgs,
1144            check_cfgs,
1145            env,
1146            metadata,
1147            rerun_if_changed,
1148            rerun_if_env_changed,
1149            log_messages,
1150        })
1151    }
1152
1153    /// Parses [`cargo::rustc-flags`] instruction.
1154    ///
1155    /// [`cargo::rustc-flags`]: https://doc.rust-lang.org/nightly/cargo/reference/build-scripts.html#cargorustc-flagsflags
1156    pub fn parse_rustc_flags(
1157        value: &str,
1158        whence: &str,
1159    ) -> CargoResult<(Vec<PathBuf>, Vec<String>)> {
1160        let value = value.trim();
1161        let mut flags_iter = value
1162            .split(|c: char| c.is_whitespace())
1163            .filter(|w| w.chars().any(|c| !c.is_whitespace()));
1164        let (mut library_paths, mut library_links) = (Vec::new(), Vec::new());
1165
1166        while let Some(flag) = flags_iter.next() {
1167            if flag.starts_with("-l") || flag.starts_with("-L") {
1168                // Check if this flag has no space before the value as is
1169                // common with tools like pkg-config
1170                // e.g. -L/some/dir/local/lib or -licui18n
1171                let (flag, mut value) = flag.split_at(2);
1172                if value.is_empty() {
1173                    value = match flags_iter.next() {
1174                        Some(v) => v,
1175                        None => bail! {
1176                            "flag in rustc-flags has no value in {}: {}",
1177                            whence,
1178                            value
1179                        },
1180                    }
1181                }
1182
1183                match flag {
1184                    "-l" => library_links.push(value.to_string()),
1185                    "-L" => library_paths.push(PathBuf::from(value)),
1186
1187                    // This was already checked above
1188                    _ => unreachable!(),
1189                };
1190            } else {
1191                bail!(
1192                    "only `-l` and `-L` flags are allowed in {}: `{}`",
1193                    whence,
1194                    value
1195                )
1196            }
1197        }
1198        Ok((library_paths, library_links))
1199    }
1200
1201    /// Parses [`cargo::rustc-env`] instruction.
1202    ///
1203    /// [`cargo::rustc-env`]: https://doc.rust-lang.org/nightly/cargo/reference/build-scripts.html#rustc-env
1204    pub fn parse_rustc_env(value: &str, whence: &str) -> CargoResult<(String, String)> {
1205        match value.split_once('=') {
1206            Some((n, v)) => Ok((n.to_owned(), v.to_owned())),
1207            _ => bail!("Variable rustc-env has no value in {whence}: {value}"),
1208        }
1209    }
1210}
1211
1212/// Prepares the Rust script for the unstable feature [metabuild].
1213///
1214/// [metabuild]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#metabuild
1215fn prepare_metabuild(
1216    build_runner: &BuildRunner<'_, '_>,
1217    unit: &Unit,
1218    deps: &[String],
1219) -> CargoResult<()> {
1220    let mut output = Vec::new();
1221    let available_deps = build_runner.unit_deps(unit);
1222    // Filter out optional dependencies, and look up the actual lib name.
1223    let meta_deps: Vec<_> = deps
1224        .iter()
1225        .filter_map(|name| {
1226            available_deps
1227                .iter()
1228                .find(|d| d.unit.pkg.name().as_str() == name.as_str())
1229                .map(|d| d.unit.target.crate_name())
1230        })
1231        .collect();
1232    output.push("fn main() {\n".to_string());
1233    for dep in &meta_deps {
1234        output.push(format!("    {}::metabuild();\n", dep));
1235    }
1236    output.push("}\n".to_string());
1237    let output = output.join("");
1238    let path = unit
1239        .pkg
1240        .manifest()
1241        .metabuild_path(build_runner.bcx.ws.build_dir());
1242    paths::create_dir_all(path.parent().unwrap())?;
1243    paths::write_if_changed(path, &output)?;
1244    Ok(())
1245}
1246
1247impl BuildDeps {
1248    /// Creates a build script dependency information from a previous
1249    /// build script output path and the content.
1250    pub fn new(output_file: &Path, output: Option<&BuildOutput>) -> BuildDeps {
1251        BuildDeps {
1252            build_script_output: output_file.to_path_buf(),
1253            rerun_if_changed: output
1254                .map(|p| &p.rerun_if_changed)
1255                .cloned()
1256                .unwrap_or_default(),
1257            rerun_if_env_changed: output
1258                .map(|p| &p.rerun_if_env_changed)
1259                .cloned()
1260                .unwrap_or_default(),
1261        }
1262    }
1263}
1264
1265/// Computes several maps in [`BuildRunner`].
1266///
1267/// - [`build_scripts`]: A map that tracks which build scripts each package
1268///   depends on.
1269/// - [`build_explicit_deps`]: Dependency statements emitted by build scripts
1270///   from a previous run.
1271/// - [`build_script_outputs`]: Pre-populates this with any overridden build
1272///   scripts.
1273///
1274/// The important one here is [`build_scripts`], which for each `(package,
1275/// metadata)` stores a [`BuildScripts`] object which contains a list of
1276/// dependencies with build scripts that the unit should consider when linking.
1277/// For example this lists all dependencies' `-L` flags which need to be
1278/// propagated transitively.
1279///
1280/// The given set of units to this function is the initial set of
1281/// targets/profiles which are being built.
1282///
1283/// [`build_scripts`]: BuildRunner::build_scripts
1284/// [`build_explicit_deps`]: BuildRunner::build_explicit_deps
1285/// [`build_script_outputs`]: BuildRunner::build_script_outputs
1286pub fn build_map(build_runner: &mut BuildRunner<'_, '_>) -> CargoResult<()> {
1287    let mut ret = HashMap::default();
1288    for unit in &build_runner.bcx.roots {
1289        build(&mut ret, build_runner, unit)?;
1290    }
1291    build_runner
1292        .build_scripts
1293        .extend(ret.into_iter().map(|(k, v)| (k, Arc::new(v))));
1294    return Ok(());
1295
1296    // Recursive function to build up the map we're constructing. This function
1297    // memoizes all of its return values as it goes along.
1298    fn build<'a>(
1299        out: &'a mut HashMap<Unit, BuildScripts>,
1300        build_runner: &mut BuildRunner<'_, '_>,
1301        unit: &Unit,
1302    ) -> CargoResult<&'a BuildScripts> {
1303        // Do a quick pre-flight check to see if we've already calculated the
1304        // set of dependencies.
1305        if out.contains_key(unit) {
1306            return Ok(&out[unit]);
1307        }
1308
1309        // If there is a build script override, pre-fill the build output.
1310        if unit.mode.is_run_custom_build() {
1311            if let Some(links) = unit.pkg.manifest().links() {
1312                if let Some(output) = unit.links_overrides.get(links) {
1313                    let metadata = build_runner.get_run_build_script_metadata(unit);
1314                    build_runner.build_script_outputs.lock().unwrap().insert(
1315                        unit.pkg.package_id(),
1316                        metadata,
1317                        output.clone(),
1318                    );
1319                }
1320            }
1321        }
1322
1323        let mut ret = BuildScripts::default();
1324
1325        // If a package has a build script, add itself as something to inspect for linking.
1326        if !unit.target.is_custom_build() && unit.pkg.has_custom_build() {
1327            let script_metas = build_runner
1328                .find_build_script_metadatas(unit)
1329                .expect("has_custom_build should have RunCustomBuild");
1330            for script_meta in script_metas {
1331                add_to_link(&mut ret, unit.pkg.package_id(), script_meta);
1332            }
1333        }
1334
1335        if unit.mode.is_run_custom_build() {
1336            parse_previous_explicit_deps(build_runner, unit);
1337        }
1338
1339        // We want to invoke the compiler deterministically to be cache-friendly
1340        // to rustc invocation caching schemes, so be sure to generate the same
1341        // set of build script dependency orderings via sorting the targets that
1342        // come out of the `Context`.
1343        let mut dependencies: Vec<Unit> = build_runner
1344            .unit_deps(unit)
1345            .iter()
1346            .map(|d| d.unit.clone())
1347            .collect();
1348        dependencies.sort_by_key(|u| u.pkg.package_id());
1349
1350        for dep_unit in dependencies.iter() {
1351            let dep_scripts = build(out, build_runner, dep_unit)?;
1352
1353            if dep_unit.target.for_host() {
1354                ret.plugins.extend(dep_scripts.to_link.iter().cloned());
1355            } else if dep_unit.target.is_linkable() {
1356                for &(pkg, metadata) in dep_scripts.to_link.iter() {
1357                    add_to_link(&mut ret, pkg, metadata);
1358                }
1359            }
1360        }
1361
1362        match out.entry(unit.clone()) {
1363            Entry::Vacant(entry) => Ok(entry.insert(ret)),
1364            Entry::Occupied(_) => panic!("cyclic dependencies in `build_map`"),
1365        }
1366    }
1367
1368    // When adding an entry to 'to_link' we only actually push it on if the
1369    // script hasn't seen it yet (e.g., we don't push on duplicates).
1370    fn add_to_link(scripts: &mut BuildScripts, pkg: PackageId, metadata: UnitHash) {
1371        if scripts.seen_to_link.insert((pkg, metadata)) {
1372            scripts.to_link.push((pkg, metadata));
1373        }
1374    }
1375
1376    /// Load any dependency declarations from a previous build script run.
1377    fn parse_previous_explicit_deps(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) {
1378        let run_files = BuildScriptRunFiles::for_unit(build_runner, unit);
1379        let (prev_output, _) = prev_build_output(build_runner, unit);
1380        let deps = BuildDeps::new(&run_files.stdout, prev_output.as_ref());
1381        build_runner.build_explicit_deps.insert(unit.clone(), deps);
1382    }
1383}
1384
1385/// Returns the previous parsed `BuildOutput`, if any, from a previous
1386/// execution.
1387///
1388/// Also returns the directory containing the output, typically used later in
1389/// processing.
1390fn prev_build_output(
1391    build_runner: &mut BuildRunner<'_, '_>,
1392    unit: &Unit,
1393) -> (Option<BuildOutput>, PathBuf) {
1394    let script_out_dir = if build_runner.bcx.gctx.cli_unstable().build_dir_new_layout {
1395        build_runner.files().out_dir_new_layout(unit)
1396    } else {
1397        build_runner.files().build_script_out_dir(unit)
1398    };
1399    let run_files = BuildScriptRunFiles::for_unit(build_runner, unit);
1400
1401    let prev_script_out_dir = paths::read_bytes(&run_files.root_output)
1402        .and_then(|bytes| paths::bytes2path(&bytes))
1403        .unwrap_or_else(|_| script_out_dir.clone());
1404
1405    (
1406        BuildOutput::parse_file(
1407            &run_files.stdout,
1408            unit.pkg.library().map(|t| t.crate_name()),
1409            &unit.pkg.to_string(),
1410            &prev_script_out_dir,
1411            &script_out_dir,
1412            build_runner.bcx.gctx.nightly_features_allowed,
1413            unit.pkg.targets(),
1414            &unit.pkg.rust_version().cloned(),
1415        )
1416        .ok(),
1417        prev_script_out_dir,
1418    )
1419}
1420
1421impl BuildScriptOutputs {
1422    /// Inserts a new entry into the map.
1423    fn insert(&mut self, pkg_id: PackageId, metadata: UnitHash, parsed_output: BuildOutput) {
1424        match self.outputs.entry(metadata) {
1425            Entry::Vacant(entry) => {
1426                entry.insert(parsed_output);
1427            }
1428            Entry::Occupied(entry) => panic!(
1429                "build script output collision for {}/{}\n\
1430                old={:?}\nnew={:?}",
1431                pkg_id,
1432                metadata,
1433                entry.get(),
1434                parsed_output
1435            ),
1436        }
1437    }
1438
1439    /// Returns `true` if the given key already exists.
1440    fn contains_key(&self, metadata: UnitHash) -> bool {
1441        self.outputs.contains_key(&metadata)
1442    }
1443
1444    /// Gets the build output for the given key.
1445    pub fn get(&self, meta: UnitHash) -> Option<&BuildOutput> {
1446        self.outputs.get(&meta)
1447    }
1448
1449    /// Returns an iterator over all entries.
1450    pub fn iter(&self) -> impl Iterator<Item = (&UnitHash, &BuildOutput)> {
1451        self.outputs.iter()
1452    }
1453}
1454
1455/// Files with information about a running build script.
1456struct BuildScriptRunFiles {
1457    /// The directory containing files related to running a build script.
1458    root: PathBuf,
1459    /// The stdout produced by the build script
1460    stdout: PathBuf,
1461    /// The stderr produced by the build script
1462    stderr: PathBuf,
1463    /// A file that contains the path to the `out` dir of the build script.
1464    /// This is used for detect if the directory was moved since the previous run.
1465    root_output: PathBuf,
1466}
1467
1468impl BuildScriptRunFiles {
1469    pub fn for_unit(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> Self {
1470        let root = build_runner.files().build_script_run_dir(unit);
1471        let stdout = if build_runner.bcx.gctx.cli_unstable().build_dir_new_layout {
1472            root.join("stdout")
1473        } else {
1474            root.join("output")
1475        };
1476        let stderr = root.join("stderr");
1477        let root_output = root.join("root-output");
1478        Self {
1479            root,
1480            stdout,
1481            stderr,
1482            root_output,
1483        }
1484    }
1485}