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