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