1#![deny(missing_docs)]
30
31use mbx_cache_core::{
32 CacheDigest, FileDigestCache, PathAliases, PathMapping as SharedPathMapping,
33 PathNormalizationError, canonical_json, normalize_mapped_path as normalize_shared_path,
34 normalize_resolved_mapped_path_with as normalize_resolved_shared_path_with,
35 resolve_path_mappings,
36};
37use serde::{Deserialize, Deserializer, Serialize, Serializer};
38use std::collections::{BTreeMap, BTreeSet};
39use std::ffi::OsString;
40use std::path::{Component, Path, PathBuf};
41use thiserror::Error;
42
43mod dep_info;
44
45const NIX_STORE_ROOT: &str = "/nix/store";
46
47pub use dep_info::{DepInfoCommand, DiscoveredInputs, RustcDepInfo};
48
49pub const ACTION_SCHEMA_VERSION: u8 = 1;
51pub const ADAPTER_VERSION: u8 = 2;
58
59impl BypassReason {
60 pub fn kind(&self) -> &'static str {
65 self.into()
66 }
67
68 pub fn remediation(&self) -> Option<&'static str> {
74 match self {
75 Self::Incremental => Some(
76 "Set `MBX_INCREMENTAL=0`; mbx will then disable Cargo incremental state and cache the compilation.",
77 ),
78 Self::UnportableNativeLink(detail) if detail.contains("linker") => Some(
79 "Make the native linker resolvable on `PATH`, or configure a linker mbx can identify for this target.",
80 ),
81 Self::UnportableNativeLink(_) => Some(
82 "Remove the reported `-C` option from the active Cargo profile or `RUSTFLAGS` to make these links cacheable.",
83 ),
84 Self::UnknownFlag(_) | Self::UnknownCodegenOption(_) => Some(
85 "Remove the reported compiler option, or upgrade mbx if the option should be modeled.",
86 ),
87 Self::UnmodeledLinkArgument(_) => Some(
88 "Remove the reported linker argument, or keep these links uncached if the argument is required.",
89 ),
90 Self::UnmappedAbsolutePath(_) => Some(
91 "Move the input under the workspace, target, Cargo, toolchain, or home roots so mbx can give it a portable cache name.",
92 ),
93 Self::BuildScriptInputOverlapsOutputs(_) => Some(
94 "Keep compiler output directories outside watched trees, or narrow `rerun-if-changed` to source and asset paths.",
95 ),
96 _ => None,
97 }
98 }
99}
100
101impl From<PathNormalizationError> for BypassReason {
102 fn from(reason: PathNormalizationError) -> Self {
103 match reason {
104 PathNormalizationError::UnmappedAbsolutePath(path) => Self::UnmappedAbsolutePath(path),
105 PathNormalizationError::NonUtf8Path(path) => Self::NonUtf8Path(path),
106 }
107 }
108}
109
110const SUPPORTED_CODEGEN_OPTIONS: &[&str] = &[
111 "codegen-units",
112 "control-flow-guard",
113 "debug-assertions",
114 "debuginfo",
115 "default-linker-libraries",
116 "embed-bitcode",
117 "extra-filename",
118 "force-frame-pointers",
119 "force-unwind-tables",
120 "instrument-coverage",
121 "link-arg",
122 "link-args",
123 "link-dead-code",
124 "link-self-contained",
125 "linker-plugin-lto",
126 "lto",
127 "metadata",
128 "no-prepopulate-passes",
129 "opt-level",
130 "overflow-checks",
131 "panic",
132 "prefer-dynamic",
133 "relocation-model",
134 "rpath",
135 "save-temps",
136 "soft-float",
137 "split-debuginfo",
138 "split-dwarf-kind",
139 "strip",
140 "symbol-mangling-version",
141 "target-cpu",
142 "target-feature",
143 "tls-model",
144];
145
146const NATIVE_DIRECTORY_PREDICTION_PREFIX: &str = "@native-directory:";
147const MAX_PREDICTED_INPUTS: usize = 16 * 1024;
148const MAX_DECODED_PREDICTION_BYTES: usize = 16 * 1024 * 1024;
152const MAX_NATIVE_INPUT_BYTES: u64 = 2 * 1024 * 1024 * 1024;
153
154const COMPILER_BUNDLED_WASM_TARGETS: &[&str] = &[
157 "wasm32-unknown-unknown",
158 "wasm32-wasip1",
159 "wasm32-wasip1-threads",
160 "wasm32-wasip2",
161 "wasm32v1-none",
162 "wasm64-unknown-unknown",
163];
164
165#[derive(Debug, Clone, PartialEq, Eq, Error, strum::IntoStaticStr)]
166#[strum(serialize_all = "kebab-case")]
167#[non_exhaustive]
177pub enum BypassReason {
178 #[error("rustc argument {index} is not valid UTF-8")]
180 NonUtf8Argument {
181 index: usize,
183 },
184 #[error("could not model rustc response file: {0}")]
186 ResponseFile(String),
187 #[error("rustc flag is not modeled by the cache adapter: {0}")]
189 UnknownFlag(String),
190 #[error("rustc codegen option is not modeled by the cache adapter: {0}")]
192 UnknownCodegenOption(String),
193 #[error("rustc flag requires a value: {0}")]
195 MissingValue(String),
196 #[error("rustc invocation is a compiler query, not a compilation")]
198 CompilerQuery,
199 #[error("rustc invocation reads source from standard input")]
201 StandardInput,
202 #[error("rustc invocation has no source input")]
204 MissingInput,
205 #[error("rustc invocation has multiple source inputs")]
207 MultipleInputs,
208 #[error("incremental compilation cannot be combined with action caching")]
210 Incremental,
211 #[error("rustc crate type is not cacheable yet: {0}")]
213 UnsupportedCrateType(String),
214 #[error("rustc output type is not cacheable yet: {0}")]
216 UnsupportedEmit(String),
217 #[error("rustc invocation does not emit a cacheable artifact")]
219 NoCacheableOutput,
220 #[error("rustc invocation does not emit dependency information")]
222 NoDepInfo,
223 #[error("rustc output paths do not share one directory")]
225 SplitOutputDirectories,
226 #[error("rustc output path has no file name: {0}")]
228 InvalidOutputPath(PathBuf),
229 #[error("rustc -o with an emit that has no explicit path is not modeled: {0}")]
231 ImplicitEmitWithOutputFile(PathBuf),
232 #[error("native library on a linked output is not cacheable yet: {0}")]
235 NativeLibrary(String),
236 #[error("native static library was not found on any search path: {0}")]
239 MissingNativeLibrary(String),
240 #[error("static library file names are not known for a custom target: {0}")]
243 CustomTargetNativeLibrary(String),
244 #[error("rustc output name does not distinguish a program from a library: {0}")]
246 AmbiguousOutputName(PathBuf),
247 #[error("native link is not reproducible across checkouts: {0}")]
249 UnportableNativeLink(String),
250 #[error("rustc link argument is not modeled by the cache adapter: {0}")]
252 UnmodeledLinkArgument(String),
253 #[error("rustc search path kind is not cacheable yet: {0}")]
255 UnsupportedSearchPath(String),
256 #[error("rustc extern does not identify an input artifact: {0}")]
258 UnresolvedExtern(String),
259 #[error("absolute path has no stable cache mapping: {0}")]
261 UnmappedAbsolutePath(PathBuf),
262 #[error("cache key paths must be valid UTF-8: {0}")]
264 NonUtf8Path(PathBuf),
265 #[error("cache action working directory must be absolute: {0}")]
267 RelativeWorkingDirectory(PathBuf),
268 #[error("cache path mapping must use an absolute root: {0}")]
270 RelativePathMapping(PathBuf),
271 #[error("cache path mapping placeholder is invalid: {0}")]
273 InvalidPathPlaceholder(String),
274 #[error("required compiler input was not provided: {0}")]
276 MissingRequiredInput(String),
277 #[error("compiler input has an invalid digest: {0}")]
279 InvalidInputDigest(String),
280 #[error("compiler input appears more than once with different content: {0}")]
282 ConflictingInput(String),
283 #[error("rustc dep-info is malformed: {0}")]
285 MalformedDepInfo(String),
286 #[error("failed to read rustc dep-info {path}: {message}")]
288 DepInfoRead {
289 path: PathBuf,
291 message: String,
293 },
294 #[error("rustc dep-info output path must be absolute: {0}")]
296 RelativeDepInfoPath(PathBuf),
297 #[error("rustc dep-info output path cannot contain a comma: {0}")]
299 UnsafeDepInfoPath(PathBuf),
300 #[error("failed to read compiler input {path}: {message}")]
302 InputRead {
303 path: PathBuf,
305 message: String,
307 },
308 #[error("declared build-script input overlaps compiler outputs: {0}")]
310 BuildScriptInputOverlapsOutputs(PathBuf),
311 #[error("Cargo has not recorded the build script's declarations yet: {0}")]
316 BuildScriptDeclarationsPending(PathBuf),
317 #[error("build-script inputs changed during compilation (declarations: {0})")]
320 BuildScriptInputsChanged(PathBuf),
321 #[error("compiler input changed after discovery: {0}")]
323 InputChanged(PathBuf),
324 #[error("compiler input was modified during compilation: {0}")]
326 InputModifiedDuringCompilation(PathBuf),
327 #[error("compiler input metadata changed during compilation: {0}")]
331 InputMetadataChangedDuringCompilation(PathBuf),
332 #[error("discovered inputs were collected from a different working directory")]
334 DiscoveryWorkingDirectory,
335 #[error("compiler environment input has conflicting values: {0}")]
337 ConflictingEnvironment(String),
338 #[error("failed to serialize the rustc action: {0}")]
340 Serialization(String),
341 #[error("rustc action prediction is unsupported")]
343 UnsupportedPrediction,
344 #[error("rustc action prediction contains an invalid input path: {0}")]
346 InvalidPredictedInput(String),
347}
348
349fn searches_native(kind: &str) -> bool {
354 matches!(kind, "native" | "all")
355}
356
357#[derive(Debug, Clone, PartialEq, Eq)]
358enum Argument {
359 Plain(String),
360 Path {
361 flag: String,
362 path: PathBuf,
363 },
364 SearchPath {
365 kind: String,
366 path: PathBuf,
367 },
368 Extern {
369 name: String,
370 path: Option<PathBuf>,
371 },
372 Emit(Vec<Emit>),
373 RemapPath {
374 from: PathBuf,
375 to: String,
376 },
377 InstallName(String),
379 OsoPrefix {
382 path: PathBuf,
383 trailing_slash: bool,
384 },
385 FuseLd(String),
389 Rpath(String),
393}
394
395#[derive(Debug, Clone, PartialEq, Eq)]
396struct Emit {
397 kind: String,
398 path: Option<PathBuf>,
399}
400
401#[derive(Debug, Clone, PartialEq, Eq)]
402pub struct RustcInvocation {
407 arguments: Vec<Argument>,
408 source: PathBuf,
409 required_inputs: Vec<PathBuf>,
410 crate_name: String,
411 extra_filename: String,
412 out_dir: Option<PathBuf>,
413 explicit_output: Option<PathBuf>,
414 emits: Vec<Emit>,
415 target: Option<String>,
416 link_output: LinkOutput,
417}
418
419#[derive(Debug, Clone, Copy, PartialEq, Eq)]
420enum LinkOutput {
421 Library,
422 WasmExecutable,
423 NativeExecutable,
424 NativeProcMacro,
425 NativeSharedLibrary,
430}
431
432#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
438#[non_exhaustive]
439pub struct ParseOptions {
440 pub cache_native_links: bool,
443 pub custom_target_search: bool,
449}
450
451impl ParseOptions {
452 pub fn caching_native_links(enabled: bool) -> Self {
454 Self {
455 cache_native_links: enabled,
456 ..Self::default()
457 }
458 }
459
460 pub fn with_custom_target_search(mut self, enabled: bool) -> Self {
463 self.custom_target_search = enabled;
464 self
465 }
466}
467
468#[derive(Debug, Clone, PartialEq, Eq)]
470pub struct RustcOutputs {
471 pub directory: PathBuf,
473 pub files: Vec<PathBuf>,
475 pub dep_info: PathBuf,
477}
478
479impl RustcInvocation {
480 pub fn parse(arguments: &[OsString]) -> Result<Self, BypassReason> {
489 Self::parse_with(arguments, ParseOptions::default())
490 }
491
492 pub fn expand_arguments(arguments: &[OsString]) -> Result<Vec<OsString>, BypassReason> {
497 Ok(expand_response_files(arguments)?.arguments)
498 }
499
500 pub fn parse_with(arguments: &[OsString], options: ParseOptions) -> Result<Self, BypassReason> {
503 let expanded = expand_response_files(arguments)?;
504 Parser::new(&expanded.arguments, options).parse()
505 }
506
507 pub fn links_natively(&self) -> bool {
510 matches!(
511 self.link_output,
512 LinkOutput::NativeExecutable
513 | LinkOutput::NativeProcMacro
514 | LinkOutput::NativeSharedLibrary
515 )
516 }
517
518 pub fn portable_install_name(&self, outputs: &RustcOutputs) -> Option<String> {
522 if !cfg!(target_os = "macos")
523 || self.link_output != LinkOutput::NativeProcMacro
524 || self
525 .arguments
526 .iter()
527 .any(|arg| matches!(arg, Argument::InstallName(_)))
528 {
529 return None;
530 }
531 let file = outputs
532 .files
533 .iter()
534 .find(|path| path.extension().is_some_and(|ext| ext == "dylib"))?;
535 let name = file.file_name()?.to_str()?;
536 if !safe_install_name(name) {
537 return None;
538 }
539 Some(format!("-Clink-arg=-Wl,-install_name,@rpath/{name}"))
540 }
541
542 pub fn linker_override(&self) -> Option<&Path> {
545 self.arguments.iter().find_map(|argument| {
546 let Argument::Plain(value) = argument else {
547 return None;
548 };
549 value.strip_prefix("--codegen=linker=").map(Path::new)
550 })
551 }
552
553 pub fn fuse_ld(&self) -> Option<&str> {
556 self.arguments.iter().find_map(|argument| {
557 let Argument::FuseLd(selection) = argument else {
558 return None;
559 };
560 Some(selection.as_str())
561 })
562 }
563
564 fn emits_windows_pdb(&self) -> bool {
565 if !cfg!(windows) || !self.links_natively() {
566 return false;
567 }
568 let mut enabled = false;
569 for argument in &self.arguments {
570 let Argument::Plain(value) = argument else {
571 continue;
572 };
573 if value == "-g" {
574 enabled = true;
575 } else if let Some(value) = value.strip_prefix("--codegen=debuginfo=") {
576 enabled = !matches!(value, "0" | "none");
577 }
578 }
579 enabled
580 }
581
582 pub fn native_search_paths(&self) -> impl Iterator<Item = &Path> {
586 self.arguments.iter().filter_map(|argument| match argument {
587 Argument::SearchPath { kind, path } if searches_native(kind) => Some(path.as_path()),
588 _ => None,
589 })
590 }
591
592 pub fn source(&self) -> &Path {
594 &self.source
595 }
596
597 pub fn required_inputs_in(&self, working_dir: &Path) -> Vec<PathBuf> {
603 self.required_inputs
604 .iter()
605 .map(|path| absolute_path(path, working_dir))
606 .collect()
607 }
608
609 pub fn target(&self) -> Option<&str> {
611 self.target.as_deref()
612 }
613
614 pub fn crate_name(&self) -> &str {
616 &self.crate_name
617 }
618
619 pub fn remaps_working_directory(&self) -> bool {
628 self.arguments.iter().any(|argument| {
629 matches!(argument, Argument::Plain(flag) if flag.starts_with("-Zremap-cwd-prefix="))
630 })
631 }
632
633 pub fn source_fingerprint(&self, discovered: &DiscoveredInputs) -> CacheDigest {
646 let linked = self
647 .arguments
648 .iter()
649 .filter_map(|argument| match argument {
650 Argument::Extern {
651 path: Some(path), ..
652 } => Some(path.as_path()),
653 _ => None,
654 })
655 .collect::<BTreeSet<_>>();
656 let owned = discovered
657 .inputs
658 .iter()
659 .filter(|input| {
660 !linked.contains(input.path.as_path()) && !discovered.is_native_only(&input.path)
661 })
662 .map(|input| (input.path.as_path(), &input.digest))
663 .collect::<BTreeMap<_, _>>();
664 let mut bytes = Vec::new();
665 for (path, digest) in owned {
666 bytes.extend_from_slice(path.as_os_str().as_encoded_bytes());
667 bytes.push(0);
668 bytes.extend_from_slice(digest.key().as_bytes());
669 bytes.push(0);
670 }
671 CacheDigest::blake3(&bytes)
672 }
673
674 pub fn outputs(&self, working_dir: &Path) -> Result<RustcOutputs, BypassReason> {
679 if !working_dir.is_absolute() {
680 return Err(BypassReason::RelativeWorkingDirectory(
681 working_dir.to_path_buf(),
682 ));
683 }
684 let explicit_output = self
685 .explicit_output
686 .as_deref()
687 .map(|path| absolute_path(path, working_dir));
688 let output_directory = explicit_output
689 .as_deref()
690 .and_then(Path::parent)
691 .map(Path::to_path_buf)
692 .or_else(|| {
693 self.out_dir
694 .as_deref()
695 .map(|path| absolute_path(path, working_dir))
696 })
697 .unwrap_or_else(|| normalize_components(working_dir));
698 if let Some(output) = &explicit_output
702 && self.emits.iter().any(|emit| {
703 emit.path.is_none()
704 && matches!(emit.kind.as_str(), "dep-info" | "link" | "metadata")
705 })
706 {
707 return Err(BypassReason::ImplicitEmitWithOutputFile(output.clone()));
708 }
709 let mut files = BTreeSet::new();
710 let mut dep_info = None;
711 for emit in &self.emits {
712 if emit.kind == "dep-info" {
713 let path = emit.path.as_ref().map_or_else(
714 || {
715 explicit_output.clone().map_or_else(
716 || {
717 output_directory
718 .join(format!("{}{}.d", self.crate_name, self.extra_filename))
719 },
720 |path| path.with_extension("d"),
721 )
722 },
723 |path| absolute_path(path, working_dir),
724 );
725 if path.file_name().is_none() {
726 return Err(BypassReason::InvalidOutputPath(path));
727 }
728 dep_info = Some(path);
729 continue;
730 }
731 let (prefix, extension) = match emit.kind.as_str() {
732 "link" => match self.link_output {
733 LinkOutput::Library => ("lib", "rlib"),
734 LinkOutput::WasmExecutable => ("", "wasm"),
735 LinkOutput::NativeExecutable => ("", std::env::consts::EXE_EXTENSION),
736 LinkOutput::NativeProcMacro | LinkOutput::NativeSharedLibrary => (
737 std::env::consts::DLL_PREFIX,
738 std::env::consts::DLL_SUFFIX.trim_start_matches('.'),
739 ),
740 },
741 "metadata" => ("lib", "rmeta"),
742 _ => continue,
743 };
744 let path = if let Some(path) = &emit.path {
745 absolute_path(path, working_dir)
746 } else {
747 let name = format!("{prefix}{}{}", self.crate_name, self.extra_filename);
748 output_directory.join(if extension.is_empty() {
749 name
750 } else {
751 format!("{name}.{extension}")
752 })
753 };
754 if path.file_name().is_none() {
755 return Err(BypassReason::InvalidOutputPath(path));
756 }
757 if path.parent() != Some(output_directory.as_path()) {
758 return Err(BypassReason::SplitOutputDirectories);
759 }
760 let has_library_extension = path
765 .extension()
766 .and_then(|extension| extension.to_str())
767 .is_some_and(|extension| matches!(extension, "rlib" | "rmeta"))
768 || (cfg!(windows)
769 && path
770 .file_stem()
771 .and_then(|stem| Path::new(stem).extension())
772 .and_then(|extension| extension.to_str())
773 .is_some_and(|extension| matches!(extension, "rlib" | "rmeta")));
774 if emit.kind == "link"
775 && !matches!(self.link_output, LinkOutput::Library)
776 && has_library_extension
777 {
778 return Err(BypassReason::AmbiguousOutputName(path));
779 }
780 if emit.kind == "link" && self.emits_windows_pdb() {
781 files.insert(path.with_extension("pdb"));
782 }
783 files.insert(path);
784 }
785 let dep_info = dep_info.ok_or(BypassReason::NoDepInfo)?;
786 if dep_info.parent() != Some(output_directory.as_path()) {
787 return Err(BypassReason::SplitOutputDirectories);
788 }
789 Ok(RustcOutputs {
790 directory: output_directory,
791 files: files.into_iter().collect(),
792 dep_info,
793 })
794 }
795
796 pub fn action(&self, context: ActionContext) -> Result<RustcAction, BypassReason> {
802 self.action_linked_by(context, None)
803 }
804
805 pub fn action_linked_by(
814 &self,
815 context: ActionContext,
816 linker: Option<LinkerIdentity>,
817 ) -> Result<RustcAction, BypassReason> {
818 ActionBuilder::new(self, context).linked_by(linker).build()
819 }
820
821 pub fn invocation_digest(&self, context: &ActionContext) -> Result<CacheDigest, BypassReason> {
823 let descriptor = ActionBuilder::new(self, context.clone()).invocation_descriptor()?;
824 let bytes = canonical_json(&descriptor)
825 .map_err(|error| BypassReason::Serialization(error.to_string()))?;
826 Ok(CacheDigest::blake3(&bytes))
827 }
828
829 pub fn prediction(
832 &self,
833 context: &ActionContext,
834 discovered: &DiscoveredInputs,
835 ) -> Result<RustcInputPrediction, BypassReason> {
836 let builder = ActionBuilder::new(self, context.clone());
837 builder.validate_mappings()?;
838 let mut native_directories = BTreeSet::new();
839 for argument in &self.arguments {
840 if let Argument::SearchPath { kind, path } = argument
841 && searches_native(kind)
842 {
843 native_directories.insert(builder.normalize_path(path)?);
844 }
845 }
846 let mut inputs = BTreeSet::new();
858 for input in &discovered.inputs {
859 let normalized = builder.normalize_file_path(&input.path)?;
860 if !under_any_directory(&normalized, &native_directories)
861 || !discovered.is_native_only(&input.path)
862 {
863 inputs.insert(normalized);
864 }
865 }
866 inputs.extend(
867 native_directories
868 .into_iter()
869 .map(|directory| format!("{NATIVE_DIRECTORY_PREDICTION_PREFIX}{directory}")),
870 );
871 Ok(RustcInputPrediction {
872 version: 4,
873 inputs: inputs.into_iter().collect(),
874 environment: discovered.environment.keys().cloned().collect(),
875 compiler_duration_ns: 0,
876 crate_name: String::new(),
877 })
878 }
879}
880
881pub fn is_build_script_crate_name(crate_name: &str) -> bool {
885 crate_name
886 .strip_prefix("build_script_")
887 .is_some_and(|stem| !stem.is_empty())
888}
889
890impl RustcOutputs {
891 pub fn build_script_executable(&self, crate_name: &str) -> Option<&Path> {
901 is_build_script_crate_name(crate_name)
902 .then(|| self.files.iter().find(|path| self.is_executable(path)))
903 .flatten()
904 .map(PathBuf::as_path)
905 }
906
907 pub fn is_executable(&self, path: &Path) -> bool {
915 self.files.iter().any(|output| output == path)
916 && !matches!(
917 path.extension().and_then(|extension| extension.to_str()),
918 Some("rlib" | "rmeta")
919 )
920 }
921}
922
923#[derive(Debug, Clone, PartialEq, Eq)]
924pub struct PathMapping {
926 pub root: PathBuf,
928 pub placeholder: String,
930}
931
932impl PathMapping {
933 pub fn new(root: impl Into<PathBuf>, placeholder: impl Into<String>) -> Self {
935 Self {
936 root: root.into(),
937 placeholder: placeholder.into(),
938 }
939 }
940
941 pub fn ordered(mappings: &[PathMapping]) -> Vec<PathMapping> {
944 let mut ordered = mappings.to_vec();
945 ordered.sort_by_key(|mapping| std::cmp::Reverse(mapping.root.components().count()));
946 ordered
947 }
948}
949
950fn shared_path_mappings(mappings: &[PathMapping]) -> Vec<SharedPathMapping> {
951 mappings
952 .iter()
953 .map(|mapping| SharedPathMapping::new(&mapping.root, &mapping.placeholder))
954 .collect()
955}
956
957pub fn normalize_mapped_path(
964 path: &Path,
965 working_dir: &Path,
966 mappings: &[PathMapping],
967) -> Result<String, BypassReason> {
968 normalize_shared_path(path, working_dir, &shared_path_mappings(mappings)).map_err(Into::into)
969}
970
971pub fn normalize_input_path(
973 path: &Path,
974 working_dir: &Path,
975 mappings: &[PathMapping],
976) -> Result<String, BypassReason> {
977 normalize_mapped_path(path, working_dir, mappings)
978 .or_else(|reason| key_nix_store_path(path, working_dir, reason))
979}
980
981#[derive(Debug, Clone, PartialEq, Eq)]
982pub struct CompilerIdentity {
984 pub toolchain: String,
986 pub rustc_version: String,
988 pub host: String,
990 pub driver: Option<String>,
992}
993
994#[derive(Debug, Clone, PartialEq, Eq)]
996pub struct ActionInput {
997 pub path: PathBuf,
999 pub digest: CacheDigest,
1001}
1002
1003#[derive(Debug, Clone, PartialEq, Eq)]
1005pub struct ActionContext {
1006 pub compiler: CompilerIdentity,
1008 pub working_dir: PathBuf,
1010 pub path_mappings: Vec<PathMapping>,
1012 pub environment: BTreeMap<String, Option<String>>,
1014 pub portable_environment: BTreeSet<String>,
1021 pub inputs: Vec<ActionInput>,
1023}
1024
1025#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1035#[serde(deny_unknown_fields)]
1036pub struct LinkerIdentity {
1037 pub driver: String,
1039 pub driver_version: String,
1041 pub linker_version: String,
1043 #[serde(skip_serializing_if = "BTreeMap::is_empty", default)]
1045 pub crt_objects: BTreeMap<String, CacheDigest>,
1046 #[serde(skip_serializing_if = "Option::is_none", default)]
1048 pub sdk: Option<String>,
1049 #[serde(skip_serializing_if = "Option::is_none", default)]
1051 pub deployment_target: Option<String>,
1052}
1053
1054#[derive(Debug, Clone, PartialEq, Eq)]
1056pub struct RustcAction {
1057 pub digest: CacheDigest,
1059 pub bytes: Vec<u8>,
1061}
1062
1063#[derive(Debug, Clone, PartialEq, Eq)]
1066pub struct RustcInputPrediction {
1067 pub version: u8,
1069 pub inputs: Vec<String>,
1071 pub environment: Vec<String>,
1073 pub compiler_duration_ns: u64,
1076 pub crate_name: String,
1078}
1079
1080#[derive(Serialize, Deserialize)]
1081#[serde(deny_unknown_fields)]
1082struct RustcInputPredictionWire {
1083 version: u8,
1084 inputs: Vec<String>,
1085 environment: Vec<String>,
1086 #[serde(default, skip_serializing_if = "is_zero")]
1087 compiler_duration_ns: u64,
1088 #[serde(default, skip_serializing_if = "String::is_empty")]
1089 crate_name: String,
1090}
1091
1092impl Serialize for RustcInputPrediction {
1093 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1094 where
1095 S: Serializer,
1096 {
1097 RustcInputPredictionWire {
1098 version: self.version,
1099 inputs: if self.version == 4 {
1100 compact_prediction_inputs(&self.inputs)
1101 } else {
1102 self.inputs.clone()
1103 },
1104 environment: self.environment.clone(),
1105 compiler_duration_ns: self.compiler_duration_ns,
1106 crate_name: self.crate_name.clone(),
1107 }
1108 .serialize(serializer)
1109 }
1110}
1111
1112impl<'de> Deserialize<'de> for RustcInputPrediction {
1113 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1114 where
1115 D: Deserializer<'de>,
1116 {
1117 let wire = RustcInputPredictionWire::deserialize(deserializer)?;
1118 let inputs = if wire.version == 4 {
1119 expand_prediction_inputs(&wire.inputs).map_err(serde::de::Error::custom)?
1120 } else {
1121 wire.inputs
1122 };
1123 Ok(Self {
1124 version: wire.version,
1125 inputs,
1126 environment: wire.environment,
1127 compiler_duration_ns: wire.compiler_duration_ns,
1128 crate_name: wire.crate_name,
1129 })
1130 }
1131}
1132
1133fn compact_prediction_inputs(inputs: &[String]) -> Vec<String> {
1134 let mut previous = "";
1135 inputs
1136 .iter()
1137 .map(|input| {
1138 let mut shared = previous
1139 .bytes()
1140 .zip(input.bytes())
1141 .take_while(|(left, right)| left == right)
1142 .count();
1143 while !input.is_char_boundary(shared) {
1144 shared -= 1;
1145 }
1146 let compact = format!("{shared}:{}", &input[shared..]);
1147 previous = input;
1148 compact
1149 })
1150 .collect()
1151}
1152
1153fn expand_prediction_inputs(inputs: &[String]) -> Result<Vec<String>, &'static str> {
1154 let mut expanded: Vec<String> = Vec::with_capacity(inputs.len());
1155 let mut decoded_bytes = 0_usize;
1156 for input in inputs {
1157 let (shared_text, suffix) = input
1158 .split_once(':')
1159 .ok_or("compact rustc prediction input has no prefix length")?;
1160 let shared: usize = shared_text
1161 .parse()
1162 .map_err(|_| "compact rustc prediction prefix length is invalid")?;
1163 if shared.to_string() != shared_text
1164 || shared > expanded.last().map_or(0, String::len)
1165 || expanded
1166 .last()
1167 .is_some_and(|previous| !previous.is_char_boundary(shared))
1168 {
1169 return Err("compact rustc prediction prefix is not canonical");
1170 }
1171 let mut path = expanded
1172 .last()
1173 .map_or_else(String::new, |previous| previous[..shared].to_string());
1174 path.push_str(suffix);
1175 decoded_bytes = decoded_bytes
1176 .checked_add(path.len())
1177 .ok_or("compact rustc prediction is too large")?;
1178 if decoded_bytes > MAX_DECODED_PREDICTION_BYTES {
1179 return Err("compact rustc prediction is too large");
1180 }
1181 expanded.push(path);
1182 }
1183 Ok(expanded)
1184}
1185
1186fn is_zero(value: &u64) -> bool {
1187 *value == 0
1188}
1189
1190impl RustcInputPrediction {
1191 pub fn discover(
1194 &self,
1195 working_dir: &Path,
1196 path_mappings: &[PathMapping],
1197 digests: &dyn FileDigestCache,
1198 ) -> Result<DiscoveredInputs, BypassReason> {
1199 self.discover_with_store(working_dir, path_mappings, digests, NIX_STORE_ROOT)
1200 }
1201
1202 fn discover_with_store(
1203 &self,
1204 working_dir: &Path,
1205 path_mappings: &[PathMapping],
1206 digests: &dyn FileDigestCache,
1207 store_root: &str,
1208 ) -> Result<DiscoveredInputs, BypassReason> {
1209 if !matches!(self.version, 2..=4) {
1210 return Err(BypassReason::UnsupportedPrediction);
1211 }
1212 if self.inputs.len() > MAX_PREDICTED_INPUTS || self.environment.len() > 4 * 1024 {
1213 return Err(BypassReason::UnsupportedPrediction);
1214 }
1215 let mut paths = BTreeSet::new();
1216 let mut named = BTreeSet::new();
1217 let admitted_roots = dep_info::native_input_roots(working_dir, path_mappings);
1218 let mut native_bytes = 0_u64;
1219 let mut counted = BTreeSet::new();
1220 for path in &self.inputs {
1221 if self.version >= 3
1222 && let Some(path) = path.strip_prefix(NATIVE_DIRECTORY_PREDICTION_PREFIX)
1223 {
1224 let directory = denormalize_path(path, path_mappings, store_root)?;
1225 dep_info::collect_native_directory(
1226 &directory,
1227 &admitted_roots,
1228 &mut paths,
1229 &mut native_bytes,
1230 &mut counted,
1231 )?;
1232 } else {
1233 let path = denormalize_path(path, path_mappings, store_root)?;
1234 named.insert(path.clone());
1235 paths.insert(path);
1236 }
1237 }
1238 let native_only = paths.difference(&named).cloned().collect();
1239 let environment = self
1240 .environment
1241 .iter()
1242 .map(|name| {
1243 if name.is_empty() || name.contains(['=', '\0']) {
1244 return Err(BypassReason::UnsupportedPrediction);
1245 }
1246 let value = std::env::var_os(name)
1247 .map(|value| {
1248 value
1249 .into_string()
1250 .map_err(|_| BypassReason::UnsupportedPrediction)
1251 })
1252 .transpose()?;
1253 Ok((name.clone(), value))
1254 })
1255 .collect::<Result<BTreeMap<_, _>, _>>()?;
1256 Ok(
1257 DiscoveredInputs::from_paths(working_dir, paths, environment, digests)?
1258 .with_native_only(native_only),
1259 )
1260 }
1261}
1262
1263#[derive(Serialize)]
1264struct ActionDescriptor {
1265 version: u8,
1266 kind: &'static str,
1267 adapter_version: u8,
1268 compiler: CompilerDescriptor,
1269 arguments: Vec<String>,
1270 environment: BTreeMap<String, Option<String>>,
1271 inputs: Vec<InputDescriptor>,
1272 #[serde(skip_serializing_if = "Option::is_none")]
1275 linker: Option<LinkerIdentity>,
1276}
1277
1278#[derive(Serialize)]
1279struct InvocationDescriptor {
1280 version: u8,
1281 kind: &'static str,
1282 adapter_version: u8,
1283 compiler: CompilerDescriptor,
1284 arguments: Vec<String>,
1285 required_inputs: Vec<String>,
1286}
1287
1288#[derive(Serialize)]
1289struct CompilerDescriptor {
1290 toolchain: String,
1291 rustc_version: String,
1292 host: String,
1293 #[serde(skip_serializing_if = "Option::is_none")]
1294 driver: Option<String>,
1295}
1296
1297#[derive(Debug, Serialize, PartialEq, Eq, PartialOrd, Ord)]
1298struct InputDescriptor {
1299 path: String,
1300 digest: CacheDigest,
1301}
1302
1303#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1305enum StaticLibraryNaming {
1306 Msvc,
1308 Unix,
1310}
1311
1312struct Parser<'a> {
1313 arguments: &'a [OsString],
1314 index: usize,
1315 parsed: Vec<Argument>,
1316 source: Option<PathBuf>,
1317 crate_types: Vec<String>,
1318 emits: Vec<Emit>,
1319 required_inputs: Vec<PathBuf>,
1320 native_libraries: Vec<String>,
1321 test: bool,
1322 crate_name: Option<String>,
1323 extra_filename: String,
1324 out_dir: Option<PathBuf>,
1325 explicit_output: Option<PathBuf>,
1326 target: Option<String>,
1327 sysroot_backend: Option<String>,
1328 options: ParseOptions,
1329}
1330
1331struct ExpandedArguments {
1332 arguments: Vec<OsString>,
1333}
1334
1335#[derive(Default)]
1336struct ResponseExpander {
1337 shell_argfiles: bool,
1338 next_is_unstable_option: bool,
1339 arguments: Vec<OsString>,
1340}
1341
1342impl ResponseExpander {
1343 fn push(&mut self, argument: String) {
1344 if self.next_is_unstable_option {
1345 self.shell_argfiles |= argument == "shell-argfiles";
1346 self.next_is_unstable_option = false;
1347 } else if let Some(option) = argument.strip_prefix("-Z") {
1348 if option.is_empty() {
1349 self.next_is_unstable_option = true;
1350 } else {
1351 self.shell_argfiles |= option == "shell-argfiles";
1352 }
1353 }
1354 self.arguments.push(argument.into());
1355 }
1356}
1357
1358fn expand_response_files(arguments: &[OsString]) -> Result<ExpandedArguments, BypassReason> {
1361 let mut expanded = ResponseExpander::default();
1362 for (index, argument) in arguments.iter().enumerate() {
1363 let argument = argument
1364 .to_str()
1365 .ok_or(BypassReason::NonUtf8Argument { index })?;
1366 let Some(argfile) = argument.strip_prefix('@') else {
1367 expanded.push(argument.to_string());
1368 continue;
1369 };
1370 let (path, shell) = match argfile.split_once(':') {
1371 Some(("shell", path)) if expanded.shell_argfiles => (path, true),
1372 _ => (argfile, false),
1373 };
1374 let contents = std::fs::read_to_string(path).map_err(|error| {
1375 BypassReason::ResponseFile(format!("{}: {error}", Path::new(path).display()))
1376 })?;
1377 if shell {
1378 let arguments = shlex::split(&contents).ok_or_else(|| {
1379 BypassReason::ResponseFile(format!(
1380 "invalid shell-style arguments in {}",
1381 Path::new(path).display()
1382 ))
1383 })?;
1384 for argument in arguments {
1385 expanded.push(argument);
1386 }
1387 } else {
1388 for argument in contents.lines() {
1389 expanded.push(argument.to_string());
1390 }
1391 }
1392 }
1393 Ok(ExpandedArguments {
1394 arguments: expanded.arguments,
1395 })
1396}
1397
1398impl<'a> Parser<'a> {
1399 fn new(arguments: &'a [OsString], options: ParseOptions) -> Self {
1400 Self {
1401 arguments,
1402 options,
1403 index: 0,
1404 parsed: Vec::new(),
1405 source: None,
1406 crate_types: Vec::new(),
1407 emits: Vec::new(),
1408 required_inputs: Vec::new(),
1409 native_libraries: Vec::new(),
1410 test: false,
1411 crate_name: None,
1412 extra_filename: String::new(),
1413 out_dir: None,
1414 explicit_output: None,
1415 target: None,
1416 sysroot_backend: None,
1417 }
1418 }
1419
1420 fn parse(mut self) -> Result<RustcInvocation, BypassReason> {
1421 while self.index < self.arguments.len() {
1422 let value = self.current()?.to_string();
1423 self.index += 1;
1424 if let Some(long) = value.strip_prefix("--") {
1425 self.parse_long(long)?;
1426 } else if value.starts_with('-') && value != "-" {
1427 self.parse_short(&value)?;
1428 } else {
1429 self.parse_input(&value)?;
1430 }
1431 }
1432
1433 if let Some(backend) = self.sysroot_backend.take()
1435 && self.parsed.iter().any(
1436 |argument| matches!(argument, Argument::Path { flag, .. } if flag == "--sysroot"),
1437 )
1438 {
1439 return Err(BypassReason::UnknownFlag(backend));
1440 }
1441 let source = self.source.clone().ok_or(BypassReason::MissingInput)?;
1442 let link_output = self.classify()?;
1443 self.require_native_libraries(link_output)?;
1444 let crate_name = self.crate_name.clone().map_or_else(
1445 || {
1446 source
1447 .file_stem()
1448 .and_then(|name| name.to_str())
1449 .map(|name| name.replace('-', "_"))
1450 .ok_or_else(|| BypassReason::NonUtf8Path(source.clone()))
1451 },
1452 Ok,
1453 )?;
1454 self.required_inputs.push(source.clone());
1455 self.drop_unobservable_diagnostic_width();
1456 Ok(RustcInvocation {
1457 arguments: self.parsed,
1458 source,
1459 required_inputs: self.required_inputs,
1460 crate_name,
1461 extra_filename: self.extra_filename,
1462 out_dir: self.out_dir,
1463 explicit_output: self.explicit_output,
1464 emits: self.emits,
1465 target: self.target,
1466 link_output,
1467 })
1468 }
1469
1470 fn current(&self) -> Result<&str, BypassReason> {
1471 self.arguments[self.index]
1472 .to_str()
1473 .ok_or(BypassReason::NonUtf8Argument { index: self.index })
1474 }
1475
1476 fn take_value(&mut self, flag: &str, inline: Option<&str>) -> Result<String, BypassReason> {
1477 if let Some(value) = inline {
1478 if value.is_empty() {
1479 return Err(BypassReason::MissingValue(flag.into()));
1480 }
1481 return Ok(value.into());
1482 }
1483 if self.index >= self.arguments.len() {
1484 return Err(BypassReason::MissingValue(flag.into()));
1485 }
1486 let value = self.current()?.to_string();
1487 self.index += 1;
1488 Ok(value)
1489 }
1490
1491 fn drop_unobservable_diagnostic_width(&mut self) {
1502 fn widths(argument: &Argument) -> Option<&str> {
1503 match argument {
1504 Argument::Plain(value) => value.strip_prefix("--diagnostic-width="),
1505 _ => None,
1506 }
1507 }
1508 let mut found = self.parsed.iter().filter_map(widths);
1509 let valid = matches!(
1510 (found.next(), found.next()),
1511 (Some(width), None) if width.parse::<usize>().is_ok()
1512 );
1513 if valid {
1514 self.parsed.retain(|argument| widths(argument).is_none());
1515 }
1516 }
1517
1518 fn parse_long(&mut self, value: &str) -> Result<(), BypassReason> {
1519 let (flag, inline) = value
1520 .split_once('=')
1521 .map_or((value, None), |(flag, value)| (flag, Some(value)));
1522 let rendered_flag = format!("--{flag}");
1523 match flag {
1524 "help" | "version" | "explain" | "print" => Err(BypassReason::CompilerQuery),
1525 "test" => {
1526 self.test = true;
1527 self.parsed.push(Argument::Plain(rendered_flag));
1528 Ok(())
1529 }
1530 "verbose" => {
1531 self.parsed.push(Argument::Plain(rendered_flag));
1532 Ok(())
1533 }
1534 "crate-name" => {
1535 let value = self.take_value(&rendered_flag, inline)?;
1536 self.crate_name = Some(value.clone());
1537 self.parsed
1538 .push(Argument::Plain(format!("{rendered_flag}={value}")));
1539 Ok(())
1540 }
1541 "cfg" | "check-cfg" | "edition" | "error-format" | "json" | "color"
1542 | "diagnostic-width" | "remap-path-scope" | "allow" | "warn" | "force-warn"
1543 | "deny" | "forbid" | "cap-lints" => {
1544 let value = self.take_value(&rendered_flag, inline)?;
1545 self.parsed
1546 .push(Argument::Plain(format!("{rendered_flag}={value}")));
1547 Ok(())
1548 }
1549 "target" => {
1550 let value = self.take_value(&rendered_flag, inline)?;
1551 let effective = self.target.is_none();
1555 if effective {
1556 self.target = Some(value.clone());
1557 }
1558 if value.ends_with(".json") || value.contains(['/', '\\']) {
1559 let path = PathBuf::from(value);
1560 if effective {
1561 self.required_inputs.push(path.clone());
1562 }
1563 self.parsed.push(Argument::Path {
1564 flag: rendered_flag,
1565 path,
1566 });
1567 } else {
1568 self.parsed
1569 .push(Argument::Plain(format!("{rendered_flag}={value}")));
1570 }
1571 Ok(())
1572 }
1573 "crate-type" => {
1574 let value = self.take_value(&rendered_flag, inline)?;
1575 self.crate_types
1576 .extend(value.split(',').map(ToOwned::to_owned));
1577 self.parsed
1578 .push(Argument::Plain(format!("{rendered_flag}={value}")));
1579 Ok(())
1580 }
1581 "emit" => {
1582 let value = self.take_value(&rendered_flag, inline)?;
1583 let emits = parse_emits(&value);
1584 self.emits.extend(emits.clone());
1585 self.parsed.push(Argument::Emit(emits));
1586 Ok(())
1587 }
1588 "out-dir" => {
1589 let path = PathBuf::from(self.take_value(&rendered_flag, inline)?);
1590 self.out_dir = Some(path.clone());
1591 self.parsed.push(Argument::Path {
1592 flag: rendered_flag,
1593 path,
1594 });
1595 Ok(())
1596 }
1597 "sysroot" => {
1598 let path = self.take_value(&rendered_flag, inline)?;
1599 self.parsed.push(Argument::Path {
1600 flag: rendered_flag,
1601 path: path.into(),
1602 });
1603 Ok(())
1604 }
1605 "extern" => {
1606 let value = self.take_value(&rendered_flag, inline)?;
1607 let (name, path) = value
1608 .split_once('=')
1609 .map_or((value.as_str(), None), |(name, path)| {
1610 (name, Some(PathBuf::from(path)))
1611 });
1612 if let Some(path) = &path {
1613 self.required_inputs.push(path.clone());
1614 }
1615 self.parsed.push(Argument::Extern {
1616 name: name.into(),
1617 path,
1618 });
1619 Ok(())
1620 }
1621 "remap-path-prefix" => {
1622 let value = self.take_value(&rendered_flag, inline)?;
1623 let Some((from, to)) = value.split_once('=') else {
1624 return Err(BypassReason::MissingValue(rendered_flag));
1625 };
1626 self.parsed.push(Argument::RemapPath {
1627 from: from.into(),
1628 to: to.into(),
1629 });
1630 Ok(())
1631 }
1632 "codegen" => {
1633 let value = self.take_value(&rendered_flag, inline)?;
1634 self.parse_codegen(&value)
1635 }
1636 "jobs-frontend" => {
1637 let value = self.take_value(&rendered_flag, inline)?;
1638 self.parsed
1639 .push(Argument::Plain(format!("{rendered_flag}={value}")));
1640 Ok(())
1641 }
1642 _ => Err(BypassReason::UnknownFlag(rendered_flag)),
1643 }
1644 }
1645
1646 fn parse_short(&mut self, value: &str) -> Result<(), BypassReason> {
1647 if let Some(attached) = value.strip_prefix("-Z") {
1648 let option = self.take_value("-Z", (!attached.is_empty()).then_some(attached))?;
1649 match option.as_str() {
1650 "embed-metadata=no"
1654 | "embed-metadata=yes"
1655 | "force-unstable-if-unmarked"
1656 | "shell-argfiles"
1657 | "unstable-options" => {
1658 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1659 return Ok(());
1660 }
1661 "use-sync-unwind=yes" | "use-sync-unwind=no" => {
1664 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1665 return Ok(());
1666 }
1667 "threads" | "threads=" => {
1668 return Err(BypassReason::MissingValue("-Zthreads".into()));
1669 }
1670 "remap-cwd-prefix" | "remap-cwd-prefix=" => {
1671 return Err(BypassReason::MissingValue("-Zremap-cwd-prefix".into()));
1672 }
1673 _ => {}
1674 }
1675 if option.starts_with("remap-cwd-prefix=") {
1681 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1682 return Ok(());
1683 }
1684 if option == "share-generics" {
1685 return Err(BypassReason::MissingValue("-Zshare-generics".into()));
1686 }
1687 if let Some(value) = option.strip_prefix("share-generics=") {
1688 if matches!(
1689 value,
1690 "y" | "yes" | "on" | "true" | "n" | "no" | "off" | "false"
1691 ) {
1692 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1693 return Ok(());
1694 }
1695 return Err(if value.is_empty() {
1696 BypassReason::MissingValue("-Zshare-generics".into())
1697 } else {
1698 BypassReason::UnknownFlag(format!("-Z{option}"))
1699 });
1700 }
1701 if option == "always-encode-mir" {
1705 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1706 return Ok(());
1707 }
1708 if let Some(level) = option.strip_prefix("mir-opt-level=") {
1709 if matches!(level, "0" | "1" | "2" | "3" | "4") {
1710 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1711 return Ok(());
1712 }
1713 return Err(if level.is_empty() {
1714 BypassReason::MissingValue("-Zmir-opt-level".into())
1715 } else {
1716 BypassReason::UnknownFlag(format!("-Z{option}"))
1717 });
1718 }
1719 if option == "mir-opt-level" {
1720 return Err(BypassReason::MissingValue("-Zmir-opt-level".into()));
1721 }
1722 if option == "inline-mir" {
1723 return Err(BypassReason::MissingValue("-Zinline-mir".into()));
1724 }
1725 if let Some(value) = option.strip_prefix("inline-mir=") {
1726 if matches!(
1727 value,
1728 "y" | "yes" | "on" | "true" | "n" | "no" | "off" | "false"
1729 ) {
1730 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1731 return Ok(());
1732 }
1733 return Err(if value.is_empty() {
1734 BypassReason::MissingValue("-Zinline-mir".into())
1735 } else {
1736 BypassReason::UnknownFlag(format!("-Z{option}"))
1737 });
1738 }
1739 if option.starts_with("threads=") {
1740 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1741 return Ok(());
1742 }
1743 if let Some(backend) = option.strip_prefix("codegen-backend=")
1745 && !backend.is_empty()
1746 && !backend.contains(['.', '/', '\\'])
1747 {
1748 self.sysroot_backend = Some(format!("-Z{option}"));
1749 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1750 return Ok(());
1751 }
1752 return Err(BypassReason::UnknownFlag(format!("-Z{option}")));
1753 }
1754 match value {
1755 "-h" | "-V" | "-vV" => return Err(BypassReason::CompilerQuery),
1758 "-g" | "-O" | "-v" => {
1759 self.parsed.push(Argument::Plain(value.into()));
1760 return Ok(());
1761 }
1762 _ => {}
1763 }
1764 for (short, long) in [
1765 ("-A", "--allow"),
1766 ("-W", "--warn"),
1767 ("-D", "--deny"),
1768 ("-F", "--forbid"),
1769 ] {
1770 if let Some(attached) = value.strip_prefix(short) {
1771 let lint = self.take_value(short, (!attached.is_empty()).then_some(attached))?;
1772 self.parsed.push(Argument::Plain(format!("{long}={lint}")));
1773 return Ok(());
1774 }
1775 }
1776 if let Some(attached) = value.strip_prefix("-C") {
1777 let option = self.take_value("-C", (!attached.is_empty()).then_some(attached))?;
1778 return self.parse_codegen(&option);
1779 }
1780 if let Some(attached) = value.strip_prefix("-L") {
1781 let search = self.take_value("-L", (!attached.is_empty()).then_some(attached))?;
1782 let (kind, path) = search
1783 .split_once('=')
1784 .map_or(("all", search.as_str()), |(kind, path)| (kind, path));
1785 if kind != "dependency" && !searches_native(kind) {
1786 return Err(BypassReason::UnsupportedSearchPath(kind.into()));
1787 }
1788 self.parsed.push(Argument::SearchPath {
1789 kind: kind.into(),
1790 path: path.into(),
1791 });
1792 return Ok(());
1793 }
1794 if let Some(attached) = value.strip_prefix("-l") {
1795 let library = self.take_value("-l", (!attached.is_empty()).then_some(attached))?;
1796 self.parsed.push(Argument::Plain(format!("-l{library}")));
1797 self.native_libraries.push(library);
1798 return Ok(());
1799 }
1800 if let Some(attached) = value.strip_prefix("-o") {
1801 let path = self.take_value("-o", (!attached.is_empty()).then_some(attached))?;
1802 self.explicit_output = Some(path.clone().into());
1803 self.parsed.push(Argument::Path {
1804 flag: "-o".into(),
1805 path: path.into(),
1806 });
1807 return Ok(());
1808 }
1809 Err(BypassReason::UnknownFlag(value.into()))
1810 }
1811
1812 fn parse_codegen(&mut self, value: &str) -> Result<(), BypassReason> {
1813 let name = value.split_once('=').map_or(value, |(name, _)| name);
1814 if name == "incremental" {
1815 return Err(BypassReason::Incremental);
1816 }
1817 if name == "profile-use" {
1818 let Some((_, profile)) = value.split_once('=') else {
1819 return Err(BypassReason::MissingValue("-Cprofile-use".into()));
1820 };
1821 if profile.is_empty() {
1822 return Err(BypassReason::MissingValue("-Cprofile-use".into()));
1823 }
1824 let path = PathBuf::from(profile);
1825 self.required_inputs.push(path.clone());
1826 self.parsed.push(Argument::Path {
1827 flag: "-Cprofile-use".into(),
1828 path,
1829 });
1830 return Ok(());
1831 }
1832 if SUPPORTED_CODEGEN_OPTIONS.binary_search(&name).is_err()
1833 && !matches!(name, "linker" | "linker-flavor")
1834 {
1835 return Err(BypassReason::UnknownCodegenOption(name.into()));
1836 }
1837 if name == "linker-plugin-lto"
1843 && let Some((_, selection)) = value.split_once('=')
1844 && !matches!(
1845 selection,
1846 "" | "y" | "yes" | "on" | "true" | "n" | "no" | "off" | "false"
1847 )
1848 {
1849 return Err(BypassReason::UnknownCodegenOption(format!(
1850 "linker-plugin-lto={selection}"
1851 )));
1852 }
1853 if name == "link-arg"
1860 && let Some((_, option)) = value.split_once('=')
1861 && let Some(selection) = option.strip_prefix("-fuse-ld=")
1862 && !selection.is_empty()
1863 && !selection.contains(',')
1864 && !self.parsed.iter().any(
1865 |argument| matches!(argument, Argument::FuseLd(existing) if existing != selection),
1866 )
1867 {
1868 if !self.parsed.iter().any(
1869 |argument| matches!(argument, Argument::FuseLd(existing) if existing == selection),
1870 ) {
1871 self.parsed.push(Argument::FuseLd(selection.to_owned()));
1872 }
1873 return Ok(());
1874 }
1875 if name == "link-arg"
1878 && let Some(option) = value.strip_prefix("link-arg=-Wl,-install_name,@rpath/")
1879 && safe_install_name(option)
1880 {
1881 self.parsed.push(Argument::InstallName(option.to_owned()));
1882 return Ok(());
1883 }
1884 if name == "link-arg"
1888 && let Some(directory) = value.strip_prefix("link-arg=-Wl,-rpath,")
1889 && directory.starts_with('/')
1890 && !directory.contains(',')
1891 {
1892 self.parsed.push(Argument::Rpath(directory.to_owned()));
1893 return Ok(());
1894 }
1895 if matches!(name, "link-arg" | "link-args")
1900 && let Some((_, option)) = value.split_once('=')
1901 && let Some(prefix) = option.strip_prefix("-Wl,-oso_prefix,")
1902 && !prefix.trim_end_matches('/').is_empty()
1903 && !prefix.contains(',')
1904 {
1905 let trailing_slash = prefix.ends_with('/');
1906 self.parsed.push(Argument::OsoPrefix {
1907 path: PathBuf::from(prefix.trim_end_matches('/')),
1908 trailing_slash,
1909 });
1910 return Ok(());
1911 }
1912 self.parsed
1913 .push(Argument::Plain(format!("--codegen={value}")));
1914 if name == "extra-filename" {
1915 self.extra_filename = value
1916 .split_once('=')
1917 .map_or(String::new(), |(_, value)| value.to_string());
1918 }
1919 Ok(())
1920 }
1921
1922 fn require_native_libraries(&mut self, link_output: LinkOutput) -> Result<(), BypassReason> {
1937 for library in std::mem::take(&mut self.native_libraries) {
1938 if link_output != LinkOutput::Library {
1939 return Err(BypassReason::NativeLibrary(library));
1940 }
1941 let Some((kind, name)) = library.split_once('=') else {
1949 continue;
1950 };
1951 let (kind, modifiers) = kind.split_once(':').unwrap_or((kind, ""));
1952 match kind {
1953 "static" => {}
1954 "dylib" | "framework" | "link-arg" => continue,
1955 _ => return Err(BypassReason::UnknownFlag(format!("-l{library}"))),
1956 }
1957 let name = name.split_once(':').map_or(name, |(_, renamed)| renamed);
1960 let (mut verbatim, mut bundle) = (false, true);
1961 for modifier in modifiers.split(',') {
1962 match modifier {
1963 "+verbatim" => verbatim = true,
1964 "-verbatim" => verbatim = false,
1965 "+bundle" => bundle = true,
1966 "-bundle" => bundle = false,
1967 _ => {}
1968 }
1969 }
1970 if !bundle {
1971 continue;
1972 }
1973 let archive = self
1974 .find_native_static_library(name, verbatim)
1975 .map_err(|()| BypassReason::CustomTargetNativeLibrary(library.clone()))?
1976 .ok_or_else(|| BypassReason::MissingNativeLibrary(library.clone()))?;
1977 self.required_inputs.push(archive);
1978 }
1979 Ok(())
1980 }
1981
1982 fn find_native_static_library(
1994 &self,
1995 name: &str,
1996 verbatim: bool,
1997 ) -> Result<Option<PathBuf>, ()> {
1998 let file_names = if verbatim {
1999 vec![name.to_owned()]
2000 } else {
2001 match self.static_library_naming() {
2002 Some(StaticLibraryNaming::Msvc) => {
2003 vec![format!("{name}.lib"), format!("lib{name}.a")]
2004 }
2005 Some(StaticLibraryNaming::Unix) => vec![format!("lib{name}.a")],
2006 None => return Err(()),
2007 }
2008 };
2009 Ok(self
2010 .parsed
2011 .iter()
2012 .filter_map(|argument| match argument {
2013 Argument::SearchPath { kind, path } if searches_native(kind) => Some(path),
2014 _ => None,
2015 })
2016 .flat_map(|directory| {
2017 file_names
2018 .iter()
2019 .map(move |file_name| directory.join(file_name))
2020 })
2021 .find(|candidate| candidate.is_file()))
2022 }
2023
2024 fn static_library_naming(&self) -> Option<StaticLibraryNaming> {
2032 let Some(target) = self.target.as_deref() else {
2033 return Some(if cfg!(any(target_env = "msvc", target_os = "uefi")) {
2034 StaticLibraryNaming::Msvc
2035 } else {
2036 StaticLibraryNaming::Unix
2037 });
2038 };
2039 if target.ends_with(".json")
2040 || target.contains(['/', '\\'])
2041 || self.options.custom_target_search
2042 {
2043 return None;
2044 }
2045 Some(if target.contains("msvc") || target.ends_with("-uefi") {
2048 StaticLibraryNaming::Msvc
2049 } else {
2050 StaticLibraryNaming::Unix
2051 })
2052 }
2053
2054 fn parse_input(&mut self, value: &str) -> Result<(), BypassReason> {
2055 if value == "-" {
2056 return Err(BypassReason::StandardInput);
2057 }
2058 if self.source.replace(value.into()).is_some() {
2059 return Err(BypassReason::MultipleInputs);
2060 }
2061 Ok(())
2062 }
2063
2064 fn classify(&self) -> Result<LinkOutput, BypassReason> {
2065 let never_links = !self.emits.iter().any(|emit| emit.kind == "link");
2074 let builds_a_library = !self.test
2075 && !self.crate_types.is_empty()
2076 && self
2077 .crate_types
2078 .iter()
2079 .all(|crate_type| matches!(crate_type.as_str(), "lib" | "rlib"));
2080 let link_output = if never_links || builds_a_library {
2081 LinkOutput::Library
2082 } else if self
2083 .target
2084 .as_deref()
2085 .is_some_and(compiler_bundled_wasm_target)
2086 && ((self.test && self.crate_types.is_empty())
2087 || matches!(self.crate_types.as_slice(), [kind] if kind == "bin" || kind == "cdylib"))
2088 {
2089 if self.parsed.iter().any(|argument| match argument {
2090 Argument::Plain(value) if value == "--codegen=link-self-contained" => false,
2091 Argument::Plain(value) if value.starts_with("--codegen=link-self-contained=") => {
2092 !matches!(
2093 value.rsplit_once('=').map(|(_, value)| value),
2094 Some("y" | "yes" | "on" | "true")
2095 )
2096 }
2097 _ => false,
2098 }) {
2099 return Err(BypassReason::UnknownCodegenOption(
2100 "link-self-contained".into(),
2101 ));
2102 }
2103 if self.target.as_deref().is_some_and(|target| target.contains("wasi"))
2104 && self.parsed.iter().any(|argument| {
2105 matches!(argument, Argument::Plain(value) if value.strip_prefix("--codegen=target-feature=").is_some_and(|features| features.split(',').any(|feature| feature == "-crt-static")))
2106 })
2107 {
2108 return Err(BypassReason::UnknownCodegenOption(
2109 "target-feature=-crt-static".into(),
2110 ));
2111 }
2112 LinkOutput::WasmExecutable
2116 } else if self.options.cache_native_links && self.links_a_native_artifact() {
2117 self.check_native_link_is_portable()?;
2118 if matches!(self.crate_types.as_slice(), [kind] if kind == "proc-macro") {
2119 LinkOutput::NativeProcMacro
2120 } else if matches!(self.crate_types.as_slice(), [kind] if kind == "cdylib") {
2121 LinkOutput::NativeSharedLibrary
2122 } else {
2123 LinkOutput::NativeExecutable
2124 }
2125 } else if self.test {
2126 return Err(BypassReason::UnsupportedCrateType("test".into()));
2127 } else {
2128 return Err(BypassReason::UnsupportedCrateType(
2129 self.crate_types
2130 .iter()
2131 .find(|crate_type| !matches!(crate_type.as_str(), "lib" | "rlib"))
2132 .cloned()
2133 .unwrap_or_else(|| "bin".into()),
2134 ));
2135 };
2136 if link_output != LinkOutput::Library
2145 && let Some(option) = self.first_link_argument(link_output)
2146 {
2147 return Err(BypassReason::UnmodeledLinkArgument(option.to_owned()));
2148 }
2149 if self
2150 .parsed
2151 .iter()
2152 .any(|arg| matches!(arg, Argument::InstallName(_)))
2153 && !(cfg!(target_os = "macos") && link_output == LinkOutput::NativeProcMacro)
2154 {
2155 return Err(BypassReason::UnmodeledLinkArgument(
2156 "link-arg=-Wl,-install_name".into(),
2157 ));
2158 }
2159 if self
2163 .parsed
2164 .iter()
2165 .any(|argument| matches!(argument, Argument::Rpath(_)))
2166 && !(link_output == LinkOutput::Library
2167 || cfg!(target_os = "macos")
2168 && matches!(
2169 link_output,
2170 LinkOutput::NativeExecutable
2171 | LinkOutput::NativeProcMacro
2172 | LinkOutput::NativeSharedLibrary
2173 ))
2174 {
2175 return Err(BypassReason::UnmodeledLinkArgument(
2176 "link-arg=-Wl,-rpath".into(),
2177 ));
2178 }
2179 if let Some(selection) = self.parsed.iter().find_map(|argument| {
2186 let Argument::FuseLd(selection) = argument else {
2187 return None;
2188 };
2189 Some(selection.as_str())
2190 }) && !matches!(
2191 link_output,
2192 LinkOutput::Library
2193 | LinkOutput::NativeExecutable
2194 | LinkOutput::NativeProcMacro
2195 | LinkOutput::NativeSharedLibrary
2196 ) {
2197 return Err(BypassReason::UnmodeledLinkArgument(format!(
2198 "link-arg=-fuse-ld={selection}"
2199 )));
2200 }
2201 if self.parsed.iter().any(|argument| {
2202 matches!(argument, Argument::Plain(value) if value.starts_with("--codegen=linker="))
2203 }) && !matches!(
2204 link_output,
2205 LinkOutput::Library
2206 | LinkOutput::NativeExecutable
2207 | LinkOutput::NativeProcMacro
2208 | LinkOutput::NativeSharedLibrary
2209 ) {
2210 return Err(BypassReason::UnknownCodegenOption("linker".into()));
2211 }
2212 if link_output != LinkOutput::Library
2217 && self.parsed.iter().any(|argument| {
2218 matches!(argument, Argument::Plain(value) if value.starts_with("--codegen=linker-flavor="))
2219 })
2220 {
2221 return Err(BypassReason::UnknownCodegenOption("linker-flavor".into()));
2222 }
2223 if !matches!(
2227 link_output,
2228 LinkOutput::Library
2229 | LinkOutput::NativeExecutable
2230 | LinkOutput::NativeProcMacro
2231 | LinkOutput::NativeSharedLibrary
2232 ) && self
2233 .parsed
2234 .iter()
2235 .any(|argument| matches!(argument, Argument::OsoPrefix { .. }))
2236 {
2237 return Err(BypassReason::UnmodeledLinkArgument(
2238 "link-arg=-Wl,-oso_prefix".into(),
2239 ));
2240 }
2241 if let Some(name) = self.parsed.iter().find_map(|argument| match argument {
2242 Argument::Extern { name, path: None } if name != "proc_macro" => Some(name),
2243 _ => None,
2244 }) {
2245 return Err(BypassReason::UnresolvedExtern(name.clone()));
2246 }
2247 if let Some(emit) = self
2248 .emits
2249 .iter()
2250 .find(|emit| !matches!(emit.kind.as_str(), "dep-info" | "link" | "metadata"))
2251 {
2252 return Err(BypassReason::UnsupportedEmit(emit.kind.clone()));
2253 }
2254 if !self
2255 .emits
2256 .iter()
2257 .any(|emit| matches!(emit.kind.as_str(), "link" | "metadata"))
2258 {
2259 return Err(BypassReason::NoCacheableOutput);
2260 }
2261 Ok(link_output)
2262 }
2263}
2264
2265impl Parser<'_> {
2266 fn first_link_argument(&self, link_output: LinkOutput) -> Option<&str> {
2269 self.parsed.iter().find_map(|argument| {
2270 let Argument::Plain(value) = argument else {
2271 return None;
2272 };
2273 let option = value.strip_prefix("--codegen=")?;
2274 let (name, value) = option.split_once('=').unwrap_or((option, ""));
2275 (matches!(name, "link-arg" | "link-args")
2276 && !(name == "link-arg" && elf_keyword_is_modeled(link_output, value))
2277 && !msvc_options_are_modeled(link_output, name, value))
2278 .then_some(option)
2279 })
2280 }
2281
2282 fn oso_prefix_covers_outputs(&self) -> bool {
2291 let Some(directory) = self
2292 .out_dir
2293 .as_deref()
2294 .or_else(|| self.explicit_output.as_deref().and_then(Path::parent))
2295 else {
2296 return false;
2297 };
2298 if !directory.is_absolute() {
2299 return false;
2300 }
2301 let directory = normalize_components(directory);
2302 self.parsed.iter().any(|argument| {
2303 let Argument::OsoPrefix { path, .. } = argument else {
2304 return false;
2305 };
2306 path.is_absolute()
2307 && (directory.starts_with(normalize_components(path))
2308 || std::fs::canonicalize(&directory)
2309 .ok()
2310 .zip(std::fs::canonicalize(path).ok())
2311 .is_some_and(|(directory, prefix)| directory.starts_with(prefix)))
2312 })
2313 }
2314
2315 fn links_a_native_artifact(&self) -> bool {
2322 self.target.is_none()
2323 && self.emits.iter().any(|emit| emit.kind == "link")
2328 && ((self.test && self.crate_types.is_empty())
2329 || matches!(self.crate_types.as_slice(), [kind] if matches!(kind.as_str(), "bin" | "proc-macro"))
2330 || (cfg!(target_os = "linux")
2331 && matches!(self.crate_types.as_slice(), [kind] if kind == "cdylib")))
2332 }
2333
2334 fn check_native_link_is_portable(&self) -> Result<(), BypassReason> {
2341 for argument in &self.parsed {
2342 let Argument::Plain(value) = argument else {
2343 continue;
2344 };
2345 let (name, value) = if value == "-g" {
2348 ("debuginfo", Some("2"))
2349 } else if let Some(option) = value.strip_prefix("--codegen=") {
2350 match option.split_once('=') {
2351 Some((name, value)) => (name, Some(value)),
2352 None => (option, None),
2356 }
2357 } else {
2358 continue;
2359 };
2360 let unportable = match name {
2361 "split-debuginfo" => match value {
2367 Some("off") => false,
2368 Some("unpacked") if cfg!(target_os = "macos") => {
2369 !self.oso_prefix_covers_outputs()
2370 }
2371 _ => true,
2372 },
2373 "debuginfo" if cfg!(target_os = "macos") => {
2382 !matches!(value, Some("0" | "none")) && !self.oso_prefix_covers_outputs()
2383 }
2384 "rpath" => is_enabled(value),
2392 "prefer-dynamic" => {
2393 is_enabled(value)
2394 && !matches!(self.crate_types.as_slice(), [kind] if kind == "proc-macro")
2395 }
2396 "link-self-contained" => true,
2399 _ => false,
2400 };
2401 if unportable {
2402 return Err(BypassReason::UnportableNativeLink(match value {
2403 Some(value) => format!("{name}={value}"),
2404 None => name.to_owned(),
2405 }));
2406 }
2407 }
2408 Ok(())
2409 }
2410}
2411
2412fn safe_install_name(name: &str) -> bool {
2413 !name.is_empty()
2414 && name
2415 .bytes()
2416 .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))
2417}
2418
2419fn is_enabled(value: Option<&str>) -> bool {
2422 matches!(value, None | Some("y" | "yes" | "on" | "true"))
2423}
2424
2425fn elf_keyword_is_modeled(link_output: LinkOutput, value: &str) -> bool {
2435 cfg!(target_os = "linux")
2436 && matches!(
2437 link_output,
2438 LinkOutput::NativeExecutable
2439 | LinkOutput::NativeProcMacro
2440 | LinkOutput::NativeSharedLibrary
2441 )
2442 && value.strip_prefix("-Wl,-z,").is_some_and(|keyword| {
2443 matches!(
2444 keyword,
2445 "defs"
2446 | "lazy"
2447 | "nodelete"
2448 | "nodlopen"
2449 | "noexecstack"
2450 | "norelro"
2451 | "now"
2452 | "origin"
2453 | "relro"
2454 )
2455 })
2456}
2457
2458fn msvc_options_are_modeled(link_output: LinkOutput, name: &str, value: &str) -> bool {
2474 cfg!(target_env = "msvc")
2475 && matches!(
2476 link_output,
2477 LinkOutput::NativeExecutable
2478 | LinkOutput::NativeProcMacro
2479 | LinkOutput::NativeSharedLibrary
2480 )
2481 && match name {
2482 "link-arg" => msvc_option_reads_no_file(value),
2483 "link-args" => {
2486 let mut options = value.split_ascii_whitespace().peekable();
2487 options.peek().is_some() && options.all(msvc_option_reads_no_file)
2488 }
2489 _ => false,
2490 }
2491}
2492
2493fn msvc_option_reads_no_file(option: &str) -> bool {
2497 let Some(option) = option.strip_prefix(['/', '-']) else {
2498 return false;
2499 };
2500 if option.eq_ignore_ascii_case("brepro") {
2501 return true;
2502 }
2503 let Some((name, sizes)) = option.split_once(':') else {
2504 return false;
2505 };
2506 let is_size = |size: &str| match size.strip_prefix("0x").or_else(|| size.strip_prefix("0X")) {
2509 Some(hex) => !hex.is_empty() && hex.bytes().all(|byte| byte.is_ascii_hexdigit()),
2510 None => !size.is_empty() && size.bytes().all(|byte| byte.is_ascii_digit()),
2511 };
2512 name.eq_ignore_ascii_case("stack")
2513 && sizes.split(',').count() <= 2
2514 && sizes.split(',').all(is_size)
2515}
2516
2517fn compiler_bundled_wasm_target(target: &str) -> bool {
2518 COMPILER_BUNDLED_WASM_TARGETS.binary_search(&target).is_ok()
2519}
2520
2521fn parse_emits(value: &str) -> Vec<Emit> {
2522 value
2523 .split(',')
2524 .map(|emit| {
2525 let (kind, path) = emit
2526 .split_once('=')
2527 .map_or((emit, None), |(kind, path)| (kind, Some(path.into())));
2528 Emit {
2529 kind: kind.into(),
2530 path,
2531 }
2532 })
2533 .collect()
2534}
2535
2536struct ActionBuilder<'a> {
2537 invocation: &'a RustcInvocation,
2538 store_root: &'a str,
2539 context: ActionContext,
2540 mappings: Vec<SharedPathMapping>,
2541 aliases: PathAliases,
2545 linker: Option<LinkerIdentity>,
2546}
2547
2548impl<'a> ActionBuilder<'a> {
2549 fn new(invocation: &'a RustcInvocation, mut context: ActionContext) -> Self {
2550 context.path_mappings = PathMapping::ordered(&context.path_mappings);
2551 let mappings = resolve_path_mappings(&shared_path_mappings(&context.path_mappings));
2552 Self {
2553 linker: None,
2554 invocation,
2555 store_root: NIX_STORE_ROOT,
2556 mappings,
2557 aliases: PathAliases::default(),
2558 context,
2559 }
2560 }
2561
2562 fn linked_by(mut self, linker: Option<LinkerIdentity>) -> Self {
2563 self.linker = linker;
2564 self
2565 }
2566
2567 fn build(self) -> Result<RustcAction, BypassReason> {
2568 self.validate_mappings()?;
2569 let invocation = self.invocation_descriptor()?;
2570 let environment = self.environment_descriptor()?;
2571
2572 let mut inputs = BTreeMap::<String, CacheDigest>::new();
2573 for input in &self.context.inputs {
2574 input
2575 .digest
2576 .validate()
2577 .map_err(|_| BypassReason::InvalidInputDigest(input.path.display().to_string()))?;
2578 let path = self.normalize_input_path(&input.path)?;
2579 if inputs
2580 .insert(path.clone(), input.digest.clone())
2581 .is_some_and(|existing| existing != input.digest)
2582 {
2583 return Err(BypassReason::ConflictingInput(path));
2584 }
2585 }
2586 let required = self
2587 .invocation
2588 .required_inputs
2589 .iter()
2590 .map(|path| self.normalize_input_path(path))
2591 .collect::<Result<BTreeSet<_>, _>>()?;
2592 if let Some(missing) = required.iter().find(|path| !inputs.contains_key(*path)) {
2593 return Err(BypassReason::MissingRequiredInput(missing.clone()));
2594 }
2595 let inputs = inputs
2596 .into_iter()
2597 .map(|(path, digest)| InputDescriptor { path, digest })
2598 .collect();
2599 if self.invocation.links_natively() && self.linker.is_none() {
2602 return Err(BypassReason::UnportableNativeLink(
2603 "linker identity is unknown".into(),
2604 ));
2605 }
2606 let descriptor = ActionDescriptor {
2607 version: ACTION_SCHEMA_VERSION,
2608 kind: "rustc",
2609 adapter_version: ADAPTER_VERSION,
2610 compiler: invocation.compiler,
2611 arguments: invocation.arguments,
2612 environment,
2613 inputs,
2614 linker: self.linker.clone(),
2615 };
2616 let bytes = canonical_json(&descriptor)
2617 .map_err(|error| BypassReason::Serialization(error.to_string()))?;
2618 let digest = CacheDigest::blake3(&bytes);
2619 Ok(RustcAction { digest, bytes })
2620 }
2621
2622 fn invocation_descriptor(&self) -> Result<InvocationDescriptor, BypassReason> {
2623 self.validate_mappings()?;
2624 let arguments = self
2625 .invocation
2626 .arguments
2627 .iter()
2628 .map(|argument| self.normalize_argument(argument))
2629 .collect::<Result<Vec<_>, _>>()?;
2630 let required_inputs = self
2631 .invocation
2632 .required_inputs
2633 .iter()
2634 .map(|path| self.normalize_file_path(path))
2635 .collect::<Result<BTreeSet<_>, _>>()?
2636 .into_iter()
2637 .collect();
2638 Ok(InvocationDescriptor {
2639 version: ACTION_SCHEMA_VERSION,
2640 kind: "rustc",
2641 adapter_version: ADAPTER_VERSION,
2642 compiler: CompilerDescriptor {
2643 toolchain: self.context.compiler.toolchain.clone(),
2644 rustc_version: self.context.compiler.rustc_version.clone(),
2645 host: self.context.compiler.host.clone(),
2646 driver: self.context.compiler.driver.clone(),
2647 },
2648 arguments,
2649 required_inputs,
2650 })
2651 }
2652
2653 fn validate_mappings(&self) -> Result<(), BypassReason> {
2654 if !self.context.working_dir.is_absolute() {
2655 return Err(BypassReason::RelativeWorkingDirectory(
2656 self.context.working_dir.clone(),
2657 ));
2658 }
2659 let mut roots = BTreeSet::new();
2660 let mut placeholders = BTreeSet::new();
2661 for mapping in &self.mappings {
2662 if !mapping.root.is_absolute() {
2663 return Err(BypassReason::RelativePathMapping(mapping.root.clone()));
2664 }
2665 if mapping.placeholder.is_empty()
2666 || !mapping
2667 .placeholder
2668 .bytes()
2669 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
2670 || !roots.insert(normalize_components(&mapping.root))
2671 || !placeholders.insert(&mapping.placeholder)
2672 {
2673 return Err(BypassReason::InvalidPathPlaceholder(
2674 mapping.placeholder.clone(),
2675 ));
2676 }
2677 }
2678 Ok(())
2679 }
2680
2681 fn normalize_argument(&self, argument: &Argument) -> Result<String, BypassReason> {
2682 match argument {
2683 Argument::Plain(value) => Ok(value.clone()),
2684 Argument::Path { flag, path } if flag == "--sysroot" => {
2685 Ok(format!("{flag}={}", self.normalize_sysroot_path(path)?))
2686 }
2687 Argument::Path { flag, path } => Ok(format!("{flag}={}", self.normalize_path(path)?)),
2688 Argument::SearchPath { kind, path } => {
2689 let text = self.normalize_path(path)?;
2690 Ok(format!("-L{kind}={text}"))
2691 }
2692 Argument::Extern { name, path } => match path {
2693 Some(path) => Ok(format!(
2694 "--extern={name}={}",
2695 self.normalize_file_path(path)?
2696 )),
2697 None => Ok(format!("--extern={name}")),
2698 },
2699 Argument::Emit(emits) => Ok(format!(
2700 "--emit={}",
2701 emits
2702 .iter()
2703 .map(|emit| match &emit.path {
2704 Some(path) => self
2705 .normalize_path(path)
2706 .map(|path| format!("{}={path}", emit.kind)),
2707 None => Ok(emit.kind.clone()),
2708 })
2709 .collect::<Result<Vec<_>, _>>()?
2710 .join(",")
2711 )),
2712 Argument::RemapPath { from, to } => Ok(format!(
2713 "--remap-path-prefix={}={}",
2714 self.normalize_path(from)?,
2715 to
2716 )),
2717 Argument::InstallName(name) => Ok(format!(
2718 "--codegen=link-arg=-Wl,-install_name,@rpath/{name}"
2719 )),
2720 Argument::OsoPrefix {
2721 path,
2722 trailing_slash,
2723 } => Ok(format!(
2724 "--codegen=link-arg=-Wl,-oso_prefix,{}{}",
2725 self.normalize_path(path)?,
2726 if *trailing_slash { "/" } else { "" }
2727 )),
2728 Argument::FuseLd(selection) => Ok(format!("--codegen=link-arg=-fuse-ld={selection}")),
2729 Argument::Rpath(directory) => Ok(format!("--codegen=link-arg=-Wl,-rpath,{directory}")),
2731 }
2732 }
2733
2734 fn environment_descriptor(&self) -> Result<BTreeMap<String, Option<String>>, BypassReason> {
2741 self.context
2742 .environment
2743 .iter()
2744 .map(|(name, value)| {
2745 let value = match value {
2746 Some(value) if self.context.portable_environment.contains(name) => {
2747 Some(self.normalize_path(Path::new(value))?)
2748 }
2749 value => value.clone(),
2750 };
2751 Ok((name.clone(), value))
2752 })
2753 .collect()
2754 }
2755
2756 fn normalize_input_path(&self, path: &Path) -> Result<String, BypassReason> {
2757 let absolute = normalize_components(&self.context.working_dir.join(path));
2758 for directory in self.invocation.native_search_paths() {
2759 let directory = normalize_components(&self.context.working_dir.join(directory));
2760 if let Ok(relative) = absolute.strip_prefix(&directory) {
2761 let suffix = relative
2767 .components()
2768 .map(|component| {
2769 component
2770 .as_os_str()
2771 .to_str()
2772 .ok_or_else(|| BypassReason::NonUtf8Path(path.to_path_buf()))
2773 })
2774 .collect::<Result<Vec<_>, _>>()?
2775 .join("/");
2776 if !suffix.is_empty() {
2777 return Ok(format!("{}/{}", self.normalize_path(&directory)?, suffix));
2778 }
2779 }
2780 }
2781 self.normalize_file_path(path)
2782 }
2783
2784 fn normalize_sysroot_path(&self, path: &Path) -> Result<String, BypassReason> {
2785 let absolute = self.context.working_dir.join(path);
2786 if !absolute.starts_with(self.store_root) {
2787 return self.normalize_path(path);
2788 }
2789 if let Some(value) = absolute.to_str()
2792 && resolve_nix_store_path(value, self.store_root).is_some_and(|path| path.is_dir())
2793 {
2794 return Ok(value.to_owned());
2795 }
2796 Err(BypassReason::UnmappedAbsolutePath(absolute))
2797 }
2798
2799 fn normalize_file_path(&self, path: &Path) -> Result<String, BypassReason> {
2800 self.normalize_path(path)
2801 .or_else(|reason| key_nix_store_path(path, &self.context.working_dir, reason))
2802 }
2803
2804 fn normalize_path(&self, path: &Path) -> Result<String, BypassReason> {
2805 normalize_resolved_shared_path_with(
2806 &self.aliases,
2807 path,
2808 &self.context.working_dir,
2809 &self.mappings,
2810 )
2811 .map_err(Into::into)
2812 }
2813}
2814
2815fn under_any_directory(path: &str, directories: &BTreeSet<String>) -> bool {
2819 directories.iter().any(|directory| {
2820 path.len() > directory.len()
2821 && path.as_bytes()[directory.len()] == b'/'
2822 && path.starts_with(directory)
2823 })
2824}
2825
2826fn denormalize_path(
2827 value: &str,
2828 mappings: &[PathMapping],
2829 store_root: &str,
2830) -> Result<PathBuf, BypassReason> {
2831 for mapping in mappings {
2832 let prefix = format!("${{{}}}", mapping.placeholder);
2833 let suffix = if value == prefix {
2834 ""
2835 } else if let Some(suffix) = value.strip_prefix(&format!("{prefix}/")) {
2836 suffix
2837 } else {
2838 continue;
2839 };
2840 if !mapping.root.is_absolute()
2841 || (!suffix.is_empty()
2842 && suffix.split('/').any(|component| {
2843 component.is_empty()
2844 || matches!(component, "." | "..")
2845 || component.contains('\\')
2846 }))
2847 {
2848 return Err(BypassReason::InvalidPredictedInput(value.into()));
2849 }
2850 let mut path = normalize_components(&mapping.root);
2851 path.extend(suffix.split('/').filter(|component| !component.is_empty()));
2852 return Ok(path);
2853 }
2854 if resolve_nix_store_path(value, store_root).is_some() {
2857 return Ok(PathBuf::from(value));
2858 }
2859 Err(BypassReason::InvalidPredictedInput(value.into()))
2860}
2861
2862fn resolve_nix_store_path(value: &str, store_root: &str) -> Option<PathBuf> {
2863 let resolved = nix_store_path(value, store_root)?.canonicalize().ok()?;
2864 nix_store_path(resolved.to_str()?, store_root)?;
2865 Some(resolved)
2866}
2867
2868fn nix_store_path<'a>(value: &'a str, store_root: &str) -> Option<&'a Path> {
2869 let path = Path::new(value);
2870 if !path.is_absolute() {
2871 return None;
2872 }
2873 let suffix = value.strip_prefix(store_root)?.strip_prefix('/')?;
2874 (!suffix.split('/').any(|component| {
2875 component.is_empty() || matches!(component, "." | "..") || component.contains('\0')
2876 }))
2877 .then_some(path)
2878}
2879
2880fn key_nix_store_path(
2881 path: &Path,
2882 working_dir: &Path,
2883 reason: BypassReason,
2884) -> Result<String, BypassReason> {
2885 if matches!(reason, BypassReason::UnmappedAbsolutePath(_)) {
2886 let absolute = working_dir.join(path);
2887 if let Some(value) = absolute.to_str()
2888 && nix_store_path(value, NIX_STORE_ROOT).is_some()
2889 {
2890 return Ok(value.to_owned());
2891 }
2892 }
2893 Err(reason)
2894}
2895
2896fn normalize_components(path: &Path) -> PathBuf {
2897 let mut normalized = PathBuf::new();
2898 for component in path.components() {
2899 match component {
2900 Component::CurDir => {}
2901 Component::ParentDir => {
2902 normalized.pop();
2903 }
2904 component => normalized.push(component.as_os_str()),
2905 }
2906 }
2907 normalized
2908}
2909
2910fn absolute_path(path: &Path, working_dir: &Path) -> PathBuf {
2911 if path.is_absolute() {
2912 normalize_components(path)
2913 } else {
2914 normalize_components(&working_dir.join(path))
2915 }
2916}
2917
2918#[cfg(test)]
2919#[path = "rustc_cache_tests.rs"]
2920mod tests;