Skip to main content

cargo/compiler/build_runner/
compilation_files.rs

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