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