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