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