Skip to main content

mbx_cache_rustc/
dep_info.rs

1use super::{
2    ActionContext, ActionInput, Argument, BypassReason, MAX_NATIVE_INPUT_BYTES,
3    MAX_PREDICTED_INPUTS, PathMapping, RustcInvocation, normalize_components,
4};
5#[cfg(test)]
6use mbx_cache_core::CacheDigest;
7use mbx_cache_core::{
8    FileDigestCache, FileDigestResolution, FileDigestScope, FileIdentity, FileSnapshot,
9    RecordedFileDigest, digest_file, digest_file_validated,
10};
11use std::collections::{BTreeMap, BTreeSet};
12use std::ffi::OsString;
13use std::path::{Path, PathBuf};
14use std::time::SystemTime;
15
16/// A side-effect-minimized rustc invocation that emits only dependency data.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct DepInfoCommand {
19    arguments: Vec<OsString>,
20    output: PathBuf,
21}
22
23impl DepInfoCommand {
24    /// Arguments for the real compiler, excluding the compiler executable.
25    pub fn arguments(&self) -> &[OsString] {
26        &self.arguments
27    }
28
29    /// Exact file the compiler must populate with dep-info.
30    pub fn output(&self) -> &Path {
31        &self.output
32    }
33}
34
35/// The source and environment inputs reported by rustc's dep-info output.
36#[derive(Debug, Clone, Default, PartialEq, Eq)]
37pub struct RustcDepInfo {
38    /// Source paths listed in the first dep-info dependency rule.
39    pub files: Vec<PathBuf>,
40    /// Environment inputs recorded by rustc `# env-dep:` lines.
41    pub environment: BTreeMap<String, Option<String>>,
42}
43
44impl RustcDepInfo {
45    /// Read and parse a dep-info file, treating missing or non-UTF-8 output as
46    /// an explicit cache bypass.
47    pub fn read(path: &Path) -> Result<Self, BypassReason> {
48        let contents =
49            std::fs::read_to_string(path).map_err(|error| BypassReason::DepInfoRead {
50                path: path.to_path_buf(),
51                message: error.to_string(),
52            })?;
53        Self::parse(&contents)
54    }
55
56    /// Parse rustc's Makefile-style dep-info format.
57    ///
58    /// This intentionally follows Cargo's parser contract: the first target
59    /// rule contains all source dependencies, spaces are escaped with a
60    /// trailing backslash on each token fragment, and `# env-dep:` records
61    /// contain the environment observed by `env!` and `option_env!`.
62    pub fn parse(contents: &str) -> Result<Self, BypassReason> {
63        let mut files = BTreeSet::new();
64        let mut environment = BTreeMap::new();
65        let mut found_dependencies = false;
66
67        for line in contents.lines() {
68            if let Some(record) = line.strip_prefix("# env-dep:") {
69                let (name, value) = record
70                    .split_once('=')
71                    .map_or((record, None), |(name, value)| (name, Some(value)));
72                let name = unescape_environment(name)?;
73                if name.is_empty() {
74                    return Err(BypassReason::MalformedDepInfo(
75                        "environment input has an empty name".into(),
76                    ));
77                }
78                let value = value.map(unescape_environment).transpose()?;
79                if environment
80                    .insert(name.clone(), value.clone())
81                    .is_some_and(|previous| previous != value)
82                {
83                    return Err(BypassReason::ConflictingEnvironment(name));
84                }
85                continue;
86            }
87
88            let Some(separator) = line.find(": ") else {
89                continue;
90            };
91            if found_dependencies {
92                continue;
93            }
94            found_dependencies = true;
95            let mut fragments = line[separator + 2..].split_whitespace();
96            while let Some(fragment) = fragments.next() {
97                let mut file = fragment.to_string();
98                while file.ends_with('\\') {
99                    file.pop();
100                    let continuation = fragments.next().ok_or_else(|| {
101                        BypassReason::MalformedDepInfo(
102                            "dependency path ends with an unterminated escape".into(),
103                        )
104                    })?;
105                    file.push(' ');
106                    file.push_str(continuation);
107                }
108                if file.is_empty() {
109                    return Err(BypassReason::MalformedDepInfo(
110                        "dependency path is empty".into(),
111                    ));
112                }
113                files.insert(PathBuf::from(file));
114            }
115        }
116
117        if !found_dependencies {
118            return Err(BypassReason::MalformedDepInfo(
119                "dependency rule is missing".into(),
120            ));
121        }
122        if files.is_empty() {
123            return Err(BypassReason::MalformedDepInfo(
124                "dependency rule contains no inputs".into(),
125            ));
126        }
127        Ok(Self {
128            files: files.into_iter().collect(),
129            environment,
130        })
131    }
132}
133
134/// A complete, content-addressed compiler input manifest.
135#[derive(Debug, Clone, PartialEq, Eq)]
136pub struct DiscoveredInputs {
137    working_dir: PathBuf,
138    /// Content-addressed compiler input files.
139    pub inputs: Vec<ActionInput>,
140    /// Environment inputs captured from dep-info.
141    pub environment: BTreeMap<String, Option<String>>,
142    /// What each input looked like on disk when its digest was established,
143    /// index-aligned with `inputs`; `None` where the filesystem gave nothing to
144    /// compare against later. Lets `verify` confirm an input by stat instead of
145    /// by reading it again.
146    identities: Vec<Option<FileIdentity>>,
147    /// Inputs that entered only because they sit in a native search directory,
148    /// not because dep-info or the invocation named them. They belong in a
149    /// shared action key, but they are not the crate's own sources.
150    native_only: BTreeSet<PathBuf>,
151}
152
153impl DiscoveredInputs {
154    pub(crate) fn from_paths(
155        working_dir: &Path,
156        paths: BTreeSet<PathBuf>,
157        environment: BTreeMap<String, Option<String>>,
158        digests: &dyn FileDigestCache,
159    ) -> Result<Self, BypassReason> {
160        if !working_dir.is_absolute() {
161            return Err(BypassReason::RelativeWorkingDirectory(
162                working_dir.to_path_buf(),
163            ));
164        }
165        let working_dir = normalize_components(working_dir);
166        // Stat everything first: the identities drive one batched ledger
167        // lookup, so an upstream rlib the session already hashed -- once, when
168        // it was materialized or published -- is not read again by every crate
169        // that links it. A file the filesystem reports no modification time
170        // for gets no identity and is simply hashed.
171        let mut identified = Vec::with_capacity(paths.len());
172        for path in paths {
173            let metadata = std::fs::metadata(&path).map_err(|error| BypassReason::InputRead {
174                path: path.clone(),
175                message: error.to_string(),
176            })?;
177            if !metadata.is_file() {
178                return Err(BypassReason::InputRead {
179                    path,
180                    message: "input is not a regular file".into(),
181                });
182            }
183            let identity = FileIdentity::for_digest_cache(&path, &metadata).map_err(|error| {
184                BypassReason::InputRead {
185                    path: path.clone(),
186                    message: error.to_string(),
187                }
188            })?;
189            identified.push((path, identity));
190        }
191        let queries = identified
192            .iter()
193            .filter_map(|(_, identity)| identity.clone())
194            .collect::<Vec<_>>();
195        let mut recorded = digests
196            .resolve(FileDigestScope::Content, &queries)
197            .into_iter();
198        let mut inputs = Vec::with_capacity(identified.len());
199        let mut identities = Vec::with_capacity(identified.len());
200        let mut fresh = Vec::new();
201        for (path, identity) in identified {
202            let resolution = identity
203                .as_ref()
204                .and_then(|_| recorded.next())
205                .unwrap_or(FileDigestResolution::Unresolved);
206            let cached = match resolution {
207                FileDigestResolution::Digest(digest)
208                    if identity.as_ref().is_some_and(|identity| {
209                        identity.len == digest.size && identity.still_describes().unwrap_or(false)
210                    }) =>
211                {
212                    Some(digest)
213                }
214                FileDigestResolution::Digest(_)
215                | FileDigestResolution::EmbeddedTimestampMacro
216                | FileDigestResolution::Unresolved => None,
217            };
218            let digest = if let Some(digest) = cached {
219                identities.push(identity);
220                digest
221            } else {
222                let observed =
223                    digest_file_validated(FileDigestScope::Content, &path).map_err(|error| {
224                        BypassReason::InputRead {
225                            path: path.clone(),
226                            message: error.to_string(),
227                        }
228                    })?;
229                let (digest, observed_identity) = if let Some(observed) = observed {
230                    let digest = observed.resolution.into_digest().ok_or_else(|| {
231                        BypassReason::InputRead {
232                            path: path.clone(),
233                            message: "content digest resolution returned no digest".into(),
234                        }
235                    })?;
236                    if let Some(file) = observed.cache_identity.clone()
237                        && file.len == digest.size
238                    {
239                        fresh.push(RecordedFileDigest {
240                            file,
241                            digest: digest.clone(),
242                        });
243                    }
244                    (digest, observed.cache_identity)
245                } else {
246                    let digest = digest_file(FileDigestScope::Content, &path)
247                        .and_then(|resolution| {
248                            resolution.into_digest().ok_or_else(|| {
249                                std::io::Error::other(
250                                    "content digest resolution returned no digest",
251                                )
252                            })
253                        })
254                        .map_err(|error| BypassReason::InputRead {
255                            path: path.clone(),
256                            message: error.to_string(),
257                        })?;
258                    (digest, None)
259                };
260                identities.push(observed_identity);
261                digest
262            };
263            inputs.push(ActionInput { path, digest });
264        }
265        if !fresh.is_empty() {
266            digests.record(FileDigestScope::Content, fresh);
267        }
268        Ok(Self {
269            working_dir,
270            inputs,
271            environment,
272            identities,
273            native_only: BTreeSet::new(),
274        })
275    }
276
277    /// Mark inputs that were found only by scanning native search directories.
278    pub(crate) fn with_native_only(mut self, native_only: BTreeSet<PathBuf>) -> Self {
279        self.native_only = native_only;
280        self
281    }
282
283    /// Whether `path` is an input only because a native search directory holds it.
284    pub fn is_native_only(&self, path: &Path) -> bool {
285        self.native_only.contains(path)
286    }
287
288    /// Reject inputs whose modification time overlaps the compiler invocation.
289    ///
290    /// Input contents are first hashed after rustc reports their paths. This
291    /// timestamp barrier prevents a post-compile write from being mistaken for
292    /// the contents that produced the artifact. `verify` closes the remaining
293    /// race after hashing.
294    pub fn verify_not_modified_since(&self, started_at: SystemTime) -> Result<(), BypassReason> {
295        self.verify_not_modified_since_with_snapshots(started_at, &BTreeMap::new())
296    }
297
298    /// Reject inputs that changed from snapshots captured before rustc ran,
299    /// falling back to the wall-clock barrier for inputs only dep-info named.
300    ///
301    /// A snapshot may use metadata or content depending on what its filesystem
302    /// can compare reliably. Metadata snapshots need a change token: without
303    /// one a same-length rewrite can restore its mtime.
304    pub fn verify_not_modified_since_with_snapshots(
305        &self,
306        started_at: SystemTime,
307        before: &BTreeMap<PathBuf, FileSnapshot>,
308    ) -> Result<(), BypassReason> {
309        self.verify_snapshots(Some(started_at), before)
310    }
311
312    /// Like [`Self::verify_not_modified_since_with_snapshots`], but judging
313    /// only the inputs that have a snapshot. Use it when the compiler may
314    /// legitimately write other inputs, such as generated files, while it runs.
315    pub fn verify_snapshots_unchanged(
316        &self,
317        before: &BTreeMap<PathBuf, FileSnapshot>,
318    ) -> Result<(), BypassReason> {
319        self.verify_snapshots(None, before)
320    }
321
322    fn verify_snapshots(
323        &self,
324        started_at: Option<SystemTime>,
325        before: &BTreeMap<PathBuf, FileSnapshot>,
326    ) -> Result<(), BypassReason> {
327        // A metadata-only change keeps the result, so it must not hide a
328        // content change to a later input.
329        let mut metadata_changed = None;
330        for input in &self.inputs {
331            if let Some(previous) = before.get(&input.path)
332                && previous.proves_content_change()
333            {
334                let metadata =
335                    std::fs::metadata(&input.path).map_err(|error| BypassReason::InputRead {
336                        path: input.path.clone(),
337                        message: error.to_string(),
338                    })?;
339                let identity = FileIdentity::for_digest_cache(&input.path, &metadata)
340                    .map_err(|error| BypassReason::InputRead {
341                        path: input.path.clone(),
342                        message: error.to_string(),
343                    })?
344                    .or_else(|| FileIdentity::describe(&input.path, &metadata));
345                if previous.matches(identity.as_ref(), &input.digest) {
346                    continue;
347                }
348                if previous.differs_only_in_change_token(identity.as_ref()) {
349                    metadata_changed.get_or_insert_with(|| input.path.clone());
350                    continue;
351                }
352                return Err(BypassReason::InputModifiedDuringCompilation(
353                    input.path.clone(),
354                ));
355            }
356            let Some(started_at) = started_at else {
357                continue;
358            };
359            let metadata =
360                std::fs::metadata(&input.path).map_err(|error| BypassReason::InputRead {
361                    path: input.path.clone(),
362                    message: error.to_string(),
363                })?;
364            let modified = metadata
365                .modified()
366                .map_err(|error| BypassReason::InputRead {
367                    path: input.path.clone(),
368                    message: error.to_string(),
369                })?;
370            if modified >= started_at {
371                return Err(BypassReason::InputModifiedDuringCompilation(
372                    input.path.clone(),
373                ));
374            }
375        }
376        metadata_changed.map_or(Ok(()), |path| {
377            Err(BypassReason::InputMetadataChangedDuringCompilation(path))
378        })
379    }
380
381    /// Compatibility form for callers that captured metadata identities.
382    pub fn verify_not_modified_since_with_identities(
383        &self,
384        started_at: SystemTime,
385        before: &BTreeMap<PathBuf, FileIdentity>,
386    ) -> Result<(), BypassReason> {
387        let snapshots = before
388            .iter()
389            .map(|(path, identity)| (path.clone(), identity.clone().into()))
390            .collect();
391        self.verify_not_modified_since_with_snapshots(started_at, &snapshots)
392    }
393
394    /// Rehash every discovered file after compilation and before publication.
395    /// This closes the discovery/compile race by degrading changed inputs to a
396    /// cache miss rather than storing outputs beneath a stale action key.
397    pub fn verify(&self) -> Result<(), BypassReason> {
398        for (index, input) in self.inputs.iter().enumerate() {
399            let read_error = |error: std::io::Error| BypassReason::InputRead {
400                path: input.path.clone(),
401                message: error.to_string(),
402            };
403            // An input still wearing the identity discovery recorded -- length,
404            // modification time, and change time -- is confirmed by that stat
405            // alone. The change time is what makes this as good as reading: it
406            // cannot be set from user space, so a rewrite that puts the old
407            // modification time back still shows, where a platform that reports
408            // none would let a same-length rewrite inside one timestamp tick
409            // through. Such an identity is not trusted here, and neither is an
410            // input that had none. Reading everything again cost as much as
411            // keying the compilation did: a large binary's dependency rlibs, a
412            // gigabyte of them, read twice for every edit.
413            if let Some(Some(identity)) = self.identities.get(index)
414                && identity.can_skip_content_verification()
415                && identity.still_describes().map_err(read_error)?
416            {
417                continue;
418            }
419            let matches = input.digest.matches_file(&input.path).map_err(|error| {
420                BypassReason::InputRead {
421                    path: input.path.clone(),
422                    message: error.to_string(),
423                }
424            })?;
425            if !matches {
426                return Err(BypassReason::InputChanged(input.path.clone()));
427            }
428        }
429        Ok(())
430    }
431
432    /// Merge the manifest into an action context after verifying that both use
433    /// the same compiler working directory.
434    pub fn apply_to(self, context: &mut ActionContext) -> Result<(), BypassReason> {
435        if normalize_components(&context.working_dir) != self.working_dir {
436            return Err(BypassReason::DiscoveryWorkingDirectory);
437        }
438        for (name, value) in &self.environment {
439            if context
440                .environment
441                .get(name)
442                .is_some_and(|previous| previous != value)
443            {
444                return Err(BypassReason::ConflictingEnvironment(name.clone()));
445            }
446        }
447        context.environment.extend(self.environment);
448        context.inputs.extend(self.inputs);
449        Ok(())
450    }
451}
452
453impl RustcInvocation {
454    /// Replace the original output flags with a single explicit dep-info file.
455    pub fn dep_info_command(&self, output: &Path) -> Result<DepInfoCommand, BypassReason> {
456        if !output.is_absolute() {
457            return Err(BypassReason::RelativeDepInfoPath(output.to_path_buf()));
458        }
459        let output_text = output
460            .to_str()
461            .ok_or_else(|| BypassReason::NonUtf8Path(output.to_path_buf()))?;
462        if output_text.contains(',') {
463            return Err(BypassReason::UnsafeDepInfoPath(output.to_path_buf()));
464        }
465
466        let mut arguments = Vec::new();
467        for argument in &self.arguments {
468            match argument {
469                Argument::Emit(_) => {}
470                Argument::Path { flag, .. } if flag == "--out-dir" || flag == "-o" => {}
471                argument => arguments.push(render_argument(argument)?),
472            }
473        }
474        arguments.push(format!("--emit=dep-info={output_text}").into());
475        arguments.push(self.source.clone().into_os_string());
476        Ok(DepInfoCommand {
477            arguments,
478            output: output.to_path_buf(),
479        })
480    }
481
482    /// Hash dep-info sources plus every direct compiler input already modeled
483    /// by the invocation (`--extern` artifacts and custom target specs).
484    pub fn discover_inputs(
485        &self,
486        dep_info: &RustcDepInfo,
487        working_dir: &Path,
488    ) -> Result<DiscoveredInputs, BypassReason> {
489        self.discover_inputs_with_mappings(
490            dep_info,
491            working_dir,
492            &[],
493            &mbx_cache_core::NoFileDigestCache,
494        )
495    }
496
497    /// Hash dep-info sources plus modeled compiler inputs, allowing native
498    /// search directories beneath the working directory or a mapped root.
499    ///
500    /// `digests` may answer for files the session already read in full;
501    /// pass [`mbx_cache_core::NoFileDigestCache`] to hash everything.
502    pub fn discover_inputs_with_mappings(
503        &self,
504        dep_info: &RustcDepInfo,
505        working_dir: &Path,
506        path_mappings: &[PathMapping],
507        digests: &dyn FileDigestCache,
508    ) -> Result<DiscoveredInputs, BypassReason> {
509        self.discover(dep_info, working_dir, Some(path_mappings), digests)
510    }
511
512    /// Hash dep-info sources and modeled compiler inputs, leaving native search
513    /// directories out.
514    ///
515    /// The result cannot key a shared action: the linker may read libraries it
516    /// does not list. It is enough to tell whether a crate's own sources changed,
517    /// which is all that private incremental state needs, so it works for a
518    /// compilation whose search paths [`Self::discover_inputs_with_mappings`]
519    /// refuses.
520    pub fn discover_source_inputs(
521        &self,
522        dep_info: &RustcDepInfo,
523        working_dir: &Path,
524        digests: &dyn FileDigestCache,
525    ) -> Result<DiscoveredInputs, BypassReason> {
526        self.discover(dep_info, working_dir, None, digests)
527    }
528
529    /// Native search directories are collected only when `path_mappings` is given.
530    fn discover(
531        &self,
532        dep_info: &RustcDepInfo,
533        working_dir: &Path,
534        path_mappings: Option<&[PathMapping]>,
535        digests: &dyn FileDigestCache,
536    ) -> Result<DiscoveredInputs, BypassReason> {
537        if !working_dir.is_absolute() {
538            return Err(BypassReason::RelativeWorkingDirectory(
539                working_dir.to_path_buf(),
540            ));
541        }
542        let working_dir = normalize_components(working_dir);
543        let absolute = |path: &PathBuf| {
544            let absolute = if path.is_absolute() {
545                path.to_path_buf()
546            } else {
547                working_dir.join(path)
548            };
549            normalize_components(&absolute)
550        };
551        // What dep-info names is the crate's own. A required input also covers
552        // the crate root, `--extern` artifacts and target specifications, so it
553        // is a source unless a native search directory holds it: there it is a
554        // library resolved from that directory, which belongs in a shared key
555        // but is no more a source than the directory around it.
556        let sources = dep_info.files.iter().map(absolute).collect::<BTreeSet<_>>();
557        let mut paths = sources.clone();
558        paths.extend(self.required_inputs.iter().map(absolute));
559        let admitted_roots = native_input_roots(&working_dir, path_mappings.unwrap_or_default());
560        let mut native_bytes = 0_u64;
561        let mut counted = BTreeSet::new();
562        for argument in &self.arguments {
563            if path_mappings.is_some()
564                && let Argument::SearchPath { kind, path } = argument
565                && super::searches_native(kind)
566            {
567                let directory = if path.is_absolute() {
568                    path.clone()
569                } else {
570                    working_dir.join(path)
571                };
572                collect_native_directory(
573                    &directory,
574                    &admitted_roots,
575                    &mut paths,
576                    &mut native_bytes,
577                    &mut counted,
578                )?;
579            }
580        }
581        let native_directories = self
582            .arguments
583            .iter()
584            .filter_map(|argument| match argument {
585                Argument::SearchPath { kind, path } if super::searches_native(kind) => {
586                    Some(absolute(path))
587                }
588                _ => None,
589            })
590            .collect::<Vec<_>>();
591        let native_only = paths
592            .difference(&sources)
593            .filter(|path| native_directories.iter().any(|root| path.starts_with(root)))
594            .cloned()
595            .collect();
596        Ok(DiscoveredInputs::from_paths(
597            &working_dir,
598            paths,
599            dep_info.environment.clone(),
600            digests,
601        )?
602        .with_native_only(native_only))
603    }
604}
605
606/// Return normalized roots whose native search directories can be tracked.
607pub(super) fn native_input_roots(
608    working_dir: &Path,
609    path_mappings: &[PathMapping],
610) -> Vec<PathBuf> {
611    std::iter::once(working_dir)
612        .chain(path_mappings.iter().map(|mapping| mapping.root.as_path()))
613        .map(normalize_components)
614        .collect()
615}
616
617/// Add regular files beneath an admitted native search directory, enforcing
618/// the prediction input count and the caller's cumulative native byte budget.
619/// `counted` holds the files already charged to that budget, so overlapping
620/// walks charge each file once even when `paths` already names it.
621pub(super) fn collect_native_directory(
622    directory: &Path,
623    admitted_roots: &[PathBuf],
624    paths: &mut BTreeSet<PathBuf>,
625    native_bytes: &mut u64,
626    counted: &mut BTreeSet<PathBuf>,
627) -> Result<(), BypassReason> {
628    let directory = normalize_components(directory);
629    if !admitted_roots
630        .iter()
631        .any(|root| directory.starts_with(root))
632    {
633        return Err(BypassReason::UnsupportedSearchPath("native".into()));
634    }
635
636    let canonical_root = match directory.canonicalize() {
637        Ok(root) => root,
638        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
639        Err(error) => {
640            return Err(BypassReason::InputRead {
641                path: directory,
642                message: error.to_string(),
643            });
644        }
645    };
646    let mut pending = vec![directory];
647    while let Some(directory) = pending.pop() {
648        let entries = match std::fs::read_dir(&directory) {
649            Ok(entries) => entries,
650            Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
651            Err(error) => {
652                return Err(BypassReason::InputRead {
653                    path: directory,
654                    message: error.to_string(),
655                });
656            }
657        };
658        for entry in entries {
659            let entry = entry.map_err(|error| BypassReason::InputRead {
660                path: directory.clone(),
661                message: error.to_string(),
662            })?;
663            let path = entry.path();
664            let file_type = entry.file_type().map_err(|error| BypassReason::InputRead {
665                path: path.clone(),
666                message: error.to_string(),
667            })?;
668            if file_type.is_dir() {
669                if !is_linker_irrelevant_directory(&path) {
670                    pending.push(path);
671                }
672            } else if is_linker_irrelevant_file(&path) {
673                continue;
674            } else if file_type.is_file() || file_type.is_symlink() {
675                // Homebrew's versionless dylibs are symlinks. Hash their
676                // referents under the searched name, but do not follow directory
677                // links, dangling links, or links outside this search tree.
678                if file_type.is_symlink() {
679                    let resolved =
680                        path.canonicalize()
681                            .map_err(|error| BypassReason::InputRead {
682                                path: path.clone(),
683                                message: error.to_string(),
684                            })?;
685                    if !resolved.starts_with(&canonical_root) || !resolved.is_file() {
686                        return Err(BypassReason::UnsupportedSearchPath("native".into()));
687                    }
688                }
689                let len = std::fs::metadata(&path)
690                    .map_err(|error| BypassReason::InputRead {
691                        path: path.clone(),
692                        message: error.to_string(),
693                    })?
694                    .len();
695                // A directory named by several `-L native=` arguments, or nested
696                // under another one, is walked more than once; count each file
697                // against the budget only the first time it is seen.
698                paths.insert(path.clone());
699                if counted.insert(path) {
700                    *native_bytes = native_bytes
701                        .checked_add(len)
702                        .ok_or_else(|| BypassReason::UnsupportedSearchPath("native".into()))?;
703                }
704            } else {
705                return Err(BypassReason::UnsupportedSearchPath("native".into()));
706            }
707            if paths.len() > MAX_PREDICTED_INPUTS || *native_bytes > MAX_NATIVE_INPUT_BYTES {
708                return Err(BypassReason::UnsupportedSearchPath("native".into()));
709            }
710        }
711    }
712    Ok(())
713}
714
715/// Directories that build scripts leave beside libraries but that a linker
716/// never reads. They often record the absolute output path (`prefix=` in
717/// pkg-config files, `binary-path:` in dSYM relocation YAML), so hashing them
718/// would make the key depend on the target directory.
719fn is_linker_irrelevant_directory(path: &Path) -> bool {
720    let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
721        return false;
722    };
723    name == "pkgconfig" || name == "cmake" || name.ends_with(".dSYM")
724}
725
726/// pkg-config and CMake metadata. Headers stay hashed: linker scripts can
727/// `INCLUDE` files from a search path, and `+verbatim` names any file.
728fn is_linker_irrelevant_file(path: &Path) -> bool {
729    path.extension()
730        .and_then(|extension| extension.to_str())
731        .is_some_and(|extension| {
732            ["pc", "cmake"]
733                .iter()
734                .any(|ignored| extension.eq_ignore_ascii_case(ignored))
735        })
736}
737
738fn render_argument(argument: &Argument) -> Result<OsString, BypassReason> {
739    let rendered = match argument {
740        Argument::Plain(value) => value.clone(),
741        Argument::Path { flag, path } => format!(
742            "{flag}={}",
743            path.to_str()
744                .ok_or_else(|| BypassReason::NonUtf8Path(path.clone()))?
745        ),
746        Argument::SearchPath { kind, path } => format!(
747            "-L{kind}={}",
748            path.to_str()
749                .ok_or_else(|| BypassReason::NonUtf8Path(path.clone()))?
750        ),
751        Argument::Extern { name, path } => match path {
752            Some(path) => format!(
753                "--extern={name}={}",
754                path.to_str()
755                    .ok_or_else(|| BypassReason::NonUtf8Path(path.clone()))?
756            ),
757            None => format!("--extern={name}"),
758        },
759        Argument::Emit(_) => unreachable!("emit arguments are removed before rendering"),
760        Argument::RemapPath { from, to } => format!(
761            "--remap-path-prefix={}={to}",
762            from.to_str()
763                .ok_or_else(|| BypassReason::NonUtf8Path(from.clone()))?
764        ),
765        // Nothing links while emitting dep-info, so the prefix is inert here;
766        // it is replayed verbatim to keep the command faithful.
767        Argument::OsoPrefix {
768            path,
769            trailing_slash,
770        } => format!(
771            "--codegen=link-arg=-Wl,-oso_prefix,{}{}",
772            path.to_str()
773                .ok_or_else(|| BypassReason::NonUtf8Path(path.clone()))?,
774            if *trailing_slash { "/" } else { "" }
775        ),
776        // Nothing links while emitting dep-info either; replayed verbatim for
777        // the same reason as the prefix above.
778        Argument::InstallName(name) => {
779            format!("--codegen=link-arg=-Wl,-install_name,@rpath/{name}")
780        }
781        Argument::Rpath(directory) => format!("--codegen=link-arg=-Wl,-rpath,{directory}"),
782        Argument::FuseLd(selection) => format!("--codegen=link-arg=-fuse-ld={selection}"),
783    };
784    Ok(rendered.into())
785}
786
787fn unescape_environment(value: &str) -> Result<String, BypassReason> {
788    let mut output = String::with_capacity(value.len());
789    let mut characters = value.chars();
790    while let Some(character) = characters.next() {
791        if character != '\\' {
792            output.push(character);
793            continue;
794        }
795        match characters.next() {
796            Some('\\') => output.push('\\'),
797            Some('n') => output.push('\n'),
798            Some('r') => output.push('\r'),
799            Some(character) => {
800                return Err(BypassReason::MalformedDepInfo(format!(
801                    "unknown environment escape \\{character}"
802                )));
803            }
804            None => {
805                return Err(BypassReason::MalformedDepInfo(
806                    "environment input ends with an unterminated escape".into(),
807                ));
808            }
809        }
810    }
811    Ok(output)
812}
813
814#[cfg(test)]
815mod tests {
816    use super::*;
817    use std::process::Command;
818
819    fn args(values: &[&str]) -> Vec<OsString> {
820        values.iter().map(OsString::from).collect()
821    }
822
823    #[test]
824    fn parses_files_spaces_and_environment_records() {
825        let parsed = RustcDepInfo::parse(
826            "target/lib.rlib: src/lib.rs src/a\\ file.rs generated.rs\n\
827             src/lib.rs:\n\
828             # env-dep:SET=value\\nnext\n\
829             # env-dep:UNSET\n\
830             # env-dep:SLASH=a\\\\b\n",
831        )
832        .unwrap();
833        assert_eq!(
834            parsed.files,
835            vec![
836                PathBuf::from("generated.rs"),
837                PathBuf::from("src/a file.rs"),
838                PathBuf::from("src/lib.rs"),
839            ]
840        );
841        assert_eq!(parsed.environment["SET"], Some("value\nnext".into()));
842        assert_eq!(parsed.environment["UNSET"], None);
843        assert_eq!(parsed.environment["SLASH"], Some(r"a\b".into()));
844    }
845
846    #[test]
847    fn malformed_dep_info_bypasses_caching() {
848        for contents in [
849            "",
850            "target: ",
851            "target: src/trailing\\\n",
852            "target: src/lib.rs\n# env-dep:NAME=bad\\q\n",
853        ] {
854            assert!(RustcDepInfo::parse(contents).is_err(), "{contents:?}");
855        }
856    }
857
858    #[test]
859    fn native_directory_byte_limit_is_cumulative() {
860        let directory = tempfile::tempdir().unwrap();
861        let native = directory.path().join("native");
862        std::fs::create_dir_all(&native).unwrap();
863        std::fs::write(native.join("input.lib"), b"xx").unwrap();
864        let roots = native_input_roots(directory.path(), &[]);
865        let mut paths = BTreeSet::new();
866        let mut native_bytes = MAX_NATIVE_INPUT_BYTES - 1;
867        let mut counted = BTreeSet::new();
868
869        assert_eq!(
870            collect_native_directory(&native, &roots, &mut paths, &mut native_bytes, &mut counted),
871            Err(BypassReason::UnsupportedSearchPath("native".into()))
872        );
873    }
874
875    #[test]
876    fn native_directory_walked_twice_counts_bytes_once() {
877        let directory = tempfile::tempdir().unwrap();
878        let native = directory.path().join("native");
879        std::fs::create_dir_all(native.join("lib")).unwrap();
880        std::fs::write(native.join("input.lib"), b"xx").unwrap();
881        std::fs::write(native.join("lib").join("nested.lib"), b"yyy").unwrap();
882        let roots = native_input_roots(directory.path(), &[]);
883        let mut paths = BTreeSet::new();
884        let mut native_bytes = 0;
885        let mut counted = BTreeSet::new();
886
887        for dir in [&native, &native, &native.join("lib")] {
888            collect_native_directory(dir, &roots, &mut paths, &mut native_bytes, &mut counted)
889                .unwrap();
890        }
891
892        assert_eq!(paths.len(), 2);
893        assert_eq!(native_bytes, 5);
894    }
895
896    #[test]
897    fn native_directory_charges_files_already_named_as_inputs() {
898        let directory = tempfile::tempdir().unwrap();
899        let native = directory.path().join("native");
900        std::fs::create_dir_all(&native).unwrap();
901        let archive = native.join("libfoo.a");
902        std::fs::write(&archive, b"xx").unwrap();
903        let roots = native_input_roots(directory.path(), &[]);
904        let mut paths = BTreeSet::from([archive]);
905        let mut native_bytes = 0;
906        let mut counted = BTreeSet::new();
907
908        collect_native_directory(&native, &roots, &mut paths, &mut native_bytes, &mut counted)
909            .unwrap();
910
911        assert_eq!(native_bytes, 2);
912    }
913
914    #[test]
915    fn native_directory_skips_files_the_linker_never_reads() {
916        let directory = tempfile::tempdir().unwrap();
917        let native = directory.path().join("native");
918        for ignored in [
919            "lib/pkgconfig/zlib.pc",
920            "check.dSYM/Contents/Resources/Relocations/aarch64/check.yml",
921            "cmake/Config.cmake",
922            "top.pc",
923        ] {
924            let path = native.join(ignored);
925            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
926            std::fs::write(path, b"prefix=/abs/target\n").unwrap();
927        }
928        std::fs::write(native.join("libz.a"), b"!<arch>\n").unwrap();
929        std::fs::create_dir_all(native.join("lib")).unwrap();
930        std::fs::write(native.join("lib/libz.so.1"), b"elf").unwrap();
931        let roots = native_input_roots(directory.path(), &[]);
932        let mut paths = BTreeSet::new();
933        let mut native_bytes = 0;
934        let mut counted = BTreeSet::new();
935
936        collect_native_directory(&native, &roots, &mut paths, &mut native_bytes, &mut counted)
937            .unwrap();
938
939        assert_eq!(
940            paths.into_iter().collect::<Vec<_>>(),
941            vec![native.join("lib/libz.so.1"), native.join("libz.a")]
942        );
943    }
944
945    #[test]
946    fn discovery_command_removes_real_outputs() {
947        let invocation = RustcInvocation::parse(&args(&[
948            "--crate-name=widget",
949            "--crate-type=lib",
950            "--emit=dep-info,metadata,link",
951            "--out-dir=target/debug/deps",
952            "-o",
953            "target/debug/libwidget.rlib",
954            "src/lib.rs",
955        ]))
956        .unwrap();
957        let output = if cfg!(windows) {
958            PathBuf::from(r"C:\tmp\mbx cache\inputs.d")
959        } else {
960            PathBuf::from("/tmp/mbx cache/inputs.d")
961        };
962        let command = invocation.dep_info_command(&output).unwrap();
963        let arguments = command
964            .arguments()
965            .iter()
966            .map(|value| value.to_string_lossy())
967            .collect::<Vec<_>>();
968        assert_eq!(
969            arguments,
970            vec![
971                "--crate-name=widget",
972                "--crate-type=lib",
973                &format!("--emit=dep-info={}", output.display()),
974                "src/lib.rs",
975            ]
976        );
977    }
978
979    #[test]
980    fn discovery_hashes_externs_and_custom_targets() {
981        let directory = tempfile::tempdir().unwrap();
982        let root = directory.path();
983        let source = root.join("src/lib.rs");
984        let external = root.join("target/libdependency.rlib");
985        let target = root.join("targets/custom.json");
986        std::fs::create_dir_all(source.parent().unwrap()).unwrap();
987        std::fs::create_dir_all(external.parent().unwrap()).unwrap();
988        std::fs::create_dir_all(target.parent().unwrap()).unwrap();
989        std::fs::write(&source, "pub fn library() {}\n").unwrap();
990        std::fs::write(&external, "dependency artifact\n").unwrap();
991        std::fs::write(&target, "{}\n").unwrap();
992
993        let invocation = RustcInvocation::parse(&[
994            "--crate-name=widget".into(),
995            "--crate-type=lib".into(),
996            "--emit=metadata".into(),
997            format!("--extern=dependency={}", external.display()).into(),
998            format!("--target={}", target.display()).into(),
999            source.clone().into_os_string(),
1000        ])
1001        .unwrap();
1002        let dep_info = RustcDepInfo::parse(&format!("output: {}\n", source.display())).unwrap();
1003        let discovered = invocation.discover_inputs(&dep_info, root).unwrap();
1004        assert_eq!(discovered.inputs.len(), 3);
1005
1006        std::fs::remove_file(&external).unwrap();
1007        assert!(matches!(
1008            invocation.discover_inputs(&dep_info, root),
1009            Err(BypassReason::InputRead { path, .. }) if path == external
1010        ));
1011    }
1012
1013    /// macOS writes extended attributes to a file a second or two after an
1014    /// app saves it, moving its change time alone. That must not discard a
1015    /// compilation as if the source had changed: it leaves it uncached. It
1016    /// must not hide a content change to another input either.
1017    #[cfg(unix)]
1018    #[test]
1019    fn a_metadata_write_during_compilation_bypasses_without_discarding() {
1020        use std::os::unix::fs::PermissionsExt as _;
1021
1022        let directory = tempfile::tempdir().unwrap();
1023        let library = directory.path().join("lib.rs");
1024        let module = directory.path().join("module.rs");
1025        std::fs::write(&library, "mod module;\n").unwrap();
1026        std::fs::write(&module, "pub fn module() {}\n").unwrap();
1027        let invocation = RustcInvocation::parse(&[
1028            "--crate-name=widget".into(),
1029            "--crate-type=lib".into(),
1030            "--emit=dep-info,metadata".into(),
1031            library.clone().into_os_string(),
1032        ])
1033        .unwrap();
1034        let dep_info = RustcDepInfo::parse(&format!(
1035            "output: {} {}\n",
1036            library.display(),
1037            module.display()
1038        ))
1039        .unwrap();
1040        let identity = |path: &Path| {
1041            FileIdentity::for_digest_cache(path, &std::fs::metadata(path).unwrap()).unwrap()
1042        };
1043        // Settled metadata snapshots, whatever the host's timestamp tick.
1044        let Some(settled) = identity(&library).filter(|identity| identity.changed.is_some()) else {
1045            return; // No change token on this filesystem.
1046        };
1047        let before = BTreeMap::from([
1048            (library.clone(), FileSnapshot::from(settled.clone())),
1049            (
1050                module.clone(),
1051                FileSnapshot::from(identity(&module).unwrap()),
1052            ),
1053        ]);
1054
1055        let mode = std::fs::metadata(&library).unwrap().permissions().mode();
1056        std::fs::set_permissions(&library, std::fs::Permissions::from_mode(mode)).unwrap();
1057        if identity(&library) == Some(settled) {
1058            return; // The change time did not move within this tick.
1059        }
1060        let discovered = invocation
1061            .discover_inputs(&dep_info, directory.path())
1062            .unwrap();
1063        assert_eq!(
1064            discovered.verify_not_modified_since_with_snapshots(SystemTime::UNIX_EPOCH, &before),
1065            Err(BypassReason::InputMetadataChangedDuringCompilation(
1066                library.clone()
1067            ))
1068        );
1069
1070        // A rewrite of a different length is still a content change, even
1071        // behind the earlier metadata-only one.
1072        std::fs::write(&module, "pub fn module() { let _ = 1; }\n").unwrap();
1073        let discovered = invocation
1074            .discover_inputs(&dep_info, directory.path())
1075            .unwrap();
1076        assert_eq!(
1077            discovered.verify_not_modified_since_with_snapshots(SystemTime::UNIX_EPOCH, &before),
1078            Err(BypassReason::InputModifiedDuringCompilation(module))
1079        );
1080    }
1081
1082    #[test]
1083    fn discovery_rejects_inputs_modified_during_compilation() {
1084        let directory = tempfile::tempdir().unwrap();
1085        let source = directory.path().join("lib.rs");
1086        std::fs::write(&source, "pub fn library() {}\n").unwrap();
1087        let invocation = RustcInvocation::parse(&[
1088            "--crate-name=widget".into(),
1089            "--crate-type=lib".into(),
1090            "--emit=dep-info,metadata".into(),
1091            source.clone().into_os_string(),
1092        ])
1093        .unwrap();
1094        let dep_info = RustcDepInfo::parse(&format!("output: {}\n", source.display())).unwrap();
1095        let discovered = invocation
1096            .discover_inputs(&dep_info, directory.path())
1097            .unwrap();
1098        let modified = std::fs::metadata(&source).unwrap().modified().unwrap();
1099
1100        assert_eq!(
1101            discovered.verify_not_modified_since(modified),
1102            Err(BypassReason::InputModifiedDuringCompilation(source))
1103        );
1104    }
1105
1106    #[test]
1107    fn profile_use_is_discovered_verified_and_rehashed_by_prediction() {
1108        let directory = tempfile::tempdir().unwrap();
1109        let root = directory.path();
1110        let source = root.join("lib.rs");
1111        let profile = root.join("profile.profdata");
1112        std::fs::write(&source, "pub fn library() {}\n").unwrap();
1113        std::fs::write(&profile, "first profile").unwrap();
1114        let invocation = RustcInvocation::parse(&[
1115            "--crate-name=widget".into(),
1116            "--crate-type=lib".into(),
1117            "--emit=dep-info,metadata".into(),
1118            format!("-Cprofile-use={}", profile.display()).into(),
1119            "lib.rs".into(),
1120        ])
1121        .unwrap();
1122        let mappings = vec![PathMapping::new(root, "workspace")];
1123        let dep_info = RustcDepInfo::parse("widget.d: lib.rs\n").unwrap();
1124        let discover = || {
1125            invocation
1126                .discover_inputs_with_mappings(
1127                    &dep_info,
1128                    root,
1129                    &mappings,
1130                    &mbx_cache_core::NoFileDigestCache,
1131                )
1132                .unwrap()
1133        };
1134        let initial_inputs = discover();
1135        assert!(
1136            initial_inputs
1137                .inputs
1138                .iter()
1139                .any(|input| input.path == profile)
1140        );
1141        let mut context = library_context(root, mappings.clone());
1142        initial_inputs.clone().apply_to(&mut context).unwrap();
1143        let initial_action = invocation.action(context.clone()).unwrap();
1144        let prediction = invocation.prediction(&context, &initial_inputs).unwrap();
1145
1146        std::fs::write(&profile, "updated profile").unwrap();
1147        assert_eq!(
1148            initial_inputs.verify(),
1149            Err(BypassReason::InputChanged(profile.clone()))
1150        );
1151        context.inputs.clear();
1152        let predicted = prediction
1153            .discover(root, &mappings, &mbx_cache_core::NoFileDigestCache)
1154            .unwrap();
1155        predicted.clone().apply_to(&mut context).unwrap();
1156        let predicted_action = invocation.action(context.clone()).unwrap();
1157        assert_ne!(predicted_action.digest, initial_action.digest);
1158        context.inputs.clear();
1159        discover().apply_to(&mut context).unwrap();
1160        assert_eq!(predicted_action, invocation.action(context).unwrap());
1161
1162        let missing_profile = root.join("missing.profdata");
1163        let missing_invocation = RustcInvocation::parse(&[
1164            "--crate-name=widget".into(),
1165            "--crate-type=lib".into(),
1166            "--emit=dep-info,metadata".into(),
1167            format!("-Cprofile-use={}", missing_profile.display()).into(),
1168            "lib.rs".into(),
1169        ])
1170        .unwrap();
1171        assert!(matches!(
1172            missing_invocation.discover_inputs_with_mappings(
1173                &dep_info,
1174                root,
1175                &mappings,
1176                &mbx_cache_core::NoFileDigestCache,
1177            ),
1178            Err(BypassReason::InputRead { path, .. }) if path == missing_profile
1179        ));
1180    }
1181
1182    #[cfg(unix)]
1183    #[test]
1184    fn precompile_snapshot_does_not_depend_on_the_host_clock() {
1185        let directory = tempfile::tempdir().unwrap();
1186        let source = directory.path().join("lib.rs");
1187        std::fs::write(&source, "pub fn library() {0}\n").unwrap();
1188        let invocation = RustcInvocation::parse(&[
1189            "--crate-name=widget".into(),
1190            "--crate-type=lib".into(),
1191            "--emit=dep-info,metadata".into(),
1192            source.clone().into_os_string(),
1193        ])
1194        .unwrap();
1195        let dep_info = RustcDepInfo::parse(&format!("output: {}\n", source.display())).unwrap();
1196        let discovered = invocation
1197            .discover_inputs(&dep_info, directory.path())
1198            .unwrap();
1199        let snapshot = FileSnapshot::capture(&source).unwrap().unwrap();
1200        let before = BTreeMap::from([(source.clone(), snapshot)]);
1201
1202        // Every ordinary mtime is after the epoch. The unchanged identity is
1203        // nevertheless enough proof when the filesystem clock is far ahead.
1204        discovered
1205            .verify_not_modified_since_with_snapshots(SystemTime::UNIX_EPOCH, &before)
1206            .unwrap();
1207
1208        // Conversely, a filesystem clock far behind must not conceal a write.
1209        // Let the coarse ZFS timestamp tick advance before this same-length rewrite.
1210        std::thread::sleep(std::time::Duration::from_millis(20));
1211        std::fs::write(&source, "pub fn library() {1}\n").unwrap();
1212        let discovered = invocation
1213            .discover_inputs(&dep_info, directory.path())
1214            .unwrap();
1215        assert_eq!(
1216            discovered.verify_not_modified_since_with_snapshots(
1217                SystemTime::now() + std::time::Duration::from_secs(60),
1218                &before,
1219            ),
1220            Err(BypassReason::InputModifiedDuringCompilation(source))
1221        );
1222    }
1223
1224    #[cfg(unix)]
1225    #[test]
1226    fn snapshot_only_check_compares_sources_after_a_generated_file() {
1227        let directory = tempfile::tempdir().unwrap();
1228        let source = directory.path().join("lib.rs");
1229        let generated = directory.path().join("a_generated.rs");
1230        std::fs::write(&source, "pub fn library() {0}\n").unwrap();
1231        let invocation = RustcInvocation::parse(&[
1232            "--crate-name=widget".into(),
1233            "--crate-type=lib".into(),
1234            "--emit=dep-info,metadata".into(),
1235            source.clone().into_os_string(),
1236        ])
1237        .unwrap();
1238        let before = BTreeMap::from([(
1239            source.clone(),
1240            FileSnapshot::capture(&source).unwrap().unwrap(),
1241        )]);
1242        // The compiler writes a generated input that sorts first, then the
1243        // source changes while it runs.
1244        std::thread::sleep(std::time::Duration::from_millis(20));
1245        std::fs::write(&generated, "// generated\n").unwrap();
1246        // Far beyond any fixed offset from the start time.
1247        std::fs::File::options()
1248            .write(true)
1249            .open(&generated)
1250            .unwrap()
1251            .set_modified(SystemTime::now() + std::time::Duration::from_secs(30 * 86_400))
1252            .unwrap();
1253        std::fs::write(&source, "pub fn library() {1}\n").unwrap();
1254        let dep_info = RustcDepInfo::parse(&format!(
1255            "output: {} {}\n",
1256            generated.display(),
1257            source.display()
1258        ))
1259        .unwrap();
1260        let discovered = invocation
1261            .discover_inputs(&dep_info, directory.path())
1262            .unwrap();
1263        assert_eq!(
1264            discovered.verify_snapshots_unchanged(&before),
1265            Err(BypassReason::InputModifiedDuringCompilation(source))
1266        );
1267    }
1268
1269    /// An external MSVC toolset directory, outside every mapped root.
1270    fn toolchain_native_directory(version: &str) -> PathBuf {
1271        if cfg!(windows) {
1272            PathBuf::from(format!(
1273                r"C:\Program Files\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\{version}\lib\x64"
1274            ))
1275        } else {
1276            PathBuf::from(format!("/opt/msvc/{version}/lib/x64"))
1277        }
1278    }
1279
1280    fn library_with_native_search(source: &Path, directory: &Path) -> RustcInvocation {
1281        RustcInvocation::parse(&[
1282            "--crate-name=widget".into(),
1283            "--crate-type=lib".into(),
1284            "--emit=metadata,link".into(),
1285            format!("-Lnative={}", directory.display()).into(),
1286            source.to_path_buf().into_os_string(),
1287        ])
1288        .unwrap()
1289    }
1290
1291    fn library_context(root: &Path, mappings: Vec<PathMapping>) -> ActionContext {
1292        ActionContext {
1293            compiler: crate::CompilerIdentity {
1294                toolchain: "core:rust@test".into(),
1295                rustc_version: "test".into(),
1296                host: std::env::consts::ARCH.into(),
1297                driver: None,
1298            },
1299            working_dir: root.to_path_buf(),
1300            path_mappings: mappings,
1301            environment: BTreeMap::new(),
1302            portable_environment: BTreeSet::new(),
1303            inputs: Vec::new(),
1304        }
1305    }
1306
1307    #[cfg(windows)]
1308    #[test]
1309    fn unmapped_toolchain_directory_cannot_hide_a_static_archive() {
1310        let directory = tempfile::tempdir().unwrap();
1311        let root = directory.path();
1312        let source = root.join("lib.rs");
1313        std::fs::write(&source, "pub fn library() {}\n").unwrap();
1314        let toolchain = toolchain_native_directory("14.51.36231");
1315        let invocation = library_with_native_search(&source, &toolchain);
1316        let mappings = vec![PathMapping::new(root, "workspace")];
1317        let dep_info = RustcDepInfo::parse(&format!("output: {}\n", source.display())).unwrap();
1318
1319        let context = library_context(root, mappings.clone());
1320        assert!(matches!(
1321            invocation.invocation_digest(&context),
1322            Err(BypassReason::UnmappedAbsolutePath(path)) if path == toolchain
1323        ));
1324        assert_eq!(
1325            invocation.discover_inputs_with_mappings(
1326                &dep_info,
1327                root,
1328                &mappings,
1329                &mbx_cache_core::NoFileDigestCache,
1330            ),
1331            Err(BypassReason::UnsupportedSearchPath("native".into()))
1332        );
1333    }
1334
1335    #[test]
1336    fn source_level_static_link_cannot_hide_an_unmapped_archive() {
1337        let directory = tempfile::tempdir().unwrap();
1338        let workspace = directory.path().join("workspace");
1339        let external = directory.path().join("external");
1340        std::fs::create_dir(&workspace).unwrap();
1341        std::fs::create_dir(&external).unwrap();
1342        let source = workspace.join("lib.rs");
1343        std::fs::write(
1344            &source,
1345            "#[link(name = \"foo\", kind = \"static\")] unsafe extern \"C\" {}\n",
1346        )
1347        .unwrap();
1348        std::fs::write(external.join("libfoo.a"), b"first archive").unwrap();
1349        let invocation = library_with_native_search(&source, &external);
1350        let mappings = vec![PathMapping::new(&workspace, "workspace")];
1351        let context = library_context(&workspace, mappings.clone());
1352        let dep_info = RustcDepInfo::parse(&format!("output: {}\n", source.display())).unwrap();
1353
1354        // rustc's dep-info names the source but not an archive from #[link].
1355        // A path-only key would restore a stale rlib after libfoo.a changed.
1356        assert!(matches!(
1357            invocation.invocation_digest(&context),
1358            Err(BypassReason::UnmappedAbsolutePath(path)) if path == external
1359        ));
1360        assert_eq!(
1361            invocation.discover_inputs_with_mappings(
1362                &dep_info,
1363                &workspace,
1364                &mappings,
1365                &mbx_cache_core::NoFileDigestCache,
1366            ),
1367            Err(BypassReason::UnsupportedSearchPath("native".into()))
1368        );
1369    }
1370
1371    #[cfg(windows)]
1372    #[test]
1373    fn project_directory_with_toolchain_suffix_is_not_trusted() {
1374        let directory = tempfile::tempdir().unwrap();
1375        let root = directory.path().join("workspace");
1376        std::fs::create_dir(&root).unwrap();
1377        let source = root.join("lib.rs");
1378        std::fs::write(&source, "pub fn library() {}\n").unwrap();
1379        let fake_toolchain = directory.path().join("MSVC/14.51.36231/lib/x64");
1380        let invocation = library_with_native_search(&source, &fake_toolchain);
1381        let context = library_context(&root, vec![PathMapping::new(&root, "workspace")]);
1382
1383        // The apparent toolset version cannot make a mutable project archive inert.
1384        assert!(matches!(
1385            invocation.invocation_digest(&context),
1386            Err(BypassReason::UnmappedAbsolutePath(path)) if path == fake_toolchain
1387        ));
1388    }
1389
1390    #[test]
1391    fn unmapped_native_directory_still_refuses_a_native_link() {
1392        let directory = tempfile::tempdir().unwrap();
1393        let root = directory.path();
1394        let source = root.join("main.rs");
1395        std::fs::write(&source, "fn main() {}\n").unwrap();
1396        let toolchain = toolchain_native_directory("14.51.36231");
1397        let invocation = RustcInvocation::parse_with(
1398            &[
1399                "--crate-name=app".into(),
1400                "--crate-type=bin".into(),
1401                "--emit=link".into(),
1402                format!("-Lnative={}", toolchain.display()).into(),
1403                source.clone().into_os_string(),
1404            ],
1405            crate::ParseOptions::caching_native_links(true),
1406        )
1407        .unwrap();
1408        let mappings = vec![PathMapping::new(root, "workspace")];
1409
1410        // A linker reads those directories, so their contents stay inputs the
1411        // key must account for, and an unmapped one stays a bypass.
1412        let context = library_context(root, mappings.clone());
1413        assert!(matches!(
1414            invocation.invocation_digest(&context),
1415            Err(BypassReason::UnmappedAbsolutePath(_))
1416        ));
1417        let dep_info = RustcDepInfo::parse(&format!("output: {}\n", source.display())).unwrap();
1418        assert_eq!(
1419            invocation.discover_inputs_with_mappings(
1420                &dep_info,
1421                root,
1422                &mappings,
1423                &mbx_cache_core::NoFileDigestCache
1424            ),
1425            Err(BypassReason::UnsupportedSearchPath("native".into()))
1426        );
1427    }
1428
1429    #[test]
1430    fn discovery_resolves_parent_components_against_the_working_directory() {
1431        let directory = tempfile::tempdir().unwrap();
1432        let root = directory.path().join("project");
1433        let shared = directory.path().join("shared.rs");
1434        std::fs::create_dir(&root).unwrap();
1435        std::fs::write(&shared, "pub fn shared() {}\n").unwrap();
1436
1437        let invocation = RustcInvocation::parse(&args(&[
1438            "--crate-name=widget",
1439            "--crate-type=lib",
1440            "--emit=metadata",
1441            "../shared.rs",
1442        ]))
1443        .unwrap();
1444        let dep_info = RustcDepInfo::parse("output: ../shared.rs\n").unwrap();
1445        let discovered = invocation.discover_inputs(&dep_info, &root).unwrap();
1446
1447        assert_eq!(discovered.inputs.len(), 1);
1448        assert_eq!(discovered.inputs[0].path, shared);
1449    }
1450
1451    #[test]
1452    fn rustc_dep_info_round_trip_discovers_real_inputs() {
1453        let directory = tempfile::tempdir().unwrap();
1454        let root = directory.path();
1455        std::fs::write(
1456            root.join("lib.rs"),
1457            "mod child; const _: &str = include_str!(\"data file.txt\"); \
1458             const _: &str = env!(\"MBX_DISCOVERY_TEST\"); \
1459             const _: Option<&str> = option_env!(\"MBX_DISCOVERY_UNSET\");",
1460        )
1461        .unwrap();
1462        std::fs::write(root.join("child.rs"), "pub fn child() {}\n").unwrap();
1463        std::fs::write(root.join("data file.txt"), "included\n").unwrap();
1464
1465        let invocation = RustcInvocation::parse(&args(&[
1466            "--crate-name=mbx_cache_discovery_test",
1467            "--crate-type=lib",
1468            "--emit=metadata,link",
1469            "lib.rs",
1470        ]))
1471        .unwrap();
1472        let dep_info_path = root.join("discovery inputs.d");
1473        let discovery_command = invocation.dep_info_command(&dep_info_path).unwrap();
1474        let rustc = std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into());
1475        let output = match Command::new(rustc)
1476            .args(discovery_command.arguments())
1477            .current_dir(root)
1478            .env("MBX_DISCOVERY_TEST", "observed")
1479            .env_remove("MBX_DISCOVERY_UNSET")
1480            .output()
1481        {
1482            Ok(output) => output,
1483            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return,
1484            Err(error) => panic!("failed to execute rustc: {error}"),
1485        };
1486        assert!(
1487            output.status.success(),
1488            "{}",
1489            String::from_utf8_lossy(&output.stderr)
1490        );
1491        let parsed = RustcDepInfo::read(&dep_info_path).unwrap();
1492        let discovered = invocation.discover_inputs(&parsed, root).unwrap();
1493        assert_eq!(
1494            discovered.environment["MBX_DISCOVERY_TEST"],
1495            Some("observed".into())
1496        );
1497        assert_eq!(discovered.environment["MBX_DISCOVERY_UNSET"], None);
1498        assert_eq!(discovered.inputs.len(), 3);
1499        assert!(
1500            discovered
1501                .inputs
1502                .iter()
1503                .all(|input| input.digest.algorithm == "blake3")
1504        );
1505        let mut context = ActionContext {
1506            compiler: crate::CompilerIdentity {
1507                toolchain: "core:rust@test".into(),
1508                rustc_version: "test".into(),
1509                host: std::env::consts::ARCH.into(),
1510                driver: None,
1511            },
1512            working_dir: root.to_path_buf(),
1513            path_mappings: vec![crate::PathMapping::new(root, "workspace")],
1514            environment: BTreeMap::new(),
1515            portable_environment: BTreeSet::new(),
1516            inputs: Vec::new(),
1517        };
1518        discovered.clone().apply_to(&mut context).unwrap();
1519        let action = invocation.action(context).unwrap();
1520        assert!(
1521            String::from_utf8(action.bytes)
1522                .unwrap()
1523                .contains(r#""MBX_DISCOVERY_TEST":"observed""#)
1524        );
1525        discovered.verify().unwrap();
1526        std::fs::write(root.join("child.rs"), "pub fn changed() {}\n").unwrap();
1527        assert_eq!(
1528            discovered.verify(),
1529            Err(BypassReason::InputChanged(root.join("child.rs")))
1530        );
1531    }
1532
1533    /// A ledger that answers with a sentinel and remembers what was recorded.
1534    struct SentinelLedger {
1535        known: FileIdentity,
1536        digest: CacheDigest,
1537        recorded: std::sync::Mutex<Vec<RecordedFileDigest>>,
1538    }
1539
1540    impl FileDigestCache for SentinelLedger {
1541        fn find(&self, scope: FileDigestScope, files: &[FileIdentity]) -> Vec<Option<CacheDigest>> {
1542            assert_eq!(scope, FileDigestScope::Content);
1543            files
1544                .iter()
1545                .map(|file| (*file == self.known).then(|| self.digest.clone()))
1546                .collect()
1547        }
1548
1549        fn record(&self, scope: FileDigestScope, entries: Vec<RecordedFileDigest>) {
1550            assert_eq!(scope, FileDigestScope::Content);
1551            self.recorded.lock().unwrap().extend(entries);
1552        }
1553    }
1554
1555    #[cfg(unix)]
1556    struct ReplacingLedger {
1557        path: PathBuf,
1558        replacement: PathBuf,
1559        recorded: std::sync::Mutex<Vec<RecordedFileDigest>>,
1560    }
1561
1562    #[cfg(unix)]
1563    impl FileDigestCache for ReplacingLedger {
1564        fn find(&self, scope: FileDigestScope, files: &[FileIdentity]) -> Vec<Option<CacheDigest>> {
1565            assert_eq!(scope, FileDigestScope::Content);
1566            assert_eq!(files.len(), 1);
1567            std::fs::remove_file(&self.path).unwrap();
1568            std::fs::rename(&self.replacement, &self.path).unwrap();
1569            // Digests of files changed this moment are withheld from reuse.
1570            std::thread::sleep(std::time::Duration::from_millis(50));
1571            vec![None]
1572        }
1573
1574        fn record(&self, scope: FileDigestScope, entries: Vec<RecordedFileDigest>) {
1575            assert_eq!(scope, FileDigestScope::Content);
1576            self.recorded.lock().unwrap().extend(entries);
1577        }
1578    }
1579
1580    #[cfg(unix)]
1581    #[test]
1582    fn discovery_binds_a_replacement_digest_to_the_replacement_identity() {
1583        let directory = tempfile::tempdir().unwrap();
1584        let root = directory.path();
1585        let path = root.join("libdep.rlib");
1586        let replacement = root.join("replacement.rlib");
1587        std::fs::write(&path, b"original....").unwrap();
1588        std::fs::File::options()
1589            .write(true)
1590            .open(&path)
1591            .unwrap()
1592            .set_times(std::fs::FileTimes::new().set_modified(SystemTime::UNIX_EPOCH))
1593            .unwrap();
1594        std::fs::write(&replacement, b"replacement!").unwrap();
1595        std::fs::File::options()
1596            .write(true)
1597            .open(&replacement)
1598            .unwrap()
1599            .set_times(std::fs::FileTimes::new().set_modified(SystemTime::UNIX_EPOCH))
1600            .unwrap();
1601        let ledger = ReplacingLedger {
1602            path: path.clone(),
1603            replacement,
1604            recorded: std::sync::Mutex::new(Vec::new()),
1605        };
1606
1607        let discovered = DiscoveredInputs::from_paths(
1608            root,
1609            BTreeSet::from([path.clone()]),
1610            BTreeMap::new(),
1611            &ledger,
1612        )
1613        .unwrap();
1614        let current = FileIdentity::for_digest_cache(&path, &std::fs::metadata(&path).unwrap())
1615            .unwrap()
1616            .unwrap();
1617        let digest = CacheDigest::blake3_file(&path).unwrap();
1618
1619        assert_eq!(discovered.inputs[0].digest, digest);
1620        assert_eq!(discovered.identities[0].as_ref(), Some(&current));
1621        assert_eq!(
1622            ledger.recorded.lock().unwrap().as_slice(),
1623            &[RecordedFileDigest {
1624                file: current,
1625                digest,
1626            }]
1627        );
1628        discovered.verify().unwrap();
1629    }
1630
1631    #[test]
1632    fn discovery_reuses_recorded_digests_and_records_fresh_ones() {
1633        let directory = tempfile::tempdir().unwrap();
1634        let root = directory.path();
1635        let known_path = root.join("libdep.rlib");
1636        let fresh_path = root.join("lib.rs");
1637        std::fs::write(&known_path, b"rlib bytes").unwrap();
1638        std::fs::write(&fresh_path, b"fn lib() {}").unwrap();
1639        // Digests of files written this moment are withheld from reuse.
1640        std::thread::sleep(std::time::Duration::from_millis(50));
1641        let metadata = std::fs::metadata(&known_path).unwrap();
1642        // A sentinel digest that hashing could never produce proves the read
1643        // was skipped: the discovered input carries it verbatim.
1644        let sentinel = CacheDigest {
1645            algorithm: "blake3".into(),
1646            hash: "c".repeat(64),
1647            size: metadata.len(),
1648        };
1649        let ledger = SentinelLedger {
1650            known: FileIdentity::describe(&known_path, &metadata).unwrap(),
1651            digest: sentinel.clone(),
1652            recorded: std::sync::Mutex::new(Vec::new()),
1653        };
1654
1655        let discovered = DiscoveredInputs::from_paths(
1656            root,
1657            BTreeSet::from([known_path.clone(), fresh_path.clone()]),
1658            BTreeMap::new(),
1659            &ledger,
1660        )
1661        .unwrap();
1662
1663        let by_path = |path: &Path| {
1664            discovered
1665                .inputs
1666                .iter()
1667                .find(|input| input.path == path)
1668                .unwrap()
1669                .digest
1670                .clone()
1671        };
1672        assert_eq!(
1673            by_path(&known_path),
1674            sentinel,
1675            "the recorded digest answers"
1676        );
1677        assert_eq!(
1678            by_path(&fresh_path),
1679            CacheDigest::blake3_file(&fresh_path).unwrap(),
1680            "an unrecorded file is hashed"
1681        );
1682        let recorded = ledger.recorded.lock().unwrap();
1683        assert_eq!(recorded.len(), 1, "only the fresh hash is recorded");
1684        assert_eq!(recorded[0].file.path, fresh_path);
1685        assert_eq!(recorded[0].digest, by_path(&fresh_path));
1686    }
1687
1688    /// Verification after the compiler runs confirms an input by its recorded
1689    /// identity rather than by reading it again; a file that has moved on is
1690    /// still read and still fails. Only where the identity carries a change
1691    /// time, which is what makes the stat as good as the read.
1692    #[cfg(unix)]
1693    #[test]
1694    fn verification_trusts_an_unchanged_identity_and_rereads_a_changed_one() {
1695        let directory = tempfile::tempdir().unwrap();
1696        let root = directory.path();
1697        let known_path = root.join("libdep.rlib");
1698        std::fs::write(&known_path, b"rlib bytes").unwrap();
1699        let metadata = std::fs::metadata(&known_path).unwrap();
1700        // The sentinel could never come from hashing the file, so a verify
1701        // that passes can only have trusted the identity.
1702        let sentinel = CacheDigest {
1703            algorithm: "blake3".into(),
1704            hash: "c".repeat(64),
1705            size: metadata.len(),
1706        };
1707        let ledger = SentinelLedger {
1708            known: FileIdentity::describe(&known_path, &metadata).unwrap(),
1709            digest: sentinel,
1710            recorded: std::sync::Mutex::new(Vec::new()),
1711        };
1712        let discovered = DiscoveredInputs::from_paths(
1713            root,
1714            BTreeSet::from([known_path.clone()]),
1715            BTreeMap::new(),
1716            &ledger,
1717        )
1718        .unwrap();
1719
1720        discovered.verify().unwrap();
1721
1722        // Rewritten with the same length: the identity moves with the write,
1723        // so the file is read again and the sentinel no longer matches it.
1724        std::thread::sleep(std::time::Duration::from_millis(20));
1725        std::fs::write(&known_path, b"RLIB BYTES").unwrap();
1726        assert_eq!(
1727            discovered.verify(),
1728            Err(BypassReason::InputChanged(known_path.clone()))
1729        );
1730
1731        std::fs::remove_file(&known_path).unwrap();
1732        assert!(matches!(
1733            discovered.verify(),
1734            Err(BypassReason::InputRead { path, .. }) if path == known_path
1735        ));
1736    }
1737
1738    /// A rewrite that restores length and modification time must still be
1739    /// hashed: the platform change token moves with every write, so the
1740    /// identity the ledger recorded no longer describes the file.
1741    #[cfg(unix)]
1742    #[test]
1743    fn a_disguised_rewrite_is_not_answered_from_the_ledger() {
1744        let directory = tempfile::tempdir().unwrap();
1745        let root = directory.path();
1746        let path = root.join("lib.rs");
1747        std::fs::write(&path, b"fn lib() -> u8 { 1 }").unwrap();
1748        let before = std::fs::metadata(&path).unwrap();
1749        let identity = FileIdentity::describe(&path, &before).unwrap();
1750
1751        // Same length, modification time put back: only the change token can
1752        // tell this file has new contents. Filesystems such as ZFS stamp
1753        // files from a 1 ms tick, so wait for the change token to move.
1754        std::thread::sleep(std::time::Duration::from_millis(20));
1755        std::fs::write(&path, b"fn lib() -> u8 { 2 }").unwrap();
1756        let file = std::fs::File::options().write(true).open(&path).unwrap();
1757        file.set_times(std::fs::FileTimes::new().set_modified(before.modified().unwrap()))
1758            .unwrap();
1759        drop(file);
1760        let after = std::fs::metadata(&path).unwrap();
1761        let disguised = FileIdentity::describe(&path, &after).unwrap();
1762        assert_eq!(disguised.len, identity.len);
1763        assert_eq!(disguised.modified, identity.modified);
1764        assert_ne!(
1765            disguised, identity,
1766            "the change token must expose the rewrite"
1767        );
1768
1769        let ledger = SentinelLedger {
1770            known: identity,
1771            digest: CacheDigest {
1772                algorithm: "blake3".into(),
1773                hash: "e".repeat(64),
1774                size: after.len(),
1775            },
1776            recorded: std::sync::Mutex::new(Vec::new()),
1777        };
1778        let discovered = DiscoveredInputs::from_paths(
1779            root,
1780            BTreeSet::from([path.clone()]),
1781            BTreeMap::new(),
1782            &ledger,
1783        )
1784        .unwrap();
1785        assert_eq!(
1786            discovered.inputs[0].digest,
1787            CacheDigest::blake3_file(&path).unwrap(),
1788            "the disguised rewrite is hashed, not answered from the ledger"
1789        );
1790    }
1791    #[cfg(unix)]
1792    #[test]
1793    fn native_file_symlinks_are_rehashed_on_prediction() {
1794        use std::os::unix::fs::symlink;
1795        let directory = tempfile::tempdir().unwrap();
1796        let workspace = directory.path().join("workspace");
1797        let native = directory.path().join("cellar/lib");
1798        std::fs::create_dir_all(&workspace).unwrap();
1799        std::fs::create_dir_all(&native).unwrap();
1800        let source = workspace.join("lib.rs");
1801        std::fs::write(&source, "pub fn value() {}\n").unwrap();
1802        std::fs::write(native.join("libssl.3.dylib"), "first").unwrap();
1803        symlink("libssl.3.dylib", native.join("libssl.dylib")).unwrap();
1804        let opt = directory.path().join("opt");
1805        symlink(&native, &opt).unwrap();
1806        let invocation = library_with_native_search(&source, &opt);
1807        let mappings = vec![
1808            PathMapping::new(&workspace, "workspace"),
1809            PathMapping::new(&opt, "native"),
1810        ];
1811        let dep_info = RustcDepInfo {
1812            files: vec![source],
1813            environment: BTreeMap::new(),
1814        };
1815        let discover = || {
1816            invocation
1817                .discover_inputs_with_mappings(
1818                    &dep_info,
1819                    &workspace,
1820                    &mappings,
1821                    &mbx_cache_core::NoFileDigestCache,
1822                )
1823                .unwrap()
1824        };
1825        let original = discover();
1826        let mut context = library_context(&workspace, mappings.clone());
1827        original.clone().apply_to(&mut context).unwrap();
1828        let initial = invocation.action(context.clone()).unwrap();
1829        let prediction = invocation.prediction(&context, &original).unwrap();
1830        context.inputs.clear();
1831        let mut previous = initial.digest;
1832        for change in ["contents", "add", "retarget", "remove"] {
1833            match change {
1834                "contents" => std::fs::write(native.join("libssl.3.dylib"), "updated").unwrap(),
1835                "add" => std::fs::write(native.join("libssl.4.dylib"), "replacement").unwrap(),
1836                "retarget" => {
1837                    std::fs::remove_file(native.join("libssl.dylib")).unwrap();
1838                    symlink("libssl.4.dylib", native.join("libssl.dylib")).unwrap();
1839                }
1840                _ => std::fs::remove_file(native.join("libssl.3.dylib")).unwrap(),
1841            }
1842            let predicted = prediction
1843                .discover(&workspace, &mappings, &mbx_cache_core::NoFileDigestCache)
1844                .unwrap();
1845            let mut predicted_context = context.clone();
1846            predicted.apply_to(&mut predicted_context).unwrap();
1847            let predicted_action = invocation.action(predicted_context).unwrap();
1848            let mut discovered_context = context.clone();
1849            discover().apply_to(&mut discovered_context).unwrap();
1850            assert_eq!(
1851                predicted_action,
1852                invocation.action(discovered_context).unwrap()
1853            );
1854            assert_ne!(predicted_action.digest, previous, "{change}");
1855            previous = predicted_action.digest;
1856        }
1857        std::fs::remove_file(native.join("libssl.dylib")).unwrap();
1858        let outside = directory.path().join("outside");
1859        std::fs::write(&outside, "untracked").unwrap();
1860        symlink(&outside, native.join("libssl.dylib")).unwrap();
1861        assert!(
1862            prediction
1863                .discover(&workspace, &mappings, &mbx_cache_core::NoFileDigestCache)
1864                .is_err()
1865        );
1866        std::fs::remove_file(native.join("libssl.dylib")).unwrap();
1867        symlink(".", native.join("loop")).unwrap();
1868        assert!(
1869            prediction
1870                .discover(&workspace, &mappings, &mbx_cache_core::NoFileDigestCache)
1871                .is_err()
1872        );
1873    }
1874}