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