cargo/core/compiler/
mod.rs

1//! # Interact with the compiler
2//!
3//! If you consider [`ops::cargo_compile::compile`] as a `rustc` driver but on
4//! Cargo side, this module is kinda the `rustc_interface` for that merits.
5//! It contains all the interaction between Cargo and the rustc compiler,
6//! from preparing the context for the entire build process, to scheduling
7//! and executing each unit of work (e.g. running `rustc`), to managing and
8//! caching the output artifact of a build.
9//!
10//! However, it hasn't yet exposed a clear definition of each phase or session,
11//! like what rustc has done. Also, no one knows if Cargo really needs that.
12//! To be pragmatic, here we list a handful of items you may want to learn:
13//!
14//! * [`BuildContext`] is a static context containing all information you need
15//!   before a build gets started.
16//! * [`BuildRunner`] is the center of the world, coordinating a running build and
17//!   collecting information from it.
18//! * [`custom_build`] is the home of build script executions and output parsing.
19//! * [`fingerprint`] not only defines but also executes a set of rules to
20//!   determine if a re-compile is needed.
21//! * [`job_queue`] is where the parallelism, job scheduling, and communication
22//!   machinery happen between Cargo and the compiler.
23//! * [`layout`] defines and manages output artifacts of a build in the filesystem.
24//! * [`unit_dependencies`] is for building a dependency graph for compilation
25//!   from a result of dependency resolution.
26//! * [`Unit`] contains sufficient information to build something, usually
27//!   turning into a compiler invocation in a later phase.
28//!
29//! [`ops::cargo_compile::compile`]: crate::ops::compile
30
31pub mod artifact;
32mod build_config;
33pub(crate) mod build_context;
34pub(crate) mod build_runner;
35mod compilation;
36mod compile_kind;
37mod crate_type;
38mod custom_build;
39pub(crate) mod fingerprint;
40pub mod future_incompat;
41pub(crate) mod job_queue;
42pub(crate) mod layout;
43mod links;
44mod lto;
45mod output_depinfo;
46mod output_sbom;
47pub mod rustdoc;
48pub mod standard_lib;
49mod timings;
50mod unit;
51pub mod unit_dependencies;
52pub mod unit_graph;
53
54use std::borrow::Cow;
55use std::cell::OnceCell;
56use std::collections::{BTreeMap, HashMap, HashSet};
57use std::env;
58use std::ffi::{OsStr, OsString};
59use std::fmt::Display;
60use std::fs::{self, File};
61use std::io::{BufRead, BufWriter, Write};
62use std::ops::Range;
63use std::path::{Path, PathBuf};
64use std::sync::{Arc, LazyLock};
65
66use annotate_snippets::{AnnotationKind, Group, Level, Renderer, Snippet};
67use anyhow::{Context as _, Error};
68use cargo_platform::{Cfg, Platform};
69use itertools::Itertools;
70use regex::Regex;
71use tracing::{debug, instrument, trace};
72
73pub use self::build_config::UserIntent;
74pub use self::build_config::{BuildConfig, CompileMode, MessageFormat, TimingOutput};
75pub use self::build_context::{
76    BuildContext, FileFlavor, FileType, RustDocFingerprint, RustcTargetData, TargetInfo,
77};
78pub use self::build_runner::{BuildRunner, Metadata, UnitHash};
79pub use self::compilation::{Compilation, Doctest, UnitOutput};
80pub use self::compile_kind::{CompileKind, CompileKindFallback, CompileTarget};
81pub use self::crate_type::CrateType;
82pub use self::custom_build::LinkArgTarget;
83pub use self::custom_build::{BuildOutput, BuildScriptOutputs, BuildScripts, LibraryPath};
84pub(crate) use self::fingerprint::DirtyReason;
85pub use self::job_queue::Freshness;
86use self::job_queue::{Job, JobQueue, JobState, Work};
87pub(crate) use self::layout::Layout;
88pub use self::lto::Lto;
89use self::output_depinfo::output_depinfo;
90use self::output_sbom::build_sbom;
91use self::unit_graph::UnitDep;
92use crate::core::compiler::future_incompat::FutureIncompatReport;
93use crate::core::compiler::timings::SectionTiming;
94pub use crate::core::compiler::unit::{Unit, UnitInterner};
95use crate::core::manifest::TargetSourcePath;
96use crate::core::profiles::{PanicStrategy, Profile, StripInner};
97use crate::core::{Feature, PackageId, Target, Verbosity};
98use crate::util::OnceExt;
99use crate::util::context::WarningHandling;
100use crate::util::errors::{CargoResult, VerboseError};
101use crate::util::interning::InternedString;
102use crate::util::lints::get_key_value;
103use crate::util::machine_message::{self, Message};
104use crate::util::{add_path_args, internal, path_args};
105use cargo_util::{ProcessBuilder, ProcessError, paths};
106use cargo_util_schemas::manifest::TomlDebugInfo;
107use cargo_util_schemas::manifest::TomlTrimPaths;
108use cargo_util_schemas::manifest::TomlTrimPathsValue;
109use rustfix::diagnostics::Applicability;
110pub(crate) use timings::CompilationSection;
111
112const RUSTDOC_CRATE_VERSION_FLAG: &str = "--crate-version";
113
114/// A glorified callback for executing calls to rustc. Rather than calling rustc
115/// directly, we'll use an `Executor`, giving clients an opportunity to intercept
116/// the build calls.
117pub trait Executor: Send + Sync + 'static {
118    /// Called after a rustc process invocation is prepared up-front for a given
119    /// unit of work (may still be modified for runtime-known dependencies, when
120    /// the work is actually executed).
121    fn init(&self, _build_runner: &BuildRunner<'_, '_>, _unit: &Unit) {}
122
123    /// In case of an `Err`, Cargo will not continue with the build process for
124    /// this package.
125    fn exec(
126        &self,
127        cmd: &ProcessBuilder,
128        id: PackageId,
129        target: &Target,
130        mode: CompileMode,
131        on_stdout_line: &mut dyn FnMut(&str) -> CargoResult<()>,
132        on_stderr_line: &mut dyn FnMut(&str) -> CargoResult<()>,
133    ) -> CargoResult<()>;
134
135    /// Queried when queuing each unit of work. If it returns true, then the
136    /// unit will always be rebuilt, independent of whether it needs to be.
137    fn force_rebuild(&self, _unit: &Unit) -> bool {
138        false
139    }
140}
141
142/// A `DefaultExecutor` calls rustc without doing anything else. It is Cargo's
143/// default behaviour.
144#[derive(Copy, Clone)]
145pub struct DefaultExecutor;
146
147impl Executor for DefaultExecutor {
148    #[instrument(name = "rustc", skip_all, fields(package = id.name().as_str(), process = cmd.to_string()))]
149    fn exec(
150        &self,
151        cmd: &ProcessBuilder,
152        id: PackageId,
153        _target: &Target,
154        _mode: CompileMode,
155        on_stdout_line: &mut dyn FnMut(&str) -> CargoResult<()>,
156        on_stderr_line: &mut dyn FnMut(&str) -> CargoResult<()>,
157    ) -> CargoResult<()> {
158        cmd.exec_with_streaming(on_stdout_line, on_stderr_line, false)
159            .map(drop)
160    }
161}
162
163/// Builds up and enqueue a list of pending jobs onto the `job` queue.
164///
165/// Starting from the `unit`, this function recursively calls itself to build
166/// all jobs for dependencies of the `unit`. Each of these jobs represents
167/// compiling a particular package.
168///
169/// Note that **no actual work is executed as part of this**, that's all done
170/// next as part of [`JobQueue::execute`] function which will run everything
171/// in order with proper parallelism.
172#[tracing::instrument(skip(build_runner, jobs, exec))]
173fn compile<'gctx>(
174    build_runner: &mut BuildRunner<'_, 'gctx>,
175    jobs: &mut JobQueue<'gctx>,
176    unit: &Unit,
177    exec: &Arc<dyn Executor>,
178    force_rebuild: bool,
179) -> CargoResult<()> {
180    let bcx = build_runner.bcx;
181    if !build_runner.compiled.insert(unit.clone()) {
182        return Ok(());
183    }
184
185    // If we are in `--compile-time-deps` and the given unit is not a compile time
186    // dependency, skip compiling the unit and jumps to dependencies, which still
187    // have chances to be compile time dependencies
188    if !unit.skip_non_compile_time_dep {
189        // Build up the work to be done to compile this unit, enqueuing it once
190        // we've got everything constructed.
191        fingerprint::prepare_init(build_runner, unit)?;
192
193        let job = if unit.mode.is_run_custom_build() {
194            custom_build::prepare(build_runner, unit)?
195        } else if unit.mode.is_doc_test() {
196            // We run these targets later, so this is just a no-op for now.
197            Job::new_fresh()
198        } else {
199            let force = exec.force_rebuild(unit) || force_rebuild;
200            let mut job = fingerprint::prepare_target(build_runner, unit, force)?;
201            job.before(if job.freshness().is_dirty() {
202                let work = if unit.mode.is_doc() || unit.mode.is_doc_scrape() {
203                    rustdoc(build_runner, unit)?
204                } else {
205                    rustc(build_runner, unit, exec)?
206                };
207                work.then(link_targets(build_runner, unit, false)?)
208            } else {
209                // We always replay the output cache,
210                // since it might contain future-incompat-report messages
211                let show_diagnostics = unit.show_warnings(bcx.gctx)
212                    && build_runner.bcx.gctx.warning_handling()? != WarningHandling::Allow;
213                let manifest = ManifestErrorContext::new(build_runner, unit);
214                let work = replay_output_cache(
215                    unit.pkg.package_id(),
216                    manifest,
217                    &unit.target,
218                    build_runner.files().message_cache_path(unit),
219                    build_runner.bcx.build_config.message_format,
220                    show_diagnostics,
221                );
222                // Need to link targets on both the dirty and fresh.
223                work.then(link_targets(build_runner, unit, true)?)
224            });
225
226            job
227        };
228        jobs.enqueue(build_runner, unit, job)?;
229    }
230
231    // Be sure to compile all dependencies of this target as well.
232    let deps = Vec::from(build_runner.unit_deps(unit)); // Create vec due to mutable borrow.
233    for dep in deps {
234        compile(build_runner, jobs, &dep.unit, exec, false)?;
235    }
236
237    Ok(())
238}
239
240/// Generates the warning message used when fallible doc-scrape units fail,
241/// either for rustdoc or rustc.
242fn make_failed_scrape_diagnostic(
243    build_runner: &BuildRunner<'_, '_>,
244    unit: &Unit,
245    top_line: impl Display,
246) -> String {
247    let manifest_path = unit.pkg.manifest_path();
248    let relative_manifest_path = manifest_path
249        .strip_prefix(build_runner.bcx.ws.root())
250        .unwrap_or(&manifest_path);
251
252    format!(
253        "\
254{top_line}
255    Try running with `--verbose` to see the error message.
256    If an example should not be scanned, then consider adding `doc-scrape-examples = false` to its `[[example]]` definition in {}",
257        relative_manifest_path.display()
258    )
259}
260
261/// Creates a unit of work invoking `rustc` for building the `unit`.
262fn rustc(
263    build_runner: &mut BuildRunner<'_, '_>,
264    unit: &Unit,
265    exec: &Arc<dyn Executor>,
266) -> CargoResult<Work> {
267    let mut rustc = prepare_rustc(build_runner, unit)?;
268
269    let name = unit.pkg.name();
270
271    let outputs = build_runner.outputs(unit)?;
272    let root = build_runner.files().out_dir(unit);
273
274    // Prepare the native lib state (extra `-L` and `-l` flags).
275    let build_script_outputs = Arc::clone(&build_runner.build_script_outputs);
276    let current_id = unit.pkg.package_id();
277    let manifest = ManifestErrorContext::new(build_runner, unit);
278    let build_scripts = build_runner.build_scripts.get(unit).cloned();
279
280    // If we are a binary and the package also contains a library, then we
281    // don't pass the `-l` flags.
282    let pass_l_flag = unit.target.is_lib() || !unit.pkg.targets().iter().any(|t| t.is_lib());
283
284    let dep_info_name =
285        if let Some(c_extra_filename) = build_runner.files().metadata(unit).c_extra_filename() {
286            format!("{}-{}.d", unit.target.crate_name(), c_extra_filename)
287        } else {
288            format!("{}.d", unit.target.crate_name())
289        };
290    let rustc_dep_info_loc = root.join(dep_info_name);
291    let dep_info_loc = fingerprint::dep_info_loc(build_runner, unit);
292
293    let mut output_options = OutputOptions::new(build_runner, unit);
294    let package_id = unit.pkg.package_id();
295    let target = Target::clone(&unit.target);
296    let mode = unit.mode;
297
298    exec.init(build_runner, unit);
299    let exec = exec.clone();
300
301    let root_output = build_runner.files().host_dest().map(|v| v.to_path_buf());
302    let build_dir = build_runner.bcx.ws.build_dir().into_path_unlocked();
303    let pkg_root = unit.pkg.root().to_path_buf();
304    let cwd = rustc
305        .get_cwd()
306        .unwrap_or_else(|| build_runner.bcx.gctx.cwd())
307        .to_path_buf();
308    let fingerprint_dir = build_runner.files().fingerprint_dir(unit);
309    let script_metadatas = build_runner.find_build_script_metadatas(unit);
310    let is_local = unit.is_local();
311    let artifact = unit.artifact;
312    let sbom_files = build_runner.sbom_output_files(unit)?;
313    let sbom = build_sbom(build_runner, unit)?;
314
315    let hide_diagnostics_for_scrape_unit = build_runner.bcx.unit_can_fail_for_docscraping(unit)
316        && !matches!(
317            build_runner.bcx.gctx.shell().verbosity(),
318            Verbosity::Verbose
319        );
320    let failed_scrape_diagnostic = hide_diagnostics_for_scrape_unit.then(|| {
321        // If this unit is needed for doc-scraping, then we generate a diagnostic that
322        // describes the set of reverse-dependencies that cause the unit to be needed.
323        let target_desc = unit.target.description_named();
324        let mut for_scrape_units = build_runner
325            .bcx
326            .scrape_units_have_dep_on(unit)
327            .into_iter()
328            .map(|unit| unit.target.description_named())
329            .collect::<Vec<_>>();
330        for_scrape_units.sort();
331        let for_scrape_units = for_scrape_units.join(", ");
332        make_failed_scrape_diagnostic(build_runner, unit, format_args!("failed to check {target_desc} in package `{name}` as a prerequisite for scraping examples from: {for_scrape_units}"))
333    });
334    if hide_diagnostics_for_scrape_unit {
335        output_options.show_diagnostics = false;
336    }
337    let env_config = Arc::clone(build_runner.bcx.gctx.env_config()?);
338    return Ok(Work::new(move |state| {
339        // Artifacts are in a different location than typical units,
340        // hence we must assure the crate- and target-dependent
341        // directory is present.
342        if artifact.is_true() {
343            paths::create_dir_all(&root)?;
344        }
345
346        // Only at runtime have we discovered what the extra -L and -l
347        // arguments are for native libraries, so we process those here. We
348        // also need to be sure to add any -L paths for our plugins to the
349        // dynamic library load path as a plugin's dynamic library may be
350        // located somewhere in there.
351        // Finally, if custom environment variables have been produced by
352        // previous build scripts, we include them in the rustc invocation.
353        if let Some(build_scripts) = build_scripts {
354            let script_outputs = build_script_outputs.lock().unwrap();
355            add_native_deps(
356                &mut rustc,
357                &script_outputs,
358                &build_scripts,
359                pass_l_flag,
360                &target,
361                current_id,
362                mode,
363            )?;
364            if let Some(ref root_output) = root_output {
365                add_plugin_deps(&mut rustc, &script_outputs, &build_scripts, root_output)?;
366            }
367            add_custom_flags(&mut rustc, &script_outputs, script_metadatas)?;
368        }
369
370        for output in outputs.iter() {
371            // If there is both an rmeta and rlib, rustc will prefer to use the
372            // rlib, even if it is older. Therefore, we must delete the rlib to
373            // force using the new rmeta.
374            if output.path.extension() == Some(OsStr::new("rmeta")) {
375                let dst = root.join(&output.path).with_extension("rlib");
376                if dst.exists() {
377                    paths::remove_file(&dst)?;
378                }
379            }
380
381            // Some linkers do not remove the executable, but truncate and modify it.
382            // That results in the old hard-link being modified even after renamed.
383            // We delete the old artifact here to prevent this behavior from confusing users.
384            // See rust-lang/cargo#8348.
385            if output.hardlink.is_some() && output.path.exists() {
386                _ = paths::remove_file(&output.path).map_err(|e| {
387                    tracing::debug!(
388                        "failed to delete previous output file `{:?}`: {e:?}",
389                        output.path
390                    );
391                });
392            }
393        }
394
395        state.running(&rustc);
396        let timestamp = paths::set_invocation_time(&fingerprint_dir)?;
397        for file in sbom_files {
398            tracing::debug!("writing sbom to {}", file.display());
399            let outfile = BufWriter::new(paths::create(&file)?);
400            serde_json::to_writer(outfile, &sbom)?;
401        }
402
403        let result = exec
404            .exec(
405                &rustc,
406                package_id,
407                &target,
408                mode,
409                &mut |line| on_stdout_line(state, line, package_id, &target),
410                &mut |line| {
411                    on_stderr_line(
412                        state,
413                        line,
414                        package_id,
415                        &manifest,
416                        &target,
417                        &mut output_options,
418                    )
419                },
420            )
421            .map_err(|e| {
422                if output_options.errors_seen == 0 {
423                    // If we didn't expect an error, do not require --verbose to fail.
424                    // This is intended to debug
425                    // https://github.com/rust-lang/crater/issues/733, where we are seeing
426                    // Cargo exit unsuccessfully while seeming to not show any errors.
427                    e
428                } else {
429                    verbose_if_simple_exit_code(e)
430                }
431            })
432            .with_context(|| {
433                // adapted from rustc_errors/src/lib.rs
434                let warnings = match output_options.warnings_seen {
435                    0 => String::new(),
436                    1 => "; 1 warning emitted".to_string(),
437                    count => format!("; {} warnings emitted", count),
438                };
439                let errors = match output_options.errors_seen {
440                    0 => String::new(),
441                    1 => " due to 1 previous error".to_string(),
442                    count => format!(" due to {} previous errors", count),
443                };
444                let name = descriptive_pkg_name(&name, &target, &mode);
445                format!("could not compile {name}{errors}{warnings}")
446            });
447
448        if let Err(e) = result {
449            if let Some(diagnostic) = failed_scrape_diagnostic {
450                state.warning(diagnostic);
451            }
452
453            return Err(e);
454        }
455
456        // Exec should never return with success *and* generate an error.
457        debug_assert_eq!(output_options.errors_seen, 0);
458
459        if rustc_dep_info_loc.exists() {
460            fingerprint::translate_dep_info(
461                &rustc_dep_info_loc,
462                &dep_info_loc,
463                &cwd,
464                &pkg_root,
465                &build_dir,
466                &rustc,
467                // Do not track source files in the fingerprint for registry dependencies.
468                is_local,
469                &env_config,
470            )
471            .with_context(|| {
472                internal(format!(
473                    "could not parse/generate dep info at: {}",
474                    rustc_dep_info_loc.display()
475                ))
476            })?;
477            // This mtime shift allows Cargo to detect if a source file was
478            // modified in the middle of the build.
479            paths::set_file_time_no_err(dep_info_loc, timestamp);
480        }
481
482        // This mtime shift for .rmeta is a workaround as rustc incremental build
483        // since rust-lang/rust#114669 (1.90.0) skips unnecessary rmeta generation.
484        //
485        // The situation is like this:
486        //
487        // 1. When build script execution's external dependendies
488        //    (rerun-if-changed, rerun-if-env-changed) got updated,
489        //    the execution unit reran and got a newer mtime.
490        // 2. rustc type-checked the associated crate, though with incremental
491        //    compilation, no rmeta regeneration. Its `.rmeta` stays old.
492        // 3. Run `cargo check` again. Cargo found build script execution had
493        //    a new mtime than existing crate rmeta, so re-checking the crate.
494        //    However the check is a no-op (input has no change), so stuck.
495        if mode.is_check() {
496            for output in outputs.iter() {
497                paths::set_file_time_no_err(&output.path, timestamp);
498            }
499        }
500
501        Ok(())
502    }));
503
504    // Add all relevant `-L` and `-l` flags from dependencies (now calculated and
505    // present in `state`) to the command provided.
506    fn add_native_deps(
507        rustc: &mut ProcessBuilder,
508        build_script_outputs: &BuildScriptOutputs,
509        build_scripts: &BuildScripts,
510        pass_l_flag: bool,
511        target: &Target,
512        current_id: PackageId,
513        mode: CompileMode,
514    ) -> CargoResult<()> {
515        let mut library_paths = vec![];
516
517        for key in build_scripts.to_link.iter() {
518            let output = build_script_outputs.get(key.1).ok_or_else(|| {
519                internal(format!(
520                    "couldn't find build script output for {}/{}",
521                    key.0, key.1
522                ))
523            })?;
524            library_paths.extend(output.library_paths.iter());
525        }
526
527        // NOTE: This very intentionally does not use the derived ord from LibraryPath because we need to
528        // retain relative ordering within the same type (i.e. not lexicographic). The use of a stable sort
529        // is also important here because it ensures that paths of the same type retain the same relative
530        // ordering (for an unstable sort to work here, the list would need to retain the idx of each element
531        // and then sort by that idx when the type is equivalent.
532        library_paths.sort_by_key(|p| match p {
533            LibraryPath::CargoArtifact(_) => 0,
534            LibraryPath::External(_) => 1,
535        });
536
537        for path in library_paths.iter() {
538            rustc.arg("-L").arg(path.as_ref());
539        }
540
541        for key in build_scripts.to_link.iter() {
542            let output = build_script_outputs.get(key.1).ok_or_else(|| {
543                internal(format!(
544                    "couldn't find build script output for {}/{}",
545                    key.0, key.1
546                ))
547            })?;
548
549            if key.0 == current_id {
550                if pass_l_flag {
551                    for name in output.library_links.iter() {
552                        rustc.arg("-l").arg(name);
553                    }
554                }
555            }
556
557            for (lt, arg) in &output.linker_args {
558                // There was an unintentional change where cdylibs were
559                // allowed to be passed via transitive dependencies. This
560                // clause should have been kept in the `if` block above. For
561                // now, continue allowing it for cdylib only.
562                // See https://github.com/rust-lang/cargo/issues/9562
563                if lt.applies_to(target, mode)
564                    && (key.0 == current_id || *lt == LinkArgTarget::Cdylib)
565                {
566                    rustc.arg("-C").arg(format!("link-arg={}", arg));
567                }
568            }
569        }
570        Ok(())
571    }
572}
573
574fn verbose_if_simple_exit_code(err: Error) -> Error {
575    // If a signal on unix (`code == None`) or an abnormal termination
576    // on Windows (codes like `0xC0000409`), don't hide the error details.
577    match err
578        .downcast_ref::<ProcessError>()
579        .as_ref()
580        .and_then(|perr| perr.code)
581    {
582        Some(n) if cargo_util::is_simple_exit_code(n) => VerboseError::new(err).into(),
583        _ => err,
584    }
585}
586
587/// Link the compiled target (often of form `foo-{metadata_hash}`) to the
588/// final target. This must happen during both "Fresh" and "Compile".
589fn link_targets(
590    build_runner: &mut BuildRunner<'_, '_>,
591    unit: &Unit,
592    fresh: bool,
593) -> CargoResult<Work> {
594    let bcx = build_runner.bcx;
595    let outputs = build_runner.outputs(unit)?;
596    let export_dir = build_runner.files().export_dir();
597    let package_id = unit.pkg.package_id();
598    let manifest_path = PathBuf::from(unit.pkg.manifest_path());
599    let profile = unit.profile.clone();
600    let unit_mode = unit.mode;
601    let features = unit.features.iter().map(|s| s.to_string()).collect();
602    let json_messages = bcx.build_config.emit_json();
603    let executable = build_runner.get_executable(unit)?;
604    let mut target = Target::clone(&unit.target);
605    if let TargetSourcePath::Metabuild = target.src_path() {
606        // Give it something to serialize.
607        let path = unit
608            .pkg
609            .manifest()
610            .metabuild_path(build_runner.bcx.ws.build_dir());
611        target.set_src_path(TargetSourcePath::Path(path));
612    }
613
614    Ok(Work::new(move |state| {
615        // If we're a "root crate", e.g., the target of this compilation, then we
616        // hard link our outputs out of the `deps` directory into the directory
617        // above. This means that `cargo build` will produce binaries in
618        // `target/debug` which one probably expects.
619        let mut destinations = vec![];
620        for output in outputs.iter() {
621            let src = &output.path;
622            // This may have been a `cargo rustc` command which changes the
623            // output, so the source may not actually exist.
624            if !src.exists() {
625                continue;
626            }
627            let Some(dst) = output.hardlink.as_ref() else {
628                destinations.push(src.clone());
629                continue;
630            };
631            destinations.push(dst.clone());
632            paths::link_or_copy(src, dst)?;
633            if let Some(ref path) = output.export_path {
634                let export_dir = export_dir.as_ref().unwrap();
635                paths::create_dir_all(export_dir)?;
636
637                paths::link_or_copy(src, path)?;
638            }
639        }
640
641        if json_messages {
642            let debuginfo = match profile.debuginfo.into_inner() {
643                TomlDebugInfo::None => machine_message::ArtifactDebuginfo::Int(0),
644                TomlDebugInfo::Limited => machine_message::ArtifactDebuginfo::Int(1),
645                TomlDebugInfo::Full => machine_message::ArtifactDebuginfo::Int(2),
646                TomlDebugInfo::LineDirectivesOnly => {
647                    machine_message::ArtifactDebuginfo::Named("line-directives-only")
648                }
649                TomlDebugInfo::LineTablesOnly => {
650                    machine_message::ArtifactDebuginfo::Named("line-tables-only")
651                }
652            };
653            let art_profile = machine_message::ArtifactProfile {
654                opt_level: profile.opt_level.as_str(),
655                debuginfo: Some(debuginfo),
656                debug_assertions: profile.debug_assertions,
657                overflow_checks: profile.overflow_checks,
658                test: unit_mode.is_any_test(),
659            };
660
661            let msg = machine_message::Artifact {
662                package_id: package_id.to_spec(),
663                manifest_path,
664                target: &target,
665                profile: art_profile,
666                features,
667                filenames: destinations,
668                executable,
669                fresh,
670            }
671            .to_json_string();
672            state.stdout(msg)?;
673        }
674        Ok(())
675    }))
676}
677
678// For all plugin dependencies, add their -L paths (now calculated and present
679// in `build_script_outputs`) to the dynamic library load path for the command
680// to execute.
681fn add_plugin_deps(
682    rustc: &mut ProcessBuilder,
683    build_script_outputs: &BuildScriptOutputs,
684    build_scripts: &BuildScripts,
685    root_output: &Path,
686) -> CargoResult<()> {
687    let var = paths::dylib_path_envvar();
688    let search_path = rustc.get_env(var).unwrap_or_default();
689    let mut search_path = env::split_paths(&search_path).collect::<Vec<_>>();
690    for (pkg_id, metadata) in &build_scripts.plugins {
691        let output = build_script_outputs
692            .get(*metadata)
693            .ok_or_else(|| internal(format!("couldn't find libs for plugin dep {}", pkg_id)))?;
694        search_path.append(&mut filter_dynamic_search_path(
695            output.library_paths.iter().map(AsRef::as_ref),
696            root_output,
697        ));
698    }
699    let search_path = paths::join_paths(&search_path, var)?;
700    rustc.env(var, &search_path);
701    Ok(())
702}
703
704fn get_dynamic_search_path(path: &Path) -> &Path {
705    match path.to_str().and_then(|s| s.split_once("=")) {
706        Some(("native" | "crate" | "dependency" | "framework" | "all", path)) => Path::new(path),
707        _ => path,
708    }
709}
710
711// Determine paths to add to the dynamic search path from -L entries
712//
713// Strip off prefixes like "native=" or "framework=" and filter out directories
714// **not** inside our output directory since they are likely spurious and can cause
715// clashes with system shared libraries (issue #3366).
716fn filter_dynamic_search_path<'a, I>(paths: I, root_output: &Path) -> Vec<PathBuf>
717where
718    I: Iterator<Item = &'a PathBuf>,
719{
720    let mut search_path = vec![];
721    for dir in paths {
722        let dir = get_dynamic_search_path(dir);
723        if dir.starts_with(&root_output) {
724            search_path.push(dir.to_path_buf());
725        } else {
726            debug!(
727                "Not including path {} in runtime library search path because it is \
728                 outside target root {}",
729                dir.display(),
730                root_output.display()
731            );
732        }
733    }
734    search_path
735}
736
737/// Prepares flags and environments we can compute for a `rustc` invocation
738/// before the job queue starts compiling any unit.
739///
740/// This builds a static view of the invocation. Flags depending on the
741/// completion of other units will be added later in runtime, such as flags
742/// from build scripts.
743fn prepare_rustc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<ProcessBuilder> {
744    let gctx = build_runner.bcx.gctx;
745    let is_primary = build_runner.is_primary_package(unit);
746    let is_workspace = build_runner.bcx.ws.is_member(&unit.pkg);
747
748    let mut base = build_runner
749        .compilation
750        .rustc_process(unit, is_primary, is_workspace)?;
751    build_base_args(build_runner, &mut base, unit)?;
752    if unit.pkg.manifest().is_embedded() {
753        if !gctx.cli_unstable().script {
754            anyhow::bail!(
755                "parsing `{}` requires `-Zscript`",
756                unit.pkg.manifest_path().display()
757            );
758        }
759        base.arg("-Z").arg("crate-attr=feature(frontmatter)");
760    }
761
762    base.inherit_jobserver(&build_runner.jobserver);
763    build_deps_args(&mut base, build_runner, unit)?;
764    add_cap_lints(build_runner.bcx, unit, &mut base);
765    if let Some(args) = build_runner.bcx.extra_args_for(unit) {
766        base.args(args);
767    }
768    base.args(&unit.rustflags);
769    if gctx.cli_unstable().binary_dep_depinfo {
770        base.arg("-Z").arg("binary-dep-depinfo");
771    }
772    if build_runner.bcx.gctx.cli_unstable().checksum_freshness {
773        base.arg("-Z").arg("checksum-hash-algorithm=blake3");
774    }
775
776    if is_primary {
777        base.env("CARGO_PRIMARY_PACKAGE", "1");
778        let file_list = std::env::join_paths(build_runner.sbom_output_files(unit)?)?;
779        base.env("CARGO_SBOM_PATH", file_list);
780    }
781
782    if unit.target.is_test() || unit.target.is_bench() {
783        let tmp = build_runner
784            .files()
785            .layout(unit.kind)
786            .build_dir()
787            .prepare_tmp()?;
788        base.env("CARGO_TARGET_TMPDIR", tmp.display().to_string());
789    }
790
791    Ok(base)
792}
793
794/// Prepares flags and environments we can compute for a `rustdoc` invocation
795/// before the job queue starts compiling any unit.
796///
797/// This builds a static view of the invocation. Flags depending on the
798/// completion of other units will be added later in runtime, such as flags
799/// from build scripts.
800fn prepare_rustdoc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<ProcessBuilder> {
801    let bcx = build_runner.bcx;
802    // script_metadata is not needed here, it is only for tests.
803    let mut rustdoc = build_runner.compilation.rustdoc_process(unit, None)?;
804    if unit.pkg.manifest().is_embedded() {
805        if !bcx.gctx.cli_unstable().script {
806            anyhow::bail!(
807                "parsing `{}` requires `-Zscript`",
808                unit.pkg.manifest_path().display()
809            );
810        }
811        rustdoc.arg("-Z").arg("crate-attr=feature(frontmatter)");
812    }
813    rustdoc.inherit_jobserver(&build_runner.jobserver);
814    let crate_name = unit.target.crate_name();
815    rustdoc.arg("--crate-name").arg(&crate_name);
816    add_path_args(bcx.ws, unit, &mut rustdoc);
817    add_cap_lints(bcx, unit, &mut rustdoc);
818
819    if let CompileKind::Target(target) = unit.kind {
820        rustdoc.arg("--target").arg(target.rustc_target());
821    }
822    let doc_dir = build_runner.files().out_dir(unit);
823    rustdoc.arg("-o").arg(&doc_dir);
824    rustdoc.args(&features_args(unit));
825    rustdoc.args(&check_cfg_args(unit));
826
827    add_error_format_and_color(build_runner, &mut rustdoc);
828    add_allow_features(build_runner, &mut rustdoc);
829
830    if build_runner.bcx.gctx.cli_unstable().rustdoc_depinfo {
831        // toolchain-shared-resources is required for keeping the shared styling resources
832        // invocation-specific is required for keeping the original rustdoc emission
833        let mut arg =
834            OsString::from("--emit=toolchain-shared-resources,invocation-specific,dep-info=");
835        arg.push(rustdoc_dep_info_loc(build_runner, unit));
836        rustdoc.arg(arg);
837
838        if build_runner.bcx.gctx.cli_unstable().checksum_freshness {
839            rustdoc.arg("-Z").arg("checksum-hash-algorithm=blake3");
840        }
841
842        rustdoc.arg("-Zunstable-options");
843    }
844
845    if let Some(trim_paths) = unit.profile.trim_paths.as_ref() {
846        trim_paths_args_rustdoc(&mut rustdoc, build_runner, unit, trim_paths)?;
847    }
848
849    rustdoc.args(unit.pkg.manifest().lint_rustflags());
850
851    let metadata = build_runner.metadata_for_doc_units[unit];
852    rustdoc
853        .arg("-C")
854        .arg(format!("metadata={}", metadata.c_metadata()));
855
856    if unit.mode.is_doc_scrape() {
857        debug_assert!(build_runner.bcx.scrape_units.contains(unit));
858
859        if unit.target.is_test() {
860            rustdoc.arg("--scrape-tests");
861        }
862
863        rustdoc.arg("-Zunstable-options");
864
865        rustdoc
866            .arg("--scrape-examples-output-path")
867            .arg(scrape_output_path(build_runner, unit)?);
868
869        // Only scrape example for items from crates in the workspace, to reduce generated file size
870        for pkg in build_runner.bcx.packages.packages() {
871            let names = pkg
872                .targets()
873                .iter()
874                .map(|target| target.crate_name())
875                .collect::<HashSet<_>>();
876            for name in names {
877                rustdoc.arg("--scrape-examples-target-crate").arg(name);
878            }
879        }
880    }
881
882    if should_include_scrape_units(build_runner.bcx, unit) {
883        rustdoc.arg("-Zunstable-options");
884    }
885
886    build_deps_args(&mut rustdoc, build_runner, unit)?;
887    rustdoc::add_root_urls(build_runner, unit, &mut rustdoc)?;
888
889    rustdoc::add_output_format(build_runner, &mut rustdoc)?;
890
891    if let Some(args) = build_runner.bcx.extra_args_for(unit) {
892        rustdoc.args(args);
893    }
894    rustdoc.args(&unit.rustdocflags);
895
896    if !crate_version_flag_already_present(&rustdoc) {
897        append_crate_version_flag(unit, &mut rustdoc);
898    }
899
900    Ok(rustdoc)
901}
902
903/// Creates a unit of work invoking `rustdoc` for documenting the `unit`.
904fn rustdoc(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<Work> {
905    let mut rustdoc = prepare_rustdoc(build_runner, unit)?;
906
907    let crate_name = unit.target.crate_name();
908    let doc_dir = build_runner.files().out_dir(unit);
909    // Create the documentation directory ahead of time as rustdoc currently has
910    // a bug where concurrent invocations will race to create this directory if
911    // it doesn't already exist.
912    paths::create_dir_all(&doc_dir)?;
913
914    let target_desc = unit.target.description_named();
915    let name = unit.pkg.name();
916    let build_script_outputs = Arc::clone(&build_runner.build_script_outputs);
917    let package_id = unit.pkg.package_id();
918    let target = Target::clone(&unit.target);
919    let manifest = ManifestErrorContext::new(build_runner, unit);
920
921    let rustdoc_dep_info_loc = rustdoc_dep_info_loc(build_runner, unit);
922    let dep_info_loc = fingerprint::dep_info_loc(build_runner, unit);
923    let build_dir = build_runner.bcx.ws.build_dir().into_path_unlocked();
924    let pkg_root = unit.pkg.root().to_path_buf();
925    let cwd = rustdoc
926        .get_cwd()
927        .unwrap_or_else(|| build_runner.bcx.gctx.cwd())
928        .to_path_buf();
929    let fingerprint_dir = build_runner.files().fingerprint_dir(unit);
930    let is_local = unit.is_local();
931    let env_config = Arc::clone(build_runner.bcx.gctx.env_config()?);
932    let rustdoc_depinfo_enabled = build_runner.bcx.gctx.cli_unstable().rustdoc_depinfo;
933
934    let mut output_options = OutputOptions::new(build_runner, unit);
935    let script_metadatas = build_runner.find_build_script_metadatas(unit);
936    let scrape_outputs = if should_include_scrape_units(build_runner.bcx, unit) {
937        Some(
938            build_runner
939                .bcx
940                .scrape_units
941                .iter()
942                .map(|unit| {
943                    Ok((
944                        build_runner.files().metadata(unit).unit_id(),
945                        scrape_output_path(build_runner, unit)?,
946                    ))
947                })
948                .collect::<CargoResult<HashMap<_, _>>>()?,
949        )
950    } else {
951        None
952    };
953
954    let failed_scrape_units = Arc::clone(&build_runner.failed_scrape_units);
955    let hide_diagnostics_for_scrape_unit = build_runner.bcx.unit_can_fail_for_docscraping(unit)
956        && !matches!(
957            build_runner.bcx.gctx.shell().verbosity(),
958            Verbosity::Verbose
959        );
960    let failed_scrape_diagnostic = hide_diagnostics_for_scrape_unit.then(|| {
961        make_failed_scrape_diagnostic(
962            build_runner,
963            unit,
964            format_args!("failed to scan {target_desc} in package `{name}` for example code usage"),
965        )
966    });
967    if hide_diagnostics_for_scrape_unit {
968        output_options.show_diagnostics = false;
969    }
970
971    Ok(Work::new(move |state| {
972        add_custom_flags(
973            &mut rustdoc,
974            &build_script_outputs.lock().unwrap(),
975            script_metadatas,
976        )?;
977
978        // Add the output of scraped examples to the rustdoc command.
979        // This action must happen after the unit's dependencies have finished,
980        // because some of those deps may be Docscrape units which have failed.
981        // So we dynamically determine which `--with-examples` flags to pass here.
982        if let Some(scrape_outputs) = scrape_outputs {
983            let failed_scrape_units = failed_scrape_units.lock().unwrap();
984            for (metadata, output_path) in &scrape_outputs {
985                if !failed_scrape_units.contains(metadata) {
986                    rustdoc.arg("--with-examples").arg(output_path);
987                }
988            }
989        }
990
991        let crate_dir = doc_dir.join(&crate_name);
992        if crate_dir.exists() {
993            // Remove output from a previous build. This ensures that stale
994            // files for removed items are removed.
995            debug!("removing pre-existing doc directory {:?}", crate_dir);
996            paths::remove_dir_all(crate_dir)?;
997        }
998        state.running(&rustdoc);
999        let timestamp = paths::set_invocation_time(&fingerprint_dir)?;
1000
1001        let result = rustdoc
1002            .exec_with_streaming(
1003                &mut |line| on_stdout_line(state, line, package_id, &target),
1004                &mut |line| {
1005                    on_stderr_line(
1006                        state,
1007                        line,
1008                        package_id,
1009                        &manifest,
1010                        &target,
1011                        &mut output_options,
1012                    )
1013                },
1014                false,
1015            )
1016            .map_err(verbose_if_simple_exit_code)
1017            .with_context(|| format!("could not document `{}`", name));
1018
1019        if let Err(e) = result {
1020            if let Some(diagnostic) = failed_scrape_diagnostic {
1021                state.warning(diagnostic);
1022            }
1023
1024            return Err(e);
1025        }
1026
1027        if rustdoc_depinfo_enabled && rustdoc_dep_info_loc.exists() {
1028            fingerprint::translate_dep_info(
1029                &rustdoc_dep_info_loc,
1030                &dep_info_loc,
1031                &cwd,
1032                &pkg_root,
1033                &build_dir,
1034                &rustdoc,
1035                // Should we track source file for doc gen?
1036                is_local,
1037                &env_config,
1038            )
1039            .with_context(|| {
1040                internal(format_args!(
1041                    "could not parse/generate dep info at: {}",
1042                    rustdoc_dep_info_loc.display()
1043                ))
1044            })?;
1045            // This mtime shift allows Cargo to detect if a source file was
1046            // modified in the middle of the build.
1047            paths::set_file_time_no_err(dep_info_loc, timestamp);
1048        }
1049
1050        Ok(())
1051    }))
1052}
1053
1054// The --crate-version flag could have already been passed in RUSTDOCFLAGS
1055// or as an extra compiler argument for rustdoc
1056fn crate_version_flag_already_present(rustdoc: &ProcessBuilder) -> bool {
1057    rustdoc.get_args().any(|flag| {
1058        flag.to_str()
1059            .map_or(false, |flag| flag.starts_with(RUSTDOC_CRATE_VERSION_FLAG))
1060    })
1061}
1062
1063fn append_crate_version_flag(unit: &Unit, rustdoc: &mut ProcessBuilder) {
1064    rustdoc
1065        .arg(RUSTDOC_CRATE_VERSION_FLAG)
1066        .arg(unit.pkg.version().to_string());
1067}
1068
1069/// Adds [`--cap-lints`] to the command to execute.
1070///
1071/// [`--cap-lints`]: https://doc.rust-lang.org/nightly/rustc/lints/levels.html#capping-lints
1072fn add_cap_lints(bcx: &BuildContext<'_, '_>, unit: &Unit, cmd: &mut ProcessBuilder) {
1073    // If this is an upstream dep we don't want warnings from, turn off all
1074    // lints.
1075    if !unit.show_warnings(bcx.gctx) {
1076        cmd.arg("--cap-lints").arg("allow");
1077
1078    // If this is an upstream dep but we *do* want warnings, make sure that they
1079    // don't fail compilation.
1080    } else if !unit.is_local() {
1081        cmd.arg("--cap-lints").arg("warn");
1082    }
1083}
1084
1085/// Forwards [`-Zallow-features`] if it is set for cargo.
1086///
1087/// [`-Zallow-features`]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#allow-features
1088fn add_allow_features(build_runner: &BuildRunner<'_, '_>, cmd: &mut ProcessBuilder) {
1089    if let Some(allow) = &build_runner.bcx.gctx.cli_unstable().allow_features {
1090        use std::fmt::Write;
1091        let mut arg = String::from("-Zallow-features=");
1092        for f in allow {
1093            let _ = write!(&mut arg, "{f},");
1094        }
1095        cmd.arg(arg.trim_end_matches(','));
1096    }
1097}
1098
1099/// Adds [`--error-format`] to the command to execute.
1100///
1101/// Cargo always uses JSON output. This has several benefits, such as being
1102/// easier to parse, handles changing formats (for replaying cached messages),
1103/// ensures atomic output (so messages aren't interleaved), allows for
1104/// intercepting messages like rmeta artifacts, etc. rustc includes a
1105/// "rendered" field in the JSON message with the message properly formatted,
1106/// which Cargo will extract and display to the user.
1107///
1108/// [`--error-format`]: https://doc.rust-lang.org/nightly/rustc/command-line-arguments.html#--error-format-control-how-errors-are-produced
1109fn add_error_format_and_color(build_runner: &BuildRunner<'_, '_>, cmd: &mut ProcessBuilder) {
1110    let enable_timings = build_runner.bcx.gctx.cli_unstable().section_timings
1111        && !build_runner.bcx.build_config.timing_outputs.is_empty();
1112    if enable_timings {
1113        cmd.arg("-Zunstable-options");
1114    }
1115
1116    cmd.arg("--error-format=json");
1117    let mut json = String::from("--json=diagnostic-rendered-ansi,artifacts,future-incompat");
1118
1119    if let MessageFormat::Short | MessageFormat::Json { short: true, .. } =
1120        build_runner.bcx.build_config.message_format
1121    {
1122        json.push_str(",diagnostic-short");
1123    } else if build_runner.bcx.gctx.shell().err_unicode()
1124        && build_runner.bcx.gctx.cli_unstable().rustc_unicode
1125    {
1126        json.push_str(",diagnostic-unicode");
1127    }
1128
1129    if enable_timings {
1130        json.push_str(",timings");
1131    }
1132
1133    cmd.arg(json);
1134
1135    let gctx = build_runner.bcx.gctx;
1136    if let Some(width) = gctx.shell().err_width().diagnostic_terminal_width() {
1137        cmd.arg(format!("--diagnostic-width={width}"));
1138    }
1139}
1140
1141/// Adds essential rustc flags and environment variables to the command to execute.
1142fn build_base_args(
1143    build_runner: &BuildRunner<'_, '_>,
1144    cmd: &mut ProcessBuilder,
1145    unit: &Unit,
1146) -> CargoResult<()> {
1147    assert!(!unit.mode.is_run_custom_build());
1148
1149    let bcx = build_runner.bcx;
1150    let Profile {
1151        ref opt_level,
1152        codegen_backend,
1153        codegen_units,
1154        debuginfo,
1155        debug_assertions,
1156        split_debuginfo,
1157        overflow_checks,
1158        rpath,
1159        ref panic,
1160        incremental,
1161        strip,
1162        rustflags: profile_rustflags,
1163        trim_paths,
1164        hint_mostly_unused: profile_hint_mostly_unused,
1165        ..
1166    } = unit.profile.clone();
1167    let hints = unit.pkg.hints().cloned().unwrap_or_default();
1168    let test = unit.mode.is_any_test();
1169
1170    let warn = |msg: &str| {
1171        bcx.gctx.shell().warn(format!(
1172            "{}@{}: {msg}",
1173            unit.pkg.package_id().name(),
1174            unit.pkg.package_id().version()
1175        ))
1176    };
1177    let unit_capped_warn = |msg: &str| {
1178        if unit.show_warnings(bcx.gctx) {
1179            warn(msg)
1180        } else {
1181            Ok(())
1182        }
1183    };
1184
1185    cmd.arg("--crate-name").arg(&unit.target.crate_name());
1186
1187    let edition = unit.target.edition();
1188    edition.cmd_edition_arg(cmd);
1189
1190    add_path_args(bcx.ws, unit, cmd);
1191    add_error_format_and_color(build_runner, cmd);
1192    add_allow_features(build_runner, cmd);
1193
1194    let mut contains_dy_lib = false;
1195    if !test {
1196        for crate_type in &unit.target.rustc_crate_types() {
1197            cmd.arg("--crate-type").arg(crate_type.as_str());
1198            contains_dy_lib |= crate_type == &CrateType::Dylib;
1199        }
1200    }
1201
1202    if unit.mode.is_check() {
1203        cmd.arg("--emit=dep-info,metadata");
1204    } else if build_runner.bcx.gctx.cli_unstable().no_embed_metadata {
1205        // Nightly rustc supports the -Zembed-metadata=no flag, which tells it to avoid including
1206        // full metadata in rlib/dylib artifacts, to save space on disk. In this case, metadata
1207        // will only be stored in .rmeta files.
1208        // When we use this flag, we should also pass --emit=metadata to all artifacts that
1209        // contain useful metadata (rlib/dylib/proc macros), so that a .rmeta file is actually
1210        // generated. If we didn't do this, the full metadata would not get written anywhere.
1211        // However, we do not want to pass --emit=metadata to artifacts that never produce useful
1212        // metadata, such as binaries, because that would just unnecessarily create empty .rmeta
1213        // files on disk.
1214        if unit.benefits_from_no_embed_metadata() {
1215            cmd.arg("--emit=dep-info,metadata,link");
1216            cmd.args(&["-Z", "embed-metadata=no"]);
1217        } else {
1218            cmd.arg("--emit=dep-info,link");
1219        }
1220    } else {
1221        // If we don't use -Zembed-metadata=no, we emit .rmeta files only for rlib outputs.
1222        // This metadata may be used in this session for a pipelined compilation, or it may
1223        // be used in a future Cargo session as part of a pipelined compile.
1224        if !unit.requires_upstream_objects() {
1225            cmd.arg("--emit=dep-info,metadata,link");
1226        } else {
1227            cmd.arg("--emit=dep-info,link");
1228        }
1229    }
1230
1231    let prefer_dynamic = (unit.target.for_host() && !unit.target.is_custom_build())
1232        || (contains_dy_lib && !build_runner.is_primary_package(unit));
1233    if prefer_dynamic {
1234        cmd.arg("-C").arg("prefer-dynamic");
1235    }
1236
1237    if opt_level.as_str() != "0" {
1238        cmd.arg("-C").arg(&format!("opt-level={}", opt_level));
1239    }
1240
1241    if *panic != PanicStrategy::Unwind {
1242        cmd.arg("-C").arg(format!("panic={}", panic));
1243    }
1244    if *panic == PanicStrategy::ImmediateAbort {
1245        cmd.arg("-Z").arg("unstable-options");
1246    }
1247
1248    cmd.args(&lto_args(build_runner, unit));
1249
1250    if let Some(backend) = codegen_backend {
1251        cmd.arg("-Z").arg(&format!("codegen-backend={}", backend));
1252    }
1253
1254    if let Some(n) = codegen_units {
1255        cmd.arg("-C").arg(&format!("codegen-units={}", n));
1256    }
1257
1258    let debuginfo = debuginfo.into_inner();
1259    // Shorten the number of arguments if possible.
1260    if debuginfo != TomlDebugInfo::None {
1261        cmd.arg("-C").arg(format!("debuginfo={debuginfo}"));
1262        // This is generally just an optimization on build time so if we don't
1263        // pass it then it's ok. The values for the flag (off, packed, unpacked)
1264        // may be supported or not depending on the platform, so availability is
1265        // checked per-value. For example, at the time of writing this code, on
1266        // Windows the only stable valid value for split-debuginfo is "packed",
1267        // while on Linux "unpacked" is also stable.
1268        if let Some(split) = split_debuginfo {
1269            if build_runner
1270                .bcx
1271                .target_data
1272                .info(unit.kind)
1273                .supports_debuginfo_split(split)
1274            {
1275                cmd.arg("-C").arg(format!("split-debuginfo={split}"));
1276            }
1277        }
1278    }
1279
1280    if let Some(trim_paths) = trim_paths {
1281        trim_paths_args(cmd, build_runner, unit, &trim_paths)?;
1282    }
1283
1284    cmd.args(unit.pkg.manifest().lint_rustflags());
1285    cmd.args(&profile_rustflags);
1286
1287    // `-C overflow-checks` is implied by the setting of `-C debug-assertions`,
1288    // so we only need to provide `-C overflow-checks` if it differs from
1289    // the value of `-C debug-assertions` we would provide.
1290    if opt_level.as_str() != "0" {
1291        if debug_assertions {
1292            cmd.args(&["-C", "debug-assertions=on"]);
1293            if !overflow_checks {
1294                cmd.args(&["-C", "overflow-checks=off"]);
1295            }
1296        } else if overflow_checks {
1297            cmd.args(&["-C", "overflow-checks=on"]);
1298        }
1299    } else if !debug_assertions {
1300        cmd.args(&["-C", "debug-assertions=off"]);
1301        if overflow_checks {
1302            cmd.args(&["-C", "overflow-checks=on"]);
1303        }
1304    } else if !overflow_checks {
1305        cmd.args(&["-C", "overflow-checks=off"]);
1306    }
1307
1308    if test && unit.target.harness() {
1309        cmd.arg("--test");
1310
1311        // Cargo has historically never compiled `--test` binaries with
1312        // `panic=abort` because the `test` crate itself didn't support it.
1313        // Support is now upstream, however, but requires an unstable flag to be
1314        // passed when compiling the test. We require, in Cargo, an unstable
1315        // flag to pass to rustc, so register that here. Eventually this flag
1316        // will simply not be needed when the behavior is stabilized in the Rust
1317        // compiler itself.
1318        if *panic == PanicStrategy::Abort || *panic == PanicStrategy::ImmediateAbort {
1319            cmd.arg("-Z").arg("panic-abort-tests");
1320        }
1321    } else if test {
1322        cmd.arg("--cfg").arg("test");
1323    }
1324
1325    cmd.args(&features_args(unit));
1326    cmd.args(&check_cfg_args(unit));
1327
1328    let meta = build_runner.files().metadata(unit);
1329    cmd.arg("-C")
1330        .arg(&format!("metadata={}", meta.c_metadata()));
1331    if let Some(c_extra_filename) = meta.c_extra_filename() {
1332        cmd.arg("-C")
1333            .arg(&format!("extra-filename=-{c_extra_filename}"));
1334    }
1335
1336    if rpath {
1337        cmd.arg("-C").arg("rpath");
1338    }
1339
1340    cmd.arg("--out-dir")
1341        .arg(&build_runner.files().out_dir(unit));
1342
1343    fn opt(cmd: &mut ProcessBuilder, key: &str, prefix: &str, val: Option<&OsStr>) {
1344        if let Some(val) = val {
1345            let mut joined = OsString::from(prefix);
1346            joined.push(val);
1347            cmd.arg(key).arg(joined);
1348        }
1349    }
1350
1351    if let CompileKind::Target(n) = unit.kind {
1352        cmd.arg("--target").arg(n.rustc_target());
1353    }
1354
1355    opt(
1356        cmd,
1357        "-C",
1358        "linker=",
1359        build_runner
1360            .compilation
1361            .target_linker(unit.kind)
1362            .as_ref()
1363            .map(|s| s.as_ref()),
1364    );
1365    if incremental {
1366        let dir = build_runner.files().incremental_dir(&unit);
1367        opt(cmd, "-C", "incremental=", Some(dir.as_os_str()));
1368    }
1369
1370    let pkg_hint_mostly_unused = match hints.mostly_unused {
1371        None => None,
1372        Some(toml::Value::Boolean(b)) => Some(b),
1373        Some(v) => {
1374            unit_capped_warn(&format!(
1375                "ignoring unsupported value type ({}) for 'hints.mostly-unused', which expects a boolean",
1376                v.type_str()
1377            ))?;
1378            None
1379        }
1380    };
1381    if profile_hint_mostly_unused
1382        .or(pkg_hint_mostly_unused)
1383        .unwrap_or(false)
1384    {
1385        if bcx.gctx.cli_unstable().profile_hint_mostly_unused {
1386            cmd.arg("-Zhint-mostly-unused");
1387        } else {
1388            if profile_hint_mostly_unused.is_some() {
1389                // Profiles come from the top-level unit, so we don't use `unit_capped_warn` here.
1390                warn(
1391                    "ignoring 'hint-mostly-unused' profile option, pass `-Zprofile-hint-mostly-unused` to enable it",
1392                )?;
1393            } else if pkg_hint_mostly_unused.is_some() {
1394                unit_capped_warn(
1395                    "ignoring 'hints.mostly-unused', pass `-Zprofile-hint-mostly-unused` to enable it",
1396                )?;
1397            }
1398        }
1399    }
1400
1401    let strip = strip.into_inner();
1402    if strip != StripInner::None {
1403        cmd.arg("-C").arg(format!("strip={}", strip));
1404    }
1405
1406    if unit.is_std {
1407        // -Zforce-unstable-if-unmarked prevents the accidental use of
1408        // unstable crates within the sysroot (such as "extern crate libc" or
1409        // any non-public crate in the sysroot).
1410        //
1411        // RUSTC_BOOTSTRAP allows unstable features on stable.
1412        cmd.arg("-Z")
1413            .arg("force-unstable-if-unmarked")
1414            .env("RUSTC_BOOTSTRAP", "1");
1415    }
1416
1417    // Add `CARGO_BIN_EXE_` environment variables for building tests.
1418    if unit.target.is_test() || unit.target.is_bench() {
1419        for bin_target in unit
1420            .pkg
1421            .manifest()
1422            .targets()
1423            .iter()
1424            .filter(|target| target.is_bin())
1425        {
1426            // For `cargo check` builds we do not uplift the CARGO_BIN_EXE_ artifacts to the
1427            // artifact-dir. We do not want to provide a path to a non-existent binary but we still
1428            // need to provide *something* so `env!("CARGO_BIN_EXE_...")` macros will compile.
1429            let exe_path = build_runner
1430                .files()
1431                .bin_link_for_target(bin_target, unit.kind, build_runner.bcx)?
1432                .map(|path| path.as_os_str().to_os_string())
1433                .unwrap_or_else(|| OsString::from(format!("placeholder:{}", bin_target.name())));
1434
1435            let name = bin_target
1436                .binary_filename()
1437                .unwrap_or(bin_target.name().to_string());
1438            let key = format!("CARGO_BIN_EXE_{}", name);
1439            cmd.env(&key, exe_path);
1440        }
1441    }
1442    Ok(())
1443}
1444
1445/// All active features for the unit passed as `--cfg features=<feature-name>`.
1446fn features_args(unit: &Unit) -> Vec<OsString> {
1447    let mut args = Vec::with_capacity(unit.features.len() * 2);
1448
1449    for feat in &unit.features {
1450        args.push(OsString::from("--cfg"));
1451        args.push(OsString::from(format!("feature=\"{}\"", feat)));
1452    }
1453
1454    args
1455}
1456
1457/// Like [`trim_paths_args`] but for rustdoc invocations.
1458fn trim_paths_args_rustdoc(
1459    cmd: &mut ProcessBuilder,
1460    build_runner: &BuildRunner<'_, '_>,
1461    unit: &Unit,
1462    trim_paths: &TomlTrimPaths,
1463) -> CargoResult<()> {
1464    match trim_paths {
1465        // rustdoc supports diagnostics trimming only.
1466        TomlTrimPaths::Values(values) if !values.contains(&TomlTrimPathsValue::Diagnostics) => {
1467            return Ok(());
1468        }
1469        _ => {}
1470    }
1471
1472    // feature gate was checked during manifest/config parsing.
1473    cmd.arg("-Zunstable-options");
1474
1475    // Order of `--remap-path-prefix` flags is important for `-Zbuild-std`.
1476    // We want to show `/rustc/<hash>/library/std` instead of `std-0.0.0`.
1477    cmd.arg(package_remap(build_runner, unit));
1478    cmd.arg(build_dir_remap(build_runner));
1479    cmd.arg(sysroot_remap(build_runner, unit));
1480
1481    Ok(())
1482}
1483
1484/// Generates the `--remap-path-scope` and `--remap-path-prefix` for [RFC 3127].
1485/// See also unstable feature [`-Ztrim-paths`].
1486///
1487/// [RFC 3127]: https://rust-lang.github.io/rfcs/3127-trim-paths.html
1488/// [`-Ztrim-paths`]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#profile-trim-paths-option
1489fn trim_paths_args(
1490    cmd: &mut ProcessBuilder,
1491    build_runner: &BuildRunner<'_, '_>,
1492    unit: &Unit,
1493    trim_paths: &TomlTrimPaths,
1494) -> CargoResult<()> {
1495    if trim_paths.is_none() {
1496        return Ok(());
1497    }
1498
1499    // feature gate was checked during manifest/config parsing.
1500    cmd.arg("-Zunstable-options");
1501    cmd.arg(format!("-Zremap-path-scope={trim_paths}"));
1502
1503    // Order of `--remap-path-prefix` flags is important for `-Zbuild-std`.
1504    // We want to show `/rustc/<hash>/library/std` instead of `std-0.0.0`.
1505    cmd.arg(package_remap(build_runner, unit));
1506    cmd.arg(build_dir_remap(build_runner));
1507    cmd.arg(sysroot_remap(build_runner, unit));
1508
1509    Ok(())
1510}
1511
1512/// Path prefix remap rules for sysroot.
1513///
1514/// This remap logic aligns with rustc:
1515/// <https://github.com/rust-lang/rust/blob/c2ef3516/src/bootstrap/src/lib.rs#L1113-L1116>
1516fn sysroot_remap(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> OsString {
1517    let mut remap = OsString::from("--remap-path-prefix=");
1518    remap.push({
1519        // See also `detect_sysroot_src_path()`.
1520        let mut sysroot = build_runner.bcx.target_data.info(unit.kind).sysroot.clone();
1521        sysroot.push("lib");
1522        sysroot.push("rustlib");
1523        sysroot.push("src");
1524        sysroot.push("rust");
1525        sysroot
1526    });
1527    remap.push("=");
1528    remap.push("/rustc/");
1529    if let Some(commit_hash) = build_runner.bcx.rustc().commit_hash.as_ref() {
1530        remap.push(commit_hash);
1531    } else {
1532        remap.push(build_runner.bcx.rustc().version.to_string());
1533    }
1534    remap
1535}
1536
1537/// Path prefix remap rules for dependencies.
1538///
1539/// * Git dependencies: remove `~/.cargo/git/checkouts` prefix.
1540/// * Registry dependencies: remove `~/.cargo/registry/src` prefix.
1541/// * Others (e.g. path dependencies):
1542///     * relative paths to workspace root if inside the workspace directory.
1543///     * otherwise remapped to `<pkg>-<version>`.
1544fn package_remap(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> OsString {
1545    let pkg_root = unit.pkg.root();
1546    let ws_root = build_runner.bcx.ws.root();
1547    let mut remap = OsString::from("--remap-path-prefix=");
1548    let source_id = unit.pkg.package_id().source_id();
1549    if source_id.is_git() {
1550        remap.push(
1551            build_runner
1552                .bcx
1553                .gctx
1554                .git_checkouts_path()
1555                .as_path_unlocked(),
1556        );
1557        remap.push("=");
1558    } else if source_id.is_registry() {
1559        remap.push(
1560            build_runner
1561                .bcx
1562                .gctx
1563                .registry_source_path()
1564                .as_path_unlocked(),
1565        );
1566        remap.push("=");
1567    } else if pkg_root.strip_prefix(ws_root).is_ok() {
1568        remap.push(ws_root);
1569        remap.push("=."); // remap to relative rustc work dir explicitly
1570    } else {
1571        remap.push(pkg_root);
1572        remap.push("=");
1573        remap.push(unit.pkg.name());
1574        remap.push("-");
1575        remap.push(unit.pkg.version().to_string());
1576    }
1577    remap
1578}
1579
1580/// Remap all paths pointing to `build.build-dir`,
1581/// i.e., `[BUILD_DIR]/debug/deps/foo-[HASH].dwo` would be remapped to
1582/// `/cargo/build-dir/debug/deps/foo-[HASH].dwo`
1583/// (note the `/cargo/build-dir` prefix).
1584///
1585/// This covers scenarios like:
1586///
1587/// * Build script generated code. For example, a build script may call `file!`
1588///   macros, and the associated crate uses [`include!`] to include the expanded
1589///   [`file!`] macro in-place via the `OUT_DIR` environment.
1590/// * On Linux, `DW_AT_GNU_dwo_name` that contains paths to split debuginfo
1591///   files (dwp and dwo).
1592fn build_dir_remap(build_runner: &BuildRunner<'_, '_>) -> OsString {
1593    let build_dir = build_runner.bcx.ws.build_dir();
1594    let mut remap = OsString::from("--remap-path-prefix=");
1595    remap.push(build_dir.as_path_unlocked());
1596    remap.push("=/cargo/build-dir");
1597    remap
1598}
1599
1600/// Generates the `--check-cfg` arguments for the `unit`.
1601fn check_cfg_args(unit: &Unit) -> Vec<OsString> {
1602    // The routine below generates the --check-cfg arguments. Our goals here are to
1603    // enable the checking of conditionals and pass the list of declared features.
1604    //
1605    // In the simplified case, it would resemble something like this:
1606    //
1607    //   --check-cfg=cfg() --check-cfg=cfg(feature, values(...))
1608    //
1609    // but having `cfg()` is redundant with the second argument (as well-known names
1610    // and values are implicitly enabled when one or more `--check-cfg` argument is
1611    // passed) so we don't emit it and just pass:
1612    //
1613    //   --check-cfg=cfg(feature, values(...))
1614    //
1615    // This way, even if there are no declared features, the config `feature` will
1616    // still be expected, meaning users would get "unexpected value" instead of name.
1617    // This wasn't always the case, see rust-lang#119930 for some details.
1618
1619    let gross_cap_estimation = unit.pkg.summary().features().len() * 7 + 25;
1620    let mut arg_feature = OsString::with_capacity(gross_cap_estimation);
1621
1622    arg_feature.push("cfg(feature, values(");
1623    for (i, feature) in unit.pkg.summary().features().keys().enumerate() {
1624        if i != 0 {
1625            arg_feature.push(", ");
1626        }
1627        arg_feature.push("\"");
1628        arg_feature.push(feature);
1629        arg_feature.push("\"");
1630    }
1631    arg_feature.push("))");
1632
1633    // In addition to the package features, we also include the `test` cfg (since
1634    // compiler-team#785, as to be able to someday apply it conditionally), as well
1635    // the `docsrs` cfg from the docs.rs service.
1636    //
1637    // We include `docsrs` here (in Cargo) instead of rustc, since there is a much closer
1638    // relationship between Cargo and docs.rs than rustc and docs.rs. In particular, all
1639    // users of docs.rs use Cargo, but not all users of rustc (like Rust-for-Linux) use docs.rs.
1640
1641    vec![
1642        OsString::from("--check-cfg"),
1643        OsString::from("cfg(docsrs,test)"),
1644        OsString::from("--check-cfg"),
1645        arg_feature,
1646    ]
1647}
1648
1649/// Adds LTO related codegen flags.
1650fn lto_args(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> Vec<OsString> {
1651    let mut result = Vec::new();
1652    let mut push = |arg: &str| {
1653        result.push(OsString::from("-C"));
1654        result.push(OsString::from(arg));
1655    };
1656    match build_runner.lto[unit] {
1657        lto::Lto::Run(None) => push("lto"),
1658        lto::Lto::Run(Some(s)) => push(&format!("lto={}", s)),
1659        lto::Lto::Off => {
1660            push("lto=off");
1661            push("embed-bitcode=no");
1662        }
1663        lto::Lto::ObjectAndBitcode => {} // this is rustc's default
1664        lto::Lto::OnlyBitcode => push("linker-plugin-lto"),
1665        lto::Lto::OnlyObject => push("embed-bitcode=no"),
1666    }
1667    result
1668}
1669
1670/// Adds dependency-relevant rustc flags and environment variables
1671/// to the command to execute, such as [`-L`] and [`--extern`].
1672///
1673/// [`-L`]: https://doc.rust-lang.org/nightly/rustc/command-line-arguments.html#-l-add-a-directory-to-the-library-search-path
1674/// [`--extern`]: https://doc.rust-lang.org/nightly/rustc/command-line-arguments.html#--extern-specify-where-an-external-library-is-located
1675fn build_deps_args(
1676    cmd: &mut ProcessBuilder,
1677    build_runner: &BuildRunner<'_, '_>,
1678    unit: &Unit,
1679) -> CargoResult<()> {
1680    let bcx = build_runner.bcx;
1681    if build_runner.bcx.gctx.cli_unstable().build_dir_new_layout {
1682        let mut map = BTreeMap::new();
1683
1684        // Recursively add all dependency args to rustc process
1685        add_dep_arg(&mut map, build_runner, unit);
1686
1687        let paths = map.into_iter().map(|(_, path)| path).sorted_unstable();
1688
1689        for path in paths {
1690            cmd.arg("-L").arg(&{
1691                let mut deps = OsString::from("dependency=");
1692                deps.push(path);
1693                deps
1694            });
1695        }
1696    } else {
1697        cmd.arg("-L").arg(&{
1698            let mut deps = OsString::from("dependency=");
1699            deps.push(build_runner.files().deps_dir(unit));
1700            deps
1701        });
1702    }
1703
1704    // Be sure that the host path is also listed. This'll ensure that proc macro
1705    // dependencies are correctly found (for reexported macros).
1706    if !unit.kind.is_host() {
1707        cmd.arg("-L").arg(&{
1708            let mut deps = OsString::from("dependency=");
1709            deps.push(build_runner.files().host_deps(unit));
1710            deps
1711        });
1712    }
1713
1714    let deps = build_runner.unit_deps(unit);
1715
1716    // If there is not one linkable target but should, rustc fails later
1717    // on if there is an `extern crate` for it. This may turn into a hard
1718    // error in the future (see PR #4797).
1719    if !deps
1720        .iter()
1721        .any(|dep| !dep.unit.mode.is_doc() && dep.unit.target.is_linkable())
1722    {
1723        if let Some(dep) = deps.iter().find(|dep| {
1724            !dep.unit.mode.is_doc() && dep.unit.target.is_lib() && !dep.unit.artifact.is_true()
1725        }) {
1726            let dep_name = dep.unit.target.crate_name();
1727            let name = unit.target.crate_name();
1728            bcx.gctx.shell().print_report(&[
1729                Level::WARNING.secondary_title(format!("the package `{dep_name}` provides no linkable target"))
1730                    .elements([
1731                        Level::NOTE.message(format!("this might cause `{name}` to fail compilation")),
1732                        Level::NOTE.message("this warning might turn into a hard error in the future"),
1733                        Level::HELP.message(format!("consider adding 'dylib' or 'rlib' to key 'crate-type' in `{dep_name}`'s Cargo.toml"))
1734                    ])
1735            ], false)?;
1736        }
1737    }
1738
1739    let mut unstable_opts = false;
1740
1741    // Add `OUT_DIR` environment variables for build scripts
1742    let first_custom_build_dep = deps.iter().find(|dep| dep.unit.mode.is_run_custom_build());
1743    if let Some(dep) = first_custom_build_dep {
1744        let out_dir = &build_runner.files().build_script_out_dir(&dep.unit);
1745        cmd.env("OUT_DIR", &out_dir);
1746    }
1747
1748    // Adding output directory for each build script
1749    let is_multiple_build_scripts_enabled = unit
1750        .pkg
1751        .manifest()
1752        .unstable_features()
1753        .require(Feature::multiple_build_scripts())
1754        .is_ok();
1755
1756    if is_multiple_build_scripts_enabled {
1757        for dep in deps {
1758            if dep.unit.mode.is_run_custom_build() {
1759                let out_dir = &build_runner.files().build_script_out_dir(&dep.unit);
1760                let target_name = dep.unit.target.name();
1761                let out_dir_prefix = target_name
1762                    .strip_prefix("build-script-")
1763                    .unwrap_or(target_name);
1764                let out_dir_name = format!("{out_dir_prefix}_OUT_DIR");
1765                cmd.env(&out_dir_name, &out_dir);
1766            }
1767        }
1768    }
1769    for arg in extern_args(build_runner, unit, &mut unstable_opts)? {
1770        cmd.arg(arg);
1771    }
1772
1773    for (var, env) in artifact::get_env(build_runner, deps)? {
1774        cmd.env(&var, env);
1775    }
1776
1777    // This will only be set if we're already using a feature
1778    // requiring nightly rust
1779    if unstable_opts {
1780        cmd.arg("-Z").arg("unstable-options");
1781    }
1782
1783    Ok(())
1784}
1785
1786fn add_dep_arg<'a, 'b: 'a>(
1787    map: &mut BTreeMap<&'a Unit, PathBuf>,
1788    build_runner: &'b BuildRunner<'b, '_>,
1789    unit: &'a Unit,
1790) {
1791    if map.contains_key(&unit) {
1792        return;
1793    }
1794    map.insert(&unit, build_runner.files().deps_dir(&unit));
1795
1796    for dep in build_runner.unit_deps(unit) {
1797        add_dep_arg(map, build_runner, &dep.unit);
1798    }
1799}
1800
1801/// Adds extra rustc flags and environment variables collected from the output
1802/// of a build-script to the command to execute, include custom environment
1803/// variables and `cfg`.
1804fn add_custom_flags(
1805    cmd: &mut ProcessBuilder,
1806    build_script_outputs: &BuildScriptOutputs,
1807    metadata_vec: Option<Vec<UnitHash>>,
1808) -> CargoResult<()> {
1809    if let Some(metadata_vec) = metadata_vec {
1810        for metadata in metadata_vec {
1811            if let Some(output) = build_script_outputs.get(metadata) {
1812                for cfg in output.cfgs.iter() {
1813                    cmd.arg("--cfg").arg(cfg);
1814                }
1815                for check_cfg in &output.check_cfgs {
1816                    cmd.arg("--check-cfg").arg(check_cfg);
1817                }
1818                for (name, value) in output.env.iter() {
1819                    cmd.env(name, value);
1820                }
1821            }
1822        }
1823    }
1824
1825    Ok(())
1826}
1827
1828/// Generates a list of `--extern` arguments.
1829pub fn extern_args(
1830    build_runner: &BuildRunner<'_, '_>,
1831    unit: &Unit,
1832    unstable_opts: &mut bool,
1833) -> CargoResult<Vec<OsString>> {
1834    let mut result = Vec::new();
1835    let deps = build_runner.unit_deps(unit);
1836
1837    let no_embed_metadata = build_runner.bcx.gctx.cli_unstable().no_embed_metadata;
1838
1839    // Closure to add one dependency to `result`.
1840    let mut link_to =
1841        |dep: &UnitDep, extern_crate_name: InternedString, noprelude: bool| -> CargoResult<()> {
1842            let mut value = OsString::new();
1843            let mut opts = Vec::new();
1844            let is_public_dependency_enabled = unit
1845                .pkg
1846                .manifest()
1847                .unstable_features()
1848                .require(Feature::public_dependency())
1849                .is_ok()
1850                || build_runner.bcx.gctx.cli_unstable().public_dependency;
1851            if !dep.public && unit.target.is_lib() && is_public_dependency_enabled {
1852                opts.push("priv");
1853                *unstable_opts = true;
1854            }
1855            if noprelude {
1856                opts.push("noprelude");
1857                *unstable_opts = true;
1858            }
1859            if !opts.is_empty() {
1860                value.push(opts.join(","));
1861                value.push(":");
1862            }
1863            value.push(extern_crate_name.as_str());
1864            value.push("=");
1865
1866            let mut pass = |file| {
1867                let mut value = value.clone();
1868                value.push(file);
1869                result.push(OsString::from("--extern"));
1870                result.push(value);
1871            };
1872
1873            let outputs = build_runner.outputs(&dep.unit)?;
1874
1875            if build_runner.only_requires_rmeta(unit, &dep.unit) || dep.unit.mode.is_check() {
1876                // Example: rlib dependency for an rlib, rmeta is all that is required.
1877                let output = outputs
1878                    .iter()
1879                    .find(|output| output.flavor == FileFlavor::Rmeta)
1880                    .expect("failed to find rmeta dep for pipelined dep");
1881                pass(&output.path);
1882            } else {
1883                // Example: a bin needs `rlib` for dependencies, it cannot use rmeta.
1884                for output in outputs.iter() {
1885                    if output.flavor == FileFlavor::Linkable {
1886                        pass(&output.path);
1887                    }
1888                    // If we use -Zembed-metadata=no, we also need to pass the path to the
1889                    // corresponding .rmeta file to the linkable artifact, because the
1890                    // normal dependency (rlib) doesn't contain the full metadata.
1891                    else if no_embed_metadata && output.flavor == FileFlavor::Rmeta {
1892                        pass(&output.path);
1893                    }
1894                }
1895            }
1896            Ok(())
1897        };
1898
1899    for dep in deps {
1900        if dep.unit.target.is_linkable() && !dep.unit.mode.is_doc() {
1901            link_to(dep, dep.extern_crate_name, dep.noprelude)?;
1902        }
1903    }
1904    if unit.target.proc_macro() {
1905        // Automatically import `proc_macro`.
1906        result.push(OsString::from("--extern"));
1907        result.push(OsString::from("proc_macro"));
1908    }
1909
1910    Ok(result)
1911}
1912
1913fn envify(s: &str) -> String {
1914    s.chars()
1915        .flat_map(|c| c.to_uppercase())
1916        .map(|c| if c == '-' { '_' } else { c })
1917        .collect()
1918}
1919
1920/// Configuration of the display of messages emitted by the compiler,
1921/// e.g. diagnostics, warnings, errors, and message caching.
1922struct OutputOptions {
1923    /// What format we're emitting from Cargo itself.
1924    format: MessageFormat,
1925    /// Where to write the JSON messages to support playback later if the unit
1926    /// is fresh. The file is created lazily so that in the normal case, lots
1927    /// of empty files are not created. If this is None, the output will not
1928    /// be cached (such as when replaying cached messages).
1929    cache_cell: Option<(PathBuf, OnceCell<File>)>,
1930    /// If `true`, display any diagnostics.
1931    /// Other types of JSON messages are processed regardless
1932    /// of the value of this flag.
1933    ///
1934    /// This is used primarily for cache replay. If you build with `-vv`, the
1935    /// cache will be filled with diagnostics from dependencies. When the
1936    /// cache is replayed without `-vv`, we don't want to show them.
1937    show_diagnostics: bool,
1938    /// Tracks the number of warnings we've seen so far.
1939    warnings_seen: usize,
1940    /// Tracks the number of errors we've seen so far.
1941    errors_seen: usize,
1942}
1943
1944impl OutputOptions {
1945    fn new(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> OutputOptions {
1946        let path = build_runner.files().message_cache_path(unit);
1947        // Remove old cache, ignore ENOENT, which is the common case.
1948        drop(fs::remove_file(&path));
1949        let cache_cell = Some((path, OnceCell::new()));
1950        let show_diagnostics =
1951            build_runner.bcx.gctx.warning_handling().unwrap_or_default() != WarningHandling::Allow;
1952        OutputOptions {
1953            format: build_runner.bcx.build_config.message_format,
1954            cache_cell,
1955            show_diagnostics,
1956            warnings_seen: 0,
1957            errors_seen: 0,
1958        }
1959    }
1960}
1961
1962/// Cloned and sendable context about the manifest file.
1963///
1964/// Sometimes we enrich rustc's errors with some locations in the manifest file; this
1965/// contains a `Send`-able copy of the manifest information that we need for the
1966/// enriched errors.
1967struct ManifestErrorContext {
1968    /// The path to the manifest.
1969    path: PathBuf,
1970    /// The locations of various spans within the manifest.
1971    spans: toml::Spanned<toml::de::DeTable<'static>>,
1972    /// The raw manifest contents.
1973    contents: String,
1974    /// A lookup for all the unambiguous renamings, mapping from the original package
1975    /// name to the renamed one.
1976    rename_table: HashMap<InternedString, InternedString>,
1977    /// A list of targets we're compiling for, to determine which of the `[target.<something>.dependencies]`
1978    /// tables might be of interest.
1979    requested_kinds: Vec<CompileKind>,
1980    /// A list of all the collections of cfg values, one collection for each target, to determine
1981    /// which of the `[target.'cfg(...)'.dependencies]` tables might be of interest.
1982    cfgs: Vec<Vec<Cfg>>,
1983    host_name: InternedString,
1984    /// Cargo's working directory (for printing out a more friendly manifest path).
1985    cwd: PathBuf,
1986    /// Terminal width for formatting diagnostics.
1987    term_width: usize,
1988}
1989
1990fn on_stdout_line(
1991    state: &JobState<'_, '_>,
1992    line: &str,
1993    _package_id: PackageId,
1994    _target: &Target,
1995) -> CargoResult<()> {
1996    state.stdout(line.to_string())?;
1997    Ok(())
1998}
1999
2000fn on_stderr_line(
2001    state: &JobState<'_, '_>,
2002    line: &str,
2003    package_id: PackageId,
2004    manifest: &ManifestErrorContext,
2005    target: &Target,
2006    options: &mut OutputOptions,
2007) -> CargoResult<()> {
2008    if on_stderr_line_inner(state, line, package_id, manifest, target, options)? {
2009        // Check if caching is enabled.
2010        if let Some((path, cell)) = &mut options.cache_cell {
2011            // Cache the output, which will be replayed later when Fresh.
2012            let f = cell.try_borrow_mut_with(|| paths::create(path))?;
2013            debug_assert!(!line.contains('\n'));
2014            f.write_all(line.as_bytes())?;
2015            f.write_all(&[b'\n'])?;
2016        }
2017    }
2018    Ok(())
2019}
2020
2021/// Returns true if the line should be cached.
2022fn on_stderr_line_inner(
2023    state: &JobState<'_, '_>,
2024    line: &str,
2025    package_id: PackageId,
2026    manifest: &ManifestErrorContext,
2027    target: &Target,
2028    options: &mut OutputOptions,
2029) -> CargoResult<bool> {
2030    // We primarily want to use this function to process JSON messages from
2031    // rustc. The compiler should always print one JSON message per line, and
2032    // otherwise it may have other output intermingled (think RUST_LOG or
2033    // something like that), so skip over everything that doesn't look like a
2034    // JSON message.
2035    if !line.starts_with('{') {
2036        state.stderr(line.to_string())?;
2037        return Ok(true);
2038    }
2039
2040    let mut compiler_message: Box<serde_json::value::RawValue> = match serde_json::from_str(line) {
2041        Ok(msg) => msg,
2042
2043        // If the compiler produced a line that started with `{` but it wasn't
2044        // valid JSON, maybe it wasn't JSON in the first place! Forward it along
2045        // to stderr.
2046        Err(e) => {
2047            debug!("failed to parse json: {:?}", e);
2048            state.stderr(line.to_string())?;
2049            return Ok(true);
2050        }
2051    };
2052
2053    let count_diagnostic = |level, options: &mut OutputOptions| {
2054        if level == "warning" {
2055            options.warnings_seen += 1;
2056        } else if level == "error" {
2057            options.errors_seen += 1;
2058        }
2059    };
2060
2061    if let Ok(report) = serde_json::from_str::<FutureIncompatReport>(compiler_message.get()) {
2062        for item in &report.future_incompat_report {
2063            count_diagnostic(&*item.diagnostic.level, options);
2064        }
2065        state.future_incompat_report(report.future_incompat_report);
2066        return Ok(true);
2067    }
2068
2069    let res = serde_json::from_str::<SectionTiming>(compiler_message.get());
2070    if let Ok(timing_record) = res {
2071        state.on_section_timing_emitted(timing_record);
2072        return Ok(false);
2073    }
2074
2075    // Returns `true` if the diagnostic was modified.
2076    let add_pub_in_priv_diagnostic = |diag: &mut String| -> bool {
2077        // We are parsing the compiler diagnostic here, as this information isn't
2078        // currently exposed elsewhere.
2079        // At the time of writing this comment, rustc emits two different
2080        // "exported_private_dependencies" errors:
2081        //  - type `FromPriv` from private dependency 'priv_dep' in public interface
2082        //  - struct `FromPriv` from private dependency 'priv_dep' is re-exported
2083        // This regex matches them both. To see if it needs to be updated, grep the rust
2084        // source for "EXPORTED_PRIVATE_DEPENDENCIES".
2085        static PRIV_DEP_REGEX: LazyLock<Regex> =
2086            LazyLock::new(|| Regex::new("from private dependency '([A-Za-z0-9-_]+)'").unwrap());
2087        if let Some(crate_name) = PRIV_DEP_REGEX.captures(diag).and_then(|m| m.get(1))
2088            && let Some(span) = manifest.find_crate_span(crate_name.as_str())
2089        {
2090            let rel_path = pathdiff::diff_paths(&manifest.path, &manifest.cwd)
2091                .unwrap_or_else(|| manifest.path.clone())
2092                .display()
2093                .to_string();
2094            let report = [Group::with_title(Level::NOTE.secondary_title(format!(
2095                "dependency `{}` declared here",
2096                crate_name.as_str()
2097            )))
2098            .element(
2099                Snippet::source(&manifest.contents)
2100                    .path(rel_path)
2101                    .annotation(AnnotationKind::Context.span(span)),
2102            )];
2103
2104            let rendered = Renderer::styled()
2105                .term_width(manifest.term_width)
2106                .render(&report);
2107            diag.push_str(&rendered);
2108            diag.push('\n');
2109            return true;
2110        }
2111        false
2112    };
2113
2114    // Depending on what we're emitting from Cargo itself, we figure out what to
2115    // do with this JSON message.
2116    match options.format {
2117        // In the "human" output formats (human/short) or if diagnostic messages
2118        // from rustc aren't being included in the output of Cargo's JSON
2119        // messages then we extract the diagnostic (if present) here and handle
2120        // it ourselves.
2121        MessageFormat::Human
2122        | MessageFormat::Short
2123        | MessageFormat::Json {
2124            render_diagnostics: true,
2125            ..
2126        } => {
2127            #[derive(serde::Deserialize)]
2128            struct CompilerMessage<'a> {
2129                // `rendered` contains escape sequences, which can't be
2130                // zero-copy deserialized by serde_json.
2131                // See https://github.com/serde-rs/json/issues/742
2132                rendered: String,
2133                #[serde(borrow)]
2134                message: Cow<'a, str>,
2135                #[serde(borrow)]
2136                level: Cow<'a, str>,
2137                children: Vec<PartialDiagnostic>,
2138                code: Option<DiagnosticCode>,
2139            }
2140
2141            // A partial rustfix::diagnostics::Diagnostic. We deserialize only a
2142            // subset of the fields because rustc's output can be extremely
2143            // deeply nested JSON in pathological cases involving macro
2144            // expansion. Rustfix's Diagnostic struct is recursive containing a
2145            // field `children: Vec<Self>`, and it can cause deserialization to
2146            // hit serde_json's default recursion limit, or overflow the stack
2147            // if we turn that off. Cargo only cares about the 1 field listed
2148            // here.
2149            #[derive(serde::Deserialize)]
2150            struct PartialDiagnostic {
2151                spans: Vec<PartialDiagnosticSpan>,
2152            }
2153
2154            // A partial rustfix::diagnostics::DiagnosticSpan.
2155            #[derive(serde::Deserialize)]
2156            struct PartialDiagnosticSpan {
2157                suggestion_applicability: Option<Applicability>,
2158            }
2159
2160            #[derive(serde::Deserialize)]
2161            struct DiagnosticCode {
2162                code: String,
2163            }
2164
2165            if let Ok(mut msg) = serde_json::from_str::<CompilerMessage<'_>>(compiler_message.get())
2166            {
2167                if msg.message.starts_with("aborting due to")
2168                    || msg.message.ends_with("warning emitted")
2169                    || msg.message.ends_with("warnings emitted")
2170                {
2171                    // Skip this line; we'll print our own summary at the end.
2172                    return Ok(true);
2173                }
2174                // state.stderr will add a newline
2175                if msg.rendered.ends_with('\n') {
2176                    msg.rendered.pop();
2177                }
2178                let mut rendered = msg.rendered;
2179                if options.show_diagnostics {
2180                    let machine_applicable: bool = msg
2181                        .children
2182                        .iter()
2183                        .map(|child| {
2184                            child
2185                                .spans
2186                                .iter()
2187                                .filter_map(|span| span.suggestion_applicability)
2188                                .any(|app| app == Applicability::MachineApplicable)
2189                        })
2190                        .any(|b| b);
2191                    count_diagnostic(&msg.level, options);
2192                    if msg
2193                        .code
2194                        .as_ref()
2195                        .is_some_and(|c| c.code == "exported_private_dependencies")
2196                        && options.format != MessageFormat::Short
2197                    {
2198                        add_pub_in_priv_diagnostic(&mut rendered);
2199                    }
2200                    let lint = msg.code.is_some();
2201                    state.emit_diag(&msg.level, rendered, lint, machine_applicable)?;
2202                }
2203                return Ok(true);
2204            }
2205        }
2206
2207        MessageFormat::Json { ansi, .. } => {
2208            #[derive(serde::Deserialize, serde::Serialize)]
2209            struct CompilerMessage<'a> {
2210                rendered: String,
2211                #[serde(flatten, borrow)]
2212                other: std::collections::BTreeMap<Cow<'a, str>, serde_json::Value>,
2213                code: Option<DiagnosticCode<'a>>,
2214            }
2215
2216            #[derive(serde::Deserialize, serde::Serialize)]
2217            struct DiagnosticCode<'a> {
2218                code: String,
2219                #[serde(flatten, borrow)]
2220                other: std::collections::BTreeMap<Cow<'a, str>, serde_json::Value>,
2221            }
2222
2223            if let Ok(mut error) =
2224                serde_json::from_str::<CompilerMessage<'_>>(compiler_message.get())
2225            {
2226                let modified_diag = if error
2227                    .code
2228                    .as_ref()
2229                    .is_some_and(|c| c.code == "exported_private_dependencies")
2230                {
2231                    add_pub_in_priv_diagnostic(&mut error.rendered)
2232                } else {
2233                    false
2234                };
2235
2236                // Remove color information from the rendered string if color is not
2237                // enabled. Cargo always asks for ANSI colors from rustc. This allows
2238                // cached replay to enable/disable colors without re-invoking rustc.
2239                if !ansi {
2240                    error.rendered = anstream::adapter::strip_str(&error.rendered).to_string();
2241                }
2242                if !ansi || modified_diag {
2243                    let new_line = serde_json::to_string(&error)?;
2244                    compiler_message = serde_json::value::RawValue::from_string(new_line)?;
2245                }
2246            }
2247        }
2248    }
2249
2250    // We always tell rustc to emit messages about artifacts being produced.
2251    // These messages feed into pipelined compilation, as well as timing
2252    // information.
2253    //
2254    // Look for a matching directive and inform Cargo internally that a
2255    // metadata file has been produced.
2256    #[derive(serde::Deserialize)]
2257    struct ArtifactNotification<'a> {
2258        #[serde(borrow)]
2259        artifact: Cow<'a, str>,
2260    }
2261
2262    if let Ok(artifact) = serde_json::from_str::<ArtifactNotification<'_>>(compiler_message.get()) {
2263        trace!("found directive from rustc: `{}`", artifact.artifact);
2264        if artifact.artifact.ends_with(".rmeta") {
2265            debug!("looks like metadata finished early!");
2266            state.rmeta_produced();
2267        }
2268        return Ok(false);
2269    }
2270
2271    // And failing all that above we should have a legitimate JSON diagnostic
2272    // from the compiler, so wrap it in an external Cargo JSON message
2273    // indicating which package it came from and then emit it.
2274
2275    if !options.show_diagnostics {
2276        return Ok(true);
2277    }
2278
2279    #[derive(serde::Deserialize)]
2280    struct CompilerMessage<'a> {
2281        #[serde(borrow)]
2282        message: Cow<'a, str>,
2283        #[serde(borrow)]
2284        level: Cow<'a, str>,
2285    }
2286
2287    if let Ok(msg) = serde_json::from_str::<CompilerMessage<'_>>(compiler_message.get()) {
2288        if msg.message.starts_with("aborting due to")
2289            || msg.message.ends_with("warning emitted")
2290            || msg.message.ends_with("warnings emitted")
2291        {
2292            // Skip this line; we'll print our own summary at the end.
2293            return Ok(true);
2294        }
2295        count_diagnostic(&msg.level, options);
2296    }
2297
2298    let msg = machine_message::FromCompiler {
2299        package_id: package_id.to_spec(),
2300        manifest_path: &manifest.path,
2301        target,
2302        message: compiler_message,
2303    }
2304    .to_json_string();
2305
2306    // Switch json lines from rustc/rustdoc that appear on stderr to stdout
2307    // instead. We want the stdout of Cargo to always be machine parseable as
2308    // stderr has our colorized human-readable messages.
2309    state.stdout(msg)?;
2310    Ok(true)
2311}
2312
2313impl ManifestErrorContext {
2314    fn new(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> ManifestErrorContext {
2315        let mut duplicates = HashSet::new();
2316        let mut rename_table = HashMap::new();
2317
2318        for dep in build_runner.unit_deps(unit) {
2319            let unrenamed_id = dep.unit.pkg.package_id().name();
2320            if duplicates.contains(&unrenamed_id) {
2321                continue;
2322            }
2323            match rename_table.entry(unrenamed_id) {
2324                std::collections::hash_map::Entry::Occupied(occ) => {
2325                    occ.remove_entry();
2326                    duplicates.insert(unrenamed_id);
2327                }
2328                std::collections::hash_map::Entry::Vacant(vac) => {
2329                    vac.insert(dep.extern_crate_name);
2330                }
2331            }
2332        }
2333
2334        let bcx = build_runner.bcx;
2335        ManifestErrorContext {
2336            path: unit.pkg.manifest_path().to_owned(),
2337            spans: unit.pkg.manifest().document().clone(),
2338            contents: unit.pkg.manifest().contents().to_owned(),
2339            requested_kinds: bcx.target_data.requested_kinds().to_owned(),
2340            host_name: bcx.rustc().host,
2341            rename_table,
2342            cwd: path_args(build_runner.bcx.ws, unit).1,
2343            cfgs: bcx
2344                .target_data
2345                .requested_kinds()
2346                .iter()
2347                .map(|k| bcx.target_data.cfg(*k).to_owned())
2348                .collect(),
2349            term_width: bcx
2350                .gctx
2351                .shell()
2352                .err_width()
2353                .diagnostic_terminal_width()
2354                .unwrap_or(annotate_snippets::renderer::DEFAULT_TERM_WIDTH),
2355        }
2356    }
2357
2358    fn requested_target_names(&self) -> impl Iterator<Item = &str> {
2359        self.requested_kinds.iter().map(|kind| match kind {
2360            CompileKind::Host => &self.host_name,
2361            CompileKind::Target(target) => target.short_name(),
2362        })
2363    }
2364
2365    /// Find a span for the dependency that specifies this unrenamed crate, if it's unique.
2366    ///
2367    /// rustc diagnostics (at least for public-in-private) mention the un-renamed
2368    /// crate: if you have `foo = { package = "bar" }`, the rustc diagnostic will
2369    /// say "bar".
2370    ///
2371    /// This function does its best to find a span for "bar", but it could fail if
2372    /// there are multiple candidates:
2373    ///
2374    /// ```toml
2375    /// foo = { package = "bar" }
2376    /// baz = { path = "../bar", package = "bar" }
2377    /// ```
2378    fn find_crate_span(&self, unrenamed: &str) -> Option<Range<usize>> {
2379        let orig_name = self.rename_table.get(unrenamed)?.as_str();
2380
2381        if let Some((k, v)) = get_key_value(&self.spans, &["dependencies", orig_name]) {
2382            // We make some effort to find the unrenamed text: in
2383            //
2384            // ```
2385            // foo = { package = "bar" }
2386            // ```
2387            //
2388            // we try to find the "bar", but fall back to "foo" if we can't (which might
2389            // happen if the renaming took place in the workspace, for example).
2390            if let Some(package) = v.get_ref().as_table().and_then(|t| t.get("package")) {
2391                return Some(package.span());
2392            } else {
2393                return Some(k.span());
2394            }
2395        }
2396
2397        // The dependency could also be in a target-specific table, like
2398        // [target.x86_64-unknown-linux-gnu.dependencies] or
2399        // [target.'cfg(something)'.dependencies]. We filter out target tables
2400        // that don't match a requested target or a requested cfg.
2401        if let Some(target) = self
2402            .spans
2403            .as_ref()
2404            .get("target")
2405            .and_then(|t| t.as_ref().as_table())
2406        {
2407            for (platform, platform_table) in target.iter() {
2408                match platform.as_ref().parse::<Platform>() {
2409                    Ok(Platform::Name(name)) => {
2410                        if !self.requested_target_names().any(|n| n == name) {
2411                            continue;
2412                        }
2413                    }
2414                    Ok(Platform::Cfg(cfg_expr)) => {
2415                        if !self.cfgs.iter().any(|cfgs| cfg_expr.matches(cfgs)) {
2416                            continue;
2417                        }
2418                    }
2419                    Err(_) => continue,
2420                }
2421
2422                let Some(platform_table) = platform_table.as_ref().as_table() else {
2423                    continue;
2424                };
2425
2426                if let Some(deps) = platform_table
2427                    .get("dependencies")
2428                    .and_then(|d| d.as_ref().as_table())
2429                {
2430                    if let Some((k, v)) = deps.get_key_value(orig_name) {
2431                        if let Some(package) = v.get_ref().as_table().and_then(|t| t.get("package"))
2432                        {
2433                            return Some(package.span());
2434                        } else {
2435                            return Some(k.span());
2436                        }
2437                    }
2438                }
2439            }
2440        }
2441        None
2442    }
2443}
2444
2445/// Creates a unit of work that replays the cached compiler message.
2446///
2447/// Usually used when a job is fresh and doesn't need to recompile.
2448fn replay_output_cache(
2449    package_id: PackageId,
2450    manifest: ManifestErrorContext,
2451    target: &Target,
2452    path: PathBuf,
2453    format: MessageFormat,
2454    show_diagnostics: bool,
2455) -> Work {
2456    let target = target.clone();
2457    let mut options = OutputOptions {
2458        format,
2459        cache_cell: None,
2460        show_diagnostics,
2461        warnings_seen: 0,
2462        errors_seen: 0,
2463    };
2464    Work::new(move |state| {
2465        if !path.exists() {
2466            // No cached output, probably didn't emit anything.
2467            return Ok(());
2468        }
2469        // We sometimes have gigabytes of output from the compiler, so avoid
2470        // loading it all into memory at once, as that can cause OOM where
2471        // otherwise there would be none.
2472        let file = paths::open(&path)?;
2473        let mut reader = std::io::BufReader::new(file);
2474        let mut line = String::new();
2475        loop {
2476            let length = reader.read_line(&mut line)?;
2477            if length == 0 {
2478                break;
2479            }
2480            let trimmed = line.trim_end_matches(&['\n', '\r'][..]);
2481            on_stderr_line(state, trimmed, package_id, &manifest, &target, &mut options)?;
2482            line.clear();
2483        }
2484        Ok(())
2485    })
2486}
2487
2488/// Provides a package name with descriptive target information,
2489/// e.g., '`foo` (bin "bar" test)', '`foo` (lib doctest)'.
2490fn descriptive_pkg_name(name: &str, target: &Target, mode: &CompileMode) -> String {
2491    let desc_name = target.description_named();
2492    let mode = if mode.is_rustc_test() && !(target.is_test() || target.is_bench()) {
2493        " test"
2494    } else if mode.is_doc_test() {
2495        " doctest"
2496    } else if mode.is_doc() {
2497        " doc"
2498    } else {
2499        ""
2500    };
2501    format!("`{name}` ({desc_name}{mode})")
2502}
2503
2504/// Applies environment variables from config `[env]` to [`ProcessBuilder`].
2505pub(crate) fn apply_env_config(
2506    gctx: &crate::GlobalContext,
2507    cmd: &mut ProcessBuilder,
2508) -> CargoResult<()> {
2509    for (key, value) in gctx.env_config()?.iter() {
2510        // never override a value that has already been set by cargo
2511        if cmd.get_envs().contains_key(key) {
2512            continue;
2513        }
2514        cmd.env(key, value);
2515    }
2516    Ok(())
2517}
2518
2519/// Checks if there are some scrape units waiting to be processed.
2520fn should_include_scrape_units(bcx: &BuildContext<'_, '_>, unit: &Unit) -> bool {
2521    unit.mode.is_doc() && bcx.scrape_units.len() > 0 && bcx.ws.unit_needs_doc_scrape(unit)
2522}
2523
2524/// Gets the file path of function call information output from `rustdoc`.
2525fn scrape_output_path(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<PathBuf> {
2526    assert!(unit.mode.is_doc() || unit.mode.is_doc_scrape());
2527    build_runner
2528        .outputs(unit)
2529        .map(|outputs| outputs[0].path.clone())
2530}
2531
2532/// Gets the dep-info file emitted by rustdoc.
2533fn rustdoc_dep_info_loc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> PathBuf {
2534    let mut loc = build_runner.files().fingerprint_file_path(unit, "");
2535    loc.set_extension("d");
2536    loc
2537}