Skip to main content

mbx_cache_rustc/
lib.rs

1//! Conservative parsing and action-key construction for `rustc` invocations.
2//!
3//! The adapter deliberately rejects any compiler option whose effect on the
4//! action key is unknown. Callers should treat [`BypassReason`] as a safe cache
5//! bypass, run the real compiler, and avoid publishing an action result.
6//!
7//! A typical integration parses an invocation, discovers precise inputs from
8//! rustc dep-info with [`RustcInvocation::discover_inputs`], adds them to an
9//! [`ActionContext`], and finally calls [`RustcInvocation::action`]. Path
10//! mappings make workspace-local absolute paths stable across machines.
11//!
12//! ```
13//! use mbx_cache_rustc::{PathMapping, normalize_mapped_path};
14//! use std::path::Path;
15//!
16//! let mappings = PathMapping::ordered(&[
17//!     PathMapping::new("/work/project", "workspace"),
18//! ]);
19//! assert_eq!(
20//!     normalize_mapped_path(
21//!         Path::new("src/lib.rs"),
22//!         Path::new("/work/project"),
23//!         &mappings,
24//!     )?,
25//!     "${workspace}/src/lib.rs",
26//! );
27//! # Ok::<(), mbx_cache_rustc::BypassReason>(())
28//! ```
29#![deny(missing_docs)]
30
31use mbx_cache_core::{
32    CacheDigest, FileDigestCache, PathAliases, PathMapping as SharedPathMapping,
33    PathNormalizationError, canonical_json, normalize_mapped_path as normalize_shared_path,
34    normalize_resolved_mapped_path_with as normalize_resolved_shared_path_with,
35    resolve_path_mappings,
36};
37use serde::{Deserialize, Deserializer, Serialize, Serializer};
38use std::collections::{BTreeMap, BTreeSet};
39use std::ffi::OsString;
40use std::path::{Component, Path, PathBuf};
41use thiserror::Error;
42
43mod dep_info;
44
45const NIX_STORE_ROOT: &str = "/nix/store";
46
47pub use dep_info::{DepInfoCommand, DiscoveredInputs, RustcDepInfo};
48
49/// Schema version embedded in canonical rustc action descriptors.
50pub const ACTION_SCHEMA_VERSION: u8 = 1;
51/// Version of the rustc argument and input model used to construct keys.
52///
53/// Bumped to 2 when the dep-info and diagnostics stored with a result stopped
54/// carrying the publishing checkout's absolute paths. Entries written before
55/// that hold the old spelling, and nothing in them says so, so they are retired
56/// by the key rather than restored into a checkout they do not describe.
57pub const ADAPTER_VERSION: u8 = 2;
58
59impl BypassReason {
60    /// A stable, low-cardinality name for this reason.
61    ///
62    /// Many variants carry a path or a flag, so `Display` text cannot be
63    /// aggregated; statistics group by this instead.
64    pub fn kind(&self) -> &'static str {
65        self.into()
66    }
67
68    /// A concrete change that can make this invocation cacheable, when one is
69    /// available.
70    ///
71    /// Expected probes and failures that require adapter support return
72    /// `None`; callers can still explain those from [`BypassReason::kind`].
73    pub fn remediation(&self) -> Option<&'static str> {
74        match self {
75            Self::Incremental => Some(
76                "Set `MBX_INCREMENTAL=0`; mbx will then disable Cargo incremental state and cache the compilation.",
77            ),
78            Self::UnportableNativeLink(detail) if detail.contains("linker") => Some(
79                "Make the native linker resolvable on `PATH`, or configure a linker mbx can identify for this target.",
80            ),
81            Self::UnportableNativeLink(_) => Some(
82                "Remove the reported `-C` option from the active Cargo profile or `RUSTFLAGS` to make these links cacheable.",
83            ),
84            Self::UnknownFlag(_) | Self::UnknownCodegenOption(_) => Some(
85                "Remove the reported compiler option, or upgrade mbx if the option should be modeled.",
86            ),
87            Self::UnmodeledLinkArgument(_) => Some(
88                "Remove the reported linker argument, or keep these links uncached if the argument is required.",
89            ),
90            Self::UnmappedAbsolutePath(_) => Some(
91                "Move the input under the workspace, target, Cargo, toolchain, or home roots so mbx can give it a portable cache name.",
92            ),
93            Self::BuildScriptInputOverlapsOutputs(_) => Some(
94                "Keep compiler output directories outside watched trees, or narrow `rerun-if-changed` to source and asset paths.",
95            ),
96            _ => None,
97        }
98    }
99}
100
101impl From<PathNormalizationError> for BypassReason {
102    fn from(reason: PathNormalizationError) -> Self {
103        match reason {
104            PathNormalizationError::UnmappedAbsolutePath(path) => Self::UnmappedAbsolutePath(path),
105            PathNormalizationError::NonUtf8Path(path) => Self::NonUtf8Path(path),
106        }
107    }
108}
109
110const SUPPORTED_CODEGEN_OPTIONS: &[&str] = &[
111    "codegen-units",
112    "control-flow-guard",
113    "debug-assertions",
114    "debuginfo",
115    "default-linker-libraries",
116    "embed-bitcode",
117    "extra-filename",
118    "force-frame-pointers",
119    "force-unwind-tables",
120    "instrument-coverage",
121    "link-arg",
122    "link-args",
123    "link-dead-code",
124    "link-self-contained",
125    "linker-plugin-lto",
126    "lto",
127    "metadata",
128    "no-prepopulate-passes",
129    "opt-level",
130    "overflow-checks",
131    "panic",
132    "prefer-dynamic",
133    "relocation-model",
134    "rpath",
135    "save-temps",
136    "soft-float",
137    "split-debuginfo",
138    "split-dwarf-kind",
139    "strip",
140    "symbol-mangling-version",
141    "target-cpu",
142    "target-feature",
143    "tls-model",
144];
145
146const NATIVE_DIRECTORY_PREDICTION_PREFIX: &str = "@native-directory:";
147const MAX_PREDICTED_INPUTS: usize = 16 * 1024;
148// A compact payload is capped on the wire by the protocol. Bound its expanded
149// form too, so a hostile prefix chain cannot turn a small manifest into an
150// unreasonable allocation while it is being decoded.
151const MAX_DECODED_PREDICTION_BYTES: usize = 16 * 1024 * 1024;
152const MAX_NATIVE_INPUT_BYTES: u64 = 2 * 1024 * 1024 * 1024;
153
154/// Built-in WebAssembly targets whose default linkers and CRT inputs ship in
155/// the Rust toolchain. Custom target specs never enter this list.
156const COMPILER_BUNDLED_WASM_TARGETS: &[&str] = &[
157    "wasm32-unknown-unknown",
158    "wasm32-wasip1",
159    "wasm32-wasip1-threads",
160    "wasm32-wasip2",
161    "wasm32v1-none",
162    "wasm64-unknown-unknown",
163];
164
165#[derive(Debug, Clone, PartialEq, Eq, Error, strum::IntoStaticStr)]
166#[strum(serialize_all = "kebab-case")]
167/// Reason an invocation cannot safely use the action cache.
168///
169/// A bypass is an expected conservative outcome, not necessarily a compiler
170/// error. Variants carry diagnostic context while [`BypassReason::kind`]
171/// provides a stable aggregation key.
172///
173/// This set exists to shrink: every invocation the adapter learns to model
174/// retires a variant, and every construct it learns to reject adds one. Match
175/// on [`BypassReason::kind`] for aggregation rather than on the variants.
176#[non_exhaustive]
177pub enum BypassReason {
178    /// An argument cannot be represented in the canonical UTF-8 key.
179    #[error("rustc argument {index} is not valid UTF-8")]
180    NonUtf8Argument {
181        /// Zero-based index in the argument slice.
182        index: usize,
183    },
184    /// A rustc response file could not be read or parsed exactly.
185    #[error("could not model rustc response file: {0}")]
186    ResponseFile(String),
187    /// A compiler flag is not modeled by this adapter version.
188    #[error("rustc flag is not modeled by the cache adapter: {0}")]
189    UnknownFlag(String),
190    /// A `-C` option is not modeled by this adapter version.
191    #[error("rustc codegen option is not modeled by the cache adapter: {0}")]
192    UnknownCodegenOption(String),
193    /// A recognized flag was not followed by its required value.
194    #[error("rustc flag requires a value: {0}")]
195    MissingValue(String),
196    /// The invocation queries compiler information instead of compiling.
197    #[error("rustc invocation is a compiler query, not a compilation")]
198    CompilerQuery,
199    /// Source would be read from standard input and cannot be rediscovered.
200    #[error("rustc invocation reads source from standard input")]
201    StandardInput,
202    /// No Rust source input was supplied.
203    #[error("rustc invocation has no source input")]
204    MissingInput,
205    /// More than one source input was supplied.
206    #[error("rustc invocation has multiple source inputs")]
207    MultipleInputs,
208    /// Incremental state makes the outputs unsuitable for action caching.
209    #[error("incremental compilation cannot be combined with action caching")]
210    Incremental,
211    /// The requested crate type is outside the supported cacheability tier.
212    #[error("rustc crate type is not cacheable yet: {0}")]
213    UnsupportedCrateType(String),
214    /// The requested emit kind is outside the supported cacheability tier.
215    #[error("rustc output type is not cacheable yet: {0}")]
216    UnsupportedEmit(String),
217    /// The invocation emits no artifact in the supported cacheability tier.
218    #[error("rustc invocation does not emit a cacheable artifact")]
219    NoCacheableOutput,
220    /// The invocation does not emit the dep-info needed for input discovery.
221    #[error("rustc invocation does not emit dependency information")]
222    NoDepInfo,
223    /// Outputs cannot be represented as one cache directory.
224    #[error("rustc output paths do not share one directory")]
225    SplitOutputDirectories,
226    /// An output path does not name a file.
227    #[error("rustc output path has no file name: {0}")]
228    InvalidOutputPath(PathBuf),
229    /// `-o` leaves the name of an implicit emit ambiguous.
230    #[error("rustc -o with an emit that has no explicit path is not modeled: {0}")]
231    ImplicitEmitWithOutputFile(PathBuf),
232    /// A linked output hands its native libraries to a linker whose search
233    /// is not modeled; only a library emit can name what rustc reads.
234    #[error("native library on a linked output is not cacheable yet: {0}")]
235    NativeLibrary(String),
236    /// A static library named by `-l` is not in any directory rustc would
237    /// read it from, so there is no archive to hash.
238    #[error("native static library was not found on any search path: {0}")]
239    MissingNativeLibrary(String),
240    /// A custom target specification chooses its own static-library file
241    /// names, so the archive rustc would read cannot be named without it.
242    #[error("static library file names are not known for a custom target: {0}")]
243    CustomTargetNativeLibrary(String),
244    /// An output's name does not say whether it is a program or a library.
245    #[error("rustc output name does not distinguish a program from a library: {0}")]
246    AmbiguousOutputName(PathBuf),
247    /// A native link would embed something no other checkout can reproduce.
248    #[error("native link is not reproducible across checkouts: {0}")]
249    UnportableNativeLink(String),
250    /// A linked output was given an argument to pass on to its linker.
251    #[error("rustc link argument is not modeled by the cache adapter: {0}")]
252    UnmodeledLinkArgument(String),
253    /// A library search-path kind is not modeled.
254    #[error("rustc search path kind is not cacheable yet: {0}")]
255    UnsupportedSearchPath(String),
256    /// An extern name does not resolve to a concrete input artifact.
257    #[error("rustc extern does not identify an input artifact: {0}")]
258    UnresolvedExtern(String),
259    /// An absolute path has no stable placeholder mapping.
260    #[error("absolute path has no stable cache mapping: {0}")]
261    UnmappedAbsolutePath(PathBuf),
262    /// A path cannot be represented in a canonical UTF-8 action key.
263    #[error("cache key paths must be valid UTF-8: {0}")]
264    NonUtf8Path(PathBuf),
265    /// The action working directory is not absolute.
266    #[error("cache action working directory must be absolute: {0}")]
267    RelativeWorkingDirectory(PathBuf),
268    /// A path-mapping root is not absolute.
269    #[error("cache path mapping must use an absolute root: {0}")]
270    RelativePathMapping(PathBuf),
271    /// A mapping placeholder is empty or contains unsafe characters.
272    #[error("cache path mapping placeholder is invalid: {0}")]
273    InvalidPathPlaceholder(String),
274    /// An input referenced by compiler arguments is missing from the context.
275    #[error("required compiler input was not provided: {0}")]
276    MissingRequiredInput(String),
277    /// A supplied compiler-input digest is malformed.
278    #[error("compiler input has an invalid digest: {0}")]
279    InvalidInputDigest(String),
280    /// One normalized input path has multiple distinct digests.
281    #[error("compiler input appears more than once with different content: {0}")]
282    ConflictingInput(String),
283    /// rustc dep-info does not follow the supported format.
284    #[error("rustc dep-info is malformed: {0}")]
285    MalformedDepInfo(String),
286    /// A dep-info file could not be read as UTF-8 text.
287    #[error("failed to read rustc dep-info {path}: {message}")]
288    DepInfoRead {
289        /// Dep-info file path.
290        path: PathBuf,
291        /// Underlying I/O or decoding error.
292        message: String,
293    },
294    /// The requested dep-info output path is not absolute.
295    #[error("rustc dep-info output path must be absolute: {0}")]
296    RelativeDepInfoPath(PathBuf),
297    /// A dep-info output path contains a comma and cannot be safely rendered.
298    #[error("rustc dep-info output path cannot contain a comma: {0}")]
299    UnsafeDepInfoPath(PathBuf),
300    /// A discovered compiler input could not be read or was not a file.
301    #[error("failed to read compiler input {path}: {message}")]
302    InputRead {
303        /// Compiler-input path.
304        path: PathBuf,
305        /// Underlying filesystem error.
306        message: String,
307    },
308    /// A declared build-script input includes files the compiler writes.
309    #[error("declared build-script input overlaps compiler outputs: {0}")]
310    BuildScriptInputOverlapsOutputs(PathBuf),
311    /// Cargo has not yet written the build script's recorded declarations.
312    ///
313    /// A build script that runs `$RUSTC` as a probe does so before it exits,
314    /// and Cargo writes its output record only afterwards.
315    #[error("Cargo has not recorded the build script's declarations yet: {0}")]
316    BuildScriptDeclarationsPending(PathBuf),
317    /// A build script's watched paths or environment changed after discovery.
318    /// The path identifies Cargo's recorded declarations, not a changed input.
319    #[error("build-script inputs changed during compilation (declarations: {0})")]
320    BuildScriptInputsChanged(PathBuf),
321    /// Input contents changed after they were hashed.
322    #[error("compiler input changed after discovery: {0}")]
323    InputChanged(PathBuf),
324    /// An input's modification time overlaps the compiler execution.
325    #[error("compiler input was modified during compilation: {0}")]
326    InputModifiedDuringCompilation(PathBuf),
327    /// An input's metadata-change token moved while the compiler ran, but
328    /// not its length, modification time or file object: a metadata write
329    /// that does not prove new contents, so the result is kept uncached.
330    #[error("compiler input metadata changed during compilation: {0}")]
331    InputMetadataChangedDuringCompilation(PathBuf),
332    /// Discovered inputs and the action use different working directories.
333    #[error("discovered inputs were collected from a different working directory")]
334    DiscoveryWorkingDirectory,
335    /// One observed environment input has conflicting values.
336    #[error("compiler environment input has conflicting values: {0}")]
337    ConflictingEnvironment(String),
338    /// Canonical action serialization failed.
339    #[error("failed to serialize the rustc action: {0}")]
340    Serialization(String),
341    /// The stored prediction uses an unsupported version or exceeds limits.
342    #[error("rustc action prediction is unsupported")]
343    UnsupportedPrediction,
344    /// A normalized predicted path cannot be mapped back to the host.
345    #[error("rustc action prediction contains an invalid input path: {0}")]
346    InvalidPredictedInput(String),
347}
348
349/// Whether a `-L` kind makes rustc look for native libraries. A bare `-L path`,
350/// which is what an untyped `cargo:rustc-link-search` produces, is `all`: it
351/// searches for crates and native libraries alike, so it is held to the same
352/// rules as `native`.
353fn searches_native(kind: &str) -> bool {
354    matches!(kind, "native" | "all")
355}
356
357#[derive(Debug, Clone, PartialEq, Eq)]
358enum Argument {
359    Plain(String),
360    Path {
361        flag: String,
362        path: PathBuf,
363    },
364    SearchPath {
365        kind: String,
366        path: PathBuf,
367    },
368    Extern {
369        name: String,
370        path: Option<PathBuf>,
371    },
372    Emit(Vec<Emit>),
373    RemapPath {
374        from: PathBuf,
375        to: String,
376    },
377    /// A single @rpath filename used as a macOS proc macro install name.
378    InstallName(String),
379    /// An `-oso_prefix` handed to ld64, whose path strips checkout-specific
380    /// prefixes from the debug map the linker records.
381    OsoPrefix {
382        path: PathBuf,
383        trailing_slash: bool,
384    },
385    /// A `-fuse-ld=<name>` handed to the driver, selecting which linker a
386    /// link invokes. Modeled for native links only, where the linker identity
387    /// probe resolves and pins the linker it names.
388    FuseLd(String),
389    /// A `-Wl,-rpath,<absolute dir>` handed to ld64, which records the
390    /// directory as an `LC_RPATH` load command and never searches it while
391    /// linking. The text is therefore the whole input and is keyed as written.
392    Rpath(String),
393}
394
395#[derive(Debug, Clone, PartialEq, Eq)]
396struct Emit {
397    kind: String,
398    path: Option<PathBuf>,
399}
400
401#[derive(Debug, Clone, PartialEq, Eq)]
402/// Parsed, cache-safe model of one `rustc` command line.
403///
404/// Fields are intentionally private so new modeled flags can be added without
405/// exposing the adapter's internal representation.
406pub struct RustcInvocation {
407    arguments: Vec<Argument>,
408    source: PathBuf,
409    required_inputs: Vec<PathBuf>,
410    crate_name: String,
411    extra_filename: String,
412    out_dir: Option<PathBuf>,
413    explicit_output: Option<PathBuf>,
414    emits: Vec<Emit>,
415    target: Option<String>,
416    link_output: LinkOutput,
417}
418
419#[derive(Debug, Clone, Copy, PartialEq, Eq)]
420enum LinkOutput {
421    Library,
422    WasmExecutable,
423    NativeExecutable,
424    NativeProcMacro,
425    /// A `cdylib` linked for the host. Admitted on Linux only: an ELF shared
426    /// object names neither its own path nor an import library beside it,
427    /// where a Mach-O dylib records its output path as its install name and
428    /// a Windows DLL leaves an import library and export file next to it.
429    NativeSharedLibrary,
430}
431
432/// What the caller is prepared to model beyond the default tier.
433///
434/// The parser itself stays pure: whether the host can describe its linker
435/// precisely enough to key a native link is the caller's question, and the
436/// answer arrives here rather than being read out of the environment.
437#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
438#[non_exhaustive]
439pub struct ParseOptions {
440    /// Admit natively linked test binaries, executables, and proc macros,
441    /// given a linker identity in the action key. Off by default.
442    pub cache_native_links: bool,
443    /// rustc may resolve this invocation's bare `--target NAME` to a custom
444    /// specification: a `NAME.json` under `RUST_TARGET_PATH` or a
445    /// `lib/rustlib/NAME/target.json` in the sysroot exists. Such a target
446    /// chooses its own static-library file names, which the parser cannot
447    /// know, so `-l static` bypasses.
448    pub custom_target_search: bool,
449}
450
451impl ParseOptions {
452    /// Options that admit native links when `enabled`.
453    pub fn caching_native_links(enabled: bool) -> Self {
454        Self {
455            cache_native_links: enabled,
456            ..Self::default()
457        }
458    }
459
460    /// Options that also say whether rustc could resolve a bare target name
461    /// to a custom specification.
462    pub fn with_custom_target_search(mut self, enabled: bool) -> Self {
463        self.custom_target_search = enabled;
464        self
465    }
466}
467
468/// The cacheable files and dependency manifest produced by a rustc invocation.
469#[derive(Debug, Clone, PartialEq, Eq)]
470pub struct RustcOutputs {
471    /// Common directory containing all modeled outputs.
472    pub directory: PathBuf,
473    /// Cacheable library, metadata, and/or linked program files.
474    pub files: Vec<PathBuf>,
475    /// Dep-info file used for precise input discovery.
476    pub dep_info: PathBuf,
477}
478
479impl RustcInvocation {
480    /// Parse rustc's arguments, excluding the compiler executable supplied as
481    /// the first argument to `RUSTC_WRAPPER`.
482    ///
483    /// Any flag whose cache semantics are not modeled returns a bypass reason
484    /// instead of guessing. A successful parse admits the rlib/rmeta tier,
485    /// every compilation that links nothing at all -- what `cargo check` and
486    /// clippy run, whatever the crate type -- and binaries linked by
487    /// compiler-bundled WebAssembly toolchains.
488    pub fn parse(arguments: &[OsString]) -> Result<Self, BypassReason> {
489        Self::parse_with(arguments, ParseOptions::default())
490    }
491
492    /// The command line with `@argfile` response files expanded, as the
493    /// parser sees it. A caller that scans the arguments before parsing, for a
494    /// `--target` a response file may carry, reads this rather than the raw
495    /// list.
496    pub fn expand_arguments(arguments: &[OsString]) -> Result<Vec<OsString>, BypassReason> {
497        Ok(expand_response_files(arguments)?.arguments)
498    }
499
500    /// Parse as [`RustcInvocation::parse`] does, admitting what `options`
501    /// says the caller can model.
502    pub fn parse_with(arguments: &[OsString], options: ParseOptions) -> Result<Self, BypassReason> {
503        let expanded = expand_response_files(arguments)?;
504        Parser::new(&expanded.arguments, options).parse()
505    }
506
507    /// Whether this invocation links a native artifact, whose key must
508    /// therefore describe the linker that produced it.
509    pub fn links_natively(&self) -> bool {
510        matches!(
511            self.link_output,
512            LinkOutput::NativeExecutable
513                | LinkOutput::NativeProcMacro
514                | LinkOutput::NativeSharedLibrary
515        )
516    }
517
518    /// Stable Mach-O identity for a cached macOS proc macro. The compiler loads
519    /// these by filename; embedding the checkout's output path only makes the
520    /// bytes (and dependent action keys) vary between otherwise identical builds.
521    pub fn portable_install_name(&self, outputs: &RustcOutputs) -> Option<String> {
522        if !cfg!(target_os = "macos")
523            || self.link_output != LinkOutput::NativeProcMacro
524            || self
525                .arguments
526                .iter()
527                .any(|arg| matches!(arg, Argument::InstallName(_)))
528        {
529            return None;
530        }
531        let file = outputs
532            .files
533            .iter()
534            .find(|path| path.extension().is_some_and(|ext| ext == "dylib"))?;
535        let name = file.file_name()?.to_str()?;
536        if !safe_install_name(name) {
537            return None;
538        }
539        Some(format!("-Clink-arg=-Wl,-install_name,@rpath/{name}"))
540    }
541
542    /// Linker selected with `-C linker`, if the invocation overrides rustc's
543    /// platform default.
544    pub fn linker_override(&self) -> Option<&Path> {
545        self.arguments.iter().find_map(|argument| {
546            let Argument::Plain(value) = argument else {
547                return None;
548            };
549            value.strip_prefix("--codegen=linker=").map(Path::new)
550        })
551    }
552
553    /// Linker selected with `-C link-arg=-fuse-ld=<name>`, if the invocation
554    /// passes one the adapter models.
555    pub fn fuse_ld(&self) -> Option<&str> {
556        self.arguments.iter().find_map(|argument| {
557            let Argument::FuseLd(selection) = argument else {
558                return None;
559            };
560            Some(selection.as_str())
561        })
562    }
563
564    fn emits_windows_pdb(&self) -> bool {
565        if !cfg!(windows) || !self.links_natively() {
566            return false;
567        }
568        let mut enabled = false;
569        for argument in &self.arguments {
570            let Argument::Plain(value) = argument else {
571                continue;
572            };
573            if value == "-g" {
574                enabled = true;
575            } else if let Some(value) = value.strip_prefix("--codegen=debuginfo=") {
576                enabled = !matches!(value, "0" | "none");
577            }
578        }
579        enabled
580    }
581
582    /// Native directories explicitly searched by this invocation. Callers can
583    /// map external installations so their contents participate in discovery
584    /// and prediction, rather than treating their paths as immutable inputs.
585    pub fn native_search_paths(&self) -> impl Iterator<Item = &Path> {
586        self.arguments.iter().filter_map(|argument| match argument {
587            Argument::SearchPath { kind, path } if searches_native(kind) => Some(path.as_path()),
588            _ => None,
589        })
590    }
591
592    /// Return the source input passed to rustc.
593    pub fn source(&self) -> &Path {
594        &self.source
595    }
596
597    /// Absolute files named directly by the invocation that rustc must read.
598    ///
599    /// This includes the source, explicit extern artifacts, and custom target
600    /// specifications. Callers can snapshot these before rustc starts even
601    /// though the complete input set is only known from dep-info afterwards.
602    pub fn required_inputs_in(&self, working_dir: &Path) -> Vec<PathBuf> {
603        self.required_inputs
604            .iter()
605            .map(|path| absolute_path(path, working_dir))
606            .collect()
607    }
608
609    /// Return the explicitly selected compilation target, if any.
610    pub fn target(&self) -> Option<&str> {
611        self.target.as_deref()
612    }
613
614    /// Return the crate name rustc will assign to this compilation.
615    pub fn crate_name(&self) -> &str {
616        &self.crate_name
617    }
618
619    /// Whether rustc records a virtual directory in place of the working
620    /// directory (`-Zremap-cwd-prefix`).
621    ///
622    /// rustc checks incremental state against its options, the working
623    /// directory included, and ignores state recorded anywhere else. Under this
624    /// flag, with the paths under the working directory named relative to it,
625    /// every checkout presents the same options, so one checkout's state is as
626    /// good as another's.
627    pub fn remaps_working_directory(&self) -> bool {
628        self.arguments.iter().any(|argument| {
629            matches!(argument, Argument::Plain(flag) if flag.starts_with("-Zremap-cwd-prefix="))
630        })
631    }
632
633    /// Digest of the inputs this compilation owns: its sources and whatever
634    /// they read, but not the artifacts it merely links against.
635    ///
636    /// This is what separates a crate someone is editing from one sitting
637    /// above it in the graph. Rebuilding a dependency changes the action key of
638    /// every crate that links it, because their keys hash its artifact; it does
639    /// not change this. A caller watching for churn has to watch this instead,
640    /// or a single edited crate would drag its whole dependent cone along.
641    ///
642    /// Host paths enter the digest as they are. This describes one checkout to
643    /// itself rather than to the cache, so there is nothing here to make
644    /// portable.
645    pub fn source_fingerprint(&self, discovered: &DiscoveredInputs) -> CacheDigest {
646        let linked = self
647            .arguments
648            .iter()
649            .filter_map(|argument| match argument {
650                Argument::Extern {
651                    path: Some(path), ..
652                } => Some(path.as_path()),
653                _ => None,
654            })
655            .collect::<BTreeSet<_>>();
656        let owned = discovered
657            .inputs
658            .iter()
659            .filter(|input| {
660                !linked.contains(input.path.as_path()) && !discovered.is_native_only(&input.path)
661            })
662            .map(|input| (input.path.as_path(), &input.digest))
663            .collect::<BTreeMap<_, _>>();
664        let mut bytes = Vec::new();
665        for (path, digest) in owned {
666            bytes.extend_from_slice(path.as_os_str().as_encoded_bytes());
667            bytes.push(0);
668            bytes.extend_from_slice(digest.key().as_bytes());
669            bytes.push(0);
670        }
671        CacheDigest::blake3(&bytes)
672    }
673
674    /// Resolve the files produced by this invocation.
675    ///
676    /// The initial cache tier requires one output directory so its artifact can
677    /// be represented by one protocol directory and restored atomically later.
678    pub fn outputs(&self, working_dir: &Path) -> Result<RustcOutputs, BypassReason> {
679        if !working_dir.is_absolute() {
680            return Err(BypassReason::RelativeWorkingDirectory(
681                working_dir.to_path_buf(),
682            ));
683        }
684        let explicit_output = self
685            .explicit_output
686            .as_deref()
687            .map(|path| absolute_path(path, working_dir));
688        let output_directory = explicit_output
689            .as_deref()
690            .and_then(Path::parent)
691            .map(Path::to_path_buf)
692            .or_else(|| {
693                self.out_dir
694                    .as_deref()
695                    .map(|path| absolute_path(path, working_dir))
696            })
697            .unwrap_or_else(|| normalize_components(working_dir));
698        // rustc applies `-o` to every emit that has no path of its own, so the
699        // file names cannot be derived from the crate name here. Cargo always
700        // uses --out-dir instead, so refusing to model this costs nothing.
701        if let Some(output) = &explicit_output
702            && self.emits.iter().any(|emit| {
703                emit.path.is_none()
704                    && matches!(emit.kind.as_str(), "dep-info" | "link" | "metadata")
705            })
706        {
707            return Err(BypassReason::ImplicitEmitWithOutputFile(output.clone()));
708        }
709        let mut files = BTreeSet::new();
710        let mut dep_info = None;
711        for emit in &self.emits {
712            if emit.kind == "dep-info" {
713                let path = emit.path.as_ref().map_or_else(
714                    || {
715                        explicit_output.clone().map_or_else(
716                            || {
717                                output_directory
718                                    .join(format!("{}{}.d", self.crate_name, self.extra_filename))
719                            },
720                            |path| path.with_extension("d"),
721                        )
722                    },
723                    |path| absolute_path(path, working_dir),
724                );
725                if path.file_name().is_none() {
726                    return Err(BypassReason::InvalidOutputPath(path));
727                }
728                dep_info = Some(path);
729                continue;
730            }
731            let (prefix, extension) = match emit.kind.as_str() {
732                "link" => match self.link_output {
733                    LinkOutput::Library => ("lib", "rlib"),
734                    LinkOutput::WasmExecutable => ("", "wasm"),
735                    LinkOutput::NativeExecutable => ("", std::env::consts::EXE_EXTENSION),
736                    LinkOutput::NativeProcMacro | LinkOutput::NativeSharedLibrary => (
737                        std::env::consts::DLL_PREFIX,
738                        std::env::consts::DLL_SUFFIX.trim_start_matches('.'),
739                    ),
740                },
741                "metadata" => ("lib", "rmeta"),
742                _ => continue,
743            };
744            let path = if let Some(path) = &emit.path {
745                absolute_path(path, working_dir)
746            } else {
747                let name = format!("{prefix}{}{}", self.crate_name, self.extra_filename);
748                output_directory.join(if extension.is_empty() {
749                    name
750                } else {
751                    format!("{name}.{extension}")
752                })
753            };
754            if path.file_name().is_none() {
755                return Err(BypassReason::InvalidOutputPath(path));
756            }
757            if path.parent() != Some(output_directory.as_path()) {
758                return Err(BypassReason::SplitOutputDirectories);
759            }
760            // Whether a restored output is a program is read back off its name,
761            // so a program that answers to a library's name would be restored
762            // without the permission that makes it runnable. Nothing cargo
763            // emits looks like this; a hand-built invocation could.
764            let has_library_extension = path
765                .extension()
766                .and_then(|extension| extension.to_str())
767                .is_some_and(|extension| matches!(extension, "rlib" | "rmeta"))
768                || (cfg!(windows)
769                    && path
770                        .file_stem()
771                        .and_then(|stem| Path::new(stem).extension())
772                        .and_then(|extension| extension.to_str())
773                        .is_some_and(|extension| matches!(extension, "rlib" | "rmeta")));
774            if emit.kind == "link"
775                && !matches!(self.link_output, LinkOutput::Library)
776                && has_library_extension
777            {
778                return Err(BypassReason::AmbiguousOutputName(path));
779            }
780            if emit.kind == "link" && self.emits_windows_pdb() {
781                files.insert(path.with_extension("pdb"));
782            }
783            files.insert(path);
784        }
785        let dep_info = dep_info.ok_or(BypassReason::NoDepInfo)?;
786        if dep_info.parent() != Some(output_directory.as_path()) {
787            return Err(BypassReason::SplitOutputDirectories);
788        }
789        Ok(RustcOutputs {
790            directory: output_directory,
791            files: files.into_iter().collect(),
792            dep_info,
793        })
794    }
795
796    /// Build canonical action bytes after precise input discovery has run.
797    ///
798    /// `context.inputs` must contain the source, every explicit extern, and
799    /// every additional source or environment-generated input discovered from
800    /// dep-info.
801    pub fn action(&self, context: ActionContext) -> Result<RustcAction, BypassReason> {
802        self.action_linked_by(context, None)
803    }
804
805    /// Build canonical action bytes for an invocation that links a native
806    /// program.
807    ///
808    /// A `linker` is required whenever [`RustcInvocation::links_natively`]
809    /// holds: the linker, its startup objects, and the platform SDK are inputs
810    /// rustc dep-info does not enumerate, so a key without them would claim
811    /// more than it can support. Passing one for anything else is ignored,
812    /// since nothing else depends on a linker.
813    pub fn action_linked_by(
814        &self,
815        context: ActionContext,
816        linker: Option<LinkerIdentity>,
817    ) -> Result<RustcAction, BypassReason> {
818        ActionBuilder::new(self, context).linked_by(linker).build()
819    }
820
821    /// Fingerprint the modeled invocation before dependency contents are known.
822    pub fn invocation_digest(&self, context: &ActionContext) -> Result<CacheDigest, BypassReason> {
823        let descriptor = ActionBuilder::new(self, context.clone()).invocation_descriptor()?;
824        let bytes = canonical_json(&descriptor)
825            .map_err(|error| BypassReason::Serialization(error.to_string()))?;
826        Ok(CacheDigest::blake3(&bytes))
827    }
828
829    /// Capture normalized dependency paths for a future invocation that has no
830    /// dep-info file yet.
831    pub fn prediction(
832        &self,
833        context: &ActionContext,
834        discovered: &DiscoveredInputs,
835    ) -> Result<RustcInputPrediction, BypassReason> {
836        let builder = ActionBuilder::new(self, context.clone());
837        builder.validate_mappings()?;
838        let mut native_directories = BTreeSet::new();
839        for argument in &self.arguments {
840            if let Argument::SearchPath { kind, path } = argument
841                && searches_native(kind)
842            {
843                native_directories.insert(builder.normalize_path(path)?);
844            }
845        }
846        // A file beneath a recorded directory is rediscovered by walking that
847        // directory, so naming it as well only makes the payload grow with the
848        // object tree a C dependency leaves in its `OUT_DIR`. `aws-lc-sys`
849        // leaves thousands of files there, which was enough to push the
850        // serialized prediction past the protocol's payload limit and lose the
851        // prediction entirely for the crate that most needed one.
852        //
853        // A file dep-info itself names stays, even beneath a recorded
854        // directory. It is a source of the crate, and rediscovery can only tell
855        // it from the objects around it if the prediction says which it is.
856        // There are few of those; the thousands of objects are not named.
857        let mut inputs = BTreeSet::new();
858        for input in &discovered.inputs {
859            let normalized = builder.normalize_file_path(&input.path)?;
860            if !under_any_directory(&normalized, &native_directories)
861                || !discovered.is_native_only(&input.path)
862            {
863                inputs.insert(normalized);
864            }
865        }
866        inputs.extend(
867            native_directories
868                .into_iter()
869                .map(|directory| format!("{NATIVE_DIRECTORY_PREDICTION_PREFIX}{directory}")),
870        );
871        Ok(RustcInputPrediction {
872            version: 4,
873            inputs: inputs.into_iter().collect(),
874            environment: discovered.environment.keys().cloned().collect(),
875            compiler_duration_ns: 0,
876            crate_name: String::new(),
877        })
878    }
879}
880
881/// Whether a crate name has the form Cargo gives every build script.
882///
883/// The name alone is not proof: see [`RustcOutputs::build_script_executable`].
884pub fn is_build_script_crate_name(crate_name: &str) -> bool {
885    crate_name
886        .strip_prefix("build_script_")
887        .is_some_and(|stem| !stem.is_empty())
888}
889
890impl RustcOutputs {
891    /// The linked executable Cargo will run as a build script, when this is a
892    /// build-script compilation.
893    ///
894    /// Cargo names a build script's crate `build_script_` plus the stem of its
895    /// source: `build_script_build` for `build.rs`, `build_script_main` for
896    /// `build = "builder/main.rs"`. A `[[bin]]` target can take the same name,
897    /// and Cargo's output directory does not tell them apart, so the caller
898    /// has to confirm from Cargo's environment that this is a build script:
899    /// Cargo sets `CARGO_BIN_NAME` for binary targets and never for one.
900    pub fn build_script_executable(&self, crate_name: &str) -> Option<&Path> {
901        is_build_script_crate_name(crate_name)
902            .then(|| self.files.iter().find(|path| self.is_executable(path)))
903            .flatten()
904            .map(PathBuf::as_path)
905    }
906
907    /// Whether `path` is a linked program whose executable permission is part
908    /// of the declared output contract.
909    /// A program is whatever this invocation emitted that is not a library
910    /// artifact. Every tier the adapter admits distinguishes the two by
911    /// extension -- `rlib` and `rmeta` are the compiler's own, and a linked
912    /// program carries either the target's (`wasm`) or none at all -- so the
913    /// name is enough and no separate list has to be carried alongside.
914    pub fn is_executable(&self, path: &Path) -> bool {
915        self.files.iter().any(|output| output == path)
916            && !matches!(
917                path.extension().and_then(|extension| extension.to_str()),
918                Some("rlib" | "rmeta")
919            )
920    }
921}
922
923#[derive(Debug, Clone, PartialEq, Eq)]
924/// Mapping from a host-specific absolute root to a stable key placeholder.
925pub struct PathMapping {
926    /// Absolute host path to replace.
927    pub root: PathBuf,
928    /// Placeholder name without the surrounding `${...}` syntax.
929    pub placeholder: String,
930}
931
932impl PathMapping {
933    /// Map an absolute host path to a stable cache-key placeholder.
934    pub fn new(root: impl Into<PathBuf>, placeholder: impl Into<String>) -> Self {
935        Self {
936            root: root.into(),
937            placeholder: placeholder.into(),
938        }
939    }
940
941    /// Order mappings deepest root first, which is what normalization needs:
942    /// a target directory inside the workspace has to win over the workspace.
943    pub fn ordered(mappings: &[PathMapping]) -> Vec<PathMapping> {
944        let mut ordered = mappings.to_vec();
945        ordered.sort_by_key(|mapping| std::cmp::Reverse(mapping.root.components().count()));
946        ordered
947    }
948}
949
950fn shared_path_mappings(mappings: &[PathMapping]) -> Vec<SharedPathMapping> {
951    mappings
952        .iter()
953        .map(|mapping| SharedPathMapping::new(&mapping.root, &mapping.placeholder))
954        .collect()
955}
956
957/// Map an absolute path to its cache-key placeholder form.
958///
959/// `mappings` must already be ordered by [`PathMapping::ordered`]. Exposed for
960/// callers that need the placeholder text before an action exists -- notably to
961/// build the `--remap-path-prefix` flag that makes a compilation independent of
962/// a path in its environment.
963pub fn normalize_mapped_path(
964    path: &Path,
965    working_dir: &Path,
966    mappings: &[PathMapping],
967) -> Result<String, BypassReason> {
968    normalize_shared_path(path, working_dir, &shared_path_mappings(mappings)).map_err(Into::into)
969}
970
971/// Key an input path using the configured mappings or its literal Nix store path.
972pub fn normalize_input_path(
973    path: &Path,
974    working_dir: &Path,
975    mappings: &[PathMapping],
976) -> Result<String, BypassReason> {
977    normalize_mapped_path(path, working_dir, mappings)
978        .or_else(|reason| key_nix_store_path(path, working_dir, reason))
979}
980
981#[derive(Debug, Clone, PartialEq, Eq)]
982/// Compiler properties that distinguish incompatible action outputs.
983pub struct CompilerIdentity {
984    /// Toolchain selector or installation identity.
985    pub toolchain: String,
986    /// Complete verbose rustc version string.
987    pub rustc_version: String,
988    /// Compiler host target triple.
989    pub host: String,
990    /// Identity of a compiler driver layered over rustc, when one is in use.
991    pub driver: Option<String>,
992}
993
994/// One file input paired with the digest used in the action key.
995#[derive(Debug, Clone, PartialEq, Eq)]
996pub struct ActionInput {
997    /// Absolute host path used to read and verify the input.
998    pub path: PathBuf,
999    /// Digest of the input contents.
1000    pub digest: CacheDigest,
1001}
1002
1003/// External information needed to construct a canonical rustc action.
1004#[derive(Debug, Clone, PartialEq, Eq)]
1005pub struct ActionContext {
1006    /// Identity of the compiler that produces the outputs.
1007    pub compiler: CompilerIdentity,
1008    /// Absolute directory in which rustc runs.
1009    pub working_dir: PathBuf,
1010    /// Host roots replaced with stable placeholders in the key.
1011    pub path_mappings: Vec<PathMapping>,
1012    /// Environment inputs and their observed values.
1013    pub environment: BTreeMap<String, Option<String>>,
1014    /// Environment inputs whose absolute values the compilation has been made
1015    /// independent of, and whose values the key therefore normalizes.
1016    ///
1017    /// Naming one here is a claim about the compilation, not a preference: the
1018    /// caller must both neutralize the value inside it (with
1019    /// `--remap-path-prefix`) and confirm no output carries the value anyway.
1020    pub portable_environment: BTreeSet<String>,
1021    /// Complete set of direct and discovered file inputs.
1022    pub inputs: Vec<ActionInput>,
1023}
1024
1025/// What produced a linked native program, beyond the compiler itself.
1026///
1027/// The fields are identity rather than content wherever a compiler's own
1028/// identity is: a driver's version output names its toolchain more cheaply than
1029/// hashing a hundred megabytes of it, and matches how rustc is identified. The
1030/// CRT objects are hashed, because nothing else pins the libc a link resolves
1031/// against. Nothing here is placeholder-mapped -- these paths are host
1032/// locations rather than checkout locations, and two hosts that differ should
1033/// miss rather than share.
1034#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1035#[serde(deny_unknown_fields)]
1036pub struct LinkerIdentity {
1037    /// Resolved absolute path of the linker driver rustc will invoke.
1038    pub driver: String,
1039    /// Version output of that driver.
1040    pub driver_version: String,
1041    /// Version of the linker the driver selects.
1042    pub linker_version: String,
1043    /// Startup objects and libc the driver resolves, by probe name.
1044    #[serde(skip_serializing_if = "BTreeMap::is_empty", default)]
1045    pub crt_objects: BTreeMap<String, CacheDigest>,
1046    /// Platform SDK identity, where the platform has one.
1047    #[serde(skip_serializing_if = "Option::is_none", default)]
1048    pub sdk: Option<String>,
1049    /// Deployment target the link was made against, where one applies.
1050    #[serde(skip_serializing_if = "Option::is_none", default)]
1051    pub deployment_target: Option<String>,
1052}
1053
1054/// Canonical action descriptor and its content digest.
1055#[derive(Debug, Clone, PartialEq, Eq)]
1056pub struct RustcAction {
1057    /// Digest of `bytes`, used as the action-cache key.
1058    pub digest: CacheDigest,
1059    /// Canonical serialized action descriptor.
1060    pub bytes: Vec<u8>,
1061}
1062
1063/// Normalized input names from the last successful execution of one modeled
1064/// rustc invocation.
1065#[derive(Debug, Clone, PartialEq, Eq)]
1066pub struct RustcInputPrediction {
1067    /// Prediction schema version.
1068    pub version: u8,
1069    /// Normalized input paths observed during the successful invocation.
1070    pub inputs: Vec<String>,
1071    /// Names of environment variables read by the compilation.
1072    pub environment: Vec<String>,
1073    /// Compiler wall time from the successful invocation that produced this
1074    /// prediction. Zero means no timing hint was recorded.
1075    pub compiler_duration_ns: u64,
1076    /// Crate name associated with the timing hint.
1077    pub crate_name: String,
1078}
1079
1080#[derive(Serialize, Deserialize)]
1081#[serde(deny_unknown_fields)]
1082struct RustcInputPredictionWire {
1083    version: u8,
1084    inputs: Vec<String>,
1085    environment: Vec<String>,
1086    #[serde(default, skip_serializing_if = "is_zero")]
1087    compiler_duration_ns: u64,
1088    #[serde(default, skip_serializing_if = "String::is_empty")]
1089    crate_name: String,
1090}
1091
1092impl Serialize for RustcInputPrediction {
1093    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1094    where
1095        S: Serializer,
1096    {
1097        RustcInputPredictionWire {
1098            version: self.version,
1099            inputs: if self.version == 4 {
1100                compact_prediction_inputs(&self.inputs)
1101            } else {
1102                self.inputs.clone()
1103            },
1104            environment: self.environment.clone(),
1105            compiler_duration_ns: self.compiler_duration_ns,
1106            crate_name: self.crate_name.clone(),
1107        }
1108        .serialize(serializer)
1109    }
1110}
1111
1112impl<'de> Deserialize<'de> for RustcInputPrediction {
1113    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1114    where
1115        D: Deserializer<'de>,
1116    {
1117        let wire = RustcInputPredictionWire::deserialize(deserializer)?;
1118        let inputs = if wire.version == 4 {
1119            expand_prediction_inputs(&wire.inputs).map_err(serde::de::Error::custom)?
1120        } else {
1121            wire.inputs
1122        };
1123        Ok(Self {
1124            version: wire.version,
1125            inputs,
1126            environment: wire.environment,
1127            compiler_duration_ns: wire.compiler_duration_ns,
1128            crate_name: wire.crate_name,
1129        })
1130    }
1131}
1132
1133fn compact_prediction_inputs(inputs: &[String]) -> Vec<String> {
1134    let mut previous = "";
1135    inputs
1136        .iter()
1137        .map(|input| {
1138            let mut shared = previous
1139                .bytes()
1140                .zip(input.bytes())
1141                .take_while(|(left, right)| left == right)
1142                .count();
1143            while !input.is_char_boundary(shared) {
1144                shared -= 1;
1145            }
1146            let compact = format!("{shared}:{}", &input[shared..]);
1147            previous = input;
1148            compact
1149        })
1150        .collect()
1151}
1152
1153fn expand_prediction_inputs(inputs: &[String]) -> Result<Vec<String>, &'static str> {
1154    let mut expanded: Vec<String> = Vec::with_capacity(inputs.len());
1155    let mut decoded_bytes = 0_usize;
1156    for input in inputs {
1157        let (shared_text, suffix) = input
1158            .split_once(':')
1159            .ok_or("compact rustc prediction input has no prefix length")?;
1160        let shared: usize = shared_text
1161            .parse()
1162            .map_err(|_| "compact rustc prediction prefix length is invalid")?;
1163        if shared.to_string() != shared_text
1164            || shared > expanded.last().map_or(0, String::len)
1165            || expanded
1166                .last()
1167                .is_some_and(|previous| !previous.is_char_boundary(shared))
1168        {
1169            return Err("compact rustc prediction prefix is not canonical");
1170        }
1171        let mut path = expanded
1172            .last()
1173            .map_or_else(String::new, |previous| previous[..shared].to_string());
1174        path.push_str(suffix);
1175        decoded_bytes = decoded_bytes
1176            .checked_add(path.len())
1177            .ok_or("compact rustc prediction is too large")?;
1178        if decoded_bytes > MAX_DECODED_PREDICTION_BYTES {
1179            return Err("compact rustc prediction is too large");
1180        }
1181        expanded.push(path);
1182    }
1183    Ok(expanded)
1184}
1185
1186fn is_zero(value: &u64) -> bool {
1187    *value == 0
1188}
1189
1190impl RustcInputPrediction {
1191    /// Rehash the predicted paths and read the current environment. The caller
1192    /// still recomputes the full action digest, so changed inputs are misses.
1193    pub fn discover(
1194        &self,
1195        working_dir: &Path,
1196        path_mappings: &[PathMapping],
1197        digests: &dyn FileDigestCache,
1198    ) -> Result<DiscoveredInputs, BypassReason> {
1199        self.discover_with_store(working_dir, path_mappings, digests, NIX_STORE_ROOT)
1200    }
1201
1202    fn discover_with_store(
1203        &self,
1204        working_dir: &Path,
1205        path_mappings: &[PathMapping],
1206        digests: &dyn FileDigestCache,
1207        store_root: &str,
1208    ) -> Result<DiscoveredInputs, BypassReason> {
1209        if !matches!(self.version, 2..=4) {
1210            return Err(BypassReason::UnsupportedPrediction);
1211        }
1212        if self.inputs.len() > MAX_PREDICTED_INPUTS || self.environment.len() > 4 * 1024 {
1213            return Err(BypassReason::UnsupportedPrediction);
1214        }
1215        let mut paths = BTreeSet::new();
1216        let mut named = BTreeSet::new();
1217        let admitted_roots = dep_info::native_input_roots(working_dir, path_mappings);
1218        let mut native_bytes = 0_u64;
1219        let mut counted = BTreeSet::new();
1220        for path in &self.inputs {
1221            if self.version >= 3
1222                && let Some(path) = path.strip_prefix(NATIVE_DIRECTORY_PREDICTION_PREFIX)
1223            {
1224                let directory = denormalize_path(path, path_mappings, store_root)?;
1225                dep_info::collect_native_directory(
1226                    &directory,
1227                    &admitted_roots,
1228                    &mut paths,
1229                    &mut native_bytes,
1230                    &mut counted,
1231                )?;
1232            } else {
1233                let path = denormalize_path(path, path_mappings, store_root)?;
1234                named.insert(path.clone());
1235                paths.insert(path);
1236            }
1237        }
1238        let native_only = paths.difference(&named).cloned().collect();
1239        let environment = self
1240            .environment
1241            .iter()
1242            .map(|name| {
1243                if name.is_empty() || name.contains(['=', '\0']) {
1244                    return Err(BypassReason::UnsupportedPrediction);
1245                }
1246                let value = std::env::var_os(name)
1247                    .map(|value| {
1248                        value
1249                            .into_string()
1250                            .map_err(|_| BypassReason::UnsupportedPrediction)
1251                    })
1252                    .transpose()?;
1253                Ok((name.clone(), value))
1254            })
1255            .collect::<Result<BTreeMap<_, _>, _>>()?;
1256        Ok(
1257            DiscoveredInputs::from_paths(working_dir, paths, environment, digests)?
1258                .with_native_only(native_only),
1259        )
1260    }
1261}
1262
1263#[derive(Serialize)]
1264struct ActionDescriptor {
1265    version: u8,
1266    kind: &'static str,
1267    adapter_version: u8,
1268    compiler: CompilerDescriptor,
1269    arguments: Vec<String>,
1270    environment: BTreeMap<String, Option<String>>,
1271    inputs: Vec<InputDescriptor>,
1272    /// Omitted entirely unless the invocation links natively, so every key
1273    /// written before this field existed still serializes to the same bytes.
1274    #[serde(skip_serializing_if = "Option::is_none")]
1275    linker: Option<LinkerIdentity>,
1276}
1277
1278#[derive(Serialize)]
1279struct InvocationDescriptor {
1280    version: u8,
1281    kind: &'static str,
1282    adapter_version: u8,
1283    compiler: CompilerDescriptor,
1284    arguments: Vec<String>,
1285    required_inputs: Vec<String>,
1286}
1287
1288#[derive(Serialize)]
1289struct CompilerDescriptor {
1290    toolchain: String,
1291    rustc_version: String,
1292    host: String,
1293    #[serde(skip_serializing_if = "Option::is_none")]
1294    driver: Option<String>,
1295}
1296
1297#[derive(Debug, Serialize, PartialEq, Eq, PartialOrd, Ord)]
1298struct InputDescriptor {
1299    path: String,
1300    digest: CacheDigest,
1301}
1302
1303/// The static-library file names a built-in target uses.
1304#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1305enum StaticLibraryNaming {
1306    /// `NAME.lib`, then the Unix spelling as a fallback.
1307    Msvc,
1308    /// `libNAME.a`.
1309    Unix,
1310}
1311
1312struct Parser<'a> {
1313    arguments: &'a [OsString],
1314    index: usize,
1315    parsed: Vec<Argument>,
1316    source: Option<PathBuf>,
1317    crate_types: Vec<String>,
1318    emits: Vec<Emit>,
1319    required_inputs: Vec<PathBuf>,
1320    native_libraries: Vec<String>,
1321    test: bool,
1322    crate_name: Option<String>,
1323    extra_filename: String,
1324    out_dir: Option<PathBuf>,
1325    explicit_output: Option<PathBuf>,
1326    target: Option<String>,
1327    sysroot_backend: Option<String>,
1328    options: ParseOptions,
1329}
1330
1331struct ExpandedArguments {
1332    arguments: Vec<OsString>,
1333}
1334
1335#[derive(Default)]
1336struct ResponseExpander {
1337    shell_argfiles: bool,
1338    next_is_unstable_option: bool,
1339    arguments: Vec<OsString>,
1340}
1341
1342impl ResponseExpander {
1343    fn push(&mut self, argument: String) {
1344        if self.next_is_unstable_option {
1345            self.shell_argfiles |= argument == "shell-argfiles";
1346            self.next_is_unstable_option = false;
1347        } else if let Some(option) = argument.strip_prefix("-Z") {
1348            if option.is_empty() {
1349                self.next_is_unstable_option = true;
1350            } else {
1351                self.shell_argfiles |= option == "shell-argfiles";
1352            }
1353        }
1354        self.arguments.push(argument.into());
1355    }
1356}
1357
1358/// Match rustc's argfile expansion: UTF-8, one option per line, no recursive
1359/// expansion, with the nightly shell form enabled only after its `-Z` flag.
1360fn expand_response_files(arguments: &[OsString]) -> Result<ExpandedArguments, BypassReason> {
1361    let mut expanded = ResponseExpander::default();
1362    for (index, argument) in arguments.iter().enumerate() {
1363        let argument = argument
1364            .to_str()
1365            .ok_or(BypassReason::NonUtf8Argument { index })?;
1366        let Some(argfile) = argument.strip_prefix('@') else {
1367            expanded.push(argument.to_string());
1368            continue;
1369        };
1370        let (path, shell) = match argfile.split_once(':') {
1371            Some(("shell", path)) if expanded.shell_argfiles => (path, true),
1372            _ => (argfile, false),
1373        };
1374        let contents = std::fs::read_to_string(path).map_err(|error| {
1375            BypassReason::ResponseFile(format!("{}: {error}", Path::new(path).display()))
1376        })?;
1377        if shell {
1378            let arguments = shlex::split(&contents).ok_or_else(|| {
1379                BypassReason::ResponseFile(format!(
1380                    "invalid shell-style arguments in {}",
1381                    Path::new(path).display()
1382                ))
1383            })?;
1384            for argument in arguments {
1385                expanded.push(argument);
1386            }
1387        } else {
1388            for argument in contents.lines() {
1389                expanded.push(argument.to_string());
1390            }
1391        }
1392    }
1393    Ok(ExpandedArguments {
1394        arguments: expanded.arguments,
1395    })
1396}
1397
1398impl<'a> Parser<'a> {
1399    fn new(arguments: &'a [OsString], options: ParseOptions) -> Self {
1400        Self {
1401            arguments,
1402            options,
1403            index: 0,
1404            parsed: Vec::new(),
1405            source: None,
1406            crate_types: Vec::new(),
1407            emits: Vec::new(),
1408            required_inputs: Vec::new(),
1409            native_libraries: Vec::new(),
1410            test: false,
1411            crate_name: None,
1412            extra_filename: String::new(),
1413            out_dir: None,
1414            explicit_output: None,
1415            target: None,
1416            sysroot_backend: None,
1417        }
1418    }
1419
1420    fn parse(mut self) -> Result<RustcInvocation, BypassReason> {
1421        while self.index < self.arguments.len() {
1422            let value = self.current()?.to_string();
1423            self.index += 1;
1424            if let Some(long) = value.strip_prefix("--") {
1425                self.parse_long(long)?;
1426            } else if value.starts_with('-') && value != "-" {
1427                self.parse_short(&value)?;
1428            } else {
1429                self.parse_input(&value)?;
1430            }
1431        }
1432
1433        // rustc searches an explicit sysroot for the backend first, and only the compiler's own is hashed.
1434        if let Some(backend) = self.sysroot_backend.take()
1435            && self.parsed.iter().any(
1436                |argument| matches!(argument, Argument::Path { flag, .. } if flag == "--sysroot"),
1437            )
1438        {
1439            return Err(BypassReason::UnknownFlag(backend));
1440        }
1441        let source = self.source.clone().ok_or(BypassReason::MissingInput)?;
1442        let link_output = self.classify()?;
1443        self.require_native_libraries(link_output)?;
1444        let crate_name = self.crate_name.clone().map_or_else(
1445            || {
1446                source
1447                    .file_stem()
1448                    .and_then(|name| name.to_str())
1449                    .map(|name| name.replace('-', "_"))
1450                    .ok_or_else(|| BypassReason::NonUtf8Path(source.clone()))
1451            },
1452            Ok,
1453        )?;
1454        self.required_inputs.push(source.clone());
1455        self.drop_unobservable_diagnostic_width();
1456        Ok(RustcInvocation {
1457            arguments: self.parsed,
1458            source,
1459            required_inputs: self.required_inputs,
1460            crate_name,
1461            extra_filename: self.extra_filename,
1462            out_dir: self.out_dir,
1463            explicit_output: self.explicit_output,
1464            emits: self.emits,
1465            target: self.target,
1466            link_output,
1467        })
1468    }
1469
1470    fn current(&self) -> Result<&str, BypassReason> {
1471        self.arguments[self.index]
1472            .to_str()
1473            .ok_or(BypassReason::NonUtf8Argument { index: self.index })
1474    }
1475
1476    fn take_value(&mut self, flag: &str, inline: Option<&str>) -> Result<String, BypassReason> {
1477        if let Some(value) = inline {
1478            if value.is_empty() {
1479                return Err(BypassReason::MissingValue(flag.into()));
1480            }
1481            return Ok(value.into());
1482        }
1483        if self.index >= self.arguments.len() {
1484            return Err(BypassReason::MissingValue(flag.into()));
1485        }
1486        let value = self.current()?.to_string();
1487        self.index += 1;
1488        Ok(value)
1489    }
1490
1491    /// Cargo passes `--diagnostic-width` only when stderr is a terminal, with
1492    /// the terminal's width as the value, so keying it splits the cache by how
1493    /// a build was launched. The width only wraps rendered diagnostics and
1494    /// never changes the artifacts, so it is left out of the key for every
1495    /// crate. Diagnostics replayed from a cached entry keep the wrapping of
1496    /// the build that produced them.
1497    ///
1498    /// rustc rejects a repeated flag and a non-numeric value, so only a single
1499    /// well-formed width is dropped; anything else stays keyed and cannot
1500    /// share an entry with a build that rustc would accept.
1501    fn drop_unobservable_diagnostic_width(&mut self) {
1502        fn widths(argument: &Argument) -> Option<&str> {
1503            match argument {
1504                Argument::Plain(value) => value.strip_prefix("--diagnostic-width="),
1505                _ => None,
1506            }
1507        }
1508        let mut found = self.parsed.iter().filter_map(widths);
1509        let valid = matches!(
1510            (found.next(), found.next()),
1511            (Some(width), None) if width.parse::<usize>().is_ok()
1512        );
1513        if valid {
1514            self.parsed.retain(|argument| widths(argument).is_none());
1515        }
1516    }
1517
1518    fn parse_long(&mut self, value: &str) -> Result<(), BypassReason> {
1519        let (flag, inline) = value
1520            .split_once('=')
1521            .map_or((value, None), |(flag, value)| (flag, Some(value)));
1522        let rendered_flag = format!("--{flag}");
1523        match flag {
1524            "help" | "version" | "explain" | "print" => Err(BypassReason::CompilerQuery),
1525            "test" => {
1526                self.test = true;
1527                self.parsed.push(Argument::Plain(rendered_flag));
1528                Ok(())
1529            }
1530            "verbose" => {
1531                self.parsed.push(Argument::Plain(rendered_flag));
1532                Ok(())
1533            }
1534            "crate-name" => {
1535                let value = self.take_value(&rendered_flag, inline)?;
1536                self.crate_name = Some(value.clone());
1537                self.parsed
1538                    .push(Argument::Plain(format!("{rendered_flag}={value}")));
1539                Ok(())
1540            }
1541            "cfg" | "check-cfg" | "edition" | "error-format" | "json" | "color"
1542            | "diagnostic-width" | "remap-path-scope" | "allow" | "warn" | "force-warn"
1543            | "deny" | "forbid" | "cap-lints" => {
1544                let value = self.take_value(&rendered_flag, inline)?;
1545                self.parsed
1546                    .push(Argument::Plain(format!("{rendered_flag}={value}")));
1547                Ok(())
1548            }
1549            "target" => {
1550                let value = self.take_value(&rendered_flag, inline)?;
1551                // rustc reads the first `--target`, as getopts does; a later
1552                // one is still keyed as an argument but does not decide the
1553                // target, so it is not read and not a required input either.
1554                let effective = self.target.is_none();
1555                if effective {
1556                    self.target = Some(value.clone());
1557                }
1558                if value.ends_with(".json") || value.contains(['/', '\\']) {
1559                    let path = PathBuf::from(value);
1560                    if effective {
1561                        self.required_inputs.push(path.clone());
1562                    }
1563                    self.parsed.push(Argument::Path {
1564                        flag: rendered_flag,
1565                        path,
1566                    });
1567                } else {
1568                    self.parsed
1569                        .push(Argument::Plain(format!("{rendered_flag}={value}")));
1570                }
1571                Ok(())
1572            }
1573            "crate-type" => {
1574                let value = self.take_value(&rendered_flag, inline)?;
1575                self.crate_types
1576                    .extend(value.split(',').map(ToOwned::to_owned));
1577                self.parsed
1578                    .push(Argument::Plain(format!("{rendered_flag}={value}")));
1579                Ok(())
1580            }
1581            "emit" => {
1582                let value = self.take_value(&rendered_flag, inline)?;
1583                let emits = parse_emits(&value);
1584                self.emits.extend(emits.clone());
1585                self.parsed.push(Argument::Emit(emits));
1586                Ok(())
1587            }
1588            "out-dir" => {
1589                let path = PathBuf::from(self.take_value(&rendered_flag, inline)?);
1590                self.out_dir = Some(path.clone());
1591                self.parsed.push(Argument::Path {
1592                    flag: rendered_flag,
1593                    path,
1594                });
1595                Ok(())
1596            }
1597            "sysroot" => {
1598                let path = self.take_value(&rendered_flag, inline)?;
1599                self.parsed.push(Argument::Path {
1600                    flag: rendered_flag,
1601                    path: path.into(),
1602                });
1603                Ok(())
1604            }
1605            "extern" => {
1606                let value = self.take_value(&rendered_flag, inline)?;
1607                let (name, path) = value
1608                    .split_once('=')
1609                    .map_or((value.as_str(), None), |(name, path)| {
1610                        (name, Some(PathBuf::from(path)))
1611                    });
1612                if let Some(path) = &path {
1613                    self.required_inputs.push(path.clone());
1614                }
1615                self.parsed.push(Argument::Extern {
1616                    name: name.into(),
1617                    path,
1618                });
1619                Ok(())
1620            }
1621            "remap-path-prefix" => {
1622                let value = self.take_value(&rendered_flag, inline)?;
1623                let Some((from, to)) = value.split_once('=') else {
1624                    return Err(BypassReason::MissingValue(rendered_flag));
1625                };
1626                self.parsed.push(Argument::RemapPath {
1627                    from: from.into(),
1628                    to: to.into(),
1629                });
1630                Ok(())
1631            }
1632            "codegen" => {
1633                let value = self.take_value(&rendered_flag, inline)?;
1634                self.parse_codegen(&value)
1635            }
1636            "jobs-frontend" => {
1637                let value = self.take_value(&rendered_flag, inline)?;
1638                self.parsed
1639                    .push(Argument::Plain(format!("{rendered_flag}={value}")));
1640                Ok(())
1641            }
1642            _ => Err(BypassReason::UnknownFlag(rendered_flag)),
1643        }
1644    }
1645
1646    fn parse_short(&mut self, value: &str) -> Result<(), BypassReason> {
1647        if let Some(attached) = value.strip_prefix("-Z") {
1648            let option = self.take_value("-Z", (!attached.is_empty()).then_some(attached))?;
1649            match option.as_str() {
1650                // Cargo passes `force-unstable-if-unmarked` to every standard
1651                // library unit under `-Zbuild-std`. It changes the stability
1652                // recorded in the crate's metadata, so it stays in the key.
1653                "embed-metadata=no"
1654                | "embed-metadata=yes"
1655                | "force-unstable-if-unmarked"
1656                | "shell-argfiles"
1657                | "unstable-options" => {
1658                    self.parsed.push(Argument::Plain(format!("-Z{option}")));
1659                    return Ok(());
1660                }
1661                // Selects a distinct unwind-table encoding. Preserve the
1662                // exact value in the action key; reject other spellings.
1663                "use-sync-unwind=yes" | "use-sync-unwind=no" => {
1664                    self.parsed.push(Argument::Plain(format!("-Z{option}")));
1665                    return Ok(());
1666                }
1667                "threads" | "threads=" => {
1668                    return Err(BypassReason::MissingValue("-Zthreads".into()));
1669                }
1670                "remap-cwd-prefix" | "remap-cwd-prefix=" => {
1671                    return Err(BypassReason::MissingValue("-Zremap-cwd-prefix".into()));
1672                }
1673                _ => {}
1674            }
1675            // Replaces the working directory in every path rustc records, and
1676            // in the options its incremental state is checked against. The
1677            // value is the virtual directory written in the working
1678            // directory's place, kept verbatim like `--remap-path-prefix`'s
1679            // destination.
1680            if option.starts_with("remap-cwd-prefix=") {
1681                self.parsed.push(Argument::Plain(format!("-Z{option}")));
1682                return Ok(());
1683            }
1684            if option == "share-generics" {
1685                return Err(BypassReason::MissingValue("-Zshare-generics".into()));
1686            }
1687            if let Some(value) = option.strip_prefix("share-generics=") {
1688                if matches!(
1689                    value,
1690                    "y" | "yes" | "on" | "true" | "n" | "no" | "off" | "false"
1691                ) {
1692                    self.parsed.push(Argument::Plain(format!("-Z{option}")));
1693                    return Ok(());
1694                }
1695                return Err(if value.is_empty() {
1696                    BypassReason::MissingValue("-Zshare-generics".into())
1697                } else {
1698                    BypassReason::UnknownFlag(format!("-Z{option}"))
1699                });
1700            }
1701            // These change what rustc encodes into the rmeta: the MIR of
1702            // every item, or the optimized MIR. Keep the exact spelling in
1703            // the key; reject values rustc would not accept.
1704            if option == "always-encode-mir" {
1705                self.parsed.push(Argument::Plain(format!("-Z{option}")));
1706                return Ok(());
1707            }
1708            if let Some(level) = option.strip_prefix("mir-opt-level=") {
1709                if matches!(level, "0" | "1" | "2" | "3" | "4") {
1710                    self.parsed.push(Argument::Plain(format!("-Z{option}")));
1711                    return Ok(());
1712                }
1713                return Err(if level.is_empty() {
1714                    BypassReason::MissingValue("-Zmir-opt-level".into())
1715                } else {
1716                    BypassReason::UnknownFlag(format!("-Z{option}"))
1717                });
1718            }
1719            if option == "mir-opt-level" {
1720                return Err(BypassReason::MissingValue("-Zmir-opt-level".into()));
1721            }
1722            if option == "inline-mir" {
1723                return Err(BypassReason::MissingValue("-Zinline-mir".into()));
1724            }
1725            if let Some(value) = option.strip_prefix("inline-mir=") {
1726                if matches!(
1727                    value,
1728                    "y" | "yes" | "on" | "true" | "n" | "no" | "off" | "false"
1729                ) {
1730                    self.parsed.push(Argument::Plain(format!("-Z{option}")));
1731                    return Ok(());
1732                }
1733                return Err(if value.is_empty() {
1734                    BypassReason::MissingValue("-Zinline-mir".into())
1735                } else {
1736                    BypassReason::UnknownFlag(format!("-Z{option}"))
1737                });
1738            }
1739            if option.starts_with("threads=") {
1740                self.parsed.push(Argument::Plain(format!("-Z{option}")));
1741                return Ok(());
1742            }
1743            // rustc loads a value containing a `.` as a library path, which the key doesn't hash.
1744            if let Some(backend) = option.strip_prefix("codegen-backend=")
1745                && !backend.is_empty()
1746                && !backend.contains(['.', '/', '\\'])
1747            {
1748                self.sysroot_backend = Some(format!("-Z{option}"));
1749                self.parsed.push(Argument::Plain(format!("-Z{option}")));
1750                return Ok(());
1751            }
1752            return Err(BypassReason::UnknownFlag(format!("-Z{option}")));
1753        }
1754        match value {
1755            // `-vV` is how cargo and build scripts ask for the verbose
1756            // version, so it is a query rather than a flag left unmodeled.
1757            "-h" | "-V" | "-vV" => return Err(BypassReason::CompilerQuery),
1758            "-g" | "-O" | "-v" => {
1759                self.parsed.push(Argument::Plain(value.into()));
1760                return Ok(());
1761            }
1762            _ => {}
1763        }
1764        for (short, long) in [
1765            ("-A", "--allow"),
1766            ("-W", "--warn"),
1767            ("-D", "--deny"),
1768            ("-F", "--forbid"),
1769        ] {
1770            if let Some(attached) = value.strip_prefix(short) {
1771                let lint = self.take_value(short, (!attached.is_empty()).then_some(attached))?;
1772                self.parsed.push(Argument::Plain(format!("{long}={lint}")));
1773                return Ok(());
1774            }
1775        }
1776        if let Some(attached) = value.strip_prefix("-C") {
1777            let option = self.take_value("-C", (!attached.is_empty()).then_some(attached))?;
1778            return self.parse_codegen(&option);
1779        }
1780        if let Some(attached) = value.strip_prefix("-L") {
1781            let search = self.take_value("-L", (!attached.is_empty()).then_some(attached))?;
1782            let (kind, path) = search
1783                .split_once('=')
1784                .map_or(("all", search.as_str()), |(kind, path)| (kind, path));
1785            if kind != "dependency" && !searches_native(kind) {
1786                return Err(BypassReason::UnsupportedSearchPath(kind.into()));
1787            }
1788            self.parsed.push(Argument::SearchPath {
1789                kind: kind.into(),
1790                path: path.into(),
1791            });
1792            return Ok(());
1793        }
1794        if let Some(attached) = value.strip_prefix("-l") {
1795            let library = self.take_value("-l", (!attached.is_empty()).then_some(attached))?;
1796            self.parsed.push(Argument::Plain(format!("-l{library}")));
1797            self.native_libraries.push(library);
1798            return Ok(());
1799        }
1800        if let Some(attached) = value.strip_prefix("-o") {
1801            let path = self.take_value("-o", (!attached.is_empty()).then_some(attached))?;
1802            self.explicit_output = Some(path.clone().into());
1803            self.parsed.push(Argument::Path {
1804                flag: "-o".into(),
1805                path: path.into(),
1806            });
1807            return Ok(());
1808        }
1809        Err(BypassReason::UnknownFlag(value.into()))
1810    }
1811
1812    fn parse_codegen(&mut self, value: &str) -> Result<(), BypassReason> {
1813        let name = value.split_once('=').map_or(value, |(name, _)| name);
1814        if name == "incremental" {
1815            return Err(BypassReason::Incremental);
1816        }
1817        if name == "profile-use" {
1818            let Some((_, profile)) = value.split_once('=') else {
1819                return Err(BypassReason::MissingValue("-Cprofile-use".into()));
1820            };
1821            if profile.is_empty() {
1822                return Err(BypassReason::MissingValue("-Cprofile-use".into()));
1823            }
1824            let path = PathBuf::from(profile);
1825            self.required_inputs.push(path.clone());
1826            self.parsed.push(Argument::Path {
1827                flag: "-Cprofile-use".into(),
1828                path,
1829            });
1830            return Ok(());
1831        }
1832        if SUPPORTED_CODEGEN_OPTIONS.binary_search(&name).is_err()
1833            && !matches!(name, "linker" | "linker-flavor")
1834        {
1835            return Err(BypassReason::UnknownCodegenOption(name.into()));
1836        }
1837        // Cargo compiles every dependency of an LTO build with this flag, so
1838        // the rlibs carry bitcode for the final link to optimize across. The
1839        // switch is keyed as text like any other option. A value naming the
1840        // linker plugin is a host file the key does not describe, so that
1841        // spelling still bypasses.
1842        if name == "linker-plugin-lto"
1843            && let Some((_, selection)) = value.split_once('=')
1844            && !matches!(
1845                selection,
1846                "" | "y" | "yes" | "on" | "true" | "n" | "no" | "off" | "false"
1847            )
1848        {
1849            return Err(BypassReason::UnknownCodegenOption(format!(
1850                "linker-plugin-lto={selection}"
1851            )));
1852        }
1853        // `-fuse-ld=<name>` selects the linker the driver invokes. Parsed
1854        // rather than keyed as text so the linker identity probe can pin the
1855        // selected linker; a repeated selection dedups, and a conflicting
1856        // second selection falls through to Plain, which native-link handling
1857        // declines to model. The driver honors the last selection, so a
1858        // conflict is a link whose linker this adapter cannot name.
1859        if name == "link-arg"
1860            && let Some((_, option)) = value.split_once('=')
1861            && let Some(selection) = option.strip_prefix("-fuse-ld=")
1862            && !selection.is_empty()
1863            && !selection.contains(',')
1864            && !self.parsed.iter().any(
1865                |argument| matches!(argument, Argument::FuseLd(existing) if existing != selection),
1866            )
1867        {
1868            if !self.parsed.iter().any(
1869                |argument| matches!(argument, Argument::FuseLd(existing) if existing == selection),
1870            ) {
1871                self.parsed.push(Argument::FuseLd(selection.to_owned()));
1872            }
1873            return Ok(());
1874        }
1875        // Only a single filename under @rpath is modeled. Other spellings,
1876        // combined linker options, and explicit absolute names still bypass.
1877        if name == "link-arg"
1878            && let Some(option) = value.strip_prefix("link-arg=-Wl,-install_name,@rpath/")
1879            && safe_install_name(option)
1880        {
1881            self.parsed.push(Argument::InstallName(option.to_owned()));
1882            return Ok(());
1883        }
1884        // An absolute rpath is only recorded in the output. Relative and
1885        // `@`-prefixed entries, and several options in one argument, stay
1886        // unmodeled text.
1887        if name == "link-arg"
1888            && let Some(directory) = value.strip_prefix("link-arg=-Wl,-rpath,")
1889            && directory.starts_with('/')
1890            && !directory.contains(',')
1891        {
1892            self.parsed.push(Argument::Rpath(directory.to_owned()));
1893            return Ok(());
1894        }
1895        // `-oso_prefix` names a checkout-specific path, so it is parsed
1896        // rather than keyed as text: the path normalizes like every other
1897        // path in the key, which is what lets two checkouts passing their own
1898        // prefixes agree on one action.
1899        if matches!(name, "link-arg" | "link-args")
1900            && let Some((_, option)) = value.split_once('=')
1901            && let Some(prefix) = option.strip_prefix("-Wl,-oso_prefix,")
1902            && !prefix.trim_end_matches('/').is_empty()
1903            && !prefix.contains(',')
1904        {
1905            let trailing_slash = prefix.ends_with('/');
1906            self.parsed.push(Argument::OsoPrefix {
1907                path: PathBuf::from(prefix.trim_end_matches('/')),
1908                trailing_slash,
1909            });
1910            return Ok(());
1911        }
1912        self.parsed
1913            .push(Argument::Plain(format!("--codegen={value}")));
1914        if name == "extra-filename" {
1915            self.extra_filename = value
1916                .split_once('=')
1917                .map_or(String::new(), |(_, value)| value.to_string());
1918        }
1919        Ok(())
1920    }
1921
1922    /// Model what rustc reads for each `-l`, now that the emit is known.
1923    ///
1924    /// A library emit runs no linker. For `dylib`, `framework`, `link-arg`,
1925    /// and an unspecified kind, rustc only records the name in the crate's
1926    /// metadata, so the flag text already in the key is the whole input. A
1927    /// `static` library is different: rustc opens the archive and bundles its
1928    /// members into the rlib, so the archive's content decides the output. It
1929    /// is found the way rustc finds it and named as a required input, keyed
1930    /// by content exactly like an `--extern` artifact. With `-bundle` rustc
1931    /// records the name for a downstream link instead of reading the archive,
1932    /// so that flag is text like the name-only kinds.
1933    ///
1934    /// A linked output hands every `-l` to its linker, whose search is not
1935    /// modeled here, so those still bypass whatever the kind.
1936    fn require_native_libraries(&mut self, link_output: LinkOutput) -> Result<(), BypassReason> {
1937        for library in std::mem::take(&mut self.native_libraries) {
1938            if link_output != LinkOutput::Library {
1939                return Err(BypassReason::NativeLibrary(library));
1940            }
1941            // `-l [KIND[:MODIFIERS]=]NAME[:RENAME]`. Without a kind the
1942            // library is rustc's "unspecified" kind: it is handed to the
1943            // linker of whatever finally links, and an rlib only records the
1944            // name. rustc bundles into an rlib only what `-l static` names
1945            // (`link_rlib` takes `NativeLibKind::Static` with bundling on),
1946            // so a `libNAME.a` that later appears beside a plain `-l NAME`
1947            // changes that final link, not this compilation.
1948            let Some((kind, name)) = library.split_once('=') else {
1949                continue;
1950            };
1951            let (kind, modifiers) = kind.split_once(':').unwrap_or((kind, ""));
1952            match kind {
1953                "static" => {}
1954                "dylib" | "framework" | "link-arg" => continue,
1955                _ => return Err(BypassReason::UnknownFlag(format!("-l{library}"))),
1956            }
1957            // A rename links RENAME in place of the NAME a `#[link]` attribute
1958            // gave, so RENAME is the archive on disk.
1959            let name = name.split_once(':').map_or(name, |(_, renamed)| renamed);
1960            let (mut verbatim, mut bundle) = (false, true);
1961            for modifier in modifiers.split(',') {
1962                match modifier {
1963                    "+verbatim" => verbatim = true,
1964                    "-verbatim" => verbatim = false,
1965                    "+bundle" => bundle = true,
1966                    "-bundle" => bundle = false,
1967                    _ => {}
1968                }
1969            }
1970            if !bundle {
1971                continue;
1972            }
1973            let archive = self
1974                .find_native_static_library(name, verbatim)
1975                .map_err(|()| BypassReason::CustomTargetNativeLibrary(library.clone()))?
1976                .ok_or_else(|| BypassReason::MissingNativeLibrary(library.clone()))?;
1977            self.required_inputs.push(archive);
1978        }
1979        Ok(())
1980    }
1981
1982    /// Resolve a static library the way rustc does: the first `-L native`
1983    /// directory, in command-line order, holding the target's file name for
1984    /// it. rustc would also search a plain `-L` directory, but that kind
1985    /// already bypasses as unsupported before it gets here. Targets with
1986    /// MSVC-style libraries (Windows MSVC and UEFI) accept `NAME.lib` before
1987    /// falling back to the `libNAME.a` every built-in target otherwise uses;
1988    /// `+verbatim` names the file literally. A custom target specification
1989    /// sets its own prefix and suffix, which are not read here, so it is an
1990    /// `Err` rather than a guess that could hash a different archive than
1991    /// rustc bundles. A relative search directory resolves against the
1992    /// process working directory, as it does for rustc.
1993    fn find_native_static_library(
1994        &self,
1995        name: &str,
1996        verbatim: bool,
1997    ) -> Result<Option<PathBuf>, ()> {
1998        let file_names = if verbatim {
1999            vec![name.to_owned()]
2000        } else {
2001            match self.static_library_naming() {
2002                Some(StaticLibraryNaming::Msvc) => {
2003                    vec![format!("{name}.lib"), format!("lib{name}.a")]
2004                }
2005                Some(StaticLibraryNaming::Unix) => vec![format!("lib{name}.a")],
2006                None => return Err(()),
2007            }
2008        };
2009        Ok(self
2010            .parsed
2011            .iter()
2012            .filter_map(|argument| match argument {
2013                Argument::SearchPath { kind, path } if searches_native(kind) => Some(path),
2014                _ => None,
2015            })
2016            .flat_map(|directory| {
2017                file_names
2018                    .iter()
2019                    .map(move |file_name| directory.join(file_name))
2020            })
2021            .find(|candidate| candidate.is_file()))
2022    }
2023
2024    /// How the target names a static library, or `None` for a custom target
2025    /// specification, whose names only the specification knows.
2026    ///
2027    /// A bare name is a built-in target unless a specification file for it
2028    /// exists where rustc would look, under `RUST_TARGET_PATH` or in the
2029    /// sysroot, which the caller reports through
2030    /// [`ParseOptions::custom_target_search`].
2031    fn static_library_naming(&self) -> Option<StaticLibraryNaming> {
2032        let Some(target) = self.target.as_deref() else {
2033            return Some(if cfg!(any(target_env = "msvc", target_os = "uefi")) {
2034                StaticLibraryNaming::Msvc
2035            } else {
2036                StaticLibraryNaming::Unix
2037            });
2038        };
2039        if target.ends_with(".json")
2040            || target.contains(['/', '\\'])
2041            || self.options.custom_target_search
2042        {
2043            return None;
2044        }
2045        // rustc's `is_like_msvc` targets: `*-windows-msvc`, `*-win7-windows-msvc`,
2046        // and the UEFI targets, which borrow the MSVC toolchain's conventions.
2047        Some(if target.contains("msvc") || target.ends_with("-uefi") {
2048            StaticLibraryNaming::Msvc
2049        } else {
2050            StaticLibraryNaming::Unix
2051        })
2052    }
2053
2054    fn parse_input(&mut self, value: &str) -> Result<(), BypassReason> {
2055        if value == "-" {
2056            return Err(BypassReason::StandardInput);
2057        }
2058        if self.source.replace(value.into()).is_some() {
2059            return Err(BypassReason::MultipleInputs);
2060        }
2061        Ok(())
2062    }
2063
2064    fn classify(&self) -> Result<LinkOutput, BypassReason> {
2065        // A compilation that emits no `link` produces exactly what an rlib's
2066        // metadata emit does -- dep-info and `lib<name>.rmeta` -- whatever it
2067        // calls its crate type. `cargo check` and clippy compile every binary
2068        // and test target this way, and those were bypassing as an
2069        // unsupported crate type for a linked artifact none of them asked
2070        // for. No linker runs, so nothing downstream needs a linker identity
2071        // to describe, and rustc names the metadata the same way for every
2072        // crate type.
2073        let never_links = !self.emits.iter().any(|emit| emit.kind == "link");
2074        let builds_a_library = !self.test
2075            && !self.crate_types.is_empty()
2076            && self
2077                .crate_types
2078                .iter()
2079                .all(|crate_type| matches!(crate_type.as_str(), "lib" | "rlib"));
2080        let link_output = if never_links || builds_a_library {
2081            LinkOutput::Library
2082        } else if self
2083            .target
2084            .as_deref()
2085            .is_some_and(compiler_bundled_wasm_target)
2086            && ((self.test && self.crate_types.is_empty())
2087                || matches!(self.crate_types.as_slice(), [kind] if kind == "bin" || kind == "cdylib"))
2088        {
2089            if self.parsed.iter().any(|argument| match argument {
2090                Argument::Plain(value) if value == "--codegen=link-self-contained" => false,
2091                Argument::Plain(value) if value.starts_with("--codegen=link-self-contained=") => {
2092                    !matches!(
2093                        value.rsplit_once('=').map(|(_, value)| value),
2094                        Some("y" | "yes" | "on" | "true")
2095                    )
2096                }
2097                _ => false,
2098            }) {
2099                return Err(BypassReason::UnknownCodegenOption(
2100                    "link-self-contained".into(),
2101                ));
2102            }
2103            if self.target.as_deref().is_some_and(|target| target.contains("wasi"))
2104                && self.parsed.iter().any(|argument| {
2105                    matches!(argument, Argument::Plain(value) if value.strip_prefix("--codegen=target-feature=").is_some_and(|features| features.split(',').any(|feature| feature == "-crt-static")))
2106                })
2107            {
2108                return Err(BypassReason::UnknownCodegenOption(
2109                    "target-feature=-crt-static".into(),
2110                ));
2111            }
2112            // These targets use a linker and, where applicable, CRT objects
2113            // and libc shipped in the Rust toolchain. Unlike native linking,
2114            // there are no implicit host inputs outside compiler identity.
2115            LinkOutput::WasmExecutable
2116        } else if self.options.cache_native_links && self.links_a_native_artifact() {
2117            self.check_native_link_is_portable()?;
2118            if matches!(self.crate_types.as_slice(), [kind] if kind == "proc-macro") {
2119                LinkOutput::NativeProcMacro
2120            } else if matches!(self.crate_types.as_slice(), [kind] if kind == "cdylib") {
2121                LinkOutput::NativeSharedLibrary
2122            } else {
2123                LinkOutput::NativeExecutable
2124            }
2125        } else if self.test {
2126            return Err(BypassReason::UnsupportedCrateType("test".into()));
2127        } else {
2128            return Err(BypassReason::UnsupportedCrateType(
2129                self.crate_types
2130                    .iter()
2131                    .find(|crate_type| !matches!(crate_type.as_str(), "lib" | "rlib"))
2132                    .cloned()
2133                    .unwrap_or_else(|| "bin".into()),
2134            ));
2135        };
2136        // A link argument is handed to the linker verbatim, and its text is all
2137        // the adapter has to go on. `-Clink-arg=-Tlink.x` names a linker script
2138        // resolved off the search path, `-Clink-arg=-fuse-ld=lld` replaces the
2139        // linker the identity in the key describes, and neither is told apart
2140        // from `/STACK:8000000` by any rule short of knowing the linker's own
2141        // grammar. Where nothing links there is nothing to tell apart: an rlib
2142        // or an rmeta is produced without a linker invocation, so the option is
2143        // inert and the key carries its text like any other codegen option.
2144        if link_output != LinkOutput::Library
2145            && let Some(option) = self.first_link_argument(link_output)
2146        {
2147            return Err(BypassReason::UnmodeledLinkArgument(option.to_owned()));
2148        }
2149        if self
2150            .parsed
2151            .iter()
2152            .any(|arg| matches!(arg, Argument::InstallName(_)))
2153            && !(cfg!(target_os = "macos") && link_output == LinkOutput::NativeProcMacro)
2154        {
2155            return Err(BypassReason::UnmodeledLinkArgument(
2156                "link-arg=-Wl,-install_name".into(),
2157            ));
2158        }
2159        // ld64 never searches an rpath directory while linking, so the
2160        // argument is modeled only for a native macOS link. GNU ld searches
2161        // it for a shared object's own dependencies, which the key cannot see.
2162        if self
2163            .parsed
2164            .iter()
2165            .any(|argument| matches!(argument, Argument::Rpath(_)))
2166            && !(link_output == LinkOutput::Library
2167                || cfg!(target_os = "macos")
2168                    && matches!(
2169                        link_output,
2170                        LinkOutput::NativeExecutable
2171                            | LinkOutput::NativeProcMacro
2172                            | LinkOutput::NativeSharedLibrary
2173                    ))
2174        {
2175            return Err(BypassReason::UnmodeledLinkArgument(
2176                "link-arg=-Wl,-rpath".into(),
2177            ));
2178        }
2179        // `-fuse-ld` is modeled only for native links, where the linker
2180        // identity probe resolves and pins the linker it names. A wasm or
2181        // other non-native link consuming the selection has no identity that
2182        // describes it, so it declines the action like any other link
2183        // argument. Where nothing links, the selection is inert and the key
2184        // carries its text.
2185        if let Some(selection) = self.parsed.iter().find_map(|argument| {
2186            let Argument::FuseLd(selection) = argument else {
2187                return None;
2188            };
2189            Some(selection.as_str())
2190        }) && !matches!(
2191            link_output,
2192            LinkOutput::Library
2193                | LinkOutput::NativeExecutable
2194                | LinkOutput::NativeProcMacro
2195                | LinkOutput::NativeSharedLibrary
2196        ) {
2197            return Err(BypassReason::UnmodeledLinkArgument(format!(
2198                "link-arg=-fuse-ld={selection}"
2199            )));
2200        }
2201        if self.parsed.iter().any(|argument| {
2202            matches!(argument, Argument::Plain(value) if value.starts_with("--codegen=linker="))
2203        }) && !matches!(
2204            link_output,
2205            LinkOutput::Library
2206                | LinkOutput::NativeExecutable
2207                | LinkOutput::NativeProcMacro
2208                | LinkOutput::NativeSharedLibrary
2209        ) {
2210            return Err(BypassReason::UnknownCodegenOption("linker".into()));
2211        }
2212        // `-Clinker-flavor` tells rustc how to drive the linker, which no
2213        // identity probe describes, so every real link declines it. An rlib or
2214        // a metadata-only compilation never reaches the linker, so the value
2215        // is inert there and the key carries its text.
2216        if link_output != LinkOutput::Library
2217            && self.parsed.iter().any(|argument| {
2218                matches!(argument, Argument::Plain(value) if value.starts_with("--codegen=linker-flavor="))
2219            })
2220        {
2221            return Err(BypassReason::UnknownCodegenOption("linker-flavor".into()));
2222        }
2223        // `-oso_prefix` is modeled, but only where ld64 is the linker reading
2224        // it: a native macOS link. Any other linker sees an option this
2225        // adapter cannot vouch for, exactly like the arguments above.
2226        if !matches!(
2227            link_output,
2228            LinkOutput::Library
2229                | LinkOutput::NativeExecutable
2230                | LinkOutput::NativeProcMacro
2231                | LinkOutput::NativeSharedLibrary
2232        ) && self
2233            .parsed
2234            .iter()
2235            .any(|argument| matches!(argument, Argument::OsoPrefix { .. }))
2236        {
2237            return Err(BypassReason::UnmodeledLinkArgument(
2238                "link-arg=-Wl,-oso_prefix".into(),
2239            ));
2240        }
2241        if let Some(name) = self.parsed.iter().find_map(|argument| match argument {
2242            Argument::Extern { name, path: None } if name != "proc_macro" => Some(name),
2243            _ => None,
2244        }) {
2245            return Err(BypassReason::UnresolvedExtern(name.clone()));
2246        }
2247        if let Some(emit) = self
2248            .emits
2249            .iter()
2250            .find(|emit| !matches!(emit.kind.as_str(), "dep-info" | "link" | "metadata"))
2251        {
2252            return Err(BypassReason::UnsupportedEmit(emit.kind.clone()));
2253        }
2254        if !self
2255            .emits
2256            .iter()
2257            .any(|emit| matches!(emit.kind.as_str(), "link" | "metadata"))
2258        {
2259            return Err(BypassReason::NoCacheableOutput);
2260        }
2261        Ok(link_output)
2262    }
2263}
2264
2265impl Parser<'_> {
2266    /// The first `-C link-arg` or `-C link-args` option in the invocation,
2267    /// rendered as it appears in the action key.
2268    fn first_link_argument(&self, link_output: LinkOutput) -> Option<&str> {
2269        self.parsed.iter().find_map(|argument| {
2270            let Argument::Plain(value) = argument else {
2271                return None;
2272            };
2273            let option = value.strip_prefix("--codegen=")?;
2274            let (name, value) = option.split_once('=').unwrap_or((option, ""));
2275            (matches!(name, "link-arg" | "link-args")
2276                && !(name == "link-arg" && elf_keyword_is_modeled(link_output, value))
2277                && !msvc_options_are_modeled(link_output, name, value))
2278            .then_some(option)
2279        })
2280    }
2281
2282    /// Whether an `-oso_prefix` strips the directory this link's objects live
2283    /// in from the debug map ld64 records.
2284    ///
2285    /// The objects a native link reads -- this unit's own compiled objects
2286    /// and the rlibs it links -- sit in the output directory, so a prefix
2287    /// covering that directory leaves the debug map naming spellings every
2288    /// checkout shares. Toolchain objects stay absolute, as they do in the
2289    /// paths rustc itself embeds on every platform.
2290    fn oso_prefix_covers_outputs(&self) -> bool {
2291        let Some(directory) = self
2292            .out_dir
2293            .as_deref()
2294            .or_else(|| self.explicit_output.as_deref().and_then(Path::parent))
2295        else {
2296            return false;
2297        };
2298        if !directory.is_absolute() {
2299            return false;
2300        }
2301        let directory = normalize_components(directory);
2302        self.parsed.iter().any(|argument| {
2303            let Argument::OsoPrefix { path, .. } = argument else {
2304                return false;
2305            };
2306            path.is_absolute()
2307                && (directory.starts_with(normalize_components(path))
2308                    || std::fs::canonicalize(&directory)
2309                        .ok()
2310                        .zip(std::fs::canonicalize(path).ok())
2311                        .is_some_and(|(directory, prefix)| directory.starts_with(prefix)))
2312        })
2313    }
2314
2315    /// Whether this invocation links an artifact for the host.
2316    ///
2317    /// An explicit `--target` bypasses even when it spells the host triple:
2318    /// rustc without one links for the host by construction, which is the
2319    /// cheapest description of "the linker this adapter can identify", and
2320    /// cargo omits it for host builds anyway.
2321    fn links_a_native_artifact(&self) -> bool {
2322        self.target.is_none()
2323            // A compilation that emits no linked artifact did not link, so it
2324            // needs no linker to describe it. `cargo check --tests` asks for
2325            // metadata alone, and reading that as a link would send it looking
2326            // for a linker identity and refusing flags no linker ever saw.
2327            && self.emits.iter().any(|emit| emit.kind == "link")
2328            && ((self.test && self.crate_types.is_empty())
2329                || matches!(self.crate_types.as_slice(), [kind] if matches!(kind.as_str(), "bin" | "proc-macro"))
2330                || (cfg!(target_os = "linux")
2331                    && matches!(self.crate_types.as_slice(), [kind] if kind == "cdylib")))
2332    }
2333
2334    /// Reject a native link whose result depends on something the key cannot
2335    /// describe, or that leaves artifacts beside the ones mbx would store.
2336    ///
2337    /// Each check names a value rather than a flag: an option absent from the
2338    /// invocation keeps rustc's default, which the compiler identity already
2339    /// pins, while any other spelling is refused rather than guessed at.
2340    fn check_native_link_is_portable(&self) -> Result<(), BypassReason> {
2341        for argument in &self.parsed {
2342            let Argument::Plain(value) = argument else {
2343                continue;
2344            };
2345            // `-g` is rustc's shorthand for debug info, and arrives as itself
2346            // rather than as a codegen option.
2347            let (name, value) = if value == "-g" {
2348                ("debuginfo", Some("2"))
2349            } else if let Some(option) = value.strip_prefix("--codegen=") {
2350                match option.split_once('=') {
2351                    Some((name, value)) => (name, Some(value)),
2352                    // A codegen flag with no value asks for its enabled form,
2353                    // which is what cargo passes for `-Crpath`. Reading it as
2354                    // "nothing to check" is how these slipped through.
2355                    None => (option, None),
2356                }
2357            } else {
2358                continue;
2359            };
2360            let unportable = match name {
2361                // Packed debug info leaves a .dSYM bundle or .dwp file beside
2362                // the binary, and mbx stores neither. Unpacked is macOS's
2363                // debug-map arrangement -- debug info stays in the objects and
2364                // nothing lands beside the binary -- so the same covering
2365                // `-oso_prefix` that makes the debug map portable covers it.
2366                "split-debuginfo" => match value {
2367                    Some("off") => false,
2368                    Some("unpacked") if cfg!(target_os = "macos") => {
2369                        !self.oso_prefix_covers_outputs()
2370                    }
2371                    _ => true,
2372                },
2373                // ld64 records absolute object paths and their timestamps in
2374                // the binary's debug map, so the same source links to
2375                // different bytes in another checkout -- or the same one
2376                // twice. An `-oso_prefix` covering the output directory
2377                // strips those paths down to spellings every checkout
2378                // shares, which is the same leniency a Linux link already
2379                // gets for the paths rustc itself embeds; what remains
2380                // (object timestamps) only shows up under verification.
2381                "debuginfo" if cfg!(target_os = "macos") => {
2382                    !matches!(value, Some("0" | "none")) && !self.oso_prefix_covers_outputs()
2383                }
2384                // An rpath and a dynamically linked native program embed this
2385                // checkout's absolute target directory. Cargo also passes
2386                // `prefer-dynamic` to proc macros, but their dynamic runtime
2387                // is rustc's own sysroot (already pinned by compiler identity),
2388                // while Cargo's dependencies are linked into the macro. There
2389                // is no checkout rpath to carry; keep rejecting an explicit
2390                // `rpath` independently.
2391                "rpath" => is_enabled(value),
2392                "prefer-dynamic" => {
2393                    is_enabled(value)
2394                        && !matches!(self.crate_types.as_slice(), [kind] if kind == "proc-macro")
2395                }
2396                // The CRT objects a self-contained link uses come from
2397                // somewhere other than where the driver reports.
2398                "link-self-contained" => true,
2399                _ => false,
2400            };
2401            if unportable {
2402                return Err(BypassReason::UnportableNativeLink(match value {
2403                    Some(value) => format!("{name}={value}"),
2404                    None => name.to_owned(),
2405                }));
2406            }
2407        }
2408        Ok(())
2409    }
2410}
2411
2412fn safe_install_name(name: &str) -> bool {
2413    !name.is_empty()
2414        && name
2415            .bytes()
2416            .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))
2417}
2418
2419/// Whether a boolean codegen option is asking for its enabled form. Absent a
2420/// value, rustc reads the flag itself as the request.
2421fn is_enabled(value: Option<&str>) -> bool {
2422    matches!(value, None | Some("y" | "yes" | "on" | "true"))
2423}
2424
2425/// Whether `-Wl,-z,KEYWORD` is a native Linux link option the key can carry
2426/// as text.
2427///
2428/// A link argument is refused because its text cannot say whether it names a
2429/// file. These keywords are the exception: each sets a flag or a dynamic
2430/// section entry in the ELF output and reads nothing, in every linker the
2431/// identity probe resolves (GNU ld, gold, lld, and mold all spell them the
2432/// same). napi-build passes `-z nodelete` to every Node-API addon, so without
2433/// it no such addon caches.
2434fn elf_keyword_is_modeled(link_output: LinkOutput, value: &str) -> bool {
2435    cfg!(target_os = "linux")
2436        && matches!(
2437            link_output,
2438            LinkOutput::NativeExecutable
2439                | LinkOutput::NativeProcMacro
2440                | LinkOutput::NativeSharedLibrary
2441        )
2442        && value.strip_prefix("-Wl,-z,").is_some_and(|keyword| {
2443            matches!(
2444                keyword,
2445                "defs"
2446                    | "lazy"
2447                    | "nodelete"
2448                    | "nodlopen"
2449                    | "noexecstack"
2450                    | "norelro"
2451                    | "now"
2452                    | "origin"
2453                    | "relro"
2454            )
2455        })
2456}
2457
2458/// `-C link-arg` / `-C link-args` values that `link.exe` and `lld-link` read
2459/// as a plain switch or number and never as a file name.
2460///
2461/// `-C link-arg=/STACK:8000000` is how projects raise the main thread's stack
2462/// for Windows, usually through a `rustflags` entry in `.cargo/config.toml`
2463/// that reaches every proc macro, build script, and binary the workspace
2464/// builds. Refusing it leaves each of those linking on every build, and a MSVC
2465/// link is not reproducible (the PE header and PDB carry a timestamp and a
2466/// GUID), so each fresh proc-macro DLL hashes differently and every crate
2467/// compiled against it misses too.
2468///
2469/// Only spellings whose grammar is closed are listed: a number after
2470/// `/STACK:`, and `/Brepro`, which makes the link reproducible. Anything else
2471/// (`/DEF:`, `/MANIFESTINPUT:`, `/LIBPATH:`, a bare file name) can name a file
2472/// the key never hashes, so it still bypasses.
2473fn msvc_options_are_modeled(link_output: LinkOutput, name: &str, value: &str) -> bool {
2474    cfg!(target_env = "msvc")
2475        && matches!(
2476            link_output,
2477            LinkOutput::NativeExecutable
2478                | LinkOutput::NativeProcMacro
2479                | LinkOutput::NativeSharedLibrary
2480        )
2481        && match name {
2482            "link-arg" => msvc_option_reads_no_file(value),
2483            // The plural spelling is a whitespace-separated list, each entry
2484            // of which has to qualify.
2485            "link-args" => {
2486                let mut options = value.split_ascii_whitespace().peekable();
2487                options.peek().is_some() && options.all(msvc_option_reads_no_file)
2488            }
2489            _ => false,
2490        }
2491}
2492
2493/// One MSVC linker option from the closed list in [`msvc_options_are_modeled`].
2494/// The linker takes `-` for `/` and ignores the case of option names, and so
2495/// does this.
2496fn msvc_option_reads_no_file(option: &str) -> bool {
2497    let Some(option) = option.strip_prefix(['/', '-']) else {
2498        return false;
2499    };
2500    if option.eq_ignore_ascii_case("brepro") {
2501        return true;
2502    }
2503    let Some((name, sizes)) = option.split_once(':') else {
2504        return false;
2505    };
2506    // `/STACK:reserve[,commit]`. Sizes are decimal or `0x` hexadecimal, and
2507    // nothing else, so a value cannot smuggle in a path.
2508    let is_size = |size: &str| match size.strip_prefix("0x").or_else(|| size.strip_prefix("0X")) {
2509        Some(hex) => !hex.is_empty() && hex.bytes().all(|byte| byte.is_ascii_hexdigit()),
2510        None => !size.is_empty() && size.bytes().all(|byte| byte.is_ascii_digit()),
2511    };
2512    name.eq_ignore_ascii_case("stack")
2513        && sizes.split(',').count() <= 2
2514        && sizes.split(',').all(is_size)
2515}
2516
2517fn compiler_bundled_wasm_target(target: &str) -> bool {
2518    COMPILER_BUNDLED_WASM_TARGETS.binary_search(&target).is_ok()
2519}
2520
2521fn parse_emits(value: &str) -> Vec<Emit> {
2522    value
2523        .split(',')
2524        .map(|emit| {
2525            let (kind, path) = emit
2526                .split_once('=')
2527                .map_or((emit, None), |(kind, path)| (kind, Some(path.into())));
2528            Emit {
2529                kind: kind.into(),
2530                path,
2531            }
2532        })
2533        .collect()
2534}
2535
2536struct ActionBuilder<'a> {
2537    invocation: &'a RustcInvocation,
2538    store_root: &'a str,
2539    context: ActionContext,
2540    mappings: Vec<SharedPathMapping>,
2541    /// The directories resolved while building this one action. Its inputs
2542    /// share a few parents, and resolving each once is what keeps a crate
2543    /// with hundreds of them from paying a `realpath` walk per input.
2544    aliases: PathAliases,
2545    linker: Option<LinkerIdentity>,
2546}
2547
2548impl<'a> ActionBuilder<'a> {
2549    fn new(invocation: &'a RustcInvocation, mut context: ActionContext) -> Self {
2550        context.path_mappings = PathMapping::ordered(&context.path_mappings);
2551        let mappings = resolve_path_mappings(&shared_path_mappings(&context.path_mappings));
2552        Self {
2553            linker: None,
2554            invocation,
2555            store_root: NIX_STORE_ROOT,
2556            mappings,
2557            aliases: PathAliases::default(),
2558            context,
2559        }
2560    }
2561
2562    fn linked_by(mut self, linker: Option<LinkerIdentity>) -> Self {
2563        self.linker = linker;
2564        self
2565    }
2566
2567    fn build(self) -> Result<RustcAction, BypassReason> {
2568        self.validate_mappings()?;
2569        let invocation = self.invocation_descriptor()?;
2570        let environment = self.environment_descriptor()?;
2571
2572        let mut inputs = BTreeMap::<String, CacheDigest>::new();
2573        for input in &self.context.inputs {
2574            input
2575                .digest
2576                .validate()
2577                .map_err(|_| BypassReason::InvalidInputDigest(input.path.display().to_string()))?;
2578            let path = self.normalize_input_path(&input.path)?;
2579            if inputs
2580                .insert(path.clone(), input.digest.clone())
2581                .is_some_and(|existing| existing != input.digest)
2582            {
2583                return Err(BypassReason::ConflictingInput(path));
2584            }
2585        }
2586        let required = self
2587            .invocation
2588            .required_inputs
2589            .iter()
2590            .map(|path| self.normalize_input_path(path))
2591            .collect::<Result<BTreeSet<_>, _>>()?;
2592        if let Some(missing) = required.iter().find(|path| !inputs.contains_key(*path)) {
2593            return Err(BypassReason::MissingRequiredInput(missing.clone()));
2594        }
2595        let inputs = inputs
2596            .into_iter()
2597            .map(|(path, digest)| InputDescriptor { path, digest })
2598            .collect();
2599        // A native link without a linker identity would be keyed as though the
2600        // host did not matter. Refuse rather than publish that claim.
2601        if self.invocation.links_natively() && self.linker.is_none() {
2602            return Err(BypassReason::UnportableNativeLink(
2603                "linker identity is unknown".into(),
2604            ));
2605        }
2606        let descriptor = ActionDescriptor {
2607            version: ACTION_SCHEMA_VERSION,
2608            kind: "rustc",
2609            adapter_version: ADAPTER_VERSION,
2610            compiler: invocation.compiler,
2611            arguments: invocation.arguments,
2612            environment,
2613            inputs,
2614            linker: self.linker.clone(),
2615        };
2616        let bytes = canonical_json(&descriptor)
2617            .map_err(|error| BypassReason::Serialization(error.to_string()))?;
2618        let digest = CacheDigest::blake3(&bytes);
2619        Ok(RustcAction { digest, bytes })
2620    }
2621
2622    fn invocation_descriptor(&self) -> Result<InvocationDescriptor, BypassReason> {
2623        self.validate_mappings()?;
2624        let arguments = self
2625            .invocation
2626            .arguments
2627            .iter()
2628            .map(|argument| self.normalize_argument(argument))
2629            .collect::<Result<Vec<_>, _>>()?;
2630        let required_inputs = self
2631            .invocation
2632            .required_inputs
2633            .iter()
2634            .map(|path| self.normalize_file_path(path))
2635            .collect::<Result<BTreeSet<_>, _>>()?
2636            .into_iter()
2637            .collect();
2638        Ok(InvocationDescriptor {
2639            version: ACTION_SCHEMA_VERSION,
2640            kind: "rustc",
2641            adapter_version: ADAPTER_VERSION,
2642            compiler: CompilerDescriptor {
2643                toolchain: self.context.compiler.toolchain.clone(),
2644                rustc_version: self.context.compiler.rustc_version.clone(),
2645                host: self.context.compiler.host.clone(),
2646                driver: self.context.compiler.driver.clone(),
2647            },
2648            arguments,
2649            required_inputs,
2650        })
2651    }
2652
2653    fn validate_mappings(&self) -> Result<(), BypassReason> {
2654        if !self.context.working_dir.is_absolute() {
2655            return Err(BypassReason::RelativeWorkingDirectory(
2656                self.context.working_dir.clone(),
2657            ));
2658        }
2659        let mut roots = BTreeSet::new();
2660        let mut placeholders = BTreeSet::new();
2661        for mapping in &self.mappings {
2662            if !mapping.root.is_absolute() {
2663                return Err(BypassReason::RelativePathMapping(mapping.root.clone()));
2664            }
2665            if mapping.placeholder.is_empty()
2666                || !mapping
2667                    .placeholder
2668                    .bytes()
2669                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
2670                || !roots.insert(normalize_components(&mapping.root))
2671                || !placeholders.insert(&mapping.placeholder)
2672            {
2673                return Err(BypassReason::InvalidPathPlaceholder(
2674                    mapping.placeholder.clone(),
2675                ));
2676            }
2677        }
2678        Ok(())
2679    }
2680
2681    fn normalize_argument(&self, argument: &Argument) -> Result<String, BypassReason> {
2682        match argument {
2683            Argument::Plain(value) => Ok(value.clone()),
2684            Argument::Path { flag, path } if flag == "--sysroot" => {
2685                Ok(format!("{flag}={}", self.normalize_sysroot_path(path)?))
2686            }
2687            Argument::Path { flag, path } => Ok(format!("{flag}={}", self.normalize_path(path)?)),
2688            Argument::SearchPath { kind, path } => {
2689                let text = self.normalize_path(path)?;
2690                Ok(format!("-L{kind}={text}"))
2691            }
2692            Argument::Extern { name, path } => match path {
2693                Some(path) => Ok(format!(
2694                    "--extern={name}={}",
2695                    self.normalize_file_path(path)?
2696                )),
2697                None => Ok(format!("--extern={name}")),
2698            },
2699            Argument::Emit(emits) => Ok(format!(
2700                "--emit={}",
2701                emits
2702                    .iter()
2703                    .map(|emit| match &emit.path {
2704                        Some(path) => self
2705                            .normalize_path(path)
2706                            .map(|path| format!("{}={path}", emit.kind)),
2707                        None => Ok(emit.kind.clone()),
2708                    })
2709                    .collect::<Result<Vec<_>, _>>()?
2710                    .join(",")
2711            )),
2712            Argument::RemapPath { from, to } => Ok(format!(
2713                "--remap-path-prefix={}={}",
2714                self.normalize_path(from)?,
2715                to
2716            )),
2717            Argument::InstallName(name) => Ok(format!(
2718                "--codegen=link-arg=-Wl,-install_name,@rpath/{name}"
2719            )),
2720            Argument::OsoPrefix {
2721                path,
2722                trailing_slash,
2723            } => Ok(format!(
2724                "--codegen=link-arg=-Wl,-oso_prefix,{}{}",
2725                self.normalize_path(path)?,
2726                if *trailing_slash { "/" } else { "" }
2727            )),
2728            Argument::FuseLd(selection) => Ok(format!("--codegen=link-arg=-fuse-ld={selection}")),
2729            // Keyed as written: the directory is only recorded in the output.
2730            Argument::Rpath(directory) => Ok(format!("--codegen=link-arg=-Wl,-rpath,{directory}")),
2731        }
2732    }
2733
2734    /// Environment values enter the key verbatim, because rustc may embed one
2735    /// through `env!`: unlike a path used to locate an input, changing the value
2736    /// changes the artifact.
2737    ///
2738    /// A name in `portable_environment` is the exception the caller has earned.
2739    /// Its value normalizes like any other path, so two checkouts agree on it.
2740    fn environment_descriptor(&self) -> Result<BTreeMap<String, Option<String>>, BypassReason> {
2741        self.context
2742            .environment
2743            .iter()
2744            .map(|(name, value)| {
2745                let value = match value {
2746                    Some(value) if self.context.portable_environment.contains(name) => {
2747                        Some(self.normalize_path(Path::new(value))?)
2748                    }
2749                    value => value.clone(),
2750                };
2751                Ok((name.clone(), value))
2752            })
2753            .collect()
2754    }
2755
2756    fn normalize_input_path(&self, path: &Path) -> Result<String, BypassReason> {
2757        let absolute = normalize_components(&self.context.working_dir.join(path));
2758        for directory in self.invocation.native_search_paths() {
2759            let directory = normalize_components(&self.context.working_dir.join(directory));
2760            if let Ok(relative) = absolute.strip_prefix(&directory) {
2761                // Preserve the searched filename. Resolving a symlink here
2762                // would collapse libssl.dylib into its versioned referent, so
2763                // retargeting that link between two existing files could leave
2764                // the input map unchanged. Discovery rejects directory links
2765                // inside the tree and hashes regular-file links by content.
2766                let suffix = relative
2767                    .components()
2768                    .map(|component| {
2769                        component
2770                            .as_os_str()
2771                            .to_str()
2772                            .ok_or_else(|| BypassReason::NonUtf8Path(path.to_path_buf()))
2773                    })
2774                    .collect::<Result<Vec<_>, _>>()?
2775                    .join("/");
2776                if !suffix.is_empty() {
2777                    return Ok(format!("{}/{}", self.normalize_path(&directory)?, suffix));
2778                }
2779            }
2780        }
2781        self.normalize_file_path(path)
2782    }
2783
2784    fn normalize_sysroot_path(&self, path: &Path) -> Result<String, BypassReason> {
2785        let absolute = self.context.working_dir.join(path);
2786        if !absolute.starts_with(self.store_root) {
2787            return self.normalize_path(path);
2788        }
2789        // Dep-info omits implicit libraries from the sysroot. Its literal
2790        // path can identify them only when the directory stays in the store.
2791        if let Some(value) = absolute.to_str()
2792            && resolve_nix_store_path(value, self.store_root).is_some_and(|path| path.is_dir())
2793        {
2794            return Ok(value.to_owned());
2795        }
2796        Err(BypassReason::UnmappedAbsolutePath(absolute))
2797    }
2798
2799    fn normalize_file_path(&self, path: &Path) -> Result<String, BypassReason> {
2800        self.normalize_path(path)
2801            .or_else(|reason| key_nix_store_path(path, &self.context.working_dir, reason))
2802    }
2803
2804    fn normalize_path(&self, path: &Path) -> Result<String, BypassReason> {
2805        normalize_resolved_shared_path_with(
2806            &self.aliases,
2807            path,
2808            &self.context.working_dir,
2809            &self.mappings,
2810        )
2811        .map_err(Into::into)
2812    }
2813}
2814
2815/// Whether a normalized path names something strictly beneath one of
2816/// `directories`, which are normalized the same way and so share its `/`
2817/// separator regardless of platform.
2818fn under_any_directory(path: &str, directories: &BTreeSet<String>) -> bool {
2819    directories.iter().any(|directory| {
2820        path.len() > directory.len()
2821            && path.as_bytes()[directory.len()] == b'/'
2822            && path.starts_with(directory)
2823    })
2824}
2825
2826fn denormalize_path(
2827    value: &str,
2828    mappings: &[PathMapping],
2829    store_root: &str,
2830) -> Result<PathBuf, BypassReason> {
2831    for mapping in mappings {
2832        let prefix = format!("${{{}}}", mapping.placeholder);
2833        let suffix = if value == prefix {
2834            ""
2835        } else if let Some(suffix) = value.strip_prefix(&format!("{prefix}/")) {
2836            suffix
2837        } else {
2838            continue;
2839        };
2840        if !mapping.root.is_absolute()
2841            || (!suffix.is_empty()
2842                && suffix.split('/').any(|component| {
2843                    component.is_empty()
2844                        || matches!(component, "." | "..")
2845                        || component.contains('\\')
2846                }))
2847        {
2848            return Err(BypassReason::InvalidPredictedInput(value.into()));
2849        }
2850        let mut path = normalize_components(&mapping.root);
2851        path.extend(suffix.split('/').filter(|component| !component.is_empty()));
2852        return Ok(path);
2853    }
2854    // Predictions can come from a shared cache. Check the symlink target as
2855    // well as the spelling before allowing the caller to read the file.
2856    if resolve_nix_store_path(value, store_root).is_some() {
2857        return Ok(PathBuf::from(value));
2858    }
2859    Err(BypassReason::InvalidPredictedInput(value.into()))
2860}
2861
2862fn resolve_nix_store_path(value: &str, store_root: &str) -> Option<PathBuf> {
2863    let resolved = nix_store_path(value, store_root)?.canonicalize().ok()?;
2864    nix_store_path(resolved.to_str()?, store_root)?;
2865    Some(resolved)
2866}
2867
2868fn nix_store_path<'a>(value: &'a str, store_root: &str) -> Option<&'a Path> {
2869    let path = Path::new(value);
2870    if !path.is_absolute() {
2871        return None;
2872    }
2873    let suffix = value.strip_prefix(store_root)?.strip_prefix('/')?;
2874    (!suffix.split('/').any(|component| {
2875        component.is_empty() || matches!(component, "." | "..") || component.contains('\0')
2876    }))
2877    .then_some(path)
2878}
2879
2880fn key_nix_store_path(
2881    path: &Path,
2882    working_dir: &Path,
2883    reason: BypassReason,
2884) -> Result<String, BypassReason> {
2885    if matches!(reason, BypassReason::UnmappedAbsolutePath(_)) {
2886        let absolute = working_dir.join(path);
2887        if let Some(value) = absolute.to_str()
2888            && nix_store_path(value, NIX_STORE_ROOT).is_some()
2889        {
2890            return Ok(value.to_owned());
2891        }
2892    }
2893    Err(reason)
2894}
2895
2896fn normalize_components(path: &Path) -> PathBuf {
2897    let mut normalized = PathBuf::new();
2898    for component in path.components() {
2899        match component {
2900            Component::CurDir => {}
2901            Component::ParentDir => {
2902                normalized.pop();
2903            }
2904            component => normalized.push(component.as_os_str()),
2905        }
2906    }
2907    normalized
2908}
2909
2910fn absolute_path(path: &Path, working_dir: &Path) -> PathBuf {
2911    if path.is_absolute() {
2912        normalize_components(path)
2913    } else {
2914        normalize_components(&working_dir.join(path))
2915    }
2916}
2917
2918#[cfg(test)]
2919#[path = "rustc_cache_tests.rs"]
2920mod tests;