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 PREFETCH_GROUP_CODEGEN_OPTIONS: &[&str] = &[
116 "debug-assertions",
117 "debuginfo",
118 "opt-level",
119 "overflow-checks",
120 "panic",
121];
122
123const PREFETCH_GROUP_LEN: usize = 16;
126
127pub const PREDICTION_VERSION: u8 = 6;
129
130const SUPPORTED_CODEGEN_OPTIONS: &[&str] = &[
131 "codegen-units",
132 "control-flow-guard",
133 "debug-assertions",
134 "debuginfo",
135 "default-linker-libraries",
136 "embed-bitcode",
137 "extra-filename",
138 "force-frame-pointers",
139 "force-unwind-tables",
140 "instrument-coverage",
141 "link-arg",
142 "link-args",
143 "link-dead-code",
144 "link-self-contained",
145 "linker-plugin-lto",
146 "lto",
147 "metadata",
148 "no-prepopulate-passes",
149 "opt-level",
150 "overflow-checks",
151 "panic",
152 "prefer-dynamic",
153 "relocation-model",
154 "rpath",
155 "save-temps",
156 "soft-float",
157 "split-debuginfo",
158 "split-dwarf-kind",
159 "strip",
160 "symbol-mangling-version",
161 "target-cpu",
162 "target-feature",
163 "tls-model",
164 "unsafe-allow-abi-mismatch",
167];
168
169const NATIVE_DIRECTORY_PREDICTION_PREFIX: &str = "@native-directory:";
170const MAX_PREDICTED_INPUTS: usize = 16 * 1024;
171const MAX_DECODED_PREDICTION_BYTES: usize = 16 * 1024 * 1024;
175const MAX_NATIVE_INPUT_BYTES: u64 = 2 * 1024 * 1024 * 1024;
176
177const COMPILER_BUNDLED_WASM_TARGETS: &[&str] = &[
180 "wasm32-unknown-unknown",
181 "wasm32-wasip1",
182 "wasm32-wasip1-threads",
183 "wasm32-wasip2",
184 "wasm32v1-none",
185 "wasm64-unknown-unknown",
186];
187
188#[derive(Debug, Clone, PartialEq, Eq, Error, strum::IntoStaticStr)]
189#[strum(serialize_all = "kebab-case")]
190#[non_exhaustive]
200pub enum BypassReason {
201 #[error("rustc argument {index} is not valid UTF-8")]
203 NonUtf8Argument {
204 index: usize,
206 },
207 #[error("could not model rustc response file: {0}")]
209 ResponseFile(String),
210 #[error("rustc flag is not modeled by the cache adapter: {0}")]
212 UnknownFlag(String),
213 #[error("rustc codegen option is not modeled by the cache adapter: {0}")]
215 UnknownCodegenOption(String),
216 #[error("rustc flag requires a value: {0}")]
218 MissingValue(String),
219 #[error("rustc invocation is a compiler query, not a compilation")]
221 CompilerQuery,
222 #[error("rustc invocation reads source from standard input")]
224 StandardInput,
225 #[error("rustc invocation has no source input")]
227 MissingInput,
228 #[error("rustc invocation has multiple source inputs")]
230 MultipleInputs,
231 #[error("incremental compilation cannot be combined with action caching")]
233 Incremental,
234 #[error("rustc crate type is not cacheable yet: {0}")]
236 UnsupportedCrateType(String),
237 #[error("rustc output type is not cacheable yet: {0}")]
239 UnsupportedEmit(String),
240 #[error("rustc invocation does not emit a cacheable artifact")]
242 NoCacheableOutput,
243 #[error("rustc invocation does not emit dependency information")]
245 NoDepInfo,
246 #[error("rustc output paths do not share one directory")]
248 SplitOutputDirectories,
249 #[error("rustc output path has no file name: {0}")]
251 InvalidOutputPath(PathBuf),
252 #[error("rustc -o with an emit that has no explicit path is not modeled: {0}")]
254 ImplicitEmitWithOutputFile(PathBuf),
255 #[error("native library on a linked output is not cacheable yet: {0}")]
258 NativeLibrary(String),
259 #[error("native static library was not found on any search path: {0}")]
262 MissingNativeLibrary(String),
263 #[error("static library file names are not known for a custom target: {0}")]
266 CustomTargetNativeLibrary(String),
267 #[error("rustc output name does not distinguish a program from a library: {0}")]
269 AmbiguousOutputName(PathBuf),
270 #[error("native link is not reproducible across checkouts: {0}")]
272 UnportableNativeLink(String),
273 #[error("rustc link argument is not modeled by the cache adapter: {0}")]
275 UnmodeledLinkArgument(String),
276 #[error("rustc search path kind is not cacheable yet: {0}")]
278 UnsupportedSearchPath(String),
279 #[error("rustc extern does not identify an input artifact: {0}")]
281 UnresolvedExtern(String),
282 #[error("absolute path has no stable cache mapping: {0}")]
284 UnmappedAbsolutePath(PathBuf),
285 #[error("cache key paths must be valid UTF-8: {0}")]
287 NonUtf8Path(PathBuf),
288 #[error("cache action working directory must be absolute: {0}")]
290 RelativeWorkingDirectory(PathBuf),
291 #[error("cache path mapping must use an absolute root: {0}")]
293 RelativePathMapping(PathBuf),
294 #[error("cache path mapping placeholder is invalid: {0}")]
296 InvalidPathPlaceholder(String),
297 #[error("required compiler input was not provided: {0}")]
299 MissingRequiredInput(String),
300 #[error("compiler input has an invalid digest: {0}")]
302 InvalidInputDigest(String),
303 #[error("compiler input appears more than once with different content: {0}")]
305 ConflictingInput(String),
306 #[error("rustc dep-info is malformed: {0}")]
308 MalformedDepInfo(String),
309 #[error("failed to read rustc dep-info {path}: {message}")]
311 DepInfoRead {
312 path: PathBuf,
314 message: String,
316 },
317 #[error("rustc dep-info output path must be absolute: {0}")]
319 RelativeDepInfoPath(PathBuf),
320 #[error("rustc dep-info output path cannot contain a comma: {0}")]
322 UnsafeDepInfoPath(PathBuf),
323 #[error("failed to read compiler input {path}: {message}")]
325 InputRead {
326 path: PathBuf,
328 message: String,
330 },
331 #[error("declared build-script input overlaps compiler outputs: {0}")]
333 BuildScriptInputOverlapsOutputs(PathBuf),
334 #[error("Cargo has not recorded the build script's declarations yet: {0}")]
339 BuildScriptDeclarationsPending(PathBuf),
340 #[error("build-script inputs changed during compilation (declarations: {0})")]
343 BuildScriptInputsChanged(PathBuf),
344 #[error("compiler input changed after discovery: {0}")]
346 InputChanged(PathBuf),
347 #[error("compiler input was modified during compilation: {0}")]
349 InputModifiedDuringCompilation(PathBuf),
350 #[error("compiler input metadata changed during compilation: {0}")]
354 InputMetadataChangedDuringCompilation(PathBuf),
355 #[error("discovered inputs were collected from a different working directory")]
357 DiscoveryWorkingDirectory,
358 #[error("compiler environment input has conflicting values: {0}")]
360 ConflictingEnvironment(String),
361 #[error("failed to serialize the rustc action: {0}")]
363 Serialization(String),
364 #[error("rustc action prediction is unsupported")]
366 UnsupportedPrediction,
367 #[error("rustc action prediction contains an invalid input path: {0}")]
369 InvalidPredictedInput(String),
370}
371
372fn searches_native(kind: &str) -> bool {
377 matches!(kind, "native" | "all")
378}
379
380#[derive(Debug, Clone, PartialEq, Eq)]
381enum Argument {
382 Plain(String),
383 Path {
384 flag: String,
385 path: PathBuf,
386 },
387 SearchPath {
388 kind: String,
389 path: PathBuf,
390 },
391 Extern {
392 name: String,
393 path: Option<PathBuf>,
394 },
395 Emit(Vec<Emit>),
396 RemapPath {
397 from: PathBuf,
398 to: String,
399 },
400 InstallName(String),
402 OsoPrefix {
405 path: PathBuf,
406 trailing_slash: bool,
407 },
408 FuseLd(String),
412 Rpath(String),
416}
417
418#[derive(Debug, Clone, PartialEq, Eq)]
419struct Emit {
420 kind: String,
421 path: Option<PathBuf>,
422}
423
424#[derive(Debug, Clone, PartialEq, Eq)]
425pub struct RustcInvocation {
430 arguments: Vec<Argument>,
431 source: PathBuf,
432 required_inputs: Vec<PathBuf>,
433 crate_name: String,
434 extra_filename: String,
435 out_dir: Option<PathBuf>,
436 explicit_output: Option<PathBuf>,
437 emits: Vec<Emit>,
438 target: Option<String>,
439 link_output: LinkOutput,
440}
441
442#[derive(Debug, Clone, Copy, PartialEq, Eq)]
443enum LinkOutput {
444 Library,
445 WasmExecutable,
446 NativeExecutable,
447 NativeProcMacro,
448 NativeSharedLibrary,
453}
454
455#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
461#[non_exhaustive]
462pub struct ParseOptions {
463 pub cache_native_links: bool,
466 pub custom_target_search: bool,
472}
473
474impl ParseOptions {
475 pub fn caching_native_links(enabled: bool) -> Self {
477 Self {
478 cache_native_links: enabled,
479 ..Self::default()
480 }
481 }
482
483 pub fn with_custom_target_search(mut self, enabled: bool) -> Self {
486 self.custom_target_search = enabled;
487 self
488 }
489}
490
491#[derive(Debug, Clone, PartialEq, Eq)]
493pub struct RustcOutputs {
494 pub directory: PathBuf,
496 pub files: Vec<PathBuf>,
498 pub dep_info: PathBuf,
500}
501
502impl RustcInvocation {
503 pub fn parse(arguments: &[OsString]) -> Result<Self, BypassReason> {
512 Self::parse_with(arguments, ParseOptions::default())
513 }
514
515 pub fn expand_arguments(arguments: &[OsString]) -> Result<Vec<OsString>, BypassReason> {
520 Ok(expand_response_files(arguments)?.arguments)
521 }
522
523 pub fn parse_with(arguments: &[OsString], options: ParseOptions) -> Result<Self, BypassReason> {
526 let expanded = expand_response_files(arguments)?;
527 Parser::new(&expanded.arguments, options).parse()
528 }
529
530 pub fn links_natively(&self) -> bool {
533 matches!(
534 self.link_output,
535 LinkOutput::NativeExecutable
536 | LinkOutput::NativeProcMacro
537 | LinkOutput::NativeSharedLibrary
538 )
539 }
540
541 pub fn portable_install_name(&self, outputs: &RustcOutputs) -> Option<String> {
545 if !cfg!(target_os = "macos")
546 || self.link_output != LinkOutput::NativeProcMacro
547 || self
548 .arguments
549 .iter()
550 .any(|arg| matches!(arg, Argument::InstallName(_)))
551 {
552 return None;
553 }
554 let file = outputs
555 .files
556 .iter()
557 .find(|path| path.extension().is_some_and(|ext| ext == "dylib"))?;
558 let name = file.file_name()?.to_str()?;
559 if !safe_install_name(name) {
560 return None;
561 }
562 Some(format!("-Clink-arg=-Wl,-install_name,@rpath/{name}"))
563 }
564
565 pub fn linker_override(&self) -> Option<&Path> {
568 self.arguments.iter().find_map(|argument| {
569 let Argument::Plain(value) = argument else {
570 return None;
571 };
572 value.strip_prefix("--codegen=linker=").map(Path::new)
573 })
574 }
575
576 pub fn fuse_ld(&self) -> Option<&str> {
579 self.arguments.iter().find_map(|argument| {
580 let Argument::FuseLd(selection) = argument else {
581 return None;
582 };
583 Some(selection.as_str())
584 })
585 }
586
587 fn emits_windows_pdb(&self) -> bool {
588 if !cfg!(windows) || !self.links_natively() {
589 return false;
590 }
591 let mut enabled = false;
592 for argument in &self.arguments {
593 let Argument::Plain(value) = argument else {
594 continue;
595 };
596 if value == "-g" {
597 enabled = true;
598 } else if let Some(value) = value.strip_prefix("--codegen=debuginfo=") {
599 enabled = !matches!(value, "0" | "none");
600 }
601 }
602 enabled
603 }
604
605 pub fn native_search_paths(&self) -> impl Iterator<Item = &Path> {
609 self.arguments.iter().filter_map(|argument| match argument {
610 Argument::SearchPath { kind, path } if searches_native(kind) => Some(path.as_path()),
611 _ => None,
612 })
613 }
614
615 pub fn source(&self) -> &Path {
617 &self.source
618 }
619
620 pub fn required_inputs_in(&self, working_dir: &Path) -> Vec<PathBuf> {
626 self.required_inputs
627 .iter()
628 .map(|path| absolute_path(path, working_dir))
629 .collect()
630 }
631
632 pub fn target(&self) -> Option<&str> {
634 self.target.as_deref()
635 }
636
637 pub fn prefetch_group(&self) -> String {
657 let mut material = vec![format!("target={}", self.target.as_deref().unwrap_or(""))];
658 for argument in &self.arguments {
659 let Argument::Plain(value) = argument else {
660 continue;
661 };
662 let option = match value.as_str() {
663 "-O" => "opt-level=3",
664 "-g" => "debuginfo=2",
665 value => match value.strip_prefix("--codegen=") {
666 Some(option) => option,
667 None => continue,
668 },
669 };
670 let name = option.split_once('=').map_or(option, |(name, _)| name);
671 if PREFETCH_GROUP_CODEGEN_OPTIONS.contains(&name) {
672 material.push(option.to_string());
673 }
674 }
675 let digest = CacheDigest::blake3(
676 format!("rustc-prefetch-group-v1\0{}", material.join("\0")).as_bytes(),
677 );
678 digest.hash[..PREFETCH_GROUP_LEN].to_string()
679 }
680
681 pub fn crate_name(&self) -> &str {
683 &self.crate_name
684 }
685
686 pub fn remaps_working_directory(&self) -> bool {
695 self.arguments.iter().any(|argument| {
696 matches!(argument, Argument::Plain(flag) if flag.starts_with("-Zremap-cwd-prefix="))
697 })
698 }
699
700 pub fn source_fingerprint(&self, discovered: &DiscoveredInputs) -> CacheDigest {
713 let linked = self
714 .arguments
715 .iter()
716 .filter_map(|argument| match argument {
717 Argument::Extern {
718 path: Some(path), ..
719 } => Some(path.as_path()),
720 _ => None,
721 })
722 .collect::<BTreeSet<_>>();
723 let owned = discovered
724 .inputs
725 .iter()
726 .filter(|input| {
727 !linked.contains(input.path.as_path()) && !discovered.is_native_only(&input.path)
728 })
729 .map(|input| (input.path.as_path(), &input.digest))
730 .collect::<BTreeMap<_, _>>();
731 let mut bytes = Vec::new();
732 for (path, digest) in owned {
733 bytes.extend_from_slice(path.as_os_str().as_encoded_bytes());
734 bytes.push(0);
735 bytes.extend_from_slice(digest.key().as_bytes());
736 bytes.push(0);
737 }
738 CacheDigest::blake3(&bytes)
739 }
740
741 pub fn outputs(&self, working_dir: &Path) -> Result<RustcOutputs, BypassReason> {
746 if !working_dir.is_absolute() {
747 return Err(BypassReason::RelativeWorkingDirectory(
748 working_dir.to_path_buf(),
749 ));
750 }
751 let explicit_output = self
752 .explicit_output
753 .as_deref()
754 .map(|path| absolute_path(path, working_dir));
755 let output_directory = explicit_output
756 .as_deref()
757 .and_then(Path::parent)
758 .map(Path::to_path_buf)
759 .or_else(|| {
760 self.out_dir
761 .as_deref()
762 .map(|path| absolute_path(path, working_dir))
763 })
764 .unwrap_or_else(|| normalize_components(working_dir));
765 if let Some(output) = &explicit_output
769 && self.emits.iter().any(|emit| {
770 emit.path.is_none()
771 && matches!(emit.kind.as_str(), "dep-info" | "link" | "metadata")
772 })
773 {
774 return Err(BypassReason::ImplicitEmitWithOutputFile(output.clone()));
775 }
776 let mut files = BTreeSet::new();
777 let mut dep_info = None;
778 for emit in &self.emits {
779 if emit.kind == "dep-info" {
780 let path = emit.path.as_ref().map_or_else(
781 || {
782 explicit_output.clone().map_or_else(
783 || {
784 output_directory
785 .join(format!("{}{}.d", self.crate_name, self.extra_filename))
786 },
787 |path| path.with_extension("d"),
788 )
789 },
790 |path| absolute_path(path, working_dir),
791 );
792 if path.file_name().is_none() {
793 return Err(BypassReason::InvalidOutputPath(path));
794 }
795 dep_info = Some(path);
796 continue;
797 }
798 let (prefix, extension) = match emit.kind.as_str() {
799 "link" => match self.link_output {
800 LinkOutput::Library => ("lib", "rlib"),
801 LinkOutput::WasmExecutable => ("", "wasm"),
802 LinkOutput::NativeExecutable => ("", std::env::consts::EXE_EXTENSION),
803 LinkOutput::NativeProcMacro | LinkOutput::NativeSharedLibrary => (
804 std::env::consts::DLL_PREFIX,
805 std::env::consts::DLL_SUFFIX.trim_start_matches('.'),
806 ),
807 },
808 "metadata" => ("lib", "rmeta"),
809 _ => continue,
810 };
811 let path = if let Some(path) = &emit.path {
812 absolute_path(path, working_dir)
813 } else {
814 let name = format!("{prefix}{}{}", self.crate_name, self.extra_filename);
815 output_directory.join(if extension.is_empty() {
816 name
817 } else {
818 format!("{name}.{extension}")
819 })
820 };
821 if path.file_name().is_none() {
822 return Err(BypassReason::InvalidOutputPath(path));
823 }
824 if path.parent() != Some(output_directory.as_path()) {
825 return Err(BypassReason::SplitOutputDirectories);
826 }
827 let has_library_extension = path
832 .extension()
833 .and_then(|extension| extension.to_str())
834 .is_some_and(|extension| matches!(extension, "rlib" | "rmeta"))
835 || (cfg!(windows)
836 && path
837 .file_stem()
838 .and_then(|stem| Path::new(stem).extension())
839 .and_then(|extension| extension.to_str())
840 .is_some_and(|extension| matches!(extension, "rlib" | "rmeta")));
841 if emit.kind == "link"
842 && !matches!(self.link_output, LinkOutput::Library)
843 && has_library_extension
844 {
845 return Err(BypassReason::AmbiguousOutputName(path));
846 }
847 if emit.kind == "link" && self.emits_windows_pdb() {
848 files.insert(path.with_extension("pdb"));
849 }
850 files.insert(path);
851 }
852 let dep_info = dep_info.ok_or(BypassReason::NoDepInfo)?;
853 if dep_info.parent() != Some(output_directory.as_path()) {
854 return Err(BypassReason::SplitOutputDirectories);
855 }
856 Ok(RustcOutputs {
857 directory: output_directory,
858 files: files.into_iter().collect(),
859 dep_info,
860 })
861 }
862
863 pub fn action(&self, context: ActionContext) -> Result<RustcAction, BypassReason> {
869 self.action_linked_by(context, None)
870 }
871
872 pub fn action_linked_by(
881 &self,
882 context: ActionContext,
883 linker: Option<LinkerIdentity>,
884 ) -> Result<RustcAction, BypassReason> {
885 self.action_with_incremental_state(context, linker, None)
886 }
887
888 pub fn action_with_incremental_state(
897 &self,
898 context: ActionContext,
899 linker: Option<LinkerIdentity>,
900 incremental_state: Option<String>,
901 ) -> Result<RustcAction, BypassReason> {
902 ActionBuilder::new(self, context)
903 .linked_by(linker)
904 .carrying_incremental_state(incremental_state)
905 .build()
906 }
907
908 pub fn invocation_digest(&self, context: &ActionContext) -> Result<CacheDigest, BypassReason> {
910 let descriptor = ActionBuilder::new(self, context.clone()).invocation_descriptor()?;
911 let bytes = canonical_json(&descriptor)
912 .map_err(|error| BypassReason::Serialization(error.to_string()))?;
913 Ok(CacheDigest::blake3(&bytes))
914 }
915
916 pub fn prediction(
919 &self,
920 context: &ActionContext,
921 discovered: &DiscoveredInputs,
922 ) -> Result<RustcInputPrediction, BypassReason> {
923 let builder = ActionBuilder::new(self, context.clone());
924 builder.validate_mappings()?;
925 let mut native_directories = BTreeSet::new();
926 for argument in &self.arguments {
927 if let Argument::SearchPath { kind, path } = argument
928 && searches_native(kind)
929 {
930 native_directories.insert(builder.normalize_path(path)?);
931 }
932 }
933 let mut inputs = BTreeSet::new();
945 for input in &discovered.inputs {
946 let normalized = builder.normalize_file_path(&input.path)?;
947 if !under_any_directory(&normalized, &native_directories)
948 || !discovered.is_native_only(&input.path)
949 {
950 inputs.insert(normalized);
951 }
952 }
953 inputs.extend(
954 native_directories
955 .into_iter()
956 .map(|directory| format!("{NATIVE_DIRECTORY_PREDICTION_PREFIX}{directory}")),
957 );
958 Ok(RustcInputPrediction {
959 version: PREDICTION_VERSION,
960 inputs: inputs.into_iter().collect(),
961 environment: discovered.environment.keys().cloned().collect(),
962 compiler_duration_ns: 0,
963 compiler_cpu_ns: 0,
964 crate_name: String::new(),
965 prefetch_group: self.prefetch_group(),
966 })
967 }
968}
969
970pub fn is_build_script_crate_name(crate_name: &str) -> bool {
974 crate_name
975 .strip_prefix("build_script_")
976 .is_some_and(|stem| !stem.is_empty())
977}
978
979impl RustcOutputs {
980 pub fn build_script_executable(&self, crate_name: &str) -> Option<&Path> {
990 is_build_script_crate_name(crate_name)
991 .then(|| self.files.iter().find(|path| self.is_executable(path)))
992 .flatten()
993 .map(PathBuf::as_path)
994 }
995
996 pub fn is_executable(&self, path: &Path) -> bool {
1004 self.files.iter().any(|output| output == path)
1005 && !matches!(
1006 path.extension().and_then(|extension| extension.to_str()),
1007 Some("rlib" | "rmeta")
1008 )
1009 }
1010}
1011
1012#[derive(Debug, Clone, PartialEq, Eq)]
1013pub struct PathMapping {
1015 pub root: PathBuf,
1017 pub placeholder: String,
1019}
1020
1021impl PathMapping {
1022 pub fn new(root: impl Into<PathBuf>, placeholder: impl Into<String>) -> Self {
1024 Self {
1025 root: root.into(),
1026 placeholder: placeholder.into(),
1027 }
1028 }
1029
1030 pub fn ordered(mappings: &[PathMapping]) -> Vec<PathMapping> {
1033 let mut ordered = mappings.to_vec();
1034 ordered.sort_by_key(|mapping| std::cmp::Reverse(mapping.root.components().count()));
1035 ordered
1036 }
1037}
1038
1039fn shared_path_mappings(mappings: &[PathMapping]) -> Vec<SharedPathMapping> {
1040 mappings
1041 .iter()
1042 .map(|mapping| SharedPathMapping::new(&mapping.root, &mapping.placeholder))
1043 .collect()
1044}
1045
1046pub fn normalize_mapped_path(
1053 path: &Path,
1054 working_dir: &Path,
1055 mappings: &[PathMapping],
1056) -> Result<String, BypassReason> {
1057 normalize_shared_path(path, working_dir, &shared_path_mappings(mappings)).map_err(Into::into)
1058}
1059
1060pub fn normalize_input_path(
1062 path: &Path,
1063 working_dir: &Path,
1064 mappings: &[PathMapping],
1065) -> Result<String, BypassReason> {
1066 normalize_mapped_path(path, working_dir, mappings)
1067 .or_else(|reason| key_nix_store_path(path, working_dir, reason))
1068}
1069
1070#[derive(Debug, Clone, PartialEq, Eq)]
1071pub struct CompilerIdentity {
1073 pub toolchain: String,
1075 pub rustc_version: String,
1077 pub host: String,
1079 pub driver: Option<String>,
1081}
1082
1083#[derive(Debug, Clone, PartialEq, Eq)]
1085pub struct ActionInput {
1086 pub path: PathBuf,
1088 pub digest: CacheDigest,
1090}
1091
1092#[derive(Debug, Clone, PartialEq, Eq)]
1094pub struct ActionContext {
1095 pub compiler: CompilerIdentity,
1097 pub working_dir: PathBuf,
1099 pub path_mappings: Vec<PathMapping>,
1101 pub environment: BTreeMap<String, Option<String>>,
1103 pub portable_environment: BTreeSet<String>,
1110 pub inputs: Vec<ActionInput>,
1112}
1113
1114#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1124#[serde(deny_unknown_fields)]
1125pub struct LinkerIdentity {
1126 pub driver: String,
1128 pub driver_version: String,
1130 pub linker_version: String,
1132 #[serde(skip_serializing_if = "BTreeMap::is_empty", default)]
1134 pub crt_objects: BTreeMap<String, CacheDigest>,
1135 #[serde(skip_serializing_if = "Option::is_none", default)]
1137 pub sdk: Option<String>,
1138 #[serde(skip_serializing_if = "Option::is_none", default)]
1140 pub deployment_target: Option<String>,
1141}
1142
1143#[derive(Debug, Clone, PartialEq, Eq)]
1145pub struct RustcAction {
1146 pub digest: CacheDigest,
1148 pub bytes: Vec<u8>,
1150}
1151
1152#[derive(Debug, Clone, PartialEq, Eq)]
1155pub struct RustcInputPrediction {
1156 pub version: u8,
1158 pub inputs: Vec<String>,
1160 pub environment: Vec<String>,
1162 pub compiler_duration_ns: u64,
1165 pub compiler_cpu_ns: u64,
1168 pub crate_name: String,
1170 pub prefetch_group: String,
1174}
1175
1176#[derive(Serialize, Deserialize)]
1177#[serde(deny_unknown_fields)]
1178struct RustcInputPredictionWire {
1179 version: u8,
1180 inputs: Vec<String>,
1181 environment: Vec<String>,
1182 #[serde(default, skip_serializing_if = "is_zero")]
1183 compiler_duration_ns: u64,
1184 #[serde(default, skip_serializing_if = "is_zero")]
1185 compiler_cpu_ns: u64,
1186 #[serde(default, skip_serializing_if = "String::is_empty")]
1187 crate_name: String,
1188 #[serde(default, skip_serializing_if = "String::is_empty")]
1189 prefetch_group: String,
1190}
1191
1192impl Serialize for RustcInputPrediction {
1193 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1194 where
1195 S: Serializer,
1196 {
1197 RustcInputPredictionWire {
1198 version: self.version,
1199 inputs: if self.version >= 4 {
1200 mbx_cache_core::prefix_coding::compact_paths(&self.inputs)
1201 } else {
1202 self.inputs.clone()
1203 },
1204 environment: self.environment.clone(),
1205 compiler_duration_ns: self.compiler_duration_ns,
1206 compiler_cpu_ns: self.compiler_cpu_ns,
1207 crate_name: self.crate_name.clone(),
1208 prefetch_group: self.prefetch_group.clone(),
1209 }
1210 .serialize(serializer)
1211 }
1212}
1213
1214impl<'de> Deserialize<'de> for RustcInputPrediction {
1215 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1216 where
1217 D: Deserializer<'de>,
1218 {
1219 let wire = RustcInputPredictionWire::deserialize(deserializer)?;
1220 let group_is_valid = if wire.version >= 5 {
1221 wire.prefetch_group.len() == PREFETCH_GROUP_LEN
1222 && wire
1223 .prefetch_group
1224 .bytes()
1225 .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
1226 } else {
1227 wire.prefetch_group.is_empty()
1228 };
1229 if !group_is_valid {
1230 return Err(serde::de::Error::custom(
1231 "rustc prediction prefetch group is invalid for its version",
1232 ));
1233 }
1234 if wire.version < 6 && wire.compiler_cpu_ns != 0 {
1235 return Err(serde::de::Error::custom(
1236 "rustc prediction CPU time is invalid for its version",
1237 ));
1238 }
1239 let inputs = if wire.version >= 4 {
1240 mbx_cache_core::prefix_coding::expand_paths(&wire.inputs, MAX_DECODED_PREDICTION_BYTES)
1241 .map_err(serde::de::Error::custom)?
1242 } else {
1243 wire.inputs
1244 };
1245 Ok(Self {
1246 version: wire.version,
1247 inputs,
1248 environment: wire.environment,
1249 compiler_duration_ns: wire.compiler_duration_ns,
1250 compiler_cpu_ns: wire.compiler_cpu_ns,
1251 crate_name: wire.crate_name,
1252 prefetch_group: wire.prefetch_group,
1253 })
1254 }
1255}
1256
1257fn is_zero(value: &u64) -> bool {
1258 *value == 0
1259}
1260
1261impl RustcInputPrediction {
1262 pub fn with_prefetch_group(&self, group: String) -> Option<Self> {
1269 let converts = match self.version {
1270 3 | 4 => true,
1271 2 => !self
1272 .inputs
1273 .iter()
1274 .any(|input| input.starts_with(NATIVE_DIRECTORY_PREDICTION_PREFIX)),
1275 _ => false,
1276 };
1277 converts.then(|| Self {
1278 version: PREDICTION_VERSION,
1279 prefetch_group: group,
1280 ..self.clone()
1281 })
1282 }
1283
1284 pub fn discover(
1287 &self,
1288 working_dir: &Path,
1289 path_mappings: &[PathMapping],
1290 digests: &dyn FileDigestCache,
1291 ) -> Result<DiscoveredInputs, BypassReason> {
1292 self.discover_with_store(working_dir, path_mappings, digests, NIX_STORE_ROOT)
1293 }
1294
1295 fn discover_with_store(
1296 &self,
1297 working_dir: &Path,
1298 path_mappings: &[PathMapping],
1299 digests: &dyn FileDigestCache,
1300 store_root: &str,
1301 ) -> Result<DiscoveredInputs, BypassReason> {
1302 if !matches!(self.version, 2..=PREDICTION_VERSION) {
1303 return Err(BypassReason::UnsupportedPrediction);
1304 }
1305 if self.inputs.len() > MAX_PREDICTED_INPUTS || self.environment.len() > 4 * 1024 {
1306 return Err(BypassReason::UnsupportedPrediction);
1307 }
1308 let mut paths = BTreeSet::new();
1309 let mut named = BTreeSet::new();
1310 let admitted_roots = dep_info::native_input_roots(working_dir, path_mappings);
1311 let mut native_bytes = 0_u64;
1312 let mut counted = BTreeSet::new();
1313 let mut native_walk = dep_info::NativeWalk::default();
1314 for path in &self.inputs {
1315 if self.version >= 3
1316 && let Some(path) = path.strip_prefix(NATIVE_DIRECTORY_PREDICTION_PREFIX)
1317 {
1318 let directory = denormalize_path(path, path_mappings, store_root)?;
1319 native_walk.extend(dep_info::collect_native_directory(
1320 &directory,
1321 &admitted_roots,
1322 &mut paths,
1323 &mut native_bytes,
1324 &mut counted,
1325 )?);
1326 } else {
1327 let path = denormalize_path(path, path_mappings, store_root)?;
1328 named.insert(path.clone());
1329 paths.insert(path);
1330 }
1331 }
1332 let native_only = paths.difference(&named).cloned().collect();
1333 let environment = self
1334 .environment
1335 .iter()
1336 .map(|name| {
1337 if name.is_empty() || name.contains(['=', '\0']) {
1338 return Err(BypassReason::UnsupportedPrediction);
1339 }
1340 let value = std::env::var_os(name)
1341 .map(|value| {
1342 value
1343 .into_string()
1344 .map_err(|_| BypassReason::UnsupportedPrediction)
1345 })
1346 .transpose()?;
1347 Ok((name.clone(), value))
1348 })
1349 .collect::<Result<BTreeMap<_, _>, _>>()?;
1350 Ok(
1351 DiscoveredInputs::from_paths(working_dir, paths, environment, digests)?
1352 .with_native_only(native_only)
1353 .with_native_walk(native_walk),
1354 )
1355 }
1356}
1357
1358#[derive(Serialize)]
1359struct ActionDescriptor {
1360 version: u8,
1361 kind: &'static str,
1362 adapter_version: u8,
1363 compiler: CompilerDescriptor,
1364 arguments: Vec<String>,
1365 environment: BTreeMap<String, Option<String>>,
1366 inputs: Vec<InputDescriptor>,
1367 #[serde(skip_serializing_if = "Option::is_none")]
1370 linker: Option<LinkerIdentity>,
1371 #[serde(skip_serializing_if = "Option::is_none")]
1375 incremental_state: Option<String>,
1376}
1377
1378#[derive(Serialize)]
1379struct InvocationDescriptor {
1380 version: u8,
1381 kind: &'static str,
1382 adapter_version: u8,
1383 compiler: CompilerDescriptor,
1384 arguments: Vec<String>,
1385 required_inputs: Vec<String>,
1386}
1387
1388#[derive(Serialize)]
1389struct CompilerDescriptor {
1390 toolchain: String,
1391 rustc_version: String,
1392 host: String,
1393 #[serde(skip_serializing_if = "Option::is_none")]
1394 driver: Option<String>,
1395}
1396
1397#[derive(Debug, Serialize, PartialEq, Eq, PartialOrd, Ord)]
1398struct InputDescriptor {
1399 path: String,
1400 digest: CacheDigest,
1401}
1402
1403#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1405enum StaticLibraryNaming {
1406 Msvc,
1408 Unix,
1410}
1411
1412struct Parser<'a> {
1413 arguments: &'a [OsString],
1414 index: usize,
1415 parsed: Vec<Argument>,
1416 source: Option<PathBuf>,
1417 crate_types: Vec<String>,
1418 emits: Vec<Emit>,
1419 required_inputs: Vec<PathBuf>,
1420 native_libraries: Vec<String>,
1421 test: bool,
1422 crate_name: Option<String>,
1423 extra_filename: String,
1424 out_dir: Option<PathBuf>,
1425 explicit_output: Option<PathBuf>,
1426 target: Option<String>,
1427 sysroot_backend: Option<String>,
1428 options: ParseOptions,
1429}
1430
1431struct ExpandedArguments {
1432 arguments: Vec<OsString>,
1433}
1434
1435#[derive(Default)]
1436struct ResponseExpander {
1437 shell_argfiles: bool,
1438 next_is_unstable_option: bool,
1439 arguments: Vec<OsString>,
1440}
1441
1442impl ResponseExpander {
1443 fn push(&mut self, argument: String) {
1444 if self.next_is_unstable_option {
1445 self.shell_argfiles |= argument == "shell-argfiles";
1446 self.next_is_unstable_option = false;
1447 } else if let Some(option) = argument.strip_prefix("-Z") {
1448 if option.is_empty() {
1449 self.next_is_unstable_option = true;
1450 } else {
1451 self.shell_argfiles |= option == "shell-argfiles";
1452 }
1453 }
1454 self.arguments.push(argument.into());
1455 }
1456}
1457
1458fn expand_response_files(arguments: &[OsString]) -> Result<ExpandedArguments, BypassReason> {
1461 let mut expanded = ResponseExpander::default();
1462 for (index, argument) in arguments.iter().enumerate() {
1463 let argument = argument
1464 .to_str()
1465 .ok_or(BypassReason::NonUtf8Argument { index })?;
1466 let Some(argfile) = argument.strip_prefix('@') else {
1467 expanded.push(argument.to_string());
1468 continue;
1469 };
1470 let (path, shell) = match argfile.split_once(':') {
1471 Some(("shell", path)) if expanded.shell_argfiles => (path, true),
1472 _ => (argfile, false),
1473 };
1474 let contents = std::fs::read_to_string(path).map_err(|error| {
1475 BypassReason::ResponseFile(format!("{}: {error}", Path::new(path).display()))
1476 })?;
1477 if shell {
1478 let arguments = shlex::split(&contents).ok_or_else(|| {
1479 BypassReason::ResponseFile(format!(
1480 "invalid shell-style arguments in {}",
1481 Path::new(path).display()
1482 ))
1483 })?;
1484 for argument in arguments {
1485 expanded.push(argument);
1486 }
1487 } else {
1488 for argument in contents.lines() {
1489 expanded.push(argument.to_string());
1490 }
1491 }
1492 }
1493 Ok(ExpandedArguments {
1494 arguments: expanded.arguments,
1495 })
1496}
1497
1498impl<'a> Parser<'a> {
1499 fn new(arguments: &'a [OsString], options: ParseOptions) -> Self {
1500 Self {
1501 arguments,
1502 options,
1503 index: 0,
1504 parsed: Vec::new(),
1505 source: None,
1506 crate_types: Vec::new(),
1507 emits: Vec::new(),
1508 required_inputs: Vec::new(),
1509 native_libraries: Vec::new(),
1510 test: false,
1511 crate_name: None,
1512 extra_filename: String::new(),
1513 out_dir: None,
1514 explicit_output: None,
1515 target: None,
1516 sysroot_backend: None,
1517 }
1518 }
1519
1520 fn parse(mut self) -> Result<RustcInvocation, BypassReason> {
1521 while self.index < self.arguments.len() {
1522 let value = self.current()?.to_string();
1523 self.index += 1;
1524 if let Some(long) = value.strip_prefix("--") {
1525 self.parse_long(long)?;
1526 } else if value.starts_with('-') && value != "-" {
1527 self.parse_short(&value)?;
1528 } else {
1529 self.parse_input(&value)?;
1530 }
1531 }
1532
1533 if let Some(backend) = self.sysroot_backend.take()
1535 && self.parsed.iter().any(
1536 |argument| matches!(argument, Argument::Path { flag, .. } if flag == "--sysroot"),
1537 )
1538 {
1539 return Err(BypassReason::UnknownFlag(backend));
1540 }
1541 let source = self.source.clone().ok_or(BypassReason::MissingInput)?;
1542 let link_output = self.classify()?;
1543 self.require_native_libraries(link_output)?;
1544 let crate_name = self.crate_name.clone().map_or_else(
1545 || {
1546 source
1547 .file_stem()
1548 .and_then(|name| name.to_str())
1549 .map(|name| name.replace('-', "_"))
1550 .ok_or_else(|| BypassReason::NonUtf8Path(source.clone()))
1551 },
1552 Ok,
1553 )?;
1554 self.required_inputs.push(source.clone());
1555 self.drop_unobservable_diagnostic_width();
1556 Ok(RustcInvocation {
1557 arguments: self.parsed,
1558 source,
1559 required_inputs: self.required_inputs,
1560 crate_name,
1561 extra_filename: self.extra_filename,
1562 out_dir: self.out_dir,
1563 explicit_output: self.explicit_output,
1564 emits: self.emits,
1565 target: self.target,
1566 link_output,
1567 })
1568 }
1569
1570 fn current(&self) -> Result<&str, BypassReason> {
1571 self.arguments[self.index]
1572 .to_str()
1573 .ok_or(BypassReason::NonUtf8Argument { index: self.index })
1574 }
1575
1576 fn take_value(&mut self, flag: &str, inline: Option<&str>) -> Result<String, BypassReason> {
1577 if let Some(value) = inline {
1578 if value.is_empty() {
1579 return Err(BypassReason::MissingValue(flag.into()));
1580 }
1581 return Ok(value.into());
1582 }
1583 if self.index >= self.arguments.len() {
1584 return Err(BypassReason::MissingValue(flag.into()));
1585 }
1586 let value = self.current()?.to_string();
1587 self.index += 1;
1588 Ok(value)
1589 }
1590
1591 fn drop_unobservable_diagnostic_width(&mut self) {
1602 fn widths(argument: &Argument) -> Option<&str> {
1603 match argument {
1604 Argument::Plain(value) => value.strip_prefix("--diagnostic-width="),
1605 _ => None,
1606 }
1607 }
1608 let mut found = self.parsed.iter().filter_map(widths);
1609 let valid = matches!(
1610 (found.next(), found.next()),
1611 (Some(width), None) if width.parse::<usize>().is_ok()
1612 );
1613 if valid {
1614 self.parsed.retain(|argument| widths(argument).is_none());
1615 }
1616 }
1617
1618 fn parse_long(&mut self, value: &str) -> Result<(), BypassReason> {
1619 let (flag, inline) = value
1620 .split_once('=')
1621 .map_or((value, None), |(flag, value)| (flag, Some(value)));
1622 let rendered_flag = format!("--{flag}");
1623 match flag {
1624 "help" | "version" | "explain" | "print" => Err(BypassReason::CompilerQuery),
1625 "test" => {
1626 self.test = true;
1627 self.parsed.push(Argument::Plain(rendered_flag));
1628 Ok(())
1629 }
1630 "verbose" => {
1631 self.parsed.push(Argument::Plain(rendered_flag));
1632 Ok(())
1633 }
1634 "crate-name" => {
1635 let value = self.take_value(&rendered_flag, inline)?;
1636 self.crate_name = Some(value.clone());
1637 self.parsed
1638 .push(Argument::Plain(format!("{rendered_flag}={value}")));
1639 Ok(())
1640 }
1641 "cfg" | "check-cfg" | "edition" | "error-format" | "json" | "color"
1642 | "diagnostic-width" | "remap-path-scope" | "allow" | "warn" | "force-warn"
1643 | "deny" | "forbid" | "cap-lints" => {
1644 let value = self.take_value(&rendered_flag, inline)?;
1645 self.parsed
1646 .push(Argument::Plain(format!("{rendered_flag}={value}")));
1647 Ok(())
1648 }
1649 "target" => {
1650 let value = self.take_value(&rendered_flag, inline)?;
1651 let effective = self.target.is_none();
1655 if effective {
1656 self.target = Some(value.clone());
1657 }
1658 if value.ends_with(".json") || value.contains(['/', '\\']) {
1659 let path = PathBuf::from(value);
1660 if effective {
1661 self.required_inputs.push(path.clone());
1662 }
1663 self.parsed.push(Argument::Path {
1664 flag: rendered_flag,
1665 path,
1666 });
1667 } else {
1668 self.parsed
1669 .push(Argument::Plain(format!("{rendered_flag}={value}")));
1670 }
1671 Ok(())
1672 }
1673 "crate-type" => {
1674 let value = self.take_value(&rendered_flag, inline)?;
1675 self.crate_types
1676 .extend(value.split(',').map(ToOwned::to_owned));
1677 self.parsed
1678 .push(Argument::Plain(format!("{rendered_flag}={value}")));
1679 Ok(())
1680 }
1681 "emit" => {
1682 let value = self.take_value(&rendered_flag, inline)?;
1683 let emits = parse_emits(&value);
1684 self.emits.extend(emits.clone());
1685 self.parsed.push(Argument::Emit(emits));
1686 Ok(())
1687 }
1688 "out-dir" => {
1689 let path = PathBuf::from(self.take_value(&rendered_flag, inline)?);
1690 self.out_dir = Some(path.clone());
1691 self.parsed.push(Argument::Path {
1692 flag: rendered_flag,
1693 path,
1694 });
1695 Ok(())
1696 }
1697 "sysroot" => {
1698 let path = self.take_value(&rendered_flag, inline)?;
1699 self.parsed.push(Argument::Path {
1700 flag: rendered_flag,
1701 path: path.into(),
1702 });
1703 Ok(())
1704 }
1705 "extern" => {
1706 let value = self.take_value(&rendered_flag, inline)?;
1707 let (name, path) = value
1708 .split_once('=')
1709 .map_or((value.as_str(), None), |(name, path)| {
1710 (name, Some(PathBuf::from(path)))
1711 });
1712 if let Some(path) = &path {
1713 self.required_inputs.push(path.clone());
1714 }
1715 self.parsed.push(Argument::Extern {
1716 name: name.into(),
1717 path,
1718 });
1719 Ok(())
1720 }
1721 "remap-path-prefix" => {
1722 let value = self.take_value(&rendered_flag, inline)?;
1723 let Some((from, to)) = value.split_once('=') else {
1724 return Err(BypassReason::MissingValue(rendered_flag));
1725 };
1726 self.parsed.push(Argument::RemapPath {
1727 from: from.into(),
1728 to: to.into(),
1729 });
1730 Ok(())
1731 }
1732 "codegen" => {
1733 let value = self.take_value(&rendered_flag, inline)?;
1734 self.parse_codegen(&value)
1735 }
1736 "jobs-frontend" => {
1737 let value = self.take_value(&rendered_flag, inline)?;
1738 self.parsed
1739 .push(Argument::Plain(format!("{rendered_flag}={value}")));
1740 Ok(())
1741 }
1742 _ => Err(BypassReason::UnknownFlag(rendered_flag)),
1743 }
1744 }
1745
1746 fn parse_short(&mut self, value: &str) -> Result<(), BypassReason> {
1747 if let Some(attached) = value.strip_prefix("-Z") {
1748 let option = self.take_value("-Z", (!attached.is_empty()).then_some(attached))?;
1749 match option.as_str() {
1750 "embed-metadata=no"
1754 | "embed-metadata=yes"
1755 | "force-unstable-if-unmarked"
1756 | "shell-argfiles"
1757 | "unstable-options" => {
1758 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1759 return Ok(());
1760 }
1761 "use-sync-unwind=yes" | "use-sync-unwind=no" => {
1764 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1765 return Ok(());
1766 }
1767 "threads" | "threads=" => {
1768 return Err(BypassReason::MissingValue("-Zthreads".into()));
1769 }
1770 "remap-cwd-prefix" | "remap-cwd-prefix=" => {
1771 return Err(BypassReason::MissingValue("-Zremap-cwd-prefix".into()));
1772 }
1773 _ => {}
1774 }
1775 if option.starts_with("remap-cwd-prefix=") {
1781 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1782 return Ok(());
1783 }
1784 if option == "share-generics" {
1785 return Err(BypassReason::MissingValue("-Zshare-generics".into()));
1786 }
1787 if let Some(value) = option.strip_prefix("share-generics=") {
1788 if matches!(
1789 value,
1790 "y" | "yes" | "on" | "true" | "n" | "no" | "off" | "false"
1791 ) {
1792 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1793 return Ok(());
1794 }
1795 return Err(if value.is_empty() {
1796 BypassReason::MissingValue("-Zshare-generics".into())
1797 } else {
1798 BypassReason::UnknownFlag(format!("-Z{option}"))
1799 });
1800 }
1801 if option == "always-encode-mir" {
1805 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1806 return Ok(());
1807 }
1808 if let Some(level) = option.strip_prefix("mir-opt-level=") {
1809 if matches!(level, "0" | "1" | "2" | "3" | "4") {
1810 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1811 return Ok(());
1812 }
1813 return Err(if level.is_empty() {
1814 BypassReason::MissingValue("-Zmir-opt-level".into())
1815 } else {
1816 BypassReason::UnknownFlag(format!("-Z{option}"))
1817 });
1818 }
1819 if option == "mir-opt-level" {
1820 return Err(BypassReason::MissingValue("-Zmir-opt-level".into()));
1821 }
1822 let (name, value) = option
1825 .split_once('=')
1826 .map_or((option.as_str(), None), |(name, value)| (name, Some(value)));
1827 if matches!(name, "inline-mir" | "ub-checks") {
1828 return match value {
1829 Some("y" | "yes" | "on" | "true" | "n" | "no" | "off" | "false") => {
1830 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1831 Ok(())
1832 }
1833 None | Some("") => Err(BypassReason::MissingValue(format!("-Z{name}"))),
1834 Some(_) => Err(BypassReason::UnknownFlag(format!("-Z{option}"))),
1835 };
1836 }
1837 if name == "mir-enable-passes" {
1840 return match value {
1841 Some(list)
1842 if list
1843 .split(',')
1844 .all(|entry| entry.len() > 1 && entry.starts_with(['+', '-'])) =>
1845 {
1846 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1847 Ok(())
1848 }
1849 None | Some("") => Err(BypassReason::MissingValue(format!("-Z{name}"))),
1850 Some(_) => Err(BypassReason::UnknownFlag(format!("-Z{option}"))),
1851 };
1852 }
1853 if option.starts_with("threads=") {
1854 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1855 return Ok(());
1856 }
1857 if let Some(backend) = option.strip_prefix("codegen-backend=")
1859 && !backend.is_empty()
1860 && !backend.contains(['.', '/', '\\'])
1861 {
1862 self.sysroot_backend = Some(format!("-Z{option}"));
1863 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1864 return Ok(());
1865 }
1866 return Err(BypassReason::UnknownFlag(format!("-Z{option}")));
1867 }
1868 match value {
1869 "-h" | "-V" | "-vV" => return Err(BypassReason::CompilerQuery),
1872 "-g" | "-O" | "-v" => {
1873 self.parsed.push(Argument::Plain(value.into()));
1874 return Ok(());
1875 }
1876 _ => {}
1877 }
1878 for (short, long) in [
1879 ("-A", "--allow"),
1880 ("-W", "--warn"),
1881 ("-D", "--deny"),
1882 ("-F", "--forbid"),
1883 ] {
1884 if let Some(attached) = value.strip_prefix(short) {
1885 let lint = self.take_value(short, (!attached.is_empty()).then_some(attached))?;
1886 self.parsed.push(Argument::Plain(format!("{long}={lint}")));
1887 return Ok(());
1888 }
1889 }
1890 if let Some(attached) = value.strip_prefix("-C") {
1891 let option = self.take_value("-C", (!attached.is_empty()).then_some(attached))?;
1892 return self.parse_codegen(&option);
1893 }
1894 if let Some(attached) = value.strip_prefix("-L") {
1895 let search = self.take_value("-L", (!attached.is_empty()).then_some(attached))?;
1896 let (kind, path) = search
1897 .split_once('=')
1898 .map_or(("all", search.as_str()), |(kind, path)| (kind, path));
1899 if kind != "dependency" && !searches_native(kind) {
1900 return Err(BypassReason::UnsupportedSearchPath(kind.into()));
1901 }
1902 self.parsed.push(Argument::SearchPath {
1903 kind: kind.into(),
1904 path: path.into(),
1905 });
1906 return Ok(());
1907 }
1908 if let Some(attached) = value.strip_prefix("-l") {
1909 let library = self.take_value("-l", (!attached.is_empty()).then_some(attached))?;
1910 self.parsed.push(Argument::Plain(format!("-l{library}")));
1911 self.native_libraries.push(library);
1912 return Ok(());
1913 }
1914 if let Some(attached) = value.strip_prefix("-o") {
1915 let path = self.take_value("-o", (!attached.is_empty()).then_some(attached))?;
1916 self.explicit_output = Some(path.clone().into());
1917 self.parsed.push(Argument::Path {
1918 flag: "-o".into(),
1919 path: path.into(),
1920 });
1921 return Ok(());
1922 }
1923 Err(BypassReason::UnknownFlag(value.into()))
1924 }
1925
1926 fn parse_codegen(&mut self, value: &str) -> Result<(), BypassReason> {
1927 let name = value.split_once('=').map_or(value, |(name, _)| name);
1928 if name == "incremental" {
1929 return Err(BypassReason::Incremental);
1930 }
1931 if name == "profile-use" {
1932 let Some((_, profile)) = value.split_once('=') else {
1933 return Err(BypassReason::MissingValue("-Cprofile-use".into()));
1934 };
1935 if profile.is_empty() {
1936 return Err(BypassReason::MissingValue("-Cprofile-use".into()));
1937 }
1938 let path = PathBuf::from(profile);
1939 self.required_inputs.push(path.clone());
1940 self.parsed.push(Argument::Path {
1941 flag: "-Cprofile-use".into(),
1942 path,
1943 });
1944 return Ok(());
1945 }
1946 if SUPPORTED_CODEGEN_OPTIONS.binary_search(&name).is_err()
1947 && !matches!(name, "linker" | "linker-flavor")
1948 {
1949 return Err(BypassReason::UnknownCodegenOption(name.into()));
1950 }
1951 if name == "linker-plugin-lto"
1957 && let Some((_, selection)) = value.split_once('=')
1958 && !matches!(
1959 selection,
1960 "" | "y" | "yes" | "on" | "true" | "n" | "no" | "off" | "false"
1961 )
1962 {
1963 return Err(BypassReason::UnknownCodegenOption(format!(
1964 "linker-plugin-lto={selection}"
1965 )));
1966 }
1967 if name == "link-arg"
1974 && let Some((_, option)) = value.split_once('=')
1975 && let Some(selection) = option.strip_prefix("-fuse-ld=")
1976 && !selection.is_empty()
1977 && !selection.contains(',')
1978 && !self.parsed.iter().any(
1979 |argument| matches!(argument, Argument::FuseLd(existing) if existing != selection),
1980 )
1981 {
1982 if !self.parsed.iter().any(
1983 |argument| matches!(argument, Argument::FuseLd(existing) if existing == selection),
1984 ) {
1985 self.parsed.push(Argument::FuseLd(selection.to_owned()));
1986 }
1987 return Ok(());
1988 }
1989 if name == "link-arg"
1992 && let Some(option) = value.strip_prefix("link-arg=-Wl,-install_name,@rpath/")
1993 && safe_install_name(option)
1994 {
1995 self.parsed.push(Argument::InstallName(option.to_owned()));
1996 return Ok(());
1997 }
1998 if name == "link-arg"
2002 && let Some(directory) = value.strip_prefix("link-arg=-Wl,-rpath,")
2003 && directory.starts_with('/')
2004 && !directory.contains(',')
2005 {
2006 self.parsed.push(Argument::Rpath(directory.to_owned()));
2007 return Ok(());
2008 }
2009 if matches!(name, "link-arg" | "link-args")
2014 && let Some((_, option)) = value.split_once('=')
2015 && let Some(prefix) = option.strip_prefix("-Wl,-oso_prefix,")
2016 && !prefix.trim_end_matches('/').is_empty()
2017 && !prefix.contains(',')
2018 {
2019 let trailing_slash = prefix.ends_with('/');
2020 self.parsed.push(Argument::OsoPrefix {
2021 path: PathBuf::from(prefix.trim_end_matches('/')),
2022 trailing_slash,
2023 });
2024 return Ok(());
2025 }
2026 self.parsed
2027 .push(Argument::Plain(format!("--codegen={value}")));
2028 if name == "extra-filename" {
2029 self.extra_filename = value
2030 .split_once('=')
2031 .map_or(String::new(), |(_, value)| value.to_string());
2032 }
2033 Ok(())
2034 }
2035
2036 fn require_native_libraries(&mut self, link_output: LinkOutput) -> Result<(), BypassReason> {
2051 for library in std::mem::take(&mut self.native_libraries) {
2052 if link_output != LinkOutput::Library {
2053 return Err(BypassReason::NativeLibrary(library));
2054 }
2055 let Some((kind, name)) = library.split_once('=') else {
2063 continue;
2064 };
2065 let (kind, modifiers) = kind.split_once(':').unwrap_or((kind, ""));
2066 match kind {
2067 "static" => {}
2068 "dylib" | "framework" | "link-arg" => continue,
2069 _ => return Err(BypassReason::UnknownFlag(format!("-l{library}"))),
2070 }
2071 let name = name.split_once(':').map_or(name, |(_, renamed)| renamed);
2074 let (mut verbatim, mut bundle) = (false, true);
2075 for modifier in modifiers.split(',') {
2076 match modifier {
2077 "+verbatim" => verbatim = true,
2078 "-verbatim" => verbatim = false,
2079 "+bundle" => bundle = true,
2080 "-bundle" => bundle = false,
2081 _ => {}
2082 }
2083 }
2084 if !bundle {
2085 continue;
2086 }
2087 let archive = self
2088 .find_native_static_library(name, verbatim)
2089 .map_err(|()| BypassReason::CustomTargetNativeLibrary(library.clone()))?
2090 .ok_or_else(|| BypassReason::MissingNativeLibrary(library.clone()))?;
2091 self.required_inputs.push(archive);
2092 }
2093 Ok(())
2094 }
2095
2096 fn find_native_static_library(
2108 &self,
2109 name: &str,
2110 verbatim: bool,
2111 ) -> Result<Option<PathBuf>, ()> {
2112 let file_names = if verbatim {
2113 vec![name.to_owned()]
2114 } else {
2115 match self.static_library_naming() {
2116 Some(StaticLibraryNaming::Msvc) => {
2117 vec![format!("{name}.lib"), format!("lib{name}.a")]
2118 }
2119 Some(StaticLibraryNaming::Unix) => vec![format!("lib{name}.a")],
2120 None => return Err(()),
2121 }
2122 };
2123 Ok(self
2124 .parsed
2125 .iter()
2126 .filter_map(|argument| match argument {
2127 Argument::SearchPath { kind, path } if searches_native(kind) => Some(path),
2128 _ => None,
2129 })
2130 .flat_map(|directory| {
2131 file_names
2132 .iter()
2133 .map(move |file_name| directory.join(file_name))
2134 })
2135 .find(|candidate| candidate.is_file()))
2136 }
2137
2138 fn static_library_naming(&self) -> Option<StaticLibraryNaming> {
2146 let Some(target) = self.target.as_deref() else {
2147 return Some(if cfg!(any(target_env = "msvc", target_os = "uefi")) {
2148 StaticLibraryNaming::Msvc
2149 } else {
2150 StaticLibraryNaming::Unix
2151 });
2152 };
2153 if target.ends_with(".json")
2154 || target.contains(['/', '\\'])
2155 || self.options.custom_target_search
2156 {
2157 return None;
2158 }
2159 Some(if target.contains("msvc") || target.ends_with("-uefi") {
2162 StaticLibraryNaming::Msvc
2163 } else {
2164 StaticLibraryNaming::Unix
2165 })
2166 }
2167
2168 fn parse_input(&mut self, value: &str) -> Result<(), BypassReason> {
2169 if value == "-" {
2170 return Err(BypassReason::StandardInput);
2171 }
2172 if self.source.replace(value.into()).is_some() {
2173 return Err(BypassReason::MultipleInputs);
2174 }
2175 Ok(())
2176 }
2177
2178 fn classify(&self) -> Result<LinkOutput, BypassReason> {
2179 let never_links = !self.emits.iter().any(|emit| emit.kind == "link");
2188 let builds_a_library = !self.test
2189 && !self.crate_types.is_empty()
2190 && self
2191 .crate_types
2192 .iter()
2193 .all(|crate_type| matches!(crate_type.as_str(), "lib" | "rlib"));
2194 let link_output = if never_links || builds_a_library {
2195 LinkOutput::Library
2196 } else if self
2197 .target
2198 .as_deref()
2199 .is_some_and(compiler_bundled_wasm_target)
2200 && ((self.test && self.crate_types.is_empty())
2201 || matches!(self.crate_types.as_slice(), [kind] if kind == "bin" || kind == "cdylib"))
2202 {
2203 if self.parsed.iter().any(|argument| match argument {
2204 Argument::Plain(value) if value == "--codegen=link-self-contained" => false,
2205 Argument::Plain(value) if value.starts_with("--codegen=link-self-contained=") => {
2206 !matches!(
2207 value.rsplit_once('=').map(|(_, value)| value),
2208 Some("y" | "yes" | "on" | "true")
2209 )
2210 }
2211 _ => false,
2212 }) {
2213 return Err(BypassReason::UnknownCodegenOption(
2214 "link-self-contained".into(),
2215 ));
2216 }
2217 if self.target.as_deref().is_some_and(|target| target.contains("wasi"))
2218 && self.parsed.iter().any(|argument| {
2219 matches!(argument, Argument::Plain(value) if value.strip_prefix("--codegen=target-feature=").is_some_and(|features| features.split(',').any(|feature| feature == "-crt-static")))
2220 })
2221 {
2222 return Err(BypassReason::UnknownCodegenOption(
2223 "target-feature=-crt-static".into(),
2224 ));
2225 }
2226 LinkOutput::WasmExecutable
2230 } else if self.options.cache_native_links && self.links_a_native_artifact() {
2231 self.check_native_link_is_portable()?;
2232 if matches!(self.crate_types.as_slice(), [kind] if kind == "proc-macro") {
2233 LinkOutput::NativeProcMacro
2234 } else if matches!(self.crate_types.as_slice(), [kind] if kind == "cdylib") {
2235 LinkOutput::NativeSharedLibrary
2236 } else {
2237 LinkOutput::NativeExecutable
2238 }
2239 } else if self.test {
2240 return Err(BypassReason::UnsupportedCrateType("test".into()));
2241 } else {
2242 return Err(BypassReason::UnsupportedCrateType(
2243 self.crate_types
2244 .iter()
2245 .find(|crate_type| !matches!(crate_type.as_str(), "lib" | "rlib"))
2246 .cloned()
2247 .unwrap_or_else(|| "bin".into()),
2248 ));
2249 };
2250 if link_output != LinkOutput::Library
2259 && let Some(option) = self.first_link_argument(link_output)
2260 {
2261 return Err(BypassReason::UnmodeledLinkArgument(option.to_owned()));
2262 }
2263 if self
2264 .parsed
2265 .iter()
2266 .any(|arg| matches!(arg, Argument::InstallName(_)))
2267 && !(cfg!(target_os = "macos") && link_output == LinkOutput::NativeProcMacro)
2268 {
2269 return Err(BypassReason::UnmodeledLinkArgument(
2270 "link-arg=-Wl,-install_name".into(),
2271 ));
2272 }
2273 if self
2277 .parsed
2278 .iter()
2279 .any(|argument| matches!(argument, Argument::Rpath(_)))
2280 && !(link_output == LinkOutput::Library
2281 || cfg!(target_os = "macos")
2282 && matches!(
2283 link_output,
2284 LinkOutput::NativeExecutable
2285 | LinkOutput::NativeProcMacro
2286 | LinkOutput::NativeSharedLibrary
2287 ))
2288 {
2289 return Err(BypassReason::UnmodeledLinkArgument(
2290 "link-arg=-Wl,-rpath".into(),
2291 ));
2292 }
2293 if let Some(selection) = self.parsed.iter().find_map(|argument| {
2300 let Argument::FuseLd(selection) = argument else {
2301 return None;
2302 };
2303 Some(selection.as_str())
2304 }) && !matches!(
2305 link_output,
2306 LinkOutput::Library
2307 | LinkOutput::NativeExecutable
2308 | LinkOutput::NativeProcMacro
2309 | LinkOutput::NativeSharedLibrary
2310 ) {
2311 return Err(BypassReason::UnmodeledLinkArgument(format!(
2312 "link-arg=-fuse-ld={selection}"
2313 )));
2314 }
2315 if self.parsed.iter().any(|argument| {
2316 matches!(argument, Argument::Plain(value) if value.starts_with("--codegen=linker="))
2317 }) && !matches!(
2318 link_output,
2319 LinkOutput::Library
2320 | LinkOutput::NativeExecutable
2321 | LinkOutput::NativeProcMacro
2322 | LinkOutput::NativeSharedLibrary
2323 ) {
2324 return Err(BypassReason::UnknownCodegenOption("linker".into()));
2325 }
2326 if link_output != LinkOutput::Library
2331 && self.parsed.iter().any(|argument| {
2332 matches!(argument, Argument::Plain(value) if value.starts_with("--codegen=linker-flavor="))
2333 })
2334 {
2335 return Err(BypassReason::UnknownCodegenOption("linker-flavor".into()));
2336 }
2337 if !matches!(
2341 link_output,
2342 LinkOutput::Library
2343 | LinkOutput::NativeExecutable
2344 | LinkOutput::NativeProcMacro
2345 | LinkOutput::NativeSharedLibrary
2346 ) && self
2347 .parsed
2348 .iter()
2349 .any(|argument| matches!(argument, Argument::OsoPrefix { .. }))
2350 {
2351 return Err(BypassReason::UnmodeledLinkArgument(
2352 "link-arg=-Wl,-oso_prefix".into(),
2353 ));
2354 }
2355 if let Some(name) = self.parsed.iter().find_map(|argument| match argument {
2356 Argument::Extern { name, path: None } if name != "proc_macro" => Some(name),
2357 _ => None,
2358 }) {
2359 return Err(BypassReason::UnresolvedExtern(name.clone()));
2360 }
2361 if let Some(emit) = self
2362 .emits
2363 .iter()
2364 .find(|emit| !matches!(emit.kind.as_str(), "dep-info" | "link" | "metadata"))
2365 {
2366 return Err(BypassReason::UnsupportedEmit(emit.kind.clone()));
2367 }
2368 if !self
2369 .emits
2370 .iter()
2371 .any(|emit| matches!(emit.kind.as_str(), "link" | "metadata"))
2372 {
2373 return Err(BypassReason::NoCacheableOutput);
2374 }
2375 Ok(link_output)
2376 }
2377}
2378
2379impl Parser<'_> {
2380 fn first_link_argument(&self, link_output: LinkOutput) -> Option<&str> {
2383 self.parsed.iter().find_map(|argument| {
2384 let Argument::Plain(value) = argument else {
2385 return None;
2386 };
2387 let option = value.strip_prefix("--codegen=")?;
2388 let (name, value) = option.split_once('=').unwrap_or((option, ""));
2389 (matches!(name, "link-arg" | "link-args")
2390 && !(name == "link-arg" && elf_keyword_is_modeled(link_output, value))
2391 && !msvc_options_are_modeled(link_output, name, value))
2392 .then_some(option)
2393 })
2394 }
2395
2396 fn oso_prefix_covers_outputs(&self) -> bool {
2405 let Some(directory) = self
2406 .out_dir
2407 .as_deref()
2408 .or_else(|| self.explicit_output.as_deref().and_then(Path::parent))
2409 else {
2410 return false;
2411 };
2412 if !directory.is_absolute() {
2413 return false;
2414 }
2415 let directory = normalize_components(directory);
2416 self.parsed.iter().any(|argument| {
2417 let Argument::OsoPrefix { path, .. } = argument else {
2418 return false;
2419 };
2420 path.is_absolute()
2421 && (directory.starts_with(normalize_components(path))
2422 || std::fs::canonicalize(&directory)
2423 .ok()
2424 .zip(std::fs::canonicalize(path).ok())
2425 .is_some_and(|(directory, prefix)| directory.starts_with(prefix)))
2426 })
2427 }
2428
2429 fn links_a_native_artifact(&self) -> bool {
2436 self.target.is_none()
2437 && self.emits.iter().any(|emit| emit.kind == "link")
2442 && ((self.test && self.crate_types.is_empty())
2443 || matches!(self.crate_types.as_slice(), [kind] if matches!(kind.as_str(), "bin" | "proc-macro"))
2444 || (cfg!(target_os = "linux")
2445 && matches!(self.crate_types.as_slice(), [kind] if kind == "cdylib")))
2446 }
2447
2448 fn check_native_link_is_portable(&self) -> Result<(), BypassReason> {
2455 for argument in &self.parsed {
2456 let Argument::Plain(value) = argument else {
2457 continue;
2458 };
2459 let (name, value) = if value == "-g" {
2462 ("debuginfo", Some("2"))
2463 } else if let Some(option) = value.strip_prefix("--codegen=") {
2464 match option.split_once('=') {
2465 Some((name, value)) => (name, Some(value)),
2466 None => (option, None),
2470 }
2471 } else {
2472 continue;
2473 };
2474 let unportable = match name {
2475 "split-debuginfo" => match value {
2481 Some("off") => false,
2482 Some("unpacked") if cfg!(target_os = "macos") => {
2483 !self.oso_prefix_covers_outputs()
2484 }
2485 _ => true,
2486 },
2487 "debuginfo" if cfg!(target_os = "macos") => {
2496 !matches!(value, Some("0" | "none")) && !self.oso_prefix_covers_outputs()
2497 }
2498 "rpath" => is_enabled(value),
2506 "prefer-dynamic" => {
2507 is_enabled(value)
2508 && !matches!(self.crate_types.as_slice(), [kind] if kind == "proc-macro")
2509 }
2510 "link-self-contained" => true,
2513 _ => false,
2514 };
2515 if unportable {
2516 return Err(BypassReason::UnportableNativeLink(match value {
2517 Some(value) => format!("{name}={value}"),
2518 None => name.to_owned(),
2519 }));
2520 }
2521 }
2522 Ok(())
2523 }
2524}
2525
2526fn safe_install_name(name: &str) -> bool {
2527 !name.is_empty()
2528 && name
2529 .bytes()
2530 .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))
2531}
2532
2533fn is_enabled(value: Option<&str>) -> bool {
2536 matches!(value, None | Some("y" | "yes" | "on" | "true"))
2537}
2538
2539fn elf_keyword_is_modeled(link_output: LinkOutput, value: &str) -> bool {
2549 cfg!(target_os = "linux")
2550 && matches!(
2551 link_output,
2552 LinkOutput::NativeExecutable
2553 | LinkOutput::NativeProcMacro
2554 | LinkOutput::NativeSharedLibrary
2555 )
2556 && value.strip_prefix("-Wl,-z,").is_some_and(|keyword| {
2557 matches!(
2558 keyword,
2559 "defs"
2560 | "lazy"
2561 | "nodelete"
2562 | "nodlopen"
2563 | "noexecstack"
2564 | "norelro"
2565 | "now"
2566 | "origin"
2567 | "relro"
2568 )
2569 })
2570}
2571
2572fn msvc_options_are_modeled(link_output: LinkOutput, name: &str, value: &str) -> bool {
2588 cfg!(target_env = "msvc")
2589 && matches!(
2590 link_output,
2591 LinkOutput::NativeExecutable
2592 | LinkOutput::NativeProcMacro
2593 | LinkOutput::NativeSharedLibrary
2594 )
2595 && match name {
2596 "link-arg" => msvc_option_reads_no_file(value),
2597 "link-args" => {
2600 let mut options = value.split_ascii_whitespace().peekable();
2601 options.peek().is_some() && options.all(msvc_option_reads_no_file)
2602 }
2603 _ => false,
2604 }
2605}
2606
2607fn msvc_option_reads_no_file(option: &str) -> bool {
2611 let Some(option) = option.strip_prefix(['/', '-']) else {
2612 return false;
2613 };
2614 if option.eq_ignore_ascii_case("brepro") {
2615 return true;
2616 }
2617 let Some((name, sizes)) = option.split_once(':') else {
2618 return false;
2619 };
2620 let is_size = |size: &str| match size.strip_prefix("0x").or_else(|| size.strip_prefix("0X")) {
2623 Some(hex) => !hex.is_empty() && hex.bytes().all(|byte| byte.is_ascii_hexdigit()),
2624 None => !size.is_empty() && size.bytes().all(|byte| byte.is_ascii_digit()),
2625 };
2626 name.eq_ignore_ascii_case("stack")
2627 && sizes.split(',').count() <= 2
2628 && sizes.split(',').all(is_size)
2629}
2630
2631fn compiler_bundled_wasm_target(target: &str) -> bool {
2632 COMPILER_BUNDLED_WASM_TARGETS.binary_search(&target).is_ok()
2633}
2634
2635fn parse_emits(value: &str) -> Vec<Emit> {
2636 value
2637 .split(',')
2638 .map(|emit| {
2639 let (kind, path) = emit
2640 .split_once('=')
2641 .map_or((emit, None), |(kind, path)| (kind, Some(path.into())));
2642 Emit {
2643 kind: kind.into(),
2644 path,
2645 }
2646 })
2647 .collect()
2648}
2649
2650struct ActionBuilder<'a> {
2651 invocation: &'a RustcInvocation,
2652 store_root: &'a str,
2653 context: ActionContext,
2654 mappings: Vec<SharedPathMapping>,
2655 aliases: PathAliases,
2659 linker: Option<LinkerIdentity>,
2660 incremental_state: Option<String>,
2661}
2662
2663impl<'a> ActionBuilder<'a> {
2664 fn new(invocation: &'a RustcInvocation, mut context: ActionContext) -> Self {
2665 context.path_mappings = PathMapping::ordered(&context.path_mappings);
2666 let mappings = resolve_path_mappings(&shared_path_mappings(&context.path_mappings));
2667 Self {
2668 linker: None,
2669 incremental_state: None,
2670 invocation,
2671 store_root: NIX_STORE_ROOT,
2672 mappings,
2673 aliases: PathAliases::default(),
2674 context,
2675 }
2676 }
2677
2678 fn linked_by(mut self, linker: Option<LinkerIdentity>) -> Self {
2679 self.linker = linker;
2680 self
2681 }
2682
2683 fn carrying_incremental_state(mut self, generation: Option<String>) -> Self {
2684 self.incremental_state = generation;
2685 self
2686 }
2687
2688 fn build(self) -> Result<RustcAction, BypassReason> {
2689 self.validate_mappings()?;
2690 let invocation = self.invocation_descriptor()?;
2691 let environment = self.environment_descriptor()?;
2692
2693 let mut inputs = BTreeMap::<String, CacheDigest>::new();
2694 for input in &self.context.inputs {
2695 input
2696 .digest
2697 .validate()
2698 .map_err(|_| BypassReason::InvalidInputDigest(input.path.display().to_string()))?;
2699 let path = self.normalize_input_path(&input.path)?;
2700 if inputs
2701 .insert(path.clone(), input.digest.clone())
2702 .is_some_and(|existing| existing != input.digest)
2703 {
2704 return Err(BypassReason::ConflictingInput(path));
2705 }
2706 }
2707 let required = self
2708 .invocation
2709 .required_inputs
2710 .iter()
2711 .map(|path| self.normalize_input_path(path))
2712 .collect::<Result<BTreeSet<_>, _>>()?;
2713 if let Some(missing) = required.iter().find(|path| !inputs.contains_key(*path)) {
2714 return Err(BypassReason::MissingRequiredInput(missing.clone()));
2715 }
2716 let inputs = inputs
2717 .into_iter()
2718 .map(|(path, digest)| InputDescriptor { path, digest })
2719 .collect();
2720 if self.invocation.links_natively() && self.linker.is_none() {
2723 return Err(BypassReason::UnportableNativeLink(
2724 "linker identity is unknown".into(),
2725 ));
2726 }
2727 let descriptor = ActionDescriptor {
2728 version: ACTION_SCHEMA_VERSION,
2729 kind: "rustc",
2730 adapter_version: ADAPTER_VERSION,
2731 compiler: invocation.compiler,
2732 arguments: invocation.arguments,
2733 environment,
2734 inputs,
2735 linker: self.linker.clone(),
2736 incremental_state: self.incremental_state.clone(),
2737 };
2738 let bytes = canonical_json(&descriptor)
2739 .map_err(|error| BypassReason::Serialization(error.to_string()))?;
2740 let digest = CacheDigest::blake3(&bytes);
2741 Ok(RustcAction { digest, bytes })
2742 }
2743
2744 fn invocation_descriptor(&self) -> Result<InvocationDescriptor, BypassReason> {
2745 self.validate_mappings()?;
2746 let arguments = self
2747 .invocation
2748 .arguments
2749 .iter()
2750 .map(|argument| self.normalize_argument(argument))
2751 .collect::<Result<Vec<_>, _>>()?;
2752 let required_inputs = self
2753 .invocation
2754 .required_inputs
2755 .iter()
2756 .map(|path| self.normalize_file_path(path))
2757 .collect::<Result<BTreeSet<_>, _>>()?
2758 .into_iter()
2759 .collect();
2760 Ok(InvocationDescriptor {
2761 version: ACTION_SCHEMA_VERSION,
2762 kind: "rustc",
2763 adapter_version: ADAPTER_VERSION,
2764 compiler: CompilerDescriptor {
2765 toolchain: self.context.compiler.toolchain.clone(),
2766 rustc_version: self.context.compiler.rustc_version.clone(),
2767 host: self.context.compiler.host.clone(),
2768 driver: self.context.compiler.driver.clone(),
2769 },
2770 arguments,
2771 required_inputs,
2772 })
2773 }
2774
2775 fn validate_mappings(&self) -> Result<(), BypassReason> {
2776 if !self.context.working_dir.is_absolute() {
2777 return Err(BypassReason::RelativeWorkingDirectory(
2778 self.context.working_dir.clone(),
2779 ));
2780 }
2781 let mut roots = BTreeSet::new();
2782 let mut placeholders = BTreeSet::new();
2783 for mapping in &self.mappings {
2784 if !mapping.root.is_absolute() {
2785 return Err(BypassReason::RelativePathMapping(mapping.root.clone()));
2786 }
2787 if mapping.placeholder.is_empty()
2788 || !mapping
2789 .placeholder
2790 .bytes()
2791 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
2792 || !roots.insert(normalize_components(&mapping.root))
2793 || !placeholders.insert(&mapping.placeholder)
2794 {
2795 return Err(BypassReason::InvalidPathPlaceholder(
2796 mapping.placeholder.clone(),
2797 ));
2798 }
2799 }
2800 Ok(())
2801 }
2802
2803 fn normalize_argument(&self, argument: &Argument) -> Result<String, BypassReason> {
2804 match argument {
2805 Argument::Plain(value) => Ok(value.clone()),
2806 Argument::Path { flag, path } if flag == "--sysroot" => {
2807 Ok(format!("{flag}={}", self.normalize_sysroot_path(path)?))
2808 }
2809 Argument::Path { flag, path } => Ok(format!("{flag}={}", self.normalize_path(path)?)),
2810 Argument::SearchPath { kind, path } => {
2811 let text = self.normalize_path(path)?;
2812 Ok(format!("-L{kind}={text}"))
2813 }
2814 Argument::Extern { name, path } => match path {
2815 Some(path) => Ok(format!(
2816 "--extern={name}={}",
2817 self.normalize_file_path(path)?
2818 )),
2819 None => Ok(format!("--extern={name}")),
2820 },
2821 Argument::Emit(emits) => Ok(format!(
2822 "--emit={}",
2823 emits
2824 .iter()
2825 .map(|emit| match &emit.path {
2826 Some(path) => self
2827 .normalize_path(path)
2828 .map(|path| format!("{}={path}", emit.kind)),
2829 None => Ok(emit.kind.clone()),
2830 })
2831 .collect::<Result<Vec<_>, _>>()?
2832 .join(",")
2833 )),
2834 Argument::RemapPath { from, to } => Ok(format!(
2835 "--remap-path-prefix={}={}",
2836 self.normalize_path(from)?,
2837 to
2838 )),
2839 Argument::InstallName(name) => Ok(format!(
2840 "--codegen=link-arg=-Wl,-install_name,@rpath/{name}"
2841 )),
2842 Argument::OsoPrefix {
2843 path,
2844 trailing_slash,
2845 } => Ok(format!(
2846 "--codegen=link-arg=-Wl,-oso_prefix,{}{}",
2847 self.normalize_path(path)?,
2848 if *trailing_slash { "/" } else { "" }
2849 )),
2850 Argument::FuseLd(selection) => Ok(format!("--codegen=link-arg=-fuse-ld={selection}")),
2851 Argument::Rpath(directory) => Ok(format!("--codegen=link-arg=-Wl,-rpath,{directory}")),
2853 }
2854 }
2855
2856 fn environment_descriptor(&self) -> Result<BTreeMap<String, Option<String>>, BypassReason> {
2863 self.context
2864 .environment
2865 .iter()
2866 .map(|(name, value)| {
2867 let value = match value {
2868 Some(value) if self.context.portable_environment.contains(name) => {
2869 Some(self.normalize_path(Path::new(value))?)
2870 }
2871 value => value.clone(),
2872 };
2873 Ok((name.clone(), value))
2874 })
2875 .collect()
2876 }
2877
2878 fn normalize_input_path(&self, path: &Path) -> Result<String, BypassReason> {
2879 let absolute = normalize_components(&self.context.working_dir.join(path));
2880 for directory in self.invocation.native_search_paths() {
2881 let directory = normalize_components(&self.context.working_dir.join(directory));
2882 if let Ok(relative) = absolute.strip_prefix(&directory) {
2883 let suffix = relative
2889 .components()
2890 .map(|component| {
2891 component
2892 .as_os_str()
2893 .to_str()
2894 .ok_or_else(|| BypassReason::NonUtf8Path(path.to_path_buf()))
2895 })
2896 .collect::<Result<Vec<_>, _>>()?
2897 .join("/");
2898 if !suffix.is_empty() {
2899 return Ok(format!("{}/{}", self.normalize_path(&directory)?, suffix));
2900 }
2901 }
2902 }
2903 self.normalize_file_path(path)
2904 }
2905
2906 fn normalize_sysroot_path(&self, path: &Path) -> Result<String, BypassReason> {
2907 let absolute = self.context.working_dir.join(path);
2908 if !absolute.starts_with(self.store_root) {
2909 return self.normalize_path(path);
2910 }
2911 if let Some(value) = absolute.to_str()
2914 && resolve_nix_store_path(value, self.store_root).is_some_and(|path| path.is_dir())
2915 {
2916 return Ok(value.to_owned());
2917 }
2918 Err(BypassReason::UnmappedAbsolutePath(absolute))
2919 }
2920
2921 fn normalize_file_path(&self, path: &Path) -> Result<String, BypassReason> {
2922 self.normalize_path(path)
2923 .or_else(|reason| key_nix_store_path(path, &self.context.working_dir, reason))
2924 }
2925
2926 fn normalize_path(&self, path: &Path) -> Result<String, BypassReason> {
2927 normalize_resolved_shared_path_with(
2928 &self.aliases,
2929 path,
2930 &self.context.working_dir,
2931 &self.mappings,
2932 )
2933 .map_err(Into::into)
2934 }
2935}
2936
2937fn under_any_directory(path: &str, directories: &BTreeSet<String>) -> bool {
2941 directories.iter().any(|directory| {
2942 path.len() > directory.len()
2943 && path.as_bytes()[directory.len()] == b'/'
2944 && path.starts_with(directory)
2945 })
2946}
2947
2948fn denormalize_path(
2949 value: &str,
2950 mappings: &[PathMapping],
2951 store_root: &str,
2952) -> Result<PathBuf, BypassReason> {
2953 for mapping in mappings {
2954 let prefix = format!("${{{}}}", mapping.placeholder);
2955 let suffix = if value == prefix {
2956 ""
2957 } else if let Some(suffix) = value.strip_prefix(&format!("{prefix}/")) {
2958 suffix
2959 } else {
2960 continue;
2961 };
2962 if !mapping.root.is_absolute()
2963 || (!suffix.is_empty()
2964 && suffix.split('/').any(|component| {
2965 component.is_empty()
2966 || matches!(component, "." | "..")
2967 || component.contains('\\')
2968 }))
2969 {
2970 return Err(BypassReason::InvalidPredictedInput(value.into()));
2971 }
2972 let mut path = normalize_components(&mapping.root);
2973 path.extend(suffix.split('/').filter(|component| !component.is_empty()));
2974 return Ok(path);
2975 }
2976 if resolve_nix_store_path(value, store_root).is_some() {
2979 return Ok(PathBuf::from(value));
2980 }
2981 Err(BypassReason::InvalidPredictedInput(value.into()))
2982}
2983
2984fn resolve_nix_store_path(value: &str, store_root: &str) -> Option<PathBuf> {
2985 let resolved = nix_store_path(value, store_root)?.canonicalize().ok()?;
2986 nix_store_path(resolved.to_str()?, store_root)?;
2987 Some(resolved)
2988}
2989
2990fn nix_store_path<'a>(value: &'a str, store_root: &str) -> Option<&'a Path> {
2991 let path = Path::new(value);
2992 if !path.is_absolute() {
2993 return None;
2994 }
2995 let suffix = value.strip_prefix(store_root)?.strip_prefix('/')?;
2996 (!suffix.split('/').any(|component| {
2997 component.is_empty() || matches!(component, "." | "..") || component.contains('\0')
2998 }))
2999 .then_some(path)
3000}
3001
3002fn key_nix_store_path(
3003 path: &Path,
3004 working_dir: &Path,
3005 reason: BypassReason,
3006) -> Result<String, BypassReason> {
3007 if matches!(reason, BypassReason::UnmappedAbsolutePath(_)) {
3008 let absolute = working_dir.join(path);
3009 if let Some(value) = absolute.to_str()
3010 && nix_store_path(value, NIX_STORE_ROOT).is_some()
3011 {
3012 return Ok(value.to_owned());
3013 }
3014 }
3015 Err(reason)
3016}
3017
3018fn normalize_components(path: &Path) -> PathBuf {
3019 let mut normalized = PathBuf::new();
3020 for component in path.components() {
3021 match component {
3022 Component::CurDir => {}
3023 Component::ParentDir => {
3024 normalized.pop();
3025 }
3026 component => normalized.push(component.as_os_str()),
3027 }
3028 }
3029 normalized
3030}
3031
3032fn absolute_path(path: &Path, working_dir: &Path) -> PathBuf {
3033 if path.is_absolute() {
3034 normalize_components(path)
3035 } else {
3036 normalize_components(&working_dir.join(path))
3037 }
3038}
3039
3040#[cfg(test)]
3041#[path = "rustc_cache_tests.rs"]
3042mod tests;