Skip to main content

cargo/compiler/fingerprint/
mod.rs

1//! Tracks changes to determine if something needs to be recompiled.
2//!
3//! This module implements change-tracking so that Cargo can know whether or
4//! not something needs to be recompiled. A Cargo [`Unit`] can be either "dirty"
5//! (needs to be recompiled) or "fresh" (it does not need to be recompiled).
6//!
7//! ## Mechanisms affecting freshness
8//!
9//! There are several mechanisms that influence a Unit's freshness:
10//!
11//! - The [`Fingerprint`] is a hash, saved to the filesystem in the
12//!   `.fingerprint` directory, that tracks information about the Unit. If the
13//!   fingerprint is missing (such as the first time the unit is being
14//!   compiled), then the unit is dirty. If any of the fingerprint fields
15//!   change (like the name of the source file), then the Unit is considered
16//!   dirty.
17//!
18//!   The `Fingerprint` also tracks the fingerprints of all its dependencies,
19//!   so a change in a dependency will propagate the "dirty" status up.
20//!
21//! - Filesystem mtime tracking is also used to check if a unit is dirty.
22//!   See the section below on "Mtime comparison" for more details. There
23//!   are essentially two parts to mtime tracking:
24//!
25//!   1. The mtime of a Unit's output files is compared to the mtime of all
26//!      its dependencies' output file mtimes (see
27//!      [`check_filesystem`]). If any output is missing, or is
28//!      older than a dependency's output, then the unit is dirty.
29//!   2. The mtime of a Unit's source files is compared to the mtime of its
30//!      dep-info file in the fingerprint directory (see [`find_stale_file`]).
31//!      The dep-info file is used as an anchor to know when the last build of
32//!      the unit was done. See the "dep-info files" section below for more
33//!      details. If any input files are missing, or are newer than the
34//!      dep-info, then the unit is dirty.
35//!
36//!  - Alternatively if you're using the unstable feature `checksum-freshness`
37//!    mtimes are ignored entirely in favor of comparing first the file size, and
38//!    then the checksum with a known prior value emitted by rustc. Only nightly
39//!    rustc will emit the needed metadata at the time of writing. This is dependent
40//!    on the unstable feature `-Z checksum-hash-algorithm`.
41//!
42//! Note: Fingerprinting is not a perfect solution. Filesystem mtime tracking
43//! is notoriously imprecise and problematic. Only a small part of the
44//! environment is captured. This is a balance of performance, simplicity, and
45//! completeness. Sandboxing, hashing file contents, tracking every file
46//! access, environment variable, and network operation would ensure more
47//! reliable and reproducible builds at the cost of being complex, slow, and
48//! platform-dependent.
49//!
50//! ## Fingerprints and [`UnitHash`]s
51//!
52//! [`Metadata`] tracks several [`UnitHash`]s, including
53//! [`Metadata::unit_id`], [`Metadata::c_metadata`], and [`Metadata::c_extra_filename`].
54//! See its documentation for more details.
55//!
56//! NOTE: Not all output files are isolated via filename hashes (like dylibs).
57//! The fingerprint directory uses a hash, but sometimes units share the same
58//! fingerprint directory (when they don't have Metadata) so care should be
59//! taken to handle this!
60//!
61//! Fingerprints and [`UnitHash`]s are similar, and track some of the same things.
62//! [`UnitHash`]s contains information that is required to keep Units separate.
63//! The Fingerprint includes additional information that should cause a
64//! recompile, but it is desired to reuse the same filenames. A comparison
65//! of what is tracked:
66//!
67//! Value                                      | Fingerprint | `Metadata::unit_id` [^8] | `Metadata::c_metadata`
68//! -------------------------------------------|-------------|--------------------------|-----------------------
69//! rustc                                      | ✓           | ✓                        | ✓
70//! [`Profile`]                                | ✓           | ✓                        | ✓
71//! `cargo rustc` extra args                   | ✓           | ✓[^7]                    |
72//! [`CompileMode`]                            | ✓           | ✓                        | ✓
73//! Target Name                                | ✓           | ✓                        | ✓
74//! `TargetKind` (bin/lib/etc.)                | ✓           | ✓                        | ✓
75//! Enabled Features                           | ✓           | ✓                        | ✓
76//! Declared Features                          | ✓           |                          |
77//! Immediate dependency’s hashes              | ✓[^1]       | ✓                        | ✓
78//! [`CompileKind`] (host/target)              | ✓           | ✓                        | ✓
79//! `__CARGO_DEFAULT_LIB_METADATA`[^4]         |             | ✓                        | ✓
80//! `__CARGO_RUSTC_BOOTSTRAP_WS_REMAP`[^2]     | ✓           |                          |
81//! `package_id`                               |             | ✓                        | ✓
82//! Target src path relative to ws             | ✓           |                          |
83//! Target flags (test/bench/for_host/edition) | ✓           |                          |
84//! -C incremental=… flag                      | ✓           |                          |
85//! mtime of sources                           | ✓[^3]       |                          |
86//! RUSTFLAGS/RUSTDOCFLAGS                     | ✓           | ✓[^7]                    |
87//! [`Lto`] flags                              | ✓           | ✓                        | ✓
88//! config settings[^5]                        | ✓           |                          |
89//! `is_std`                                   |             | ✓                        | ✓
90//! `[lints]` table[^6]                        | ✓           |                          |
91//! `[lints.rust.unexpected_cfgs.check-cfg]`   | ✓           |                          |
92//! `--extern priv:`                           | ✓           |                          |
93//!
94//! [^1]: Bin dependencies are not included.
95//!
96//! [^2]: `__CARGO_RUSTC_BOOTSTRAP_WS_REMAP` is set by rustc bootstrap
97//!       to customize remap-path-prefix
98//!
99//! [^3]: See below for details on mtime tracking.
100//!
101//! [^4]: `__CARGO_DEFAULT_LIB_METADATA` is set by rustbuild to embed the
102//!        release channel (bootstrap/stable/beta/nightly) in libstd.
103//!
104//! [^5]: Config settings that are not otherwise captured anywhere else.
105//!       Currently, this is only `doc.extern-map`.
106//!
107//! [^6]: Via [`Manifest::lint_rustflags`][crate::workspace::Manifest::lint_rustflags]
108//!
109//! [^7]: extra-flags and RUSTFLAGS are conditionally excluded when `--remap-path-prefix` is
110//!       present to avoid breaking build reproducibility while we wait for trim-paths
111//!
112//! [^8]: including `-Cextra-filename`
113//!
114//! When deciding what should go in the Metadata vs the Fingerprint, consider
115//! that some files (like dylibs) do not have a hash in their filename. Thus,
116//! if a value changes, only the fingerprint will detect the change (consider,
117//! for example, swapping between different features). Fields that are only in
118//! Metadata generally aren't relevant to the fingerprint because they
119//! fundamentally change the output (like target vs host changes the directory
120//! where it is emitted).
121//!
122//! ## Fingerprint files
123//!
124//! Fingerprint information is stored in the
125//! `target/{debug,release}/.fingerprint/` directory. Each Unit is stored in a
126//! separate directory. Each Unit directory contains:
127//!
128//! - A file with a 16 hex-digit hash. This is the Fingerprint hash, used for
129//!   quick loading and comparison.
130//! - A `.json` file that contains details about the Fingerprint. This is only
131//!   used to log details about *why* a fingerprint is considered dirty.
132//!   `CARGO_LOG=cargo::compiler::fingerprint=trace cargo build` can be
133//!   used to display this log information.
134//! - A "dep-info" file which is a translation of rustc's `*.d` dep-info files
135//!   to a Cargo-specific format that tweaks file names and is optimized for
136//!   reading quickly.
137//! - An `invoked.timestamp` file whose filesystem mtime is updated every time
138//!   the Unit is built. This is used for capturing the time when the build
139//!   starts, to detect if files are changed in the middle of the build. See
140//!   below for more details.
141//!
142//! Note that some units are a little different. A Unit for *running* a build
143//! script or for `rustdoc` does not have a dep-info file (it's not
144//! applicable). Build script `invoked.timestamp` files are in the build
145//! output directory.
146//!
147//! ## Fingerprint calculation
148//!
149//! After the list of Units has been calculated, the Units are added to the
150//! [`JobQueue`]. As each one is added, the fingerprint is calculated, and the
151//! dirty/fresh status is recorded. A closure is used to update the fingerprint
152//! on-disk when the Unit successfully finishes. The closure will recompute the
153//! Fingerprint based on the updated information. If the Unit fails to compile,
154//! the fingerprint is not updated.
155//!
156//! Fingerprints are cached in the [`BuildRunner`]. This makes computing
157//! Fingerprints faster, but also is necessary for properly updating
158//! dependency information. Since a Fingerprint includes the Fingerprints of
159//! all dependencies, when it is updated, by using `Arc` clones, it
160//! automatically picks up the updates to its dependencies.
161//!
162//! ### dep-info files
163//!
164//! Cargo has several kinds of "dep info" files:
165//!
166//! * dep-info files generated by `rustc`.
167//! * Fingerprint dep-info files translated from the first one.
168//! * dep-info for external build system integration.
169//! * Unstable `-Zbinary-dep-depinfo`.
170//!
171//! #### `rustc` dep-info files
172//!
173//! Cargo passes the `--emit=dep-info` flag to `rustc` so that `rustc` will
174//! generate a "dep info" file (with the `.d` extension). This is a
175//! Makefile-like syntax that includes all of the source files used to build
176//! the crate. This file is used by Cargo to know which files to check to see
177//! if the crate will need to be rebuilt. Example:
178//!
179//! ```makefile
180//! /path/to/target/debug/deps/cargo-b6219d178925203d: src/bin/main.rs src/bin/cargo/cli.rs # … etc.
181//! ```
182//!
183//! #### Fingerprint dep-info files
184//!
185//! After `rustc` exits successfully, Cargo will read the first kind of dep
186//! info file and translate it into a binary format that is stored in the
187//! fingerprint directory ([`translate_dep_info`]).
188//!
189//! These are used to quickly scan for any changed files. The mtime of the
190//! fingerprint dep-info file itself is used as the reference for comparing the
191//! source files to determine if any of the source files have been modified
192//! (see [below](#mtime-comparison) for more detail).
193//!
194//! Note that Cargo parses the special `# env-var:...` comments in dep-info
195//! files to learn about environment variables that the rustc compile depends on.
196//! Cargo then later uses this to trigger a recompile if a referenced env var
197//! changes (even if the source didn't change).
198//! This also includes env vars generated from Cargo metadata like `CARGO_PKG_DESCRIPTION`.
199//! (See [`crate::workspace::manifest::ManifestMetadata`]
200//!
201//! #### dep-info files for build system integration.
202//!
203//! There is also a third dep-info file. Cargo will extend the file created by
204//! rustc with some additional information and saves this into the output
205//! directory. This is intended for build system integration. See the
206//! [`output_depinfo`] function for more detail.
207//!
208//! #### -Zbinary-dep-depinfo
209//!
210//! `rustc` has an experimental flag `-Zbinary-dep-depinfo`. This causes
211//! `rustc` to include binary files (like rlibs) in the dep-info file. This is
212//! primarily to support rustc development, so that Cargo can check the
213//! implicit dependency to the standard library (which lives in the sysroot).
214//! We want Cargo to recompile whenever the standard library rlib/dylibs
215//! change, and this is a generic mechanism to make that work.
216//!
217//! ### Mtime comparison
218//!
219//! The use of modification timestamps is the most common way a unit will be
220//! determined to be dirty or fresh between builds. There are many subtle
221//! issues and edge cases with mtime comparisons. This gives a high-level
222//! overview, but you'll need to read the code for the gritty details. Mtime
223//! handling is different for different unit kinds. The different styles are
224//! driven by the [`Fingerprint::local`] field, which is set based on the unit
225//! kind.
226//!
227//! The status of whether or not the mtime is "stale" or "up-to-date" is
228//! stored in [`Fingerprint::fs_status`].
229//!
230//! All units will compare the mtime of its newest output file with the mtimes
231//! of the outputs of all its dependencies. If any output file is missing,
232//! then the unit is stale. If any dependency is newer, the unit is stale.
233//!
234//! #### Normal package mtime handling
235//!
236//! [`LocalFingerprint::CheckDepInfo`] is used for checking the mtime of
237//! packages. It compares the mtime of the input files (the source files) to
238//! the mtime of the dep-info file (which is written last after a build is
239//! finished). If the dep-info is missing, the unit is stale (it has never
240//! been built). The list of input files comes from the dep-info file. See the
241//! section above for details on dep-info files.
242//!
243//! Also note that although registry and git packages use [`CheckDepInfo`], none
244//! of their source files are included in the dep-info (see
245//! [`translate_dep_info`]), so for those kinds no mtime checking is done
246//! (unless `-Zbinary-dep-depinfo` is used). Repository and git packages are
247//! static, so there is no need to check anything.
248//!
249//! When a build is complete, the mtime of the dep-info file in the
250//! fingerprint directory is modified to rewind it to the time when the build
251//! started. This is done by creating an `invoked.timestamp` file when the
252//! build starts to capture the start time. The mtime is rewound to the start
253//! to handle the case where the user modifies a source file while a build is
254//! running. Cargo can't know whether or not the file was included in the
255//! build, so it takes a conservative approach of assuming the file was *not*
256//! included, and it should be rebuilt during the next build.
257//!
258//! #### Rustdoc mtime handling
259//!
260//! Rustdoc does not emit a dep-info file, so Cargo currently has a relatively
261//! simple system for detecting rebuilds. [`LocalFingerprint::Precalculated`] is
262//! used for rustdoc units. For registry packages, this is the package
263//! version. For git packages, it is the git hash. For path packages, it is
264//! a string of the mtime of the newest file in the package.
265//!
266//! There are some known bugs with how this works, so it should be improved at
267//! some point.
268//!
269//! #### Build script mtime handling
270//!
271//! Build script mtime handling runs in different modes. There is the "old
272//! style" where the build script does not emit any `rerun-if` directives. In
273//! this mode, Cargo will use [`LocalFingerprint::Precalculated`]. See the
274//! "rustdoc" section above how it works.
275//!
276//! In the new-style, each `rerun-if` directive is translated to the
277//! corresponding [`LocalFingerprint`] variant. The [`RerunIfChanged`] variant
278//! compares the mtime of the given filenames against the mtime of the
279//! "output" file.
280//!
281//! Similar to normal units, the build script "output" file mtime is rewound
282//! to the time just before the build script is executed to handle mid-build
283//! modifications.
284//!
285//! ## Considerations for inclusion in a fingerprint
286//!
287//! Over time we've realized a few items which historically were included in
288//! fingerprint hashings should not actually be included. Examples are:
289//!
290//! * Modification time values. We strive to never include a modification time
291//!   inside a `Fingerprint` to get hashed into an actual value. While
292//!   theoretically fine to do, in practice this causes issues with common
293//!   applications like Docker. Docker, after a layer is built, will zero out
294//!   the nanosecond part of all filesystem modification times. This means that
295//!   the actual modification time is different for all build artifacts, which
296//!   if we tracked the actual values of modification times would cause
297//!   unnecessary recompiles. To fix this we instead only track paths which are
298//!   relevant. These paths are checked dynamically to see if they're up to
299//!   date, and the modification time doesn't make its way into the fingerprint
300//!   hash.
301//!
302//! * Absolute path names. We strive to maintain a property where if you rename
303//!   a project directory Cargo will continue to preserve all build artifacts
304//!   and reuse the cache. This means that we can't ever hash an absolute path
305//!   name. Instead we always hash relative path names and the "root" is passed
306//!   in at runtime dynamically. Some of this is best effort, but the general
307//!   idea is that we assume all accesses within a crate stay within that
308//!   crate.
309//!
310//! These are pretty tricky to test for unfortunately, but we should have a good
311//! test suite nowadays and lord knows Cargo gets enough testing in the wild!
312//!
313//! ## Build scripts
314//!
315//! The *running* of a build script ([`CompileMode::RunCustomBuild`]) is treated
316//! significantly different than all other Unit kinds. It has its own function
317//! for calculating the Fingerprint ([`calculate_run_custom_build`]) and has some
318//! unique considerations. It does not track the same information as a normal
319//! Unit. The information tracked depends on the `rerun-if-changed` and
320//! `rerun-if-env-changed` statements produced by the build script. If the
321//! script does not emit either of these statements, the Fingerprint runs in
322//! "old style" mode where an mtime change of *any* file in the package will
323//! cause the build script to be re-run. Otherwise, the fingerprint *only*
324//! tracks the individual "rerun-if" items listed by the build script.
325//!
326//! The "rerun-if" statements from a *previous* build are stored in the build
327//! output directory in a file called `output`. Cargo parses this file when
328//! the Unit for that build script is prepared for the [`JobQueue`]. The
329//! Fingerprint code can then use that information to compute the Fingerprint
330//! and compare against the old fingerprint hash.
331//!
332//! Care must be taken with build script Fingerprints because the
333//! [`Fingerprint::local`] value may be changed after the build script runs
334//! (such as if the build script adds or removes "rerun-if" items).
335//!
336//! Another complication is if a build script is overridden. In that case, the
337//! fingerprint is the hash of the output of the override.
338//!
339//! ## Special considerations
340//!
341//! Registry dependencies do not track the mtime of files. This is because
342//! registry dependencies are not expected to change (if a new version is
343//! used, the Package ID will change, causing a rebuild). Cargo currently
344//! partially works with Docker caching. When a Docker image is built, it has
345//! normal mtime information. However, when a step is cached, the nanosecond
346//! portions of all files is zeroed out. Currently this works, but care must
347//! be taken for situations like these.
348//!
349//! HFS on macOS only supports 1 second timestamps. This causes a significant
350//! number of problems, particularly with Cargo's testsuite which does rapid
351//! builds in succession. Other filesystems have various degrees of
352//! resolution.
353//!
354//! Various weird filesystems (such as network filesystems) also can cause
355//! complications. Network filesystems may track the time on the server
356//! (except when the time is set manually such as with
357//! `filetime::set_file_times`). Not all filesystems support modifying the
358//! mtime.
359//!
360//! See the [`A-rebuild-detection`] label on the issue tracker for more.
361//!
362//! [`check_filesystem`]: Fingerprint::check_filesystem
363//! [`Metadata`]: crate::compiler::Metadata
364//! [`Metadata::unit_id`]: crate::compiler::Metadata::unit_id
365//! [`Metadata::c_metadata`]: crate::compiler::Metadata::c_metadata
366//! [`Metadata::c_extra_filename`]: crate::compiler::Metadata::c_extra_filename
367//! [`UnitHash`]: crate::compiler::UnitHash
368//! [`Profile`]: crate::workspace::profiles::Profile
369//! [`CompileMode`]: crate::compiler::CompileMode
370//! [`Lto`]: crate::compiler::Lto
371//! [`CompileKind`]: crate::compiler::CompileKind
372//! [`JobQueue`]: super::job_queue::JobQueue
373//! [`output_depinfo`]: super::output_depinfo()
374//! [`CheckDepInfo`]: LocalFingerprint::CheckDepInfo
375//! [`RerunIfChanged`]: LocalFingerprint::RerunIfChanged
376//! [`CompileMode::RunCustomBuild`]: crate::compiler::CompileMode::RunCustomBuild
377//! [`A-rebuild-detection`]: https://github.com/rust-lang/cargo/issues?q=is%3Aissue+is%3Aopen+label%3AA-rebuild-detection
378
379mod dep_info;
380mod dirty_reason;
381mod rustdoc;
382
383use crate::util::data_structures::HashMap;
384use std::collections::hash_map::Entry;
385use std::env;
386use std::ffi::OsString;
387use std::fs;
388use std::fs::File;
389use std::hash::{self, Hash, Hasher};
390use std::io::{self};
391use std::ops::Not;
392use std::path::{Path, PathBuf};
393use std::sync::{Arc, Mutex};
394use std::time::SystemTime;
395
396use anyhow::Context as _;
397use anyhow::format_err;
398use cargo_util::paths;
399use filetime::FileTime;
400use serde::de;
401use serde::ser;
402use serde::{Deserialize, Serialize};
403use tracing::{debug, info};
404
405use crate::compiler::unit_graph::UnitDep;
406use crate::util;
407use crate::util::errors::CargoResult;
408use crate::util::interning::InternedString;
409use crate::util::log_message::LogMessage;
410use crate::util::{StableHasher, internal, path_args};
411use crate::workspace::Package;
412use crate::{CARGO_ENV, GlobalContext};
413
414use super::BuildContext;
415use super::BuildRunner;
416use super::FileFlavor;
417use super::Job;
418use super::Unit;
419use super::UnitIndex;
420use super::Work;
421use super::custom_build::BuildDeps;
422
423pub use self::dep_info::Checksum;
424pub use self::dep_info::parse_dep_info;
425pub use self::dep_info::parse_rustc_dep_info;
426pub use self::dep_info::translate_dep_info;
427pub use self::dirty_reason::DirtyReason;
428pub use self::rustdoc::RustdocFingerprint;
429
430/// Result of comparing fingerprints between the current and previous builds.
431enum FingerprintComparison {
432    /// The unit does not need rebuilding.
433    Fresh,
434    /// The unit needs rebuilding.
435    Dirty {
436        /// The reason why the unit is dirty.
437        reason: DirtyReason,
438    },
439}
440
441/// Determines if a [`Unit`] is up-to-date, and if not prepares necessary work to
442/// update the persisted fingerprint.
443///
444/// This function will inspect `Unit`, calculate a fingerprint for it, and then
445/// return an appropriate [`Job`] to run. The returned `Job` will be a noop if
446/// `unit` is considered "fresh", or if it was previously built and cached.
447/// Otherwise the `Job` returned will write out the true fingerprint to the
448/// filesystem, to be executed after the unit's work has completed.
449///
450/// The `force` flag is a way to force the `Job` to be "dirty", or always
451/// update the fingerprint. **Beware using this flag** because it does not
452/// transitively propagate throughout the dependency graph, it only forces this
453/// one unit which is very unlikely to be what you want unless you're
454/// exclusively talking about top-level units.
455#[tracing::instrument(
456    skip(build_runner, unit),
457    fields(package_id = %unit.pkg.package_id(), target = unit.target.name())
458)]
459pub fn prepare_target(
460    build_runner: &mut BuildRunner<'_, '_>,
461    unit: &Unit,
462    force: bool,
463) -> CargoResult<Job> {
464    let bcx = build_runner.bcx;
465    let loc = build_runner.files().fingerprint_file_path(unit, "");
466
467    debug!("fingerprint at: {}", loc.display());
468
469    // Figure out if this unit is up to date. After calculating the fingerprint
470    // compare it to an old version, if any, and attempt to print diagnostic
471    // information about failed comparisons to aid in debugging.
472    let fingerprint = calculate(build_runner, unit)?;
473    let mtime_on_use = build_runner.bcx.gctx.cli_unstable().mtime_on_use;
474    let dirty_reason = match compare_old_fingerprint(unit, &loc, &*fingerprint, mtime_on_use, force)
475    {
476        FingerprintComparison::Fresh => None,
477        FingerprintComparison::Dirty { reason } => Some(reason),
478    };
479
480    if let Some(logger) = bcx.logger {
481        let index = bcx.unit_to_index[unit];
482        let mut cause = None;
483        let status = match dirty_reason.as_ref() {
484            Some(reason) if reason.is_fresh_build() => util::log_message::FingerprintStatus::New,
485            Some(reason) => {
486                cause = Some(reason.clone());
487                util::log_message::FingerprintStatus::Dirty
488            }
489            None => util::log_message::FingerprintStatus::Fresh,
490        };
491        logger.log(LogMessage::UnitFingerprint {
492            index,
493            status,
494            cause,
495        });
496    }
497
498    let Some(dirty_reason) = dirty_reason else {
499        return Ok(Job::new_fresh());
500    };
501
502    // We're going to rebuild, so ensure the source of the crate passes all
503    // verification checks before we build it.
504    //
505    // The `Source::verify` method is intended to allow sources to execute
506    // pre-build checks to ensure that the relevant source code is all
507    // up-to-date and as expected. This is currently used primarily for
508    // directory sources which will use this hook to perform an integrity check
509    // on all files in the source to ensure they haven't changed. If they have
510    // changed then an error is issued.
511    let source_id = unit.pkg.package_id().source_id();
512    let sources = bcx.packages.sources();
513    let source = sources
514        .get(source_id)
515        .ok_or_else(|| internal("missing package source"))?;
516    source.verify(unit.pkg.package_id())?;
517
518    // Clear out the old fingerprint file if it exists. This protects when
519    // compilation is interrupted leaving a corrupt file. For example, a
520    // project with a lib.rs and integration test (two units):
521    //
522    // 1. Build the library and integration test.
523    // 2. Make a change to lib.rs (NOT the integration test).
524    // 3. Build the integration test, hit Ctrl-C while linking. With gcc, this
525    //    will leave behind an incomplete executable (zero size, or partially
526    //    written). NOTE: The library builds successfully, it is the linking
527    //    of the integration test that we are interrupting.
528    // 4. Build the integration test again.
529    //
530    // Without the following line, then step 3 will leave a valid fingerprint
531    // on the disk. Then step 4 will think the integration test is "fresh"
532    // because:
533    //
534    // - There is a valid fingerprint hash on disk (written in step 1).
535    // - The mtime of the output file (the corrupt integration executable
536    //   written in step 3) is newer than all of its dependencies.
537    // - The mtime of the integration test fingerprint dep-info file (written
538    //   in step 1) is newer than the integration test's source files, because
539    //   we haven't modified any of its source files.
540    //
541    // But the executable is corrupt and needs to be rebuilt. Clearing the
542    // fingerprint at step 3 ensures that Cargo never mistakes a partially
543    // written output as up-to-date.
544    if loc.exists() {
545        // Truncate instead of delete so that compare_old_fingerprint will
546        // still log the reason for the fingerprint failure instead of just
547        // reporting "failed to read fingerprint" during the next build if
548        // this build fails.
549        paths::write(&loc, b"")?;
550    }
551
552    let write_fingerprint = if unit.mode.is_run_custom_build() {
553        // For build scripts the `local` field of the fingerprint may change
554        // while we're executing it. For example it could be in the legacy
555        // "consider everything a dependency mode" and then we switch to "deps
556        // are explicitly specified" mode.
557        //
558        // To handle this movement we need to regenerate the `local` field of a
559        // build script's fingerprint after it's executed. We do this by
560        // using the `build_script_local_fingerprints` function which returns a
561        // thunk we can invoke on a foreign thread to calculate this.
562        let build_script_outputs = Arc::clone(&build_runner.build_script_outputs);
563        let metadata = build_runner.get_run_build_script_metadata(unit);
564        let (gen_local, _overridden) = build_script_local_fingerprints(build_runner, unit)?;
565        let output_path = build_runner.build_explicit_deps[unit]
566            .build_script_output
567            .clone();
568        Work::new(move |_| {
569            let outputs = build_script_outputs.lock().unwrap();
570            let output = outputs
571                .get(metadata)
572                .expect("output must exist after running");
573            let deps = BuildDeps::new(&output_path, Some(output));
574
575            // FIXME: it's basically buggy that we pass `None` to `call_box`
576            // here. See documentation on `build_script_local_fingerprints`
577            // below for more information. Despite this just try to proceed and
578            // hobble along if it happens to return `Some`.
579            if let Some(new_local) = (gen_local)(&deps, None)? {
580                *fingerprint.local.lock().unwrap() = new_local;
581            }
582
583            write_fingerprint(&loc, &fingerprint)
584        })
585    } else {
586        Work::new(move |_| write_fingerprint(&loc, &fingerprint))
587    };
588
589    Ok(Job::new_dirty(write_fingerprint, dirty_reason))
590}
591
592/// Dependency edge information for fingerprints. This is generated for each
593/// dependency and is stored in a [`Fingerprint`].
594#[derive(Clone)]
595struct DepFingerprint {
596    /// The hash of the package id that this dependency points to
597    pkg_id: u64,
598    /// The crate name we're using for this dependency, which if we change we'll
599    /// need to recompile!
600    name: InternedString,
601    /// Whether or not this dependency is flagged as a public dependency or not.
602    public: bool,
603    /// Whether or not this dependency is an rmeta dependency or a "full"
604    /// dependency. In the case of an rmeta dependency our dependency edge only
605    /// actually requires the rmeta from what we depend on, so when checking
606    /// mtime information all files other than the rmeta can be ignored.
607    only_requires_rmeta: bool,
608    /// The dependency's fingerprint we recursively point to, containing all the
609    /// other hash information we'd otherwise need.
610    fingerprint: Arc<Fingerprint>,
611}
612
613/// A fingerprint can be considered to be a "short string" representing the
614/// state of a world for a package.
615///
616/// If a fingerprint ever changes, then the package itself needs to be
617/// recompiled. Inputs to the fingerprint include source code modifications,
618/// compiler flags, compiler version, etc. This structure is not simply a
619/// `String` due to the fact that some fingerprints cannot be calculated lazily.
620///
621/// Path sources, for example, use the mtime of the corresponding dep-info file
622/// as a fingerprint (all source files must be modified *before* this mtime).
623/// This dep-info file is not generated, however, until after the crate is
624/// compiled. As a result, this structure can be thought of as a fingerprint
625/// to-be. The actual value can be calculated via [`hash_u64()`], but the operation
626/// may fail as some files may not have been generated.
627///
628/// Note that dependencies are taken into account for fingerprints because rustc
629/// requires that whenever an upstream crate is recompiled that all downstream
630/// dependents are also recompiled. This is typically tracked through
631/// [`DependencyQueue`], but it also needs to be retained here because Cargo can
632/// be interrupted while executing, losing the state of the [`DependencyQueue`]
633/// graph.
634///
635/// [`hash_u64()`]: crate::compiler::fingerprint::Fingerprint::hash_u64
636/// [`DependencyQueue`]: crate::util::DependencyQueue
637#[derive(Serialize, Deserialize)]
638pub struct Fingerprint {
639    /// Hash of the version of `rustc` used.
640    rustc: u64,
641    /// Sorted list of cfg features enabled.
642    features: String,
643    /// Sorted list of all the declared cfg features.
644    declared_features: String,
645    /// Hash of the `Target` struct, including the target name,
646    /// package-relative source path, edition, etc.
647    target: u64,
648    /// Hash of the [`Profile`], [`CompileMode`], and any extra flags passed via
649    /// `cargo rustc` or `cargo rustdoc`.
650    ///
651    /// [`Profile`]: crate::workspace::profiles::Profile
652    /// [`CompileMode`]: crate::compiler::CompileMode
653    profile: u64,
654    /// Hash of the path to the base source file. This is relative to the
655    /// workspace root for path members, or absolute for other sources.
656    path: u64,
657    /// Fingerprints of dependencies.
658    deps: Vec<DepFingerprint>,
659    /// Information about the inputs that affect this Unit (such as source
660    /// file mtimes or build script environment variables).
661    local: Mutex<Vec<LocalFingerprint>>,
662    /// Cached hash of the [`Fingerprint`] struct. Used to improve performance
663    /// for hashing.
664    #[serde(skip)]
665    memoized_hash: Mutex<Option<u64>>,
666    /// RUSTFLAGS/RUSTDOCFLAGS environment variable value (or config value).
667    rustflags: Vec<String>,
668    /// Hash of various config settings that change how things are compiled.
669    config: u64,
670    /// The rustc target. This is only relevant for `.json` files, otherwise
671    /// the metadata hash segregates the units.
672    compile_kind: u64,
673    /// Unit index for this fingerprint, used for tracing cascading rebuilds.
674    /// Not persisted to disk as indices can change between builds.
675    #[serde(skip)]
676    index: UnitIndex,
677    /// Description of whether the filesystem status for this unit is up to date
678    /// or should be considered stale.
679    #[serde(skip)]
680    fs_status: FsStatus,
681    /// Files, relative to `target_root`, that are produced by the step that
682    /// this `Fingerprint` represents. This is used to detect when the whole
683    /// fingerprint is out of date if this is missing, or if previous
684    /// fingerprints output files are regenerated and look newer than this one.
685    #[serde(skip)]
686    outputs: Vec<PathBuf>,
687}
688
689/// Indication of the status on the filesystem for a particular unit.
690#[derive(Clone, Default, Debug, Serialize, Deserialize)]
691#[serde(tag = "fs_status", rename_all = "kebab-case")]
692pub enum FsStatus {
693    /// This unit is to be considered stale, even if hash information all
694    /// matches.
695    #[default]
696    Stale,
697
698    /// File system inputs have changed (or are missing), or there were
699    /// changes to the environment variables that affect this unit. See
700    /// the variants of [`StaleItem`] for more information.
701    StaleItem(StaleItem),
702
703    /// A dependency was stale.
704    StaleDependency {
705        unit: UnitIndex,
706        #[serde(with = "serde_file_time")]
707        dep_mtime: FileTime,
708        #[serde(with = "serde_file_time")]
709        max_mtime: FileTime,
710    },
711
712    /// A dependency's fingerprint was stale.
713    StaleDepFingerprint { unit: UnitIndex },
714
715    /// This unit is up-to-date. All outputs and their corresponding mtime are
716    /// listed in the payload here for other dependencies to compare against.
717    #[serde(skip)]
718    UpToDate { mtimes: HashMap<PathBuf, FileTime> },
719}
720
721impl FsStatus {
722    fn up_to_date(&self) -> bool {
723        match self {
724            FsStatus::UpToDate { .. } => true,
725            FsStatus::Stale
726            | FsStatus::StaleItem(_)
727            | FsStatus::StaleDependency { .. }
728            | FsStatus::StaleDepFingerprint { .. } => false,
729        }
730    }
731}
732
733mod serde_file_time {
734    use filetime::FileTime;
735    use serde::Deserialize;
736    use serde::Serialize;
737
738    /// Serialize FileTime as milliseconds with nano.
739    pub(super) fn serialize<S>(ft: &FileTime, s: S) -> Result<S::Ok, S::Error>
740    where
741        S: serde::Serializer,
742    {
743        let secs_as_millis = ft.unix_seconds() as f64 * 1000.0;
744        let nanos_as_millis = ft.nanoseconds() as f64 / 1_000_000.0;
745        (secs_as_millis + nanos_as_millis).serialize(s)
746    }
747
748    /// Deserialize FileTime from milliseconds with nano.
749    pub(super) fn deserialize<'de, D>(d: D) -> Result<FileTime, D::Error>
750    where
751        D: serde::Deserializer<'de>,
752    {
753        let millis = f64::deserialize(d)?;
754        let secs = (millis / 1000.0) as i64;
755        let nanos = ((millis % 1000.0) * 1_000_000.0) as u32;
756        Ok(FileTime::from_unix_time(secs, nanos))
757    }
758}
759
760impl Serialize for DepFingerprint {
761    fn serialize<S>(&self, ser: S) -> Result<S::Ok, S::Error>
762    where
763        S: ser::Serializer,
764    {
765        (
766            &self.pkg_id,
767            &self.name,
768            &self.public,
769            &self.fingerprint.hash_u64(),
770        )
771            .serialize(ser)
772    }
773}
774
775impl<'de> Deserialize<'de> for DepFingerprint {
776    fn deserialize<D>(d: D) -> Result<DepFingerprint, D::Error>
777    where
778        D: de::Deserializer<'de>,
779    {
780        let (pkg_id, name, public, hash) = <(u64, String, bool, u64)>::deserialize(d)?;
781        Ok(DepFingerprint {
782            pkg_id,
783            name: name.into(),
784            public,
785            fingerprint: Arc::new(Fingerprint {
786                memoized_hash: Mutex::new(Some(hash)),
787                ..Fingerprint::new()
788            }),
789            // This field is never read since it's only used in
790            // `check_filesystem` which isn't used by fingerprints loaded from
791            // disk.
792            only_requires_rmeta: false,
793        })
794    }
795}
796
797/// A `LocalFingerprint` represents something that we use to detect direct
798/// changes to a `Fingerprint`.
799///
800/// This is where we track file information, env vars, etc. This
801/// `LocalFingerprint` struct is hashed and if the hash changes will force a
802/// recompile of any fingerprint it's included into. Note that the "local"
803/// terminology comes from the fact that it only has to do with one crate, and
804/// `Fingerprint` tracks the transitive propagation of fingerprint changes.
805///
806/// Note that because this is hashed its contents are carefully managed. Like
807/// mentioned in the above module docs, we don't want to hash absolute paths or
808/// mtime information.
809///
810/// Also note that a `LocalFingerprint` is used in `check_filesystem` to detect
811/// when the filesystem contains stale information (based on mtime currently).
812/// The paths here don't change much between compilations but they're used as
813/// inputs when we probe the filesystem looking at information.
814#[derive(Debug, Serialize, Deserialize, Hash)]
815enum LocalFingerprint {
816    /// This is a precalculated fingerprint which has an opaque string we just
817    /// hash as usual. This variant is primarily used for rustdoc where we
818    /// don't have a dep-info file to compare against.
819    ///
820    /// This is also used for build scripts with no `rerun-if-*` statements, but
821    /// that's overall a mistake and causes bugs in Cargo. We shouldn't use this
822    /// for build scripts.
823    Precalculated(String),
824
825    /// This is used for crate compilations. The `dep_info` file is a relative
826    /// path anchored at `target_root(...)` to the dep-info file that Cargo
827    /// generates (which is a custom serialization after parsing rustc's own
828    /// `dep-info` output).
829    ///
830    /// The `dep_info` file, when present, also lists a number of other files
831    /// for us to look at. If any of those files are newer than this file then
832    /// we need to recompile.
833    ///
834    /// If the `checksum` bool is true then the `dep_info` file is expected to
835    /// contain file checksums instead of file mtimes.
836    CheckDepInfo { dep_info: PathBuf, checksum: bool },
837
838    /// This represents a nonempty set of `rerun-if-changed` annotations printed
839    /// out by a build script. The `output` file is a relative file anchored at
840    /// `target_root(...)` which is the actual output of the build script. That
841    /// output has already been parsed and the paths printed out via
842    /// `rerun-if-changed` are listed in `paths`. The `paths` field is relative
843    /// to `pkg.root()`
844    ///
845    /// This is considered up-to-date if all of the `paths` are older than
846    /// `output`, otherwise we need to recompile.
847    RerunIfChanged {
848        output: PathBuf,
849        paths: Vec<PathBuf>,
850    },
851
852    /// This represents a single `rerun-if-env-changed` annotation printed by a
853    /// build script. The exact env var and value are hashed here. There's no
854    /// filesystem dependence here, and if the values are changed the hash will
855    /// change forcing a recompile.
856    RerunIfEnvChanged { var: String, val: Option<String> },
857}
858
859/// See [`FsStatus::StaleItem`].
860#[derive(Clone, Debug, Serialize, Deserialize)]
861#[serde(tag = "stale_item", rename_all = "kebab-case")]
862pub enum StaleItem {
863    MissingFile {
864        path: PathBuf,
865    },
866    UnableToReadFile {
867        path: PathBuf,
868    },
869    FailedToReadMetadata {
870        path: PathBuf,
871    },
872    FileSizeChanged {
873        path: PathBuf,
874        old_size: u64,
875        new_size: u64,
876    },
877    ChangedFile {
878        reference: PathBuf,
879        #[serde(with = "serde_file_time")]
880        reference_mtime: FileTime,
881        stale: PathBuf,
882        #[serde(with = "serde_file_time")]
883        stale_mtime: FileTime,
884    },
885    ChangedChecksum {
886        source: PathBuf,
887        stored_checksum: Checksum,
888        new_checksum: Checksum,
889    },
890    MissingChecksum {
891        path: PathBuf,
892    },
893    ChangedEnv {
894        var: String,
895        previous: Option<String>,
896        current: Option<String>,
897    },
898}
899
900impl LocalFingerprint {
901    /// Read the environment variable of the given env `key`, and creates a new
902    /// [`LocalFingerprint::RerunIfEnvChanged`] for it. The `env_config` is used firstly
903    /// to check if the env var is set in the config system as some envs need to be overridden.
904    /// If not, it will fallback to `std::env::var`.
905    ///
906    // TODO: `std::env::var` is allowed at this moment. Should figure out
907    // if it makes sense if permitting to read env from the env snapshot.
908    #[allow(clippy::disallowed_methods)]
909    fn from_env<K: AsRef<str>>(
910        key: K,
911        env_config: &Arc<HashMap<String, OsString>>,
912    ) -> LocalFingerprint {
913        let key = key.as_ref();
914        let var = key.to_owned();
915        let val = if let Some(val) = env_config.get(key) {
916            val.to_str().map(ToOwned::to_owned)
917        } else {
918            env::var(key).ok()
919        };
920        LocalFingerprint::RerunIfEnvChanged { var, val }
921    }
922
923    /// Checks dynamically at runtime if this `LocalFingerprint` has a stale
924    /// item inside of it.
925    ///
926    /// The main purpose of this function is to handle two different ways
927    /// fingerprints can be invalidated:
928    ///
929    /// * One is a dependency listed in rustc's dep-info files is invalid. Note
930    ///   that these could either be env vars or files. We check both here.
931    ///
932    /// * Another is the `rerun-if-changed` directive from build scripts. This
933    ///   is where we'll find whether files have actually changed
934    fn find_stale_item(
935        &self,
936        mtime_cache: &mut HashMap<PathBuf, FileTime>,
937        checksum_cache: &mut HashMap<PathBuf, Checksum>,
938        pkg: &Package,
939        build_root: &Path,
940        cargo_exe: &Path,
941        gctx: &GlobalContext,
942    ) -> CargoResult<Option<StaleItem>> {
943        let pkg_root = pkg.root();
944        match self {
945            // We need to parse `dep_info`, learn about the crate's dependencies.
946            //
947            // For each env var we see if our current process's env var still
948            // matches, and for each file we see if any of them are newer than
949            // the `dep_info` file itself whose mtime represents the start of
950            // rustc.
951            LocalFingerprint::CheckDepInfo { dep_info, checksum } => {
952                let dep_info = build_root.join(dep_info);
953                let Some(info) = parse_dep_info(pkg_root, build_root, &dep_info)? else {
954                    return Ok(Some(StaleItem::MissingFile { path: dep_info }));
955                };
956                for (key, previous) in info.env.iter() {
957                    if let Some(value) = pkg.manifest().metadata().env_var(key.as_str()) {
958                        if Some(value.as_ref()) == previous.as_deref() {
959                            continue;
960                        }
961                    }
962
963                    let current = if key == CARGO_ENV {
964                        Some(cargo_exe.to_str().ok_or_else(|| {
965                            format_err!(
966                                "cargo exe path {} must be valid UTF-8",
967                                cargo_exe.display()
968                            )
969                        })?)
970                    } else {
971                        if let Some(value) = gctx.env_config()?.get(key) {
972                            value.to_str()
973                        } else {
974                            gctx.get_env(key).ok()
975                        }
976                    };
977                    if current == previous.as_deref() {
978                        continue;
979                    }
980                    return Ok(Some(StaleItem::ChangedEnv {
981                        var: key.clone(),
982                        previous: previous.clone(),
983                        current: current.map(Into::into),
984                    }));
985                }
986                if *checksum {
987                    Ok(find_stale_file(
988                        mtime_cache,
989                        checksum_cache,
990                        &dep_info,
991                        info.files.iter().map(|(file, checksum)| (file, *checksum)),
992                        *checksum,
993                    ))
994                } else {
995                    Ok(find_stale_file(
996                        mtime_cache,
997                        checksum_cache,
998                        &dep_info,
999                        info.files.into_keys().map(|p| (p, None)),
1000                        *checksum,
1001                    ))
1002                }
1003            }
1004
1005            // We need to verify that no paths listed in `paths` are newer than
1006            // the `output` path itself, or the last time the build script ran.
1007            LocalFingerprint::RerunIfChanged { output, paths } => Ok(find_stale_file(
1008                mtime_cache,
1009                checksum_cache,
1010                &build_root.join(output),
1011                paths.iter().map(|p| (pkg_root.join(p), None)),
1012                false,
1013            )),
1014
1015            // These have no dependencies on the filesystem, and their values
1016            // are included natively in the `Fingerprint` hash so nothing
1017            // tocheck for here.
1018            LocalFingerprint::RerunIfEnvChanged { .. } => Ok(None),
1019            LocalFingerprint::Precalculated(..) => Ok(None),
1020        }
1021    }
1022
1023    fn kind(&self) -> &'static str {
1024        match self {
1025            LocalFingerprint::Precalculated(..) => "precalculated",
1026            LocalFingerprint::CheckDepInfo { .. } => "dep-info",
1027            LocalFingerprint::RerunIfChanged { .. } => "rerun-if-changed",
1028            LocalFingerprint::RerunIfEnvChanged { .. } => "rerun-if-env-changed",
1029        }
1030    }
1031}
1032
1033impl Fingerprint {
1034    fn new() -> Fingerprint {
1035        Fingerprint {
1036            rustc: 0,
1037            target: 0,
1038            profile: 0,
1039            path: 0,
1040            features: String::new(),
1041            declared_features: String::new(),
1042            deps: Vec::new(),
1043            local: Mutex::new(Vec::new()),
1044            memoized_hash: Mutex::new(None),
1045            rustflags: Vec::new(),
1046            config: 0,
1047            compile_kind: 0,
1048            index: UnitIndex::default(),
1049            fs_status: FsStatus::Stale,
1050            outputs: Vec::new(),
1051        }
1052    }
1053
1054    /// For performance reasons fingerprints will memoize their own hash, but
1055    /// there's also internal mutability with its `local` field which can
1056    /// change, for example with build scripts, during a build.
1057    ///
1058    /// This method can be used to bust all memoized hashes just before a build
1059    /// to ensure that after a build completes everything is up-to-date.
1060    pub fn clear_memoized(&self) {
1061        *self.memoized_hash.lock().unwrap() = None;
1062    }
1063
1064    fn hash_u64(&self) -> u64 {
1065        if let Some(s) = *self.memoized_hash.lock().unwrap() {
1066            return s;
1067        }
1068        let ret = util::hash_u64(self);
1069        *self.memoized_hash.lock().unwrap() = Some(ret);
1070        ret
1071    }
1072
1073    /// Compares this fingerprint with an old version which was previously
1074    /// serialized to filesystem.
1075    ///
1076    /// The purpose of this is exclusively to produce a diagnostic message
1077    /// [`DirtyReason`], indicating why we're recompiling something.
1078    fn compare(&self, old: &Fingerprint) -> DirtyReason {
1079        if self.rustc != old.rustc {
1080            return DirtyReason::RustcChanged;
1081        }
1082        if self.features != old.features {
1083            return DirtyReason::FeaturesChanged {
1084                old: old.features.clone(),
1085                new: self.features.clone(),
1086            };
1087        }
1088        if self.declared_features != old.declared_features {
1089            return DirtyReason::DeclaredFeaturesChanged {
1090                old: old.declared_features.clone(),
1091                new: self.declared_features.clone(),
1092            };
1093        }
1094        if self.target != old.target {
1095            return DirtyReason::TargetConfigurationChanged;
1096        }
1097        if self.path != old.path {
1098            return DirtyReason::PathToSourceChanged;
1099        }
1100        if self.profile != old.profile {
1101            return DirtyReason::ProfileConfigurationChanged;
1102        }
1103        if self.rustflags != old.rustflags {
1104            return DirtyReason::RustflagsChanged {
1105                old: old.rustflags.clone(),
1106                new: self.rustflags.clone(),
1107            };
1108        }
1109        if self.config != old.config {
1110            return DirtyReason::ConfigSettingsChanged;
1111        }
1112        if self.compile_kind != old.compile_kind {
1113            return DirtyReason::CompileKindChanged;
1114        }
1115        let my_local = self.local.lock().unwrap();
1116        let old_local = old.local.lock().unwrap();
1117        if my_local.len() != old_local.len() {
1118            return DirtyReason::LocalLengthsChanged;
1119        }
1120        for (new, old) in my_local.iter().zip(old_local.iter()) {
1121            match (new, old) {
1122                (LocalFingerprint::Precalculated(a), LocalFingerprint::Precalculated(b)) => {
1123                    if a != b {
1124                        return DirtyReason::PrecalculatedComponentsChanged {
1125                            old: b.to_string(),
1126                            new: a.to_string(),
1127                        };
1128                    }
1129                }
1130                (
1131                    LocalFingerprint::CheckDepInfo {
1132                        dep_info: a_dep,
1133                        checksum: checksum_a,
1134                    },
1135                    LocalFingerprint::CheckDepInfo {
1136                        dep_info: b_dep,
1137                        checksum: checksum_b,
1138                    },
1139                ) => {
1140                    if a_dep != b_dep {
1141                        return DirtyReason::DepInfoOutputChanged {
1142                            old: b_dep.clone(),
1143                            new: a_dep.clone(),
1144                        };
1145                    }
1146                    if checksum_a != checksum_b {
1147                        return DirtyReason::ChecksumUseChanged { old: *checksum_b };
1148                    }
1149                }
1150                (
1151                    LocalFingerprint::RerunIfChanged {
1152                        output: a_out,
1153                        paths: a_paths,
1154                    },
1155                    LocalFingerprint::RerunIfChanged {
1156                        output: b_out,
1157                        paths: b_paths,
1158                    },
1159                ) => {
1160                    if a_out != b_out {
1161                        return DirtyReason::RerunIfChangedOutputFileChanged {
1162                            old: b_out.clone(),
1163                            new: a_out.clone(),
1164                        };
1165                    }
1166                    if a_paths != b_paths {
1167                        return DirtyReason::RerunIfChangedOutputPathsChanged {
1168                            old: b_paths.clone(),
1169                            new: a_paths.clone(),
1170                        };
1171                    }
1172                }
1173                (
1174                    LocalFingerprint::RerunIfEnvChanged {
1175                        var: a_key,
1176                        val: a_value,
1177                    },
1178                    LocalFingerprint::RerunIfEnvChanged {
1179                        var: b_key,
1180                        val: b_value,
1181                    },
1182                ) => {
1183                    if *a_key != *b_key {
1184                        return DirtyReason::EnvVarsChanged {
1185                            old: b_key.clone(),
1186                            new: a_key.clone(),
1187                        };
1188                    }
1189                    if *a_value != *b_value {
1190                        return DirtyReason::EnvVarChanged {
1191                            name: a_key.clone(),
1192                            old_value: b_value.clone(),
1193                            new_value: a_value.clone(),
1194                        };
1195                    }
1196                }
1197                (a, b) => {
1198                    return DirtyReason::LocalFingerprintTypeChanged {
1199                        old: b.kind().to_owned(),
1200                        new: a.kind().to_owned(),
1201                    };
1202                }
1203            }
1204        }
1205
1206        if self.deps.len() != old.deps.len() {
1207            return DirtyReason::NumberOfDependenciesChanged {
1208                old: old.deps.len(),
1209                new: self.deps.len(),
1210            };
1211        }
1212        for (a, b) in self.deps.iter().zip(old.deps.iter()) {
1213            if a.name != b.name {
1214                return DirtyReason::UnitDependencyNameChanged {
1215                    old: b.name,
1216                    new: a.name,
1217                };
1218            }
1219
1220            if a.fingerprint.hash_u64() != b.fingerprint.hash_u64() {
1221                return DirtyReason::UnitDependencyInfoChanged {
1222                    unit: a.fingerprint.index,
1223                };
1224            }
1225        }
1226
1227        if !self.fs_status.up_to_date() {
1228            return DirtyReason::FsStatusOutdated(self.fs_status.clone());
1229        }
1230
1231        // This typically means some filesystem modifications happened or
1232        // something transitive was odd. In general we should strive to provide
1233        // a better error message than this, so if you see this message a lot it
1234        // likely means this method needs to be updated!
1235        DirtyReason::NothingObvious
1236    }
1237
1238    /// Dynamically inspect the local filesystem to update the `fs_status` field
1239    /// of this `Fingerprint`.
1240    ///
1241    /// This function is used just after a `Fingerprint` is constructed to check
1242    /// the local state of the filesystem and propagate any dirtiness from
1243    /// dependencies up to this unit as well. This function assumes that the
1244    /// unit starts out as [`FsStatus::Stale`] and then it will optionally switch
1245    /// it to `UpToDate` if it can.
1246    fn check_filesystem(
1247        &mut self,
1248        mtime_cache: &mut HashMap<PathBuf, FileTime>,
1249        checksum_cache: &mut HashMap<PathBuf, Checksum>,
1250        pkg: &Package,
1251        build_root: &Path,
1252        cargo_exe: &Path,
1253        gctx: &GlobalContext,
1254    ) -> CargoResult<()> {
1255        assert!(!self.fs_status.up_to_date());
1256
1257        let pkg_root = pkg.root();
1258        let mut mtimes = HashMap::default();
1259
1260        // Get the `mtime` of all outputs. Optionally update their mtime
1261        // afterwards based on the `mtime_on_use` flag. Afterwards we want the
1262        // minimum mtime as it's the one we'll be comparing to inputs and
1263        // dependencies.
1264        for output in self.outputs.iter() {
1265            let Ok(mtime) = paths::mtime(output) else {
1266                // This path failed to report its `mtime`. It probably doesn't
1267                // exists, so leave ourselves as stale and bail out.
1268                let item = StaleItem::FailedToReadMetadata {
1269                    path: output.clone(),
1270                };
1271                self.fs_status = FsStatus::StaleItem(item);
1272                return Ok(());
1273            };
1274            assert!(mtimes.insert(output.clone(), mtime).is_none());
1275        }
1276
1277        let opt_max = mtimes.iter().max_by_key(|kv| kv.1);
1278        let Some((max_path, max_mtime)) = opt_max else {
1279            // We had no output files. This means we're an overridden build
1280            // script and we're just always up to date because we aren't
1281            // watching the filesystem.
1282            self.fs_status = FsStatus::UpToDate { mtimes };
1283            return Ok(());
1284        };
1285        debug!(
1286            "max output mtime for {:?} is {:?} {}",
1287            pkg_root, max_path, max_mtime
1288        );
1289
1290        for dep in self.deps.iter() {
1291            let dep_mtimes = match &dep.fingerprint.fs_status {
1292                FsStatus::UpToDate { mtimes } => mtimes,
1293                // If our dependency is stale, so are we, so bail out.
1294                FsStatus::Stale
1295                | FsStatus::StaleItem(_)
1296                | FsStatus::StaleDependency { .. }
1297                | FsStatus::StaleDepFingerprint { .. } => {
1298                    self.fs_status = FsStatus::StaleDepFingerprint {
1299                        unit: dep.fingerprint.index,
1300                    };
1301                    return Ok(());
1302                }
1303            };
1304
1305            // If our dependency edge only requires the rmeta file to be present
1306            // then we only need to look at that one output file, otherwise we
1307            // need to consider all output files to see if we're out of date.
1308            let (dep_path, dep_mtime) = if dep.only_requires_rmeta {
1309                dep_mtimes
1310                    .iter()
1311                    .find(|(path, _mtime)| {
1312                        path.extension().and_then(|s| s.to_str()) == Some("rmeta")
1313                    })
1314                    .expect("failed to find rmeta")
1315            } else {
1316                match dep_mtimes.iter().max_by_key(|kv| kv.1) {
1317                    Some(dep_mtime) => dep_mtime,
1318                    // If our dependencies is up to date and has no filesystem
1319                    // interactions, then we can move on to the next dependency.
1320                    None => continue,
1321                }
1322            };
1323            debug!(
1324                "max dep mtime for {:?} is {:?} {}",
1325                pkg_root, dep_path, dep_mtime
1326            );
1327
1328            // If the dependency is newer than our own output then it was
1329            // recompiled previously. We transitively become stale ourselves in
1330            // that case, so bail out.
1331            //
1332            // Note that this comparison should probably be `>=`, not `>`, but
1333            // for a discussion of why it's `>` see the discussion about #5918
1334            // below in `find_stale`.
1335            if dep_mtime > max_mtime {
1336                info!(
1337                    "dependency on `{}` is newer than we are {} > {} {:?}",
1338                    dep.name, dep_mtime, max_mtime, pkg_root
1339                );
1340
1341                self.fs_status = FsStatus::StaleDependency {
1342                    unit: dep.fingerprint.index,
1343                    dep_mtime: *dep_mtime,
1344                    max_mtime: *max_mtime,
1345                };
1346
1347                return Ok(());
1348            }
1349        }
1350
1351        // If we reached this far then all dependencies are up to date. Check
1352        // all our `LocalFingerprint` information to see if we have any stale
1353        // files for this package itself. If we do find something log a helpful
1354        // message and bail out so we stay stale.
1355        for local in self.local.get_mut().unwrap().iter() {
1356            if let Some(item) = local.find_stale_item(
1357                mtime_cache,
1358                checksum_cache,
1359                pkg,
1360                build_root,
1361                cargo_exe,
1362                gctx,
1363            )? {
1364                item.log();
1365                self.fs_status = FsStatus::StaleItem(item);
1366                return Ok(());
1367            }
1368        }
1369
1370        // Everything was up to date! Record such.
1371        self.fs_status = FsStatus::UpToDate { mtimes };
1372        debug!("filesystem up-to-date {:?}", pkg_root);
1373
1374        Ok(())
1375    }
1376}
1377
1378impl hash::Hash for Fingerprint {
1379    fn hash<H: Hasher>(&self, h: &mut H) {
1380        let Fingerprint {
1381            rustc,
1382            ref features,
1383            ref declared_features,
1384            target,
1385            path,
1386            profile,
1387            ref deps,
1388            ref local,
1389            config,
1390            compile_kind,
1391            ref rustflags,
1392            ..
1393        } = *self;
1394        let local = local.lock().unwrap();
1395        (
1396            rustc,
1397            features,
1398            declared_features,
1399            target,
1400            path,
1401            profile,
1402            &*local,
1403            config,
1404            compile_kind,
1405            rustflags,
1406        )
1407            .hash(h);
1408
1409        h.write_usize(deps.len());
1410        for DepFingerprint {
1411            pkg_id,
1412            name,
1413            public,
1414            fingerprint,
1415            only_requires_rmeta: _, // static property, no need to hash
1416        } in deps
1417        {
1418            pkg_id.hash(h);
1419            name.hash(h);
1420            public.hash(h);
1421            // use memoized dep hashes to avoid exponential blowup
1422            h.write_u64(fingerprint.hash_u64());
1423        }
1424    }
1425}
1426
1427impl DepFingerprint {
1428    fn new(
1429        build_runner: &mut BuildRunner<'_, '_>,
1430        parent: &Unit,
1431        dep: &UnitDep,
1432    ) -> CargoResult<DepFingerprint> {
1433        let fingerprint = calculate(build_runner, &dep.unit)?;
1434        // We need to be careful about what we hash here. We have a goal of
1435        // supporting renaming a project directory and not rebuilding
1436        // everything. To do that, however, we need to make sure that the cwd
1437        // doesn't make its way into any hashes, and one source of that is the
1438        // `SourceId` for `path` packages.
1439        //
1440        // We already have a requirement that `path` packages all have unique
1441        // names (sort of for this same reason), so if the package source is a
1442        // `path` then we just hash the name, but otherwise we hash the full
1443        // id as it won't change when the directory is renamed.
1444        let pkg_id = if dep.unit.pkg.package_id().source_id().is_path() {
1445            util::hash_u64(dep.unit.pkg.package_id().name())
1446        } else {
1447            util::hash_u64(dep.unit.pkg.package_id())
1448        };
1449
1450        Ok(DepFingerprint {
1451            pkg_id,
1452            name: dep.extern_crate_name,
1453            public: dep.public,
1454            fingerprint,
1455            only_requires_rmeta: build_runner.only_requires_rmeta(parent, &dep.unit),
1456        })
1457    }
1458}
1459
1460impl StaleItem {
1461    /// Use the `log` crate to log a hopefully helpful message in diagnosing
1462    /// what file is considered stale and why. This is intended to be used in
1463    /// conjunction with `CARGO_LOG` to determine why Cargo is recompiling
1464    /// something. Currently there's no user-facing usage of this other than
1465    /// that.
1466    fn log(&self) {
1467        match self {
1468            StaleItem::MissingFile { path } => {
1469                info!("stale: missing {:?}", path);
1470            }
1471            StaleItem::UnableToReadFile { path } => {
1472                info!("stale: unable to read {:?}", path);
1473            }
1474            StaleItem::FailedToReadMetadata { path } => {
1475                info!("stale: couldn't read metadata {:?}", path);
1476            }
1477            StaleItem::ChangedFile {
1478                reference,
1479                reference_mtime,
1480                stale,
1481                stale_mtime,
1482            } => {
1483                info!("stale: changed {:?}", stale);
1484                info!("          (vs) {:?}", reference);
1485                info!("               {:?} < {:?}", reference_mtime, stale_mtime);
1486            }
1487            StaleItem::FileSizeChanged {
1488                path,
1489                new_size,
1490                old_size,
1491            } => {
1492                info!("stale: changed {:?}", path);
1493                info!("prior file size {old_size}");
1494                info!("  new file size {new_size}");
1495            }
1496            StaleItem::ChangedChecksum {
1497                source,
1498                stored_checksum,
1499                new_checksum,
1500            } => {
1501                info!("stale: changed {:?}", source);
1502                info!("prior checksum {stored_checksum}");
1503                info!("  new checksum {new_checksum}");
1504            }
1505            StaleItem::MissingChecksum { path } => {
1506                info!("stale: no prior checksum {:?}", path);
1507            }
1508            StaleItem::ChangedEnv {
1509                var,
1510                previous,
1511                current,
1512            } => {
1513                info!("stale: changed env {:?}", var);
1514                info!("       {:?} != {:?}", previous, current);
1515            }
1516        }
1517    }
1518}
1519
1520/// Calculates the fingerprint for a [`Unit`].
1521///
1522/// This fingerprint is used by Cargo to learn about when information such as:
1523///
1524/// * A non-path package changes (changes version, changes revision, etc).
1525/// * Any dependency changes
1526/// * The compiler changes
1527/// * The set of features a package is built with changes
1528/// * The profile a target is compiled with changes (e.g., opt-level changes)
1529/// * Any other compiler flags change that will affect the result
1530///
1531/// Information like file modification time is only calculated for path
1532/// dependencies.
1533fn calculate(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<Arc<Fingerprint>> {
1534    // This function is slammed quite a lot, so the result is memoized.
1535    if let Some(s) = build_runner.fingerprints.get(unit) {
1536        return Ok(Arc::clone(s));
1537    }
1538    let mut fingerprint = if unit.mode.is_run_custom_build() {
1539        calculate_run_custom_build(build_runner, unit)?
1540    } else if unit.mode.is_doc_test() {
1541        panic!("doc tests do not fingerprint");
1542    } else {
1543        calculate_normal(build_runner, unit)?
1544    };
1545
1546    // After we built the initial `Fingerprint` be sure to update the
1547    // `fs_status` field of it.
1548    let build_root = build_root(build_runner);
1549    let cargo_exe = build_runner.bcx.gctx.cargo_exe()?;
1550    fingerprint.check_filesystem(
1551        &mut build_runner.mtime_cache,
1552        &mut build_runner.checksum_cache,
1553        &unit.pkg,
1554        &build_root,
1555        cargo_exe,
1556        build_runner.bcx.gctx,
1557    )?;
1558
1559    let fingerprint = Arc::new(fingerprint);
1560    build_runner
1561        .fingerprints
1562        .insert(unit.clone(), Arc::clone(&fingerprint));
1563    Ok(fingerprint)
1564}
1565
1566/// Calculate a fingerprint for a "normal" unit, or anything that's not a build
1567/// script. This is an internal helper of [`calculate`], don't call directly.
1568fn calculate_normal(
1569    build_runner: &mut BuildRunner<'_, '_>,
1570    unit: &Unit,
1571) -> CargoResult<Fingerprint> {
1572    let deps = {
1573        // Recursively calculate the fingerprint for all of our dependencies.
1574        //
1575        // Skip fingerprints of binaries because they don't actually induce a
1576        // recompile, they're just dependencies in the sense that they need to be
1577        // built. The only exception here are artifact dependencies,
1578        // which is an actual dependency that needs a recompile.
1579        //
1580        // Create Vec since mutable build_runner is needed in closure.
1581        let deps = Vec::from(build_runner.unit_deps(unit));
1582        let mut deps = deps
1583            .into_iter()
1584            .filter(|dep| !dep.unit.target.is_bin() || dep.unit.artifact.is_true())
1585            .map(|dep| DepFingerprint::new(build_runner, unit, &dep))
1586            .collect::<CargoResult<Vec<_>>>()?;
1587        deps.sort_by(|a, b| a.pkg_id.cmp(&b.pkg_id));
1588        deps
1589    };
1590
1591    // Afterwards calculate our own fingerprint information.
1592    let build_root = build_root(build_runner);
1593    let is_any_doc_gen = unit.mode.is_doc() || unit.mode.is_doc_scrape();
1594    let rustdoc_depinfo_enabled = build_runner.bcx.gctx.cli_unstable().rustdoc_depinfo;
1595    let local = if is_any_doc_gen && !rustdoc_depinfo_enabled {
1596        // rustdoc does not have dep-info files.
1597        let fingerprint = pkg_fingerprint(build_runner.bcx, &unit.pkg).with_context(|| {
1598            format!(
1599                "failed to determine package fingerprint for documenting {}",
1600                unit.pkg
1601            )
1602        })?;
1603        vec![LocalFingerprint::Precalculated(fingerprint)]
1604    } else {
1605        let dep_info = dep_info_loc(build_runner, unit);
1606        let dep_info = dep_info.strip_prefix(&build_root).unwrap().to_path_buf();
1607        vec![LocalFingerprint::CheckDepInfo {
1608            dep_info,
1609            checksum: build_runner.bcx.gctx.cli_unstable().checksum_freshness,
1610        }]
1611    };
1612
1613    // Figure out what the outputs of our unit is, and we'll be storing them
1614    // into the fingerprint as well.
1615    let outputs = build_runner
1616        .outputs(unit)?
1617        .iter()
1618        .filter(|output| !matches!(output.flavor, FileFlavor::DebugInfo | FileFlavor::Auxiliary))
1619        .map(|output| output.path.clone())
1620        .collect();
1621
1622    // Fill out a bunch more information that we'll be tracking typically
1623    // hashed to take up less space on disk as we just need to know when things
1624    // change.
1625    let extra_flags = if unit.mode.is_doc() || unit.mode.is_doc_scrape() {
1626        &unit.rustdocflags
1627    } else {
1628        &unit.rustflags
1629    }
1630    .to_vec();
1631
1632    let profile_hash = util::hash_u64((
1633        &unit.profile,
1634        unit.mode,
1635        build_runner.bcx.extra_args_for(unit),
1636        build_runner.lto[unit],
1637        unit.pkg.manifest().lint_rustflags(),
1638        unit.profile
1639            .trim_paths
1640            .as_ref()
1641            .filter(|trim_paths| !trim_paths.is_none())
1642            .map(|_| {
1643                build_runner
1644                    .bcx
1645                    .gctx
1646                    .get_env(super::trim_paths::WS_REMAP_ENV)
1647                    .ok()
1648                    .filter(|prefix| !prefix.is_empty())
1649            }),
1650    ));
1651    let mut config = StableHasher::new();
1652    let linker = if unit.target.for_host() && !build_runner.bcx.gctx.target_applies_to_host()? {
1653        build_runner.compilation.host_linker()
1654    } else {
1655        build_runner.compilation.target_linker(unit.kind)
1656    };
1657    if let Some(linker) = linker {
1658        linker.hash(&mut config);
1659    }
1660    if unit.mode.is_doc() && build_runner.bcx.gctx.cli_unstable().rustdoc_map {
1661        if let Ok(map) = build_runner.bcx.gctx.doc_extern_map() {
1662            map.hash(&mut config);
1663        }
1664    }
1665    if let Some(allow_features) = &build_runner.bcx.gctx.cli_unstable().allow_features {
1666        allow_features.hash(&mut config);
1667    }
1668    // -Zpublic-dependency changes how library units pass dependency privacy
1669    // to rustc via `--extern`.
1670    (unit.target.is_lib()
1671        && build_runner.unit_deps(unit).iter().any(|dep| !dep.public)
1672        && super::is_public_dependency_enabled(build_runner, unit))
1673    .hash(&mut config);
1674    // -Zembed-metadata changes how all units are compiled, and it also changes how we tell
1675    // rustc to link to deps using `--extern`. If it changes, we should rebuild everything.
1676    build_runner
1677        .bcx
1678        .gctx
1679        .should_embed_metadata()
1680        .not()
1681        .hash(&mut config);
1682
1683    let compile_kind = unit.kind.fingerprint_hash();
1684    let mut declared_features = unit.pkg.summary().features().keys().collect::<Vec<_>>();
1685    declared_features.sort(); // to avoid useless rebuild if the user orders it's features
1686    // differently
1687    Ok(Fingerprint {
1688        rustc: util::hash_u64(&build_runner.bcx.rustc().verbose_version),
1689        target: util::hash_u64(&unit.target),
1690        profile: profile_hash,
1691        // Note that .0 is hashed here, not .1 which is the cwd. That doesn't
1692        // actually affect the output artifact so there's no need to hash it.
1693        path: util::hash_u64(path_args(build_runner.bcx.ws, unit).0),
1694        features: format!("{:?}", unit.features),
1695        declared_features: format!("{declared_features:?}"),
1696        deps,
1697        local: Mutex::new(local),
1698        memoized_hash: Mutex::new(None),
1699        config: Hasher::finish(&config),
1700        compile_kind,
1701        index: build_runner.bcx.unit_to_index[unit],
1702        rustflags: extra_flags,
1703        fs_status: FsStatus::Stale,
1704        outputs,
1705    })
1706}
1707
1708/// Calculate a fingerprint for an "execute a build script" unit.  This is an
1709/// internal helper of [`calculate`], don't call directly.
1710fn calculate_run_custom_build(
1711    build_runner: &mut BuildRunner<'_, '_>,
1712    unit: &Unit,
1713) -> CargoResult<Fingerprint> {
1714    assert!(unit.mode.is_run_custom_build());
1715    // Using the `BuildDeps` information we'll have previously parsed and
1716    // inserted into `build_explicit_deps` built an initial snapshot of the
1717    // `LocalFingerprint` list for this build script. If we previously executed
1718    // the build script this means we'll be watching files and env vars.
1719    // Otherwise if we haven't previously executed it we'll just start watching
1720    // the whole crate.
1721    let (gen_local, overridden) = build_script_local_fingerprints(build_runner, unit)?;
1722    let deps = &build_runner.build_explicit_deps[unit];
1723    let local = (gen_local)(
1724        deps,
1725        Some(&|| {
1726            const IO_ERR_MESSAGE: &str = "\
1727An I/O error happened. Please make sure you can access the file.
1728
1729By default, if your project contains a build script, cargo scans all files in
1730it to determine whether a rebuild is needed. If you don't expect to access the
1731file, specify `rerun-if-changed` in your build script.
1732See https://doc.rust-lang.org/cargo/reference/build-scripts.html#rerun-if-changed for more information.";
1733            pkg_fingerprint(build_runner.bcx, &unit.pkg).map_err(|err| {
1734                let mut message = format!("failed to determine package fingerprint for build script for {}", unit.pkg);
1735                if err.root_cause().is::<io::Error>() {
1736                    message = format!("{}\n{}", message, IO_ERR_MESSAGE)
1737                }
1738                err.context(message)
1739            })
1740        }),
1741    )?
1742    .unwrap();
1743    let output = deps.build_script_output.clone();
1744
1745    // Include any dependencies of our execution, which is typically just the
1746    // compilation of the build script itself. (if the build script changes we
1747    // should be rerun!). Note though that if we're an overridden build script
1748    // we have no dependencies so no need to recurse in that case.
1749    let deps = if overridden {
1750        // Overridden build scripts don't need to track deps.
1751        vec![]
1752    } else {
1753        // Create Vec since mutable build_runner is needed in closure.
1754        let deps = Vec::from(build_runner.unit_deps(unit));
1755        deps.into_iter()
1756            .map(|dep| DepFingerprint::new(build_runner, unit, &dep))
1757            .collect::<CargoResult<Vec<_>>>()?
1758    };
1759
1760    let rustflags = unit.rustflags.to_vec();
1761
1762    Ok(Fingerprint {
1763        local: Mutex::new(local),
1764        rustc: util::hash_u64(&build_runner.bcx.rustc().verbose_version),
1765        deps,
1766        outputs: if overridden { Vec::new() } else { vec![output] },
1767        rustflags,
1768        index: build_runner.bcx.unit_to_index[unit],
1769
1770        // Most of the other info is blank here as we don't really include it
1771        // in the execution of the build script, but... this may be a latent
1772        // bug in Cargo.
1773        ..Fingerprint::new()
1774    })
1775}
1776
1777/// Get ready to compute the [`LocalFingerprint`] values
1778/// for a [`RunCustomBuild`] unit.
1779///
1780/// This function has, what's on the surface, a seriously wonky interface.
1781/// You'll call this function and it'll return a closure and a boolean. The
1782/// boolean is pretty simple in that it indicates whether the `unit` has been
1783/// overridden via `.cargo/config.toml`. The closure is much more complicated.
1784///
1785/// This closure is intended to capture any local state necessary to compute
1786/// the `LocalFingerprint` values for this unit. It is `Send` and `'static` to
1787/// be sent to other threads as well (such as when we're executing build
1788/// scripts). That deduplication is the rationale for the closure at least.
1789///
1790/// The arguments to the closure are a bit weirder, though, and I'll apologize
1791/// in advance for the weirdness too. The first argument to the closure is a
1792/// `&BuildDeps`. This is the parsed version of a build script, and when Cargo
1793/// starts up this is cached from previous runs of a build script.  After a
1794/// build script executes the output file is reparsed and passed in here.
1795///
1796/// The second argument is the weirdest, it's *optionally* a closure to
1797/// call [`pkg_fingerprint`]. The `pkg_fingerprint` requires access to
1798/// "source map" located in `Context`. That's very non-`'static` and
1799/// non-`Send`, so it can't be used on other threads, such as when we invoke
1800/// this after a build script has finished. The `Option` allows us to for sure
1801/// calculate it on the main thread at the beginning, and then swallow the bug
1802/// for now where a worker thread after a build script has finished doesn't
1803/// have access. Ideally there would be no second argument or it would be more
1804/// "first class" and not an `Option` but something that can be sent between
1805/// threads. In any case, it's a bug for now.
1806///
1807/// This isn't the greatest of interfaces, and if there's suggestions to
1808/// improve please do so!
1809///
1810/// FIXME(#6779) - see all the words above
1811///
1812/// [`RunCustomBuild`]: crate::compiler::CompileMode::RunCustomBuild
1813fn build_script_local_fingerprints(
1814    build_runner: &mut BuildRunner<'_, '_>,
1815    unit: &Unit,
1816) -> CargoResult<(
1817    Box<
1818        dyn FnOnce(
1819                &BuildDeps,
1820                Option<&dyn Fn() -> CargoResult<String>>,
1821            ) -> CargoResult<Option<Vec<LocalFingerprint>>>
1822            + Send,
1823    >,
1824    bool,
1825)> {
1826    assert!(unit.mode.is_run_custom_build());
1827    // First up, if this build script is entirely overridden, then we just
1828    // return the hash of what we overrode it with. This is the easy case!
1829    if let Some(fingerprint) = build_script_override_fingerprint(build_runner, unit) {
1830        debug!("override local fingerprints deps {}", unit.pkg);
1831        return Ok((
1832            Box::new(
1833                move |_: &BuildDeps, _: Option<&dyn Fn() -> CargoResult<String>>| {
1834                    Ok(Some(vec![fingerprint]))
1835                },
1836            ),
1837            true, // this is an overridden build script
1838        ));
1839    }
1840
1841    // ... Otherwise this is a "real" build script and we need to return a real
1842    // closure. Our returned closure classifies the build script based on
1843    // whether it prints `rerun-if-*`. If it *doesn't* print this it's where the
1844    // magical second argument comes into play, which fingerprints a whole
1845    // package. Remember that the fact that this is an `Option` is a bug, but a
1846    // longstanding bug, in Cargo. Recent refactorings just made it painfully
1847    // obvious.
1848    let pkg_root = unit.pkg.root().to_path_buf();
1849    let build_dir = build_root(build_runner);
1850    let env_config = Arc::clone(build_runner.bcx.gctx.env_config()?);
1851    let calculate =
1852        move |deps: &BuildDeps, pkg_fingerprint: Option<&dyn Fn() -> CargoResult<String>>| {
1853            if deps.rerun_if_changed.is_empty() && deps.rerun_if_env_changed.is_empty() {
1854                match pkg_fingerprint {
1855                    // FIXME: this is somewhat buggy with respect to docker and
1856                    // weird filesystems. The `Precalculated` variant
1857                    // constructed below will, for `path` dependencies, contain
1858                    // a stringified version of the mtime for the local crate.
1859                    // This violates one of the things we describe in this
1860                    // module's doc comment, never hashing mtimes. We should
1861                    // figure out a better scheme where a package fingerprint
1862                    // may be a string (like for a registry) or a list of files
1863                    // (like for a path dependency). Those list of files would
1864                    // be stored here rather than the mtime of them.
1865                    Some(f) => {
1866                        let s = f()?;
1867                        debug!(
1868                            "old local fingerprints deps {:?} precalculated={:?}",
1869                            pkg_root, s
1870                        );
1871                        return Ok(Some(vec![LocalFingerprint::Precalculated(s)]));
1872                    }
1873                    None => return Ok(None),
1874                }
1875            }
1876
1877            // Ok so now we're in "new mode" where we can have files listed as
1878            // dependencies as well as env vars listed as dependencies. Process
1879            // them all here.
1880            Ok(Some(local_fingerprints_deps(
1881                deps,
1882                &build_dir,
1883                &pkg_root,
1884                &env_config,
1885            )))
1886        };
1887
1888    // Note that `false` == "not overridden"
1889    Ok((Box::new(calculate), false))
1890}
1891
1892/// Create a [`LocalFingerprint`] for an overridden build script.
1893/// Returns None if it is not overridden.
1894fn build_script_override_fingerprint(
1895    build_runner: &mut BuildRunner<'_, '_>,
1896    unit: &Unit,
1897) -> Option<LocalFingerprint> {
1898    // Build script output is only populated at this stage when it is
1899    // overridden.
1900    let build_script_outputs = build_runner.build_script_outputs.lock().unwrap();
1901    let metadata = build_runner.get_run_build_script_metadata(unit);
1902    // Returns None if it is not overridden.
1903    let output = build_script_outputs.get(metadata)?;
1904    let s = format!(
1905        "overridden build state with hash: {}",
1906        util::hash_u64(output)
1907    );
1908    Some(LocalFingerprint::Precalculated(s))
1909}
1910
1911/// Compute the [`LocalFingerprint`] values for a [`RunCustomBuild`] unit for
1912/// non-overridden new-style build scripts only. This is only used when `deps`
1913/// is already known to have a nonempty `rerun-if-*` somewhere.
1914///
1915/// [`RunCustomBuild`]: crate::compiler::CompileMode::RunCustomBuild
1916fn local_fingerprints_deps(
1917    deps: &BuildDeps,
1918    build_root: &Path,
1919    pkg_root: &Path,
1920    env_config: &Arc<HashMap<String, OsString>>,
1921) -> Vec<LocalFingerprint> {
1922    debug!("new local fingerprints deps {:?}", pkg_root);
1923    let mut local = Vec::new();
1924
1925    if !deps.rerun_if_changed.is_empty() {
1926        // Note that like the module comment above says we are careful to never
1927        // store an absolute path in `LocalFingerprint`, so ensure that we strip
1928        // absolute prefixes from them.
1929        let output = deps
1930            .build_script_output
1931            .strip_prefix(build_root)
1932            .unwrap()
1933            .to_path_buf();
1934        let paths = deps
1935            .rerun_if_changed
1936            .iter()
1937            .map(|p| p.strip_prefix(pkg_root).unwrap_or(p).to_path_buf())
1938            .collect();
1939        local.push(LocalFingerprint::RerunIfChanged { output, paths });
1940    }
1941
1942    local.extend(
1943        deps.rerun_if_env_changed
1944            .iter()
1945            .map(|s| LocalFingerprint::from_env(s, env_config)),
1946    );
1947
1948    local
1949}
1950
1951/// Writes the short fingerprint hash value to `<loc>`
1952/// and logs detailed JSON information to `<loc>.json`.
1953fn write_fingerprint(loc: &Path, fingerprint: &Fingerprint) -> CargoResult<()> {
1954    debug_assert_ne!(fingerprint.rustc, 0);
1955    // fingerprint::new().rustc == 0, make sure it doesn't make it to the file system.
1956    // This is mostly so outside tools can reliably find out what rust version this file is for,
1957    // as we can use the full hash.
1958    let hash = fingerprint.hash_u64();
1959    debug!("write fingerprint ({:x}) : {}", hash, loc.display());
1960    paths::write(loc, util::to_hex(hash).as_bytes())?;
1961
1962    let json = serde_json::to_string(fingerprint).unwrap();
1963    if cfg!(debug_assertions) {
1964        let f: Fingerprint = serde_json::from_str(&json).unwrap();
1965        assert_eq!(f.hash_u64(), hash);
1966    }
1967    paths::write(&loc.with_extension("json"), json.as_bytes())?;
1968    Ok(())
1969}
1970
1971/// Prepare for work when a package starts to build
1972pub fn prepare_init(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<()> {
1973    let new1 = build_runner.files().fingerprint_dir(unit);
1974
1975    // Doc tests have no output, thus no fingerprint.
1976    if !new1.exists() && !unit.mode.is_doc_test() {
1977        paths::create_dir_all(&new1)?;
1978    }
1979
1980    Ok(())
1981}
1982
1983/// Returns the location that the dep-info file will show up at
1984/// for the [`Unit`] specified.
1985pub fn dep_info_loc(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) -> PathBuf {
1986    build_runner.files().fingerprint_file_path(unit, "dep-")
1987}
1988
1989/// Returns an absolute path that build directory.
1990/// All paths are rewritten to be relative to this.
1991fn build_root(build_runner: &BuildRunner<'_, '_>) -> PathBuf {
1992    build_runner.bcx.ws.build_dir().into_path_unlocked()
1993}
1994
1995/// Reads the value from the old fingerprint hash file and compare.
1996///
1997/// If dirty, it then restores the detailed information
1998/// from the fingerprint JSON file, and provides an rich dirty reason.
1999fn compare_old_fingerprint(
2000    unit: &Unit,
2001    old_hash_path: &Path,
2002    new_fingerprint: &Fingerprint,
2003    mtime_on_use: bool,
2004    forced: bool,
2005) -> FingerprintComparison {
2006    if mtime_on_use {
2007        // update the mtime so other cleaners know we used it
2008        let t = FileTime::from_system_time(SystemTime::now());
2009        debug!("mtime-on-use forcing {:?} to {}", old_hash_path, t);
2010        paths::set_file_time_no_err(old_hash_path, t);
2011    }
2012
2013    let compare = _compare_old_fingerprint(old_hash_path, new_fingerprint);
2014
2015    match compare.as_ref() {
2016        Ok(FingerprintComparison::Fresh) => {}
2017        Ok(FingerprintComparison::Dirty { reason }) => {
2018            info!(
2019                "fingerprint dirty for {}/{:?}/{:?}",
2020                unit.pkg, unit.mode, unit.target,
2021            );
2022            info!("    dirty: {reason:?}");
2023        }
2024        Err(e) => {
2025            info!(
2026                "fingerprint error for {}/{:?}/{:?}",
2027                unit.pkg, unit.mode, unit.target,
2028            );
2029            info!("    err: {e:?}");
2030        }
2031    }
2032
2033    match compare {
2034        Ok(FingerprintComparison::Fresh) if forced => FingerprintComparison::Dirty {
2035            reason: DirtyReason::Forced,
2036        },
2037        Ok(cmp) => cmp,
2038        Err(_) => FingerprintComparison::Dirty {
2039            reason: DirtyReason::FreshBuild,
2040        },
2041    }
2042}
2043
2044fn _compare_old_fingerprint(
2045    old_hash_path: &Path,
2046    new_fingerprint: &Fingerprint,
2047) -> CargoResult<FingerprintComparison> {
2048    let old_fingerprint_short = paths::read(old_hash_path)?;
2049
2050    let new_hash = new_fingerprint.hash_u64();
2051
2052    if util::to_hex(new_hash) == old_fingerprint_short && new_fingerprint.fs_status.up_to_date() {
2053        return Ok(FingerprintComparison::Fresh);
2054    }
2055
2056    let old_fingerprint_json = paths::read(&old_hash_path.with_extension("json"))?;
2057    let old_fingerprint: Fingerprint = serde_json::from_str(&old_fingerprint_json)
2058        .with_context(|| internal("failed to deserialize json"))?;
2059    // Fingerprint can be empty after a failed rebuild (see comment in prepare_target).
2060    if !old_fingerprint_short.is_empty() {
2061        debug_assert_eq!(
2062            util::to_hex(old_fingerprint.hash_u64()),
2063            old_fingerprint_short
2064        );
2065    }
2066
2067    let reason = new_fingerprint.compare(&old_fingerprint);
2068    Ok(FingerprintComparison::Dirty { reason })
2069}
2070
2071/// Calculates the fingerprint of a unit thats contains no dep-info files.
2072fn pkg_fingerprint(bcx: &BuildContext<'_, '_>, pkg: &Package) -> CargoResult<String> {
2073    let source_id = pkg.package_id().source_id();
2074    let sources = bcx.packages.sources();
2075
2076    let source = sources
2077        .get(source_id)
2078        .ok_or_else(|| internal("missing package source"))?;
2079    source.fingerprint(pkg)
2080}
2081
2082/// The `reference` file is considered as "stale" if any file from `paths` has a newer mtime.
2083fn find_stale_file<I, P>(
2084    mtime_cache: &mut HashMap<PathBuf, FileTime>,
2085    checksum_cache: &mut HashMap<PathBuf, Checksum>,
2086    reference: &Path,
2087    paths: I,
2088    use_checksums: bool,
2089) -> Option<StaleItem>
2090where
2091    I: IntoIterator<Item = (P, Option<(u64, Checksum)>)>,
2092    P: AsRef<Path>,
2093{
2094    let reference_mtime = match paths::mtime(reference) {
2095        Ok(mtime) => mtime,
2096        Err(..) => {
2097            return Some(StaleItem::MissingFile {
2098                path: reference.to_path_buf(),
2099            });
2100        }
2101    };
2102
2103    let skippable_dirs = if let Ok(cargo_home) = home::cargo_home() {
2104        let skippable_dirs: Vec<_> = ["git", "registry"]
2105            .into_iter()
2106            .map(|subfolder| cargo_home.join(subfolder))
2107            .collect();
2108        Some(skippable_dirs)
2109    } else {
2110        None
2111    };
2112    for (path, prior_checksum) in paths {
2113        let path = path.as_ref();
2114
2115        // Assuming anything in cargo_home/{git, registry} is immutable
2116        // (see also #9455 about marking the src directory readonly) which avoids rebuilds when CI
2117        // caches $CARGO_HOME/registry/{index, cache} and $CARGO_HOME/git/db across runs, keeping
2118        // the content the same but changing the mtime.
2119        if let Some(ref skippable_dirs) = skippable_dirs {
2120            if skippable_dirs.iter().any(|dir| path.starts_with(dir)) {
2121                continue;
2122            }
2123        }
2124        if use_checksums {
2125            let Some((file_len, prior_checksum)) = prior_checksum else {
2126                return Some(StaleItem::MissingChecksum {
2127                    path: path.to_path_buf(),
2128                });
2129            };
2130            let path_buf = path.to_path_buf();
2131
2132            let path_checksum = match checksum_cache.entry(path_buf) {
2133                Entry::Occupied(o) => *o.get(),
2134                Entry::Vacant(v) => {
2135                    let Ok(current_file_len) = fs::metadata(&path).map(|m| m.len()) else {
2136                        return Some(StaleItem::FailedToReadMetadata {
2137                            path: path.to_path_buf(),
2138                        });
2139                    };
2140                    if current_file_len != file_len {
2141                        return Some(StaleItem::FileSizeChanged {
2142                            path: path.to_path_buf(),
2143                            new_size: current_file_len,
2144                            old_size: file_len,
2145                        });
2146                    }
2147                    let Ok(file) = File::open(path) else {
2148                        return Some(StaleItem::MissingFile {
2149                            path: path.to_path_buf(),
2150                        });
2151                    };
2152                    let Ok(checksum) = Checksum::compute(prior_checksum.algo(), file) else {
2153                        return Some(StaleItem::UnableToReadFile {
2154                            path: path.to_path_buf(),
2155                        });
2156                    };
2157                    *v.insert(checksum)
2158                }
2159            };
2160            if path_checksum == prior_checksum {
2161                continue;
2162            }
2163            return Some(StaleItem::ChangedChecksum {
2164                source: path.to_path_buf(),
2165                stored_checksum: prior_checksum,
2166                new_checksum: path_checksum,
2167            });
2168        } else {
2169            let path_mtime = match mtime_cache.entry(path.to_path_buf()) {
2170                Entry::Occupied(o) => *o.get(),
2171                Entry::Vacant(v) => {
2172                    let Ok(mtime) = paths::mtime_recursive(path) else {
2173                        return Some(StaleItem::MissingFile {
2174                            path: path.to_path_buf(),
2175                        });
2176                    };
2177                    *v.insert(mtime)
2178                }
2179            };
2180
2181            // TODO: fix #5918.
2182            // Note that equal mtimes should be considered "stale". For filesystems with
2183            // not much timestamp precision like 1s this is would be a conservative approximation
2184            // to handle the case where a file is modified within the same second after
2185            // a build starts. We want to make sure that incremental rebuilds pick that up!
2186            //
2187            // For filesystems with nanosecond precision it's been seen in the wild that
2188            // its "nanosecond precision" isn't really nanosecond-accurate. It turns out that
2189            // kernels may cache the current time so files created at different times actually
2190            // list the same nanosecond precision. Some digging on #5919 picked up that the
2191            // kernel caches the current time between timer ticks, which could mean that if
2192            // a file is updated at most 10ms after a build starts then Cargo may not
2193            // pick up the build changes.
2194            //
2195            // All in all, an equality check here would be a conservative assumption that,
2196            // if equal, files were changed just after a previous build finished.
2197            // Unfortunately this became problematic when (in #6484) cargo switch to more accurately
2198            // measuring the start time of builds.
2199            if path_mtime <= reference_mtime {
2200                continue;
2201            }
2202
2203            return Some(StaleItem::ChangedFile {
2204                reference: reference.to_path_buf(),
2205                reference_mtime,
2206                stale: path.to_path_buf(),
2207                stale_mtime: path_mtime,
2208            });
2209        }
2210    }
2211
2212    debug!(
2213        "all paths up-to-date relative to {:?} mtime={}",
2214        reference, reference_mtime
2215    );
2216    None
2217}