Skip to main content

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