Skip to main content

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