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