Skip to main content

cargo/compiler/build_runner/
compilation_files.rs

1//! See [`CompilationFiles`].
2
3use crate::util::data_structures::HashMap;
4use std::cell::OnceCell;
5use std::fmt;
6use std::hash::{Hash, Hasher};
7use std::path::{Path, PathBuf};
8use std::sync::Arc;
9
10use cargo_util_schemas::manifest::TomlTrimPaths;
11use tracing::debug;
12
13use super::{BuildContext, BuildRunner, CompileKind, FileFlavor, Layout};
14use crate::compiler::trim_paths;
15use crate::compiler::{CompileMode, CompileTarget, CrateType, FileType, Unit};
16use crate::util::{self, CargoResult, OnceExt, StableHasher};
17use crate::workspace::Target;
18use crate::workspace::TargetKind;
19use crate::workspace::Workspace;
20use crate::workspace::features;
21
22/// This is a generic version number that can be changed to make
23/// backwards-incompatible changes to any file structures in the output
24/// directory. For example, the fingerprint files or the build-script
25/// output files.
26///
27/// Normally cargo updates ship with rustc updates which will
28/// cause a new hash due to the rustc version changing, but this allows
29/// cargo to be extra careful to deal with different versions of cargo that
30/// use the same rustc version.
31const METADATA_VERSION: u8 = 2;
32
33/// Uniquely identify a [`Unit`] under specific circumstances, see [`Metadata`] for more.
34#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
35pub struct UnitHash(u64);
36
37impl fmt::Display for UnitHash {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        write!(f, "{:016x}", self.0)
40    }
41}
42
43impl fmt::Debug for UnitHash {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        write!(f, "UnitHash({:016x})", self.0)
46    }
47}
48
49/// [`Metadata`] tracks several [`UnitHash`]s, including
50/// [`Metadata::unit_id`], [`Metadata::c_metadata`], and [`Metadata::c_extra_filename`].
51///
52/// We use a hash because it is an easy way to guarantee
53/// that all the inputs can be converted to a valid path.
54///
55/// [`Metadata::unit_id`] is used to uniquely identify a unit in the build graph.
56/// This serves as a similar role as [`Metadata::c_extra_filename`] in that it uniquely identifies output
57/// on the filesystem except that its always present.
58///
59/// [`Metadata::c_extra_filename`] is needed for cases like:
60/// - A project may depend on crate `A` and crate `B`, so the package name must be in the file name.
61/// - Similarly a project may depend on two versions of `A`, so the version must be in the file name.
62///
63/// This also acts as the main layer of caching provided by Cargo
64/// so this must include all things that need to be distinguished in different parts of
65/// the same build. This is absolutely required or we override things before
66/// we get chance to use them.
67///
68/// For example, we want to cache `cargo build` and `cargo doc` separately, so that running one
69/// does not invalidate the artifacts for the other. We do this by including [`CompileMode`] in the
70/// hash, thus the artifacts go in different folders and do not override each other.
71/// If we don't add something that we should have, for this reason, we get the
72/// correct output but rebuild more than is needed.
73///
74/// Some things that need to be tracked to ensure the correct output should definitely *not*
75/// go in the `Metadata`. For example, the modification time of a file, should be tracked to make a
76/// rebuild when the file changes. However, it would be wasteful to include in the `Metadata`. The
77/// old artifacts are never going to be needed again. We can save space by just overwriting them.
78/// If we add something that we should not have, for this reason, we get the correct output but take
79/// more space than needed. This makes not including something in `Metadata`
80/// a form of cache invalidation.
81///
82/// Note that the `Fingerprint` is in charge of tracking everything needed to determine if a
83/// rebuild is needed.
84///
85/// [`Metadata::c_metadata`] is used for symbol mangling, because if you have two versions of
86/// the same crate linked together, their symbols need to be differentiated.
87///
88/// You should avoid anything that would interfere with reproducible
89/// builds. For example, *any* absolute path should be avoided. This is one
90/// reason that `RUSTFLAGS` is not in [`Metadata::c_metadata`], because it often has
91/// absolute paths (like `--remap-path-prefix` which is fundamentally used for
92/// reproducible builds and has absolute paths in it). Also, in some cases the
93/// mangled symbols need to be stable between different builds with different
94/// settings. For example, profile-guided optimizations need to swap
95/// `RUSTFLAGS` between runs, but needs to keep the same symbol names.
96#[derive(Copy, Clone, Debug)]
97pub struct Metadata {
98    unit_id: UnitHash,
99    c_metadata: UnitHash,
100    c_extra_filename: bool,
101    pkg_dir: bool,
102}
103
104impl Metadata {
105    /// A hash to identify a given [`Unit`] in the build graph
106    pub fn unit_id(&self) -> UnitHash {
107        self.unit_id
108    }
109
110    /// A hash to add to symbol naming through `-C metadata`
111    pub fn c_metadata(&self) -> UnitHash {
112        self.c_metadata
113    }
114
115    /// A hash to add to file names through `-C extra-filename`
116    pub fn c_extra_filename(&self) -> Option<UnitHash> {
117        self.c_extra_filename.then_some(self.unit_id)
118    }
119
120    /// A hash to add to Cargo directory names
121    pub fn pkg_dir(&self) -> Option<UnitHash> {
122        self.pkg_dir.then_some(self.unit_id)
123    }
124}
125
126/// Collection of information about the files emitted by the compiler, and the
127/// output directory structure.
128pub struct CompilationFiles<'a, 'gctx> {
129    /// The target directory layout for the host (and target if it is the same as host).
130    pub(super) host: Layout,
131    /// The target directory layout for the target (if different from then host).
132    pub(super) target: HashMap<CompileTarget, Layout>,
133    /// Additional directory to include a copy of the outputs.
134    export_dir: Option<PathBuf>,
135    /// The root targets requested by the user on the command line (does not
136    /// include dependencies).
137    roots: Vec<Unit>,
138    ws: &'a Workspace<'gctx>,
139    /// Metadata hash to use for each unit.
140    metas: HashMap<Unit, Metadata>,
141    /// For each Unit, a list all files produced.
142    outputs: HashMap<Unit, OnceCell<Arc<Vec<OutputFile>>>>,
143}
144
145/// Info about a single file emitted by the compiler.
146#[derive(Debug)]
147pub struct OutputFile {
148    /// Absolute path to the file that will be produced by the build process.
149    pub path: PathBuf,
150    /// If it should be linked into `target`, and what it should be called
151    /// (e.g., without metadata).
152    pub hardlink: Option<PathBuf>,
153    /// If `--artifact-dir` is specified, the absolute path to the exported file.
154    pub export_path: Option<PathBuf>,
155    /// Type of the file (library / debug symbol / else).
156    pub flavor: FileFlavor,
157}
158
159impl OutputFile {
160    /// Gets the hard link if present; otherwise, returns the path.
161    pub fn bin_dst(&self) -> &PathBuf {
162        match self.hardlink {
163            Some(ref link_dst) => link_dst,
164            None => &self.path,
165        }
166    }
167}
168
169impl<'a, 'gctx: 'a> CompilationFiles<'a, 'gctx> {
170    pub(super) fn new(
171        build_runner: &BuildRunner<'a, 'gctx>,
172        host: Layout,
173        target: HashMap<CompileTarget, Layout>,
174    ) -> CompilationFiles<'a, 'gctx> {
175        let mut metas = HashMap::default();
176        for unit in &build_runner.bcx.roots {
177            metadata_of(unit, build_runner, &mut metas);
178        }
179        let outputs = metas
180            .keys()
181            .cloned()
182            .map(|unit| (unit, OnceCell::new()))
183            .collect();
184        CompilationFiles {
185            ws: build_runner.bcx.ws,
186            host,
187            target,
188            export_dir: build_runner.bcx.build_config.export_dir.clone(),
189            roots: build_runner.bcx.roots.clone(),
190            metas,
191            outputs,
192        }
193    }
194
195    /// Returns the appropriate directory layout for either a plugin or not.
196    pub fn layout(&self, kind: CompileKind) -> &Layout {
197        match kind {
198            CompileKind::Host => &self.host,
199            CompileKind::Target(target) => &self.target[&target],
200        }
201    }
202
203    /// Gets the metadata for the given unit.
204    ///
205    /// See [`Metadata`] and [`fingerprint`] module for more.
206    ///
207    /// [`fingerprint`]: super::super::fingerprint#fingerprints-and-metadata
208    pub fn metadata(&self, unit: &Unit) -> Metadata {
209        self.metas[unit]
210    }
211
212    /// Gets the short hash based only on the `PackageId`.
213    /// Used for the metadata when `c_extra_filename` returns `None`.
214    fn target_short_hash(&self, unit: &Unit) -> String {
215        let hashable = unit.pkg.package_id().stable_hash(self.ws.root(), false);
216        util::short_hash(&(METADATA_VERSION, hashable))
217    }
218
219    /// Returns the directory where the artifacts for the given unit are
220    /// initially created.
221    pub fn output_dir(&self, unit: &Unit) -> PathBuf {
222        // Docscrape units need to have doc/ set as the out_dir so sources for reverse-dependencies
223        // will be put into doc/ and not into deps/ where the *.examples files are stored.
224        if unit.mode.is_doc() || unit.mode.is_doc_scrape() {
225            self.layout(unit.kind)
226                .artifact_dir()
227                .expect("artifact-dir was not locked")
228                .doc()
229                .to_path_buf()
230        } else if unit.mode.is_doc_test() {
231            panic!("doc tests do not have an out dir");
232        } else if unit.target.is_custom_build() {
233            self.build_script_dir(unit)
234        } else if unit.target.is_example() && !self.ws.gctx().cli_unstable().build_dir_new_layout {
235            self.layout(unit.kind).build_dir().examples().to_path_buf()
236        } else if unit.artifact.is_true() {
237            self.artifact_dir(unit)
238        } else {
239            self.deps_dir(unit).to_path_buf()
240        }
241    }
242
243    /// Additional export directory from `--artifact-dir`.
244    pub fn export_dir(&self) -> Option<PathBuf> {
245        self.export_dir.clone()
246    }
247
248    /// Directory name to use for a package in the form `{NAME}/{HASH}`.
249    ///
250    /// Note that some units may share the same directory, so care should be
251    /// taken in those cases!
252    fn pkg_dir(&self, unit: &Unit) -> String {
253        let separator = match self.ws.gctx().cli_unstable().build_dir_new_layout {
254            true => "/",
255            false => "-",
256        };
257        let name = unit.pkg.package_id().name();
258        let hash = self.unit_hash(unit);
259        // This function can be somewhat hot, so try to not cause unnecessary allocations here.
260        // Sadly, format! does not currently pre-allocate the correct size.
261        let mut pkg = String::with_capacity(name.len() + separator.len() + hash.len());
262        pkg.push_str(&name);
263        pkg.push_str(&separator);
264        pkg.push_str(&hash);
265        pkg
266    }
267
268    /// The directory hash to use for a given unit
269    pub fn unit_hash(&self, unit: &Unit) -> String {
270        self.metas[unit]
271            .pkg_dir()
272            .map(|h| h.to_string())
273            .unwrap_or_else(|| self.target_short_hash(unit))
274    }
275
276    /// Returns the final artifact path for the host (`/…/target/debug`)
277    pub fn host_dest(&self) -> Option<&Path> {
278        self.host.artifact_dir().map(|v| v.dest())
279    }
280
281    /// Returns the root of the build output tree for the host (`/…/build-dir`)
282    pub fn host_build_root(&self) -> &Path {
283        self.host.build_dir().root()
284    }
285
286    /// Returns the host `deps` directory path for a given build unit.
287    pub fn host_deps(&self, unit: &Unit) -> PathBuf {
288        let dir = self.pkg_dir(unit);
289        self.host.build_dir().deps(&dir)
290    }
291
292    /// Returns the directories where Rust crate dependencies are found for the
293    /// specified unit.
294    pub fn deps_dir(&self, unit: &Unit) -> PathBuf {
295        let dir = self.pkg_dir(unit);
296        self.layout(unit.kind).build_dir().deps(&dir)
297    }
298
299    /// Returns the directories where Rust crate dependencies are found for the
300    /// specified unit. (new layout)
301    ///
302    /// New features should consider using this so we can avoid their migrations.
303    pub fn out_dir_new_layout(&self, unit: &Unit) -> PathBuf {
304        let dir = self.pkg_dir(unit);
305        self.layout(unit.kind)
306            .build_dir()
307            .out_force_new_layout(&dir)
308    }
309
310    /// Directory where the fingerprint for the given unit should go.
311    pub fn fingerprint_dir(&self, unit: &Unit) -> PathBuf {
312        let dir = self.pkg_dir(unit);
313        self.layout(unit.kind).build_dir().fingerprint(&dir)
314    }
315
316    /// The lock location for a given build unit.
317    pub fn build_unit_lock(&self, unit: &Unit) -> PathBuf {
318        let dir = self.pkg_dir(unit);
319        self.layout(unit.kind)
320            .build_dir()
321            .build_unit(&dir)
322            .join(".lock")
323    }
324
325    /// Directory where incremental output for the given unit should go.
326    pub fn incremental_dir(&self, unit: &Unit) -> &Path {
327        self.layout(unit.kind).build_dir().incremental()
328    }
329
330    /// Directory where timing output should go.
331    pub fn timings_dir(&self) -> Option<&Path> {
332        self.host.artifact_dir().map(|v| v.timings())
333    }
334
335    /// Returns the path for a file in the fingerprint directory.
336    ///
337    /// The "prefix" should be something to distinguish the file from other
338    /// files in the fingerprint directory.
339    pub fn fingerprint_file_path(&self, unit: &Unit, prefix: &str) -> PathBuf {
340        // Different targets need to be distinguished in the
341        let kind = unit.target.kind().description();
342        let flavor = if unit.mode.is_any_test() {
343            "test-"
344        } else if unit.mode.is_doc() {
345            "doc-"
346        } else if unit.mode.is_run_custom_build() {
347            "run-"
348        } else {
349            ""
350        };
351        let name = format!("{}{}{}-{}", prefix, flavor, kind, unit.target.name());
352        self.fingerprint_dir(unit).join(name)
353    }
354
355    /// Path where compiler output is cached.
356    pub fn message_cache_path(&self, unit: &Unit) -> PathBuf {
357        self.fingerprint_file_path(unit, "output-")
358    }
359
360    /// Returns the directory where a compiled build script is stored.
361    /// `/path/to/target/{debug,release}/build/PKG-HASH`
362    pub fn build_script_dir(&self, unit: &Unit) -> PathBuf {
363        assert!(unit.target.is_custom_build());
364        assert!(!unit.mode.is_run_custom_build());
365        assert!(self.metas.contains_key(unit));
366        let dir = self.pkg_dir(unit);
367        self.layout(CompileKind::Host)
368            .build_dir()
369            .build_script(&dir)
370    }
371
372    /// Returns the directory for compiled artifacts files.
373    /// `/path/to/target/{debug,release}/deps/artifact/KIND/PKG-HASH`
374    fn artifact_dir(&self, unit: &Unit) -> PathBuf {
375        assert!(self.metas.contains_key(unit));
376        assert!(unit.artifact.is_true());
377        let dir = self.pkg_dir(unit);
378        let kind = match unit.target.kind() {
379            TargetKind::Bin => "bin",
380            TargetKind::Lib(lib_kinds) => match lib_kinds.as_slice() {
381                &[CrateType::Cdylib] => "cdylib",
382                &[CrateType::Staticlib] => "staticlib",
383                invalid => unreachable!(
384                    "BUG: unexpected artifact library type(s): {:?} - these should have been split",
385                    invalid
386                ),
387            },
388            invalid => unreachable!(
389                "BUG: {:?} are not supposed to be used as artifacts",
390                invalid
391            ),
392        };
393        self.layout(unit.kind).build_dir().artifact(&dir, kind)
394    }
395
396    /// Returns the directory where information about running a build script
397    /// is stored.
398    /// `/path/to/target/{debug,release}/build/PKG-HASH`
399    pub fn build_script_run_dir(&self, unit: &Unit) -> PathBuf {
400        assert!(unit.target.is_custom_build());
401        assert!(unit.mode.is_run_custom_build());
402        let dir = self.pkg_dir(unit);
403        self.layout(unit.kind)
404            .build_dir()
405            .build_script_execution(&dir)
406    }
407
408    /// Returns the "`OUT_DIR`" directory for running a build script.
409    /// `/path/to/target/{debug,release}/build/PKG-HASH/out`
410    pub fn build_script_out_dir(&self, unit: &Unit) -> PathBuf {
411        self.build_script_run_dir(unit).join("out")
412    }
413
414    /// Returns the path to the executable binary for the given bin target.
415    ///
416    /// This should only to be used when a `Unit` is not available.
417    pub fn bin_link_for_target(
418        &self,
419        target: &Target,
420        kind: CompileKind,
421        bcx: &BuildContext<'_, '_>,
422    ) -> CargoResult<Option<PathBuf>> {
423        assert!(target.is_bin());
424        let Some(dest) = self.layout(kind).artifact_dir().map(|v| v.dest()) else {
425            return Ok(None);
426        };
427        let info = bcx.target_data.info(kind);
428        let (file_types, _) = info
429            .rustc_outputs(
430                CompileMode::Build,
431                &TargetKind::Bin,
432                bcx.target_data.short_name(&kind),
433            )
434            .expect("target must support `bin`");
435
436        let file_type = file_types
437            .iter()
438            .find(|file_type| file_type.flavor == FileFlavor::Normal)
439            .expect("target must support `bin`");
440
441        Ok(Some(dest.join(file_type.uplift_filename(target))))
442    }
443
444    /// Returns the filenames that the given unit will generate.
445    ///
446    /// Note: It is not guaranteed that all of the files will be generated.
447    pub(super) fn outputs(
448        &self,
449        unit: &Unit,
450        bcx: &BuildContext<'a, 'gctx>,
451    ) -> CargoResult<Arc<Vec<OutputFile>>> {
452        self.outputs[unit]
453            .try_borrow_with(|| self.calc_outputs(unit, bcx))
454            .map(Arc::clone)
455    }
456
457    /// Returns the path where the output for the given unit and `FileType`
458    /// should be uplifted to.
459    ///
460    /// Returns `None` if the unit shouldn't be uplifted (for example, a
461    /// dependent rlib).
462    fn uplift_to(
463        &self,
464        unit: &Unit,
465        file_type: &FileType,
466        from_path: &Path,
467        bcx: &BuildContext<'_, '_>,
468    ) -> Option<PathBuf> {
469        // Tests, check, doc, etc. should not be uplifted.
470        if unit.mode != CompileMode::Build || file_type.flavor == FileFlavor::Rmeta {
471            return None;
472        }
473
474        // Artifact dependencies are never uplifted.
475        if unit.artifact.is_true() {
476            return None;
477        }
478
479        // Build script bins are never uplifted.
480        if bcx.gctx.cli_unstable().build_dir_new_layout && unit.target.is_custom_build() {
481            return None;
482        }
483
484        // We plan to stop the uplift for rlibs in future versions.
485        // Currently we do it for nightly channel only.
486        //
487        // See https://rust-lang.zulipchat.com/#narrow/channel/246057-t-cargo/topic/Usage.20of.20-Zno-embed-metadata/near/633481654
488        if file_type.crate_type == Some(CrateType::Rlib)
489            && features::is_nightly_toolchain(&bcx.rustc().version)
490            && !features::is_stop_rlib_uplift_opt_out()
491        {
492            return None;
493        }
494
495        // - Binaries: The user always wants to see these, even if they are
496        //   implicitly built (for example for integration tests).
497        // - dylibs: This ensures that the dynamic linker pulls in all the
498        //   latest copies (even if the dylib was built from a previous cargo
499        //   build). There are complex reasons for this, see #8139, #6167, #6162.
500        // - Things directly requested from the command-line (the "roots").
501        //   This one is a little questionable for rlibs (see #6131), but is
502        //   historically how Cargo has operated. This is primarily useful to
503        //   give the user access to staticlibs and cdylibs.
504        if !unit.target.is_bin()
505            && !unit.target.is_custom_build()
506            && file_type.crate_type != Some(CrateType::Dylib)
507            && !self.roots.contains(unit)
508        {
509            return None;
510        }
511
512        let filename = file_type.uplift_filename(&unit.target);
513        let uplift_path = if unit.target.is_example() {
514            // Examples live in their own little world.
515            self.layout(unit.kind)
516                .artifact_dir()?
517                .examples()
518                .join(filename)
519        } else if unit.target.is_custom_build() {
520            self.build_script_dir(unit).join(filename)
521        } else {
522            self.layout(unit.kind).artifact_dir()?.dest().join(filename)
523        };
524        if from_path == uplift_path {
525            // This can happen with things like examples that reside in the
526            // same directory, do not have a metadata hash (like on Windows),
527            // and do not have hyphens.
528            return None;
529        }
530        Some(uplift_path)
531    }
532
533    /// Calculates the filenames that the given unit will generate.
534    /// Should use [`CompilationFiles::outputs`] instead
535    /// as it caches the result of this function.
536    fn calc_outputs(
537        &self,
538        unit: &Unit,
539        bcx: &BuildContext<'a, 'gctx>,
540    ) -> CargoResult<Arc<Vec<OutputFile>>> {
541        let ret = match unit.mode {
542            _ if unit.skip_non_compile_time_dep => {
543                // This skips compilations so no outputs
544                vec![]
545            }
546            CompileMode::Doc => {
547                let wants_json_doc = bcx.build_config.intent.wants_doc_json_output();
548
549                let path = if wants_json_doc {
550                    // Always use 'new' layout for '--output-format=json'.
551                    let crate_name = unit.target.crate_name();
552                    self.out_dir_new_layout(unit)
553                        .join(format!("{crate_name}.json"))
554                } else {
555                    self.output_dir(unit)
556                        .join(unit.target.crate_name())
557                        .join("index.html")
558                };
559
560                // Uplift if output is json, from 'new' layout location for backward compatibility
561                // See #16773.
562                let hardlink = if wants_json_doc {
563                    Some(
564                        self.output_dir(unit)
565                            .join(format!("{}.json", unit.target.crate_name())),
566                    )
567                } else {
568                    None
569                };
570
571                let mut outputs = vec![OutputFile {
572                    path,
573                    hardlink,
574                    export_path: None,
575                    flavor: FileFlavor::Normal,
576                }];
577
578                if bcx.gctx.cli_unstable().rustdoc_mergeable_info && !wants_json_doc {
579                    // `-Zrustdoc-mergeable-info` always uses the new layout.
580                    outputs.push(OutputFile {
581                        path: self
582                            .out_dir_new_layout(unit)
583                            .join(unit.target.crate_name())
584                            .with_extension("json"),
585                        hardlink: None,
586                        export_path: None,
587                        flavor: FileFlavor::DocParts,
588                    })
589                }
590
591                outputs
592            }
593            CompileMode::RunCustomBuild => {
594                // At this time, this code path does not handle build script
595                // outputs.
596                vec![]
597            }
598            CompileMode::Doctest => {
599                // Doctests are built in a temporary directory and then
600                // deleted. There is the `--persist-doctests` unstable flag,
601                // but Cargo does not know about that.
602                vec![]
603            }
604            CompileMode::Docscrape => {
605                // The file name needs to be stable across Cargo sessions.
606                // This originally used unit.buildkey(), but that isn't stable,
607                // so we use metadata instead (prefixed with name for debugging).
608                let file_name = format!(
609                    "{}-{}.examples",
610                    unit.pkg.name(),
611                    self.metadata(unit).unit_id()
612                );
613                let path = self.deps_dir(unit).join(file_name);
614                vec![OutputFile {
615                    path,
616                    hardlink: None,
617                    export_path: None,
618                    flavor: FileFlavor::Normal,
619                }]
620            }
621            CompileMode::Test | CompileMode::Build | CompileMode::Check { .. } => {
622                let mut outputs = self.calc_outputs_rustc(unit, bcx)?;
623                if bcx.build_config.sbom && bcx.gctx.cli_unstable().sbom {
624                    let sbom_files: Vec<_> = outputs
625                        .iter()
626                        .filter(|o| matches!(o.flavor, FileFlavor::Normal | FileFlavor::Linkable))
627                        .map(|output| OutputFile {
628                            path: Self::append_sbom_suffix(&output.path),
629                            hardlink: output.hardlink.as_ref().map(Self::append_sbom_suffix),
630                            export_path: output.export_path.as_ref().map(Self::append_sbom_suffix),
631                            flavor: FileFlavor::Sbom,
632                        })
633                        .collect();
634                    outputs.extend(sbom_files.into_iter());
635                }
636
637                // Only generates unremap files for root units.
638                if bcx.roots.contains(unit) && trim_paths::should_emit_unremap_file(unit) {
639                    let unremap_files: Vec<_> = outputs
640                        .iter()
641                        .filter(|o| matches!(o.flavor, FileFlavor::Normal | FileFlavor::Linkable))
642                        .map(|output| OutputFile {
643                            path: trim_paths::append_unremap_suffix(&output.path),
644                            hardlink: output
645                                .hardlink
646                                .as_ref()
647                                .map(trim_paths::append_unremap_suffix),
648                            export_path: output
649                                .export_path
650                                .as_ref()
651                                .map(trim_paths::append_unremap_suffix),
652                            flavor: FileFlavor::Unremap,
653                        })
654                        .collect();
655                    outputs.extend(unremap_files.into_iter());
656                }
657                outputs
658            }
659        };
660        debug!("Target filenames: {:?}", ret);
661
662        Ok(Arc::new(ret))
663    }
664
665    /// Append the SBOM suffix to the file name.
666    fn append_sbom_suffix(link: &PathBuf) -> PathBuf {
667        const SBOM_FILE_EXTENSION: &str = ".cargo-sbom.json";
668        let mut link_buf = link.clone().into_os_string();
669        link_buf.push(SBOM_FILE_EXTENSION);
670        PathBuf::from(link_buf)
671    }
672
673    /// Computes the actual, full pathnames for all the files generated by rustc.
674    ///
675    /// The `OutputFile` also contains the paths where those files should be
676    /// "uplifted" to.
677    fn calc_outputs_rustc(
678        &self,
679        unit: &Unit,
680        bcx: &BuildContext<'a, 'gctx>,
681    ) -> CargoResult<Vec<OutputFile>> {
682        let out_dir = self.output_dir(unit);
683
684        let info = bcx.target_data.info(unit.kind);
685        let triple = bcx.target_data.short_name(&unit.kind);
686        let (file_types, unsupported) =
687            info.rustc_outputs(unit.mode, unit.target.kind(), triple)?;
688        if file_types.is_empty() {
689            if !unsupported.is_empty() {
690                let unsupported_strs: Vec<_> = unsupported.iter().map(|ct| ct.as_str()).collect();
691                anyhow::bail!(
692                    "cannot produce {} for `{}` as the target `{}` \
693                     does not support these crate types",
694                    unsupported_strs.join(", "),
695                    unit.pkg,
696                    triple,
697                )
698            }
699            anyhow::bail!(
700                "cannot compile `{}` as the target `{}` does not \
701                 support any of the output crate types",
702                unit.pkg,
703                triple,
704            );
705        }
706
707        // Convert FileType to OutputFile.
708        let mut outputs = Vec::new();
709        for file_type in file_types {
710            let meta = self.metas[unit];
711            let meta_opt = meta.c_extra_filename().map(|h| h.to_string());
712            let path = out_dir.join(file_type.output_filename(&unit.target, meta_opt.as_deref()));
713
714            // If, the `different_binary_name` feature is enabled, the name of the hardlink will
715            // be the name of the binary provided by the user in `Cargo.toml`.
716            let hardlink = self.uplift_to(unit, &file_type, &path, bcx);
717            let export_path = if unit.target.is_custom_build() {
718                None
719            } else {
720                self.export_dir.as_ref().and_then(|export_dir| {
721                    hardlink
722                        .as_ref()
723                        .map(|hardlink| export_dir.join(hardlink.file_name().unwrap()))
724                })
725            };
726            outputs.push(OutputFile {
727                path,
728                hardlink,
729                export_path,
730                flavor: file_type.flavor,
731            });
732        }
733        Ok(outputs)
734    }
735}
736
737/// Gets the metadata hash for the given [`Unit`].
738///
739/// When a metadata hash doesn't exist for the given unit,
740/// this calls itself recursively to compute metadata hashes of all its dependencies.
741/// See [`compute_metadata`] for how a single metadata hash is computed.
742fn metadata_of<'a>(
743    unit: &Unit,
744    build_runner: &BuildRunner<'_, '_>,
745    metas: &'a mut HashMap<Unit, Metadata>,
746) -> &'a Metadata {
747    if !metas.contains_key(unit) {
748        let meta = compute_metadata(unit, build_runner, metas);
749        metas.insert(unit.clone(), meta);
750        for dep in build_runner.unit_deps(unit) {
751            metadata_of(&dep.unit, build_runner, metas);
752        }
753    }
754    &metas[unit]
755}
756
757/// Computes the metadata hash for the given [`Unit`].
758fn compute_metadata(
759    unit: &Unit,
760    build_runner: &BuildRunner<'_, '_>,
761    metas: &mut HashMap<Unit, Metadata>,
762) -> Metadata {
763    let bcx = &build_runner.bcx;
764    let deps_metadata = build_runner
765        .unit_deps(unit)
766        .iter()
767        .map(|dep| *metadata_of(&dep.unit, build_runner, metas))
768        .collect::<Vec<_>>();
769    let c_extra_filename = use_extra_filename(bcx, unit);
770    let pkg_dir = use_pkg_dir(bcx, unit);
771
772    let mut shared_hasher = StableHasher::new();
773
774    METADATA_VERSION.hash(&mut shared_hasher);
775
776    // Also mix in enabled features to our metadata. This'll ensure that
777    // when changing feature sets each lib is separately cached.
778    unit.features.hash(&mut shared_hasher);
779
780    // Throw in the profile we're compiling with. This helps caching
781    // `panic=abort` and `panic=unwind` artifacts, additionally with various
782    // settings like debuginfo and whatnot.
783    unit.profile.hash(&mut shared_hasher);
784    unit.mode.hash(&mut shared_hasher);
785    build_runner.lto[unit].hash(&mut shared_hasher);
786
787    // Artifacts compiled for the host should have a different
788    // metadata piece than those compiled for the target, so make sure
789    // we throw in the unit's `kind` as well.  Use `fingerprint_hash`
790    // so that the StableHash doesn't change based on the pathnames
791    // of the custom target JSON spec files.
792    unit.kind.fingerprint_hash().hash(&mut shared_hasher);
793
794    // Finally throw in the target name/kind. This ensures that concurrent
795    // compiles of targets in the same crate don't collide.
796    unit.target.name().hash(&mut shared_hasher);
797    unit.target.kind().hash(&mut shared_hasher);
798
799    hash_rustc_version(bcx, &mut shared_hasher, unit);
800
801    if build_runner.bcx.ws.is_member(&unit.pkg) {
802        // This is primarily here for clippy. This ensures that the clippy
803        // artifacts are separate from the `check` ones.
804        if let Some(path) = &build_runner.bcx.rustc().workspace_wrapper {
805            path.hash(&mut shared_hasher);
806        }
807    }
808
809    // Seed the contents of `__CARGO_DEFAULT_LIB_METADATA` to the hasher if present.
810    // This should be the release channel, to get a different hash for each channel.
811    if let Ok(ref channel) = build_runner
812        .bcx
813        .gctx
814        .get_env("__CARGO_DEFAULT_LIB_METADATA")
815    {
816        channel.hash(&mut shared_hasher);
817    }
818
819    // std units need to be kept separate from user dependencies. std crates
820    // are differentiated in the Unit with `is_std` (for things like
821    // `-Zforce-unstable-if-unmarked`), so they are always built separately.
822    // This isn't strictly necessary for build dependencies which probably
823    // don't need unstable support. A future experiment might be to set
824    // `is_std` to false for build dependencies so that they can be shared
825    // with user dependencies.
826    unit.is_std.hash(&mut shared_hasher);
827
828    // While we don't hash RUSTFLAGS because it may contain absolute paths that
829    // hurts reproducibility, we track whether a unit's RUSTFLAGS is from host
830    // config, so that we can generate a different metadata hash for runtime
831    // and compile-time units.
832    //
833    // HACK: This is a temporary hack for fixing rust-lang/cargo#14253
834    // Need to find a long-term solution to replace this fragile workaround.
835    // See https://github.com/rust-lang/cargo/pull/14432#discussion_r1725065350
836    if unit.kind.is_host() && !bcx.gctx.target_applies_to_host().unwrap_or_default() {
837        let host_info = bcx.target_data.info(CompileKind::Host);
838        let target_configs_are_different = unit.rustflags != host_info.rustflags
839            || unit.rustdocflags != host_info.rustdocflags
840            || bcx
841                .target_data
842                .target_config(CompileKind::Host)
843                .links_overrides
844                != unit.links_overrides;
845        target_configs_are_different.hash(&mut shared_hasher);
846    }
847
848    let ws_root = if unit.is_std {
849        // SourceId for stdlib crates is an absolute path inside the sysroot.
850        // Pass the sysroot as workspace root so that we hash a relative path.
851        // This avoids the metadata hash changing depending on where the user installed rustc.
852        &bcx.target_data.get_info(unit.kind).unwrap().sysroot
853    } else {
854        bcx.ws.root()
855    };
856
857    let mut c_metadata_hasher = shared_hasher.clone();
858    // With trim-paths,
859    // rustc doesn't embed absolute paths of path dependencies outside workspace,
860    // so `-C metadata` doesn't need to hash it either.
861    let trim_paths = match unit.profile.trim_paths {
862        TomlTrimPaths::None => false,
863        TomlTrimPaths::Object | TomlTrimPaths::All => true,
864    };
865    hash_metadata(ws_root, trim_paths, &mut c_metadata_hasher, unit);
866    // Mix in the target-metadata of all the dependencies of this target.
867    let mut dep_c_metadata_hashes = deps_metadata
868        .iter()
869        .map(|m| m.c_metadata)
870        .collect::<Vec<_>>();
871    dep_c_metadata_hashes.sort();
872    dep_c_metadata_hashes.hash(&mut c_metadata_hasher);
873
874    let mut unit_id_hasher = shared_hasher.clone();
875    hash_metadata(ws_root, false, &mut unit_id_hasher, unit);
876    // Mix in the target-metadata of all the dependencies of this target.
877    let mut dep_unit_id_hashes = deps_metadata.iter().map(|m| m.unit_id).collect::<Vec<_>>();
878    dep_unit_id_hashes.sort();
879    dep_unit_id_hashes.hash(&mut unit_id_hasher);
880    // Avoid trashing the caches on RUSTFLAGS changing via `unit_id`
881    //
882    // Limited to `unit_id` to help with reproducible build / PGO issues.
883    let default = Vec::new();
884    let extra_args = build_runner.bcx.extra_args_for(unit).unwrap_or(&default);
885    if !has_remap_path_prefix(&extra_args) {
886        extra_args.hash(&mut unit_id_hasher);
887    }
888    if unit.mode.is_doc() || unit.mode.is_doc_scrape() {
889        if !has_remap_path_prefix(&unit.rustdocflags) {
890            unit.rustdocflags.hash(&mut unit_id_hasher);
891        }
892    } else {
893        if !has_remap_path_prefix(&unit.rustflags) {
894            unit.rustflags.hash(&mut unit_id_hasher);
895        }
896    }
897
898    let c_metadata = UnitHash(Hasher::finish(&c_metadata_hasher));
899    let unit_id = UnitHash(Hasher::finish(&unit_id_hasher));
900
901    Metadata {
902        unit_id,
903        c_metadata,
904        c_extra_filename,
905        pkg_dir,
906    }
907}
908
909/// HACK: Detect the *potential* presence of `--remap-path-prefix`
910///
911/// As CLI parsing is contextual and dependent on the CLI definition to understand the context, we
912/// can't say for sure whether `--remap-path-prefix` is present, so we guess if anything looks like
913/// it.
914/// If we could, we'd strip it out for hashing.
915/// Instead, we use this to avoid hashing rustflags if it might be present to avoid the risk of taking
916/// a flag that is trying to make things reproducible and making things less reproducible by the
917/// `-Cextra-filename` showing up in the rlib, even with `split-debuginfo`.
918fn has_remap_path_prefix(args: &[String]) -> bool {
919    args.iter()
920        .any(|s| s.starts_with("--remap-path-prefix=") || s == "--remap-path-prefix")
921}
922
923/// Hash the version of rustc being used during the build process.
924fn hash_rustc_version(bcx: &BuildContext<'_, '_>, hasher: &mut StableHasher, unit: &Unit) {
925    let vers = &bcx.rustc().version;
926    if vers.pre.is_empty() || bcx.gctx.cli_unstable().separate_nightlies {
927        // For stable, keep the artifacts separate. This helps if someone is
928        // testing multiple versions, to avoid recompiles. Note though that for
929        // cross-compiled builds the `host:` line of `verbose_version` is
930        // omitted since rustc should produce the same output for each target
931        // regardless of the host.
932        for line in bcx.rustc().verbose_version.lines() {
933            if unit.kind.is_host() || !line.starts_with("host: ") {
934                line.hash(hasher);
935            }
936        }
937        return;
938    }
939    // On "nightly"/"beta"/"dev"/etc, keep each "channel" separate. Don't hash
940    // the date/git information, so that whenever someone updates "nightly",
941    // they won't have a bunch of stale artifacts in the target directory.
942    //
943    // This assumes that the first segment is the important bit ("nightly",
944    // "beta", "dev", etc.). Skip other parts like the `.3` in `-beta.3`.
945    vers.pre.split('.').next().hash(hasher);
946    // Keep "host" since some people switch hosts to implicitly change
947    // targets, (like gnu vs musl or gnu vs msvc). In the future, we may want
948    // to consider hashing `unit.kind.short_name()` instead.
949    if unit.kind.is_host() {
950        bcx.rustc().host.hash(hasher);
951    }
952    // None of the other lines are important. Currently they are:
953    // binary: rustc  <-- or "rustdoc"
954    // commit-hash: 38114ff16e7856f98b2b4be7ab4cd29b38bed59a
955    // commit-date: 2020-03-21
956    // host: x86_64-apple-darwin
957    // release: 1.44.0-nightly
958    // LLVM version: 9.0
959    //
960    // The backend version ("LLVM version") might become more relevant in
961    // the future when cranelift sees more use, and people want to switch
962    // between different backends without recompiling.
963}
964
965/// Hash unique metadata per (name, source, version) triple.
966///
967/// This'll allow us to pull crates from anywhere without worrying about conflicts.
968fn hash_metadata(ws_root: &Path, trim_paths: bool, hasher: &mut StableHasher, unit: &Unit) {
969    unit.pkg
970        .package_id()
971        .stable_hash(ws_root, trim_paths)
972        .hash(hasher);
973}
974
975/// Returns whether or not this unit should use a hash in the filename to make it unique.
976fn use_extra_filename(bcx: &BuildContext<'_, '_>, unit: &Unit) -> bool {
977    if unit.mode.is_doc_test() || unit.mode.is_doc() {
978        // Doc tests do not have metadata.
979        return false;
980    }
981    if bcx.gctx.cli_unstable().build_dir_new_layout {
982        if unit.mode.is_any_test() || unit.mode.is_check() {
983            // These always use metadata.
984            return true;
985        }
986
987        if unit.target.is_custom_build() {
988            // Build scripts never use metadata
989            return false;
990        }
991        // No metadata in these cases:
992        //
993        // - dylib, cdylib, executable: `pkg_dir` avoids collisions for us and rustc isn't
994        // looking these up by `-Cextra-filename`
995        //
996        // The __CARGO_DEFAULT_LIB_METADATA env var is used to override this to
997        // force metadata in the hash. This is only used for building libstd. For
998        // example, if libstd is placed in a common location, we don't want a file
999        // named /usr/lib/libstd.so which could conflict with other rustc
1000        // installs. In addition it prevents accidentally loading a libstd of a
1001        // different compiler at runtime.
1002        // See https://github.com/rust-lang/cargo/issues/3005
1003        if (unit.target.is_dylib() || unit.target.is_cdylib() || unit.target.is_executable())
1004            && bcx.gctx.get_env("__CARGO_DEFAULT_LIB_METADATA").is_err()
1005        {
1006            return false;
1007        }
1008    } else {
1009        if unit.mode.is_any_test() || unit.mode.is_check() {
1010            // These always use metadata.
1011            return true;
1012        }
1013        // No metadata in these cases:
1014        //
1015        // - dylibs:
1016        //   - if any dylib names are encoded in executables, so they can't be renamed.
1017        //   - TODO: Maybe use `-install-name` on macOS or `-soname` on other UNIX systems
1018        //     to specify the dylib name to be used by the linker instead of the filename.
1019        // - Windows MSVC executables: The path to the PDB is embedded in the
1020        //   executable, and we don't want the PDB path to include the hash in it.
1021        // - wasm32-unknown-emscripten executables: When using emscripten, the path to the
1022        //   .wasm file is embedded in the .js file, so we don't want the hash in there.
1023        //
1024        // This is only done for local packages, as we don't expect to export
1025        // dependencies.
1026        //
1027        // The __CARGO_DEFAULT_LIB_METADATA env var is used to override this to
1028        // force metadata in the hash. This is only used for building libstd. For
1029        // example, if libstd is placed in a common location, we don't want a file
1030        // named /usr/lib/libstd.so which could conflict with other rustc
1031        // installs. In addition it prevents accidentally loading a libstd of a
1032        // different compiler at runtime.
1033        // See https://github.com/rust-lang/cargo/issues/3005
1034        let short_name = bcx.target_data.short_name(&unit.kind);
1035        if (unit.target.is_dylib()
1036            || unit.target.is_cdylib()
1037            || (unit.target.is_executable() && short_name == "wasm32-unknown-emscripten")
1038            || (unit.target.is_executable() && short_name.contains("msvc")))
1039            && unit.pkg.package_id().source_id().is_path()
1040            && bcx.gctx.get_env("__CARGO_DEFAULT_LIB_METADATA").is_err()
1041        {
1042            return false;
1043        }
1044    }
1045    true
1046}
1047
1048/// Returns whether or not this unit should use a hash in the pkg_dir to make it unique.
1049fn use_pkg_dir(bcx: &BuildContext<'_, '_>, unit: &Unit) -> bool {
1050    if unit.mode.is_doc_test() || unit.mode.is_doc() {
1051        // Doc tests do not have metadata.
1052        return false;
1053    }
1054    if bcx.gctx.cli_unstable().build_dir_new_layout {
1055        // These always use metadata.
1056        return true;
1057    }
1058    if unit.mode.is_any_test() || unit.mode.is_check() {
1059        // These always use metadata.
1060        return true;
1061    }
1062    // No metadata in these cases:
1063    //
1064    // - dylibs:
1065    //   - if any dylib names are encoded in executables, so they can't be renamed.
1066    //   - TODO: Maybe use `-install-name` on macOS or `-soname` on other UNIX systems
1067    //     to specify the dylib name to be used by the linker instead of the filename.
1068    // - Windows MSVC executables: The path to the PDB is embedded in the
1069    //   executable, and we don't want the PDB path to include the hash in it.
1070    // - wasm32-unknown-emscripten executables: When using emscripten, the path to the
1071    //   .wasm file is embedded in the .js file, so we don't want the hash in there.
1072    //
1073    // This is only done for local packages, as we don't expect to export
1074    // dependencies.
1075    //
1076    // The __CARGO_DEFAULT_LIB_METADATA env var is used to override this to
1077    // force metadata in the hash. This is only used for building libstd. For
1078    // example, if libstd is placed in a common location, we don't want a file
1079    // named /usr/lib/libstd.so which could conflict with other rustc
1080    // installs. In addition it prevents accidentally loading a libstd of a
1081    // different compiler at runtime.
1082    // See https://github.com/rust-lang/cargo/issues/3005
1083    let short_name = bcx.target_data.short_name(&unit.kind);
1084    if (unit.target.is_dylib()
1085        || unit.target.is_cdylib()
1086        || (unit.target.is_executable() && short_name == "wasm32-unknown-emscripten")
1087        || (unit.target.is_executable() && short_name.contains("msvc")))
1088        && unit.pkg.package_id().source_id().is_path()
1089        && bcx.gctx.get_env("__CARGO_DEFAULT_LIB_METADATA").is_err()
1090    {
1091        return false;
1092    }
1093    true
1094}