Skip to main content

cargo/compiler/fingerprint/
mod.rs

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