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
45pub use dep_info::{DepInfoCommand, DiscoveredInputs, RustcDepInfo};
46
47pub const ACTION_SCHEMA_VERSION: u8 = 1;
49pub const ADAPTER_VERSION: u8 = 2;
56
57impl BypassReason {
58 pub fn kind(&self) -> &'static str {
63 self.into()
64 }
65
66 pub fn remediation(&self) -> Option<&'static str> {
72 match self {
73 Self::Incremental => Some(
74 "Set `MBX_INCREMENTAL=0`; mbx will then disable Cargo incremental state and cache the compilation.",
75 ),
76 Self::UnportableNativeLink(detail) if detail.contains("linker") => Some(
77 "Make the native linker resolvable on `PATH`, or configure a linker mbx can identify for this target.",
78 ),
79 Self::UnportableNativeLink(_) => Some(
80 "Remove the reported `-C` option from the active Cargo profile or `RUSTFLAGS` to make these links cacheable.",
81 ),
82 Self::UnknownFlag(_) | Self::UnknownCodegenOption(_) => Some(
83 "Remove the reported compiler option, or upgrade mbx if the option should be modeled.",
84 ),
85 Self::UnmodeledLinkArgument(_) => Some(
86 "Remove the reported linker argument, or keep these links uncached if the argument is required.",
87 ),
88 Self::UnmappedAbsolutePath(_) => Some(
89 "Move the input under the workspace, target, Cargo, toolchain, or home roots so mbx can give it a portable cache name.",
90 ),
91 Self::BuildScriptInputOverlapsOutputs(_) => Some(
92 "Keep compiler output directories outside watched trees, or narrow `rerun-if-changed` to source and asset paths.",
93 ),
94 _ => None,
95 }
96 }
97}
98
99impl From<PathNormalizationError> for BypassReason {
100 fn from(reason: PathNormalizationError) -> Self {
101 match reason {
102 PathNormalizationError::UnmappedAbsolutePath(path) => Self::UnmappedAbsolutePath(path),
103 PathNormalizationError::NonUtf8Path(path) => Self::NonUtf8Path(path),
104 }
105 }
106}
107
108const SUPPORTED_CODEGEN_OPTIONS: &[&str] = &[
109 "codegen-units",
110 "control-flow-guard",
111 "debug-assertions",
112 "debuginfo",
113 "default-linker-libraries",
114 "embed-bitcode",
115 "extra-filename",
116 "force-frame-pointers",
117 "force-unwind-tables",
118 "instrument-coverage",
119 "link-arg",
120 "link-args",
121 "link-dead-code",
122 "link-self-contained",
123 "linker-plugin-lto",
124 "lto",
125 "metadata",
126 "no-prepopulate-passes",
127 "opt-level",
128 "overflow-checks",
129 "panic",
130 "prefer-dynamic",
131 "relocation-model",
132 "rpath",
133 "save-temps",
134 "soft-float",
135 "split-debuginfo",
136 "split-dwarf-kind",
137 "strip",
138 "symbol-mangling-version",
139 "target-cpu",
140 "target-feature",
141 "tls-model",
142];
143
144const NATIVE_DIRECTORY_PREDICTION_PREFIX: &str = "@native-directory:";
145const MAX_PREDICTED_INPUTS: usize = 16 * 1024;
146const MAX_DECODED_PREDICTION_BYTES: usize = 16 * 1024 * 1024;
150const MAX_NATIVE_INPUT_BYTES: u64 = 2 * 1024 * 1024 * 1024;
151
152const COMPILER_BUNDLED_WASM_TARGETS: &[&str] = &[
155 "wasm32-unknown-unknown",
156 "wasm32-wasip1",
157 "wasm32-wasip1-threads",
158 "wasm32-wasip2",
159 "wasm32v1-none",
160 "wasm64-unknown-unknown",
161];
162
163#[derive(Debug, Clone, PartialEq, Eq, Error, strum::IntoStaticStr)]
164#[strum(serialize_all = "kebab-case")]
165#[non_exhaustive]
175pub enum BypassReason {
176 #[error("rustc argument {index} is not valid UTF-8")]
178 NonUtf8Argument {
179 index: usize,
181 },
182 #[error("could not model rustc response file: {0}")]
184 ResponseFile(String),
185 #[error("rustc flag is not modeled by the cache adapter: {0}")]
187 UnknownFlag(String),
188 #[error("rustc codegen option is not modeled by the cache adapter: {0}")]
190 UnknownCodegenOption(String),
191 #[error("rustc flag requires a value: {0}")]
193 MissingValue(String),
194 #[error("rustc invocation is a compiler query, not a compilation")]
196 CompilerQuery,
197 #[error("rustc invocation reads source from standard input")]
199 StandardInput,
200 #[error("rustc invocation has no source input")]
202 MissingInput,
203 #[error("rustc invocation has multiple source inputs")]
205 MultipleInputs,
206 #[error("incremental compilation cannot be combined with action caching")]
208 Incremental,
209 #[error("rustc crate type is not cacheable yet: {0}")]
211 UnsupportedCrateType(String),
212 #[error("rustc output type is not cacheable yet: {0}")]
214 UnsupportedEmit(String),
215 #[error("rustc invocation does not emit a cacheable artifact")]
217 NoCacheableOutput,
218 #[error("rustc invocation does not emit dependency information")]
220 NoDepInfo,
221 #[error("rustc output paths do not share one directory")]
223 SplitOutputDirectories,
224 #[error("rustc output path has no file name: {0}")]
226 InvalidOutputPath(PathBuf),
227 #[error("rustc -o with an emit that has no explicit path is not modeled: {0}")]
229 ImplicitEmitWithOutputFile(PathBuf),
230 #[error("native library on a linked output is not cacheable yet: {0}")]
233 NativeLibrary(String),
234 #[error("native static library was not found on any search path: {0}")]
237 MissingNativeLibrary(String),
238 #[error("static library file names are not known for a custom target: {0}")]
241 CustomTargetNativeLibrary(String),
242 #[error("rustc output name does not distinguish a program from a library: {0}")]
244 AmbiguousOutputName(PathBuf),
245 #[error("native link is not reproducible across checkouts: {0}")]
247 UnportableNativeLink(String),
248 #[error("rustc link argument is not modeled by the cache adapter: {0}")]
250 UnmodeledLinkArgument(String),
251 #[error("rustc search path kind is not cacheable yet: {0}")]
253 UnsupportedSearchPath(String),
254 #[error("rustc extern does not identify an input artifact: {0}")]
256 UnresolvedExtern(String),
257 #[error("absolute path has no stable cache mapping: {0}")]
259 UnmappedAbsolutePath(PathBuf),
260 #[error("cache key paths must be valid UTF-8: {0}")]
262 NonUtf8Path(PathBuf),
263 #[error("cache action working directory must be absolute: {0}")]
265 RelativeWorkingDirectory(PathBuf),
266 #[error("cache path mapping must use an absolute root: {0}")]
268 RelativePathMapping(PathBuf),
269 #[error("cache path mapping placeholder is invalid: {0}")]
271 InvalidPathPlaceholder(String),
272 #[error("required compiler input was not provided: {0}")]
274 MissingRequiredInput(String),
275 #[error("compiler input has an invalid digest: {0}")]
277 InvalidInputDigest(String),
278 #[error("compiler input appears more than once with different content: {0}")]
280 ConflictingInput(String),
281 #[error("rustc dep-info is malformed: {0}")]
283 MalformedDepInfo(String),
284 #[error("failed to read rustc dep-info {path}: {message}")]
286 DepInfoRead {
287 path: PathBuf,
289 message: String,
291 },
292 #[error("rustc dep-info output path must be absolute: {0}")]
294 RelativeDepInfoPath(PathBuf),
295 #[error("rustc dep-info output path cannot contain a comma: {0}")]
297 UnsafeDepInfoPath(PathBuf),
298 #[error("failed to read compiler input {path}: {message}")]
300 InputRead {
301 path: PathBuf,
303 message: String,
305 },
306 #[error("declared build-script input overlaps compiler outputs: {0}")]
308 BuildScriptInputOverlapsOutputs(PathBuf),
309 #[error("Cargo has not recorded the build script's declarations yet: {0}")]
314 BuildScriptDeclarationsPending(PathBuf),
315 #[error("build-script inputs changed during compilation (declarations: {0})")]
318 BuildScriptInputsChanged(PathBuf),
319 #[error("compiler input changed after discovery: {0}")]
321 InputChanged(PathBuf),
322 #[error("compiler input was modified during compilation: {0}")]
324 InputModifiedDuringCompilation(PathBuf),
325 #[error("compiler input metadata changed during compilation: {0}")]
329 InputMetadataChangedDuringCompilation(PathBuf),
330 #[error("discovered inputs were collected from a different working directory")]
332 DiscoveryWorkingDirectory,
333 #[error("compiler environment input has conflicting values: {0}")]
335 ConflictingEnvironment(String),
336 #[error("failed to serialize the rustc action: {0}")]
338 Serialization(String),
339 #[error("rustc action prediction is unsupported")]
341 UnsupportedPrediction,
342 #[error("rustc action prediction contains an invalid input path: {0}")]
344 InvalidPredictedInput(String),
345}
346
347fn searches_native(kind: &str) -> bool {
352 matches!(kind, "native" | "all")
353}
354
355#[derive(Debug, Clone, PartialEq, Eq)]
356enum Argument {
357 Plain(String),
358 Path {
359 flag: String,
360 path: PathBuf,
361 },
362 SearchPath {
363 kind: String,
364 path: PathBuf,
365 },
366 Extern {
367 name: String,
368 path: Option<PathBuf>,
369 },
370 Emit(Vec<Emit>),
371 RemapPath {
372 from: PathBuf,
373 to: String,
374 },
375 InstallName(String),
377 OsoPrefix {
380 path: PathBuf,
381 trailing_slash: bool,
382 },
383 FuseLd(String),
387 Rpath(String),
391}
392
393#[derive(Debug, Clone, PartialEq, Eq)]
394struct Emit {
395 kind: String,
396 path: Option<PathBuf>,
397}
398
399#[derive(Debug, Clone, PartialEq, Eq)]
400pub struct RustcInvocation {
405 arguments: Vec<Argument>,
406 source: PathBuf,
407 required_inputs: Vec<PathBuf>,
408 crate_name: String,
409 extra_filename: String,
410 out_dir: Option<PathBuf>,
411 explicit_output: Option<PathBuf>,
412 emits: Vec<Emit>,
413 target: Option<String>,
414 link_output: LinkOutput,
415}
416
417#[derive(Debug, Clone, Copy, PartialEq, Eq)]
418enum LinkOutput {
419 Library,
420 WasmExecutable,
421 NativeExecutable,
422 NativeProcMacro,
423 NativeSharedLibrary,
428}
429
430#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
436#[non_exhaustive]
437pub struct ParseOptions {
438 pub cache_native_links: bool,
441 pub custom_target_search: bool,
447}
448
449impl ParseOptions {
450 pub fn caching_native_links(enabled: bool) -> Self {
452 Self {
453 cache_native_links: enabled,
454 ..Self::default()
455 }
456 }
457
458 pub fn with_custom_target_search(mut self, enabled: bool) -> Self {
461 self.custom_target_search = enabled;
462 self
463 }
464}
465
466#[derive(Debug, Clone, PartialEq, Eq)]
468pub struct RustcOutputs {
469 pub directory: PathBuf,
471 pub files: Vec<PathBuf>,
473 pub dep_info: PathBuf,
475}
476
477impl RustcInvocation {
478 pub fn parse(arguments: &[OsString]) -> Result<Self, BypassReason> {
487 Self::parse_with(arguments, ParseOptions::default())
488 }
489
490 pub fn expand_arguments(arguments: &[OsString]) -> Result<Vec<OsString>, BypassReason> {
495 Ok(expand_response_files(arguments)?.arguments)
496 }
497
498 pub fn parse_with(arguments: &[OsString], options: ParseOptions) -> Result<Self, BypassReason> {
501 let expanded = expand_response_files(arguments)?;
502 Parser::new(&expanded.arguments, options).parse()
503 }
504
505 pub fn links_natively(&self) -> bool {
508 matches!(
509 self.link_output,
510 LinkOutput::NativeExecutable
511 | LinkOutput::NativeProcMacro
512 | LinkOutput::NativeSharedLibrary
513 )
514 }
515
516 pub fn portable_install_name(&self, outputs: &RustcOutputs) -> Option<String> {
520 if !cfg!(target_os = "macos")
521 || self.link_output != LinkOutput::NativeProcMacro
522 || self
523 .arguments
524 .iter()
525 .any(|arg| matches!(arg, Argument::InstallName(_)))
526 {
527 return None;
528 }
529 let file = outputs
530 .files
531 .iter()
532 .find(|path| path.extension().is_some_and(|ext| ext == "dylib"))?;
533 let name = file.file_name()?.to_str()?;
534 if !safe_install_name(name) {
535 return None;
536 }
537 Some(format!("-Clink-arg=-Wl,-install_name,@rpath/{name}"))
538 }
539
540 pub fn linker_override(&self) -> Option<&Path> {
543 self.arguments.iter().find_map(|argument| {
544 let Argument::Plain(value) = argument else {
545 return None;
546 };
547 value.strip_prefix("--codegen=linker=").map(Path::new)
548 })
549 }
550
551 pub fn fuse_ld(&self) -> Option<&str> {
554 self.arguments.iter().find_map(|argument| {
555 let Argument::FuseLd(selection) = argument else {
556 return None;
557 };
558 Some(selection.as_str())
559 })
560 }
561
562 fn emits_windows_pdb(&self) -> bool {
563 if !cfg!(windows) || !self.links_natively() {
564 return false;
565 }
566 let mut enabled = false;
567 for argument in &self.arguments {
568 let Argument::Plain(value) = argument else {
569 continue;
570 };
571 if value == "-g" {
572 enabled = true;
573 } else if let Some(value) = value.strip_prefix("--codegen=debuginfo=") {
574 enabled = !matches!(value, "0" | "none");
575 }
576 }
577 enabled
578 }
579
580 pub fn native_search_paths(&self) -> impl Iterator<Item = &Path> {
584 self.arguments.iter().filter_map(|argument| match argument {
585 Argument::SearchPath { kind, path } if searches_native(kind) => Some(path.as_path()),
586 _ => None,
587 })
588 }
589
590 pub fn source(&self) -> &Path {
592 &self.source
593 }
594
595 pub fn required_inputs_in(&self, working_dir: &Path) -> Vec<PathBuf> {
601 self.required_inputs
602 .iter()
603 .map(|path| absolute_path(path, working_dir))
604 .collect()
605 }
606
607 pub fn target(&self) -> Option<&str> {
609 self.target.as_deref()
610 }
611
612 pub fn crate_name(&self) -> &str {
614 &self.crate_name
615 }
616
617 pub fn remaps_working_directory(&self) -> bool {
626 self.arguments.iter().any(|argument| {
627 matches!(argument, Argument::Plain(flag) if flag.starts_with("-Zremap-cwd-prefix="))
628 })
629 }
630
631 pub fn source_fingerprint(&self, discovered: &DiscoveredInputs) -> CacheDigest {
644 let linked = self
645 .arguments
646 .iter()
647 .filter_map(|argument| match argument {
648 Argument::Extern {
649 path: Some(path), ..
650 } => Some(path.as_path()),
651 _ => None,
652 })
653 .collect::<BTreeSet<_>>();
654 let owned = discovered
655 .inputs
656 .iter()
657 .filter(|input| {
658 !linked.contains(input.path.as_path()) && !discovered.is_native_only(&input.path)
659 })
660 .map(|input| (input.path.as_path(), &input.digest))
661 .collect::<BTreeMap<_, _>>();
662 let mut bytes = Vec::new();
663 for (path, digest) in owned {
664 bytes.extend_from_slice(path.as_os_str().as_encoded_bytes());
665 bytes.push(0);
666 bytes.extend_from_slice(digest.key().as_bytes());
667 bytes.push(0);
668 }
669 CacheDigest::blake3(&bytes)
670 }
671
672 pub fn outputs(&self, working_dir: &Path) -> Result<RustcOutputs, BypassReason> {
677 if !working_dir.is_absolute() {
678 return Err(BypassReason::RelativeWorkingDirectory(
679 working_dir.to_path_buf(),
680 ));
681 }
682 let explicit_output = self
683 .explicit_output
684 .as_deref()
685 .map(|path| absolute_path(path, working_dir));
686 let output_directory = explicit_output
687 .as_deref()
688 .and_then(Path::parent)
689 .map(Path::to_path_buf)
690 .or_else(|| {
691 self.out_dir
692 .as_deref()
693 .map(|path| absolute_path(path, working_dir))
694 })
695 .unwrap_or_else(|| normalize_components(working_dir));
696 if let Some(output) = &explicit_output
700 && self.emits.iter().any(|emit| {
701 emit.path.is_none()
702 && matches!(emit.kind.as_str(), "dep-info" | "link" | "metadata")
703 })
704 {
705 return Err(BypassReason::ImplicitEmitWithOutputFile(output.clone()));
706 }
707 let mut files = BTreeSet::new();
708 let mut dep_info = None;
709 for emit in &self.emits {
710 if emit.kind == "dep-info" {
711 let path = emit.path.as_ref().map_or_else(
712 || {
713 explicit_output.clone().map_or_else(
714 || {
715 output_directory
716 .join(format!("{}{}.d", self.crate_name, self.extra_filename))
717 },
718 |path| path.with_extension("d"),
719 )
720 },
721 |path| absolute_path(path, working_dir),
722 );
723 if path.file_name().is_none() {
724 return Err(BypassReason::InvalidOutputPath(path));
725 }
726 dep_info = Some(path);
727 continue;
728 }
729 let (prefix, extension) = match emit.kind.as_str() {
730 "link" => match self.link_output {
731 LinkOutput::Library => ("lib", "rlib"),
732 LinkOutput::WasmExecutable => ("", "wasm"),
733 LinkOutput::NativeExecutable => ("", std::env::consts::EXE_EXTENSION),
734 LinkOutput::NativeProcMacro | LinkOutput::NativeSharedLibrary => (
735 std::env::consts::DLL_PREFIX,
736 std::env::consts::DLL_SUFFIX.trim_start_matches('.'),
737 ),
738 },
739 "metadata" => ("lib", "rmeta"),
740 _ => continue,
741 };
742 let path = if let Some(path) = &emit.path {
743 absolute_path(path, working_dir)
744 } else {
745 let name = format!("{prefix}{}{}", self.crate_name, self.extra_filename);
746 output_directory.join(if extension.is_empty() {
747 name
748 } else {
749 format!("{name}.{extension}")
750 })
751 };
752 if path.file_name().is_none() {
753 return Err(BypassReason::InvalidOutputPath(path));
754 }
755 if path.parent() != Some(output_directory.as_path()) {
756 return Err(BypassReason::SplitOutputDirectories);
757 }
758 let has_library_extension = path
763 .extension()
764 .and_then(|extension| extension.to_str())
765 .is_some_and(|extension| matches!(extension, "rlib" | "rmeta"))
766 || (cfg!(windows)
767 && path
768 .file_stem()
769 .and_then(|stem| Path::new(stem).extension())
770 .and_then(|extension| extension.to_str())
771 .is_some_and(|extension| matches!(extension, "rlib" | "rmeta")));
772 if emit.kind == "link"
773 && !matches!(self.link_output, LinkOutput::Library)
774 && has_library_extension
775 {
776 return Err(BypassReason::AmbiguousOutputName(path));
777 }
778 if emit.kind == "link" && self.emits_windows_pdb() {
779 files.insert(path.with_extension("pdb"));
780 }
781 files.insert(path);
782 }
783 let dep_info = dep_info.ok_or(BypassReason::NoDepInfo)?;
784 if dep_info.parent() != Some(output_directory.as_path()) {
785 return Err(BypassReason::SplitOutputDirectories);
786 }
787 Ok(RustcOutputs {
788 directory: output_directory,
789 files: files.into_iter().collect(),
790 dep_info,
791 })
792 }
793
794 pub fn action(&self, context: ActionContext) -> Result<RustcAction, BypassReason> {
800 self.action_linked_by(context, None)
801 }
802
803 pub fn action_linked_by(
812 &self,
813 context: ActionContext,
814 linker: Option<LinkerIdentity>,
815 ) -> Result<RustcAction, BypassReason> {
816 ActionBuilder::new(self, context).linked_by(linker).build()
817 }
818
819 pub fn invocation_digest(&self, context: &ActionContext) -> Result<CacheDigest, BypassReason> {
821 let descriptor = ActionBuilder::new(self, context.clone()).invocation_descriptor()?;
822 let bytes = canonical_json(&descriptor)
823 .map_err(|error| BypassReason::Serialization(error.to_string()))?;
824 Ok(CacheDigest::blake3(&bytes))
825 }
826
827 pub fn prediction(
830 &self,
831 context: &ActionContext,
832 discovered: &DiscoveredInputs,
833 ) -> Result<RustcInputPrediction, BypassReason> {
834 let builder = ActionBuilder::new(self, context.clone());
835 builder.validate_mappings()?;
836 let mut native_directories = BTreeSet::new();
837 for argument in &self.arguments {
838 if let Argument::SearchPath { kind, path } = argument
839 && searches_native(kind)
840 {
841 native_directories.insert(builder.normalize_path(path)?);
842 }
843 }
844 let mut inputs = BTreeSet::new();
856 for input in &discovered.inputs {
857 let normalized = builder.normalize_path(&input.path)?;
858 if !under_any_directory(&normalized, &native_directories)
859 || !discovered.is_native_only(&input.path)
860 {
861 inputs.insert(normalized);
862 }
863 }
864 inputs.extend(
865 native_directories
866 .into_iter()
867 .map(|directory| format!("{NATIVE_DIRECTORY_PREDICTION_PREFIX}{directory}")),
868 );
869 Ok(RustcInputPrediction {
870 version: 4,
871 inputs: inputs.into_iter().collect(),
872 environment: discovered.environment.keys().cloned().collect(),
873 compiler_duration_ns: 0,
874 crate_name: String::new(),
875 })
876 }
877}
878
879pub fn is_build_script_crate_name(crate_name: &str) -> bool {
883 crate_name
884 .strip_prefix("build_script_")
885 .is_some_and(|stem| !stem.is_empty())
886}
887
888impl RustcOutputs {
889 pub fn build_script_executable(&self, crate_name: &str) -> Option<&Path> {
899 is_build_script_crate_name(crate_name)
900 .then(|| self.files.iter().find(|path| self.is_executable(path)))
901 .flatten()
902 .map(PathBuf::as_path)
903 }
904
905 pub fn is_executable(&self, path: &Path) -> bool {
913 self.files.iter().any(|output| output == path)
914 && !matches!(
915 path.extension().and_then(|extension| extension.to_str()),
916 Some("rlib" | "rmeta")
917 )
918 }
919}
920
921#[derive(Debug, Clone, PartialEq, Eq)]
922pub struct PathMapping {
924 pub root: PathBuf,
926 pub placeholder: String,
928}
929
930impl PathMapping {
931 pub fn new(root: impl Into<PathBuf>, placeholder: impl Into<String>) -> Self {
933 Self {
934 root: root.into(),
935 placeholder: placeholder.into(),
936 }
937 }
938
939 pub fn ordered(mappings: &[PathMapping]) -> Vec<PathMapping> {
942 let mut ordered = mappings.to_vec();
943 ordered.sort_by_key(|mapping| std::cmp::Reverse(mapping.root.components().count()));
944 ordered
945 }
946}
947
948fn shared_path_mappings(mappings: &[PathMapping]) -> Vec<SharedPathMapping> {
949 mappings
950 .iter()
951 .map(|mapping| SharedPathMapping::new(&mapping.root, &mapping.placeholder))
952 .collect()
953}
954
955pub fn normalize_mapped_path(
962 path: &Path,
963 working_dir: &Path,
964 mappings: &[PathMapping],
965) -> Result<String, BypassReason> {
966 normalize_shared_path(path, working_dir, &shared_path_mappings(mappings)).map_err(Into::into)
967}
968
969#[derive(Debug, Clone, PartialEq, Eq)]
970pub struct CompilerIdentity {
972 pub toolchain: String,
974 pub rustc_version: String,
976 pub host: String,
978 pub driver: Option<String>,
980}
981
982#[derive(Debug, Clone, PartialEq, Eq)]
984pub struct ActionInput {
985 pub path: PathBuf,
987 pub digest: CacheDigest,
989}
990
991#[derive(Debug, Clone, PartialEq, Eq)]
993pub struct ActionContext {
994 pub compiler: CompilerIdentity,
996 pub working_dir: PathBuf,
998 pub path_mappings: Vec<PathMapping>,
1000 pub environment: BTreeMap<String, Option<String>>,
1002 pub portable_environment: BTreeSet<String>,
1009 pub inputs: Vec<ActionInput>,
1011}
1012
1013#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1023#[serde(deny_unknown_fields)]
1024pub struct LinkerIdentity {
1025 pub driver: String,
1027 pub driver_version: String,
1029 pub linker_version: String,
1031 #[serde(skip_serializing_if = "BTreeMap::is_empty", default)]
1033 pub crt_objects: BTreeMap<String, CacheDigest>,
1034 #[serde(skip_serializing_if = "Option::is_none", default)]
1036 pub sdk: Option<String>,
1037 #[serde(skip_serializing_if = "Option::is_none", default)]
1039 pub deployment_target: Option<String>,
1040}
1041
1042#[derive(Debug, Clone, PartialEq, Eq)]
1044pub struct RustcAction {
1045 pub digest: CacheDigest,
1047 pub bytes: Vec<u8>,
1049}
1050
1051#[derive(Debug, Clone, PartialEq, Eq)]
1054pub struct RustcInputPrediction {
1055 pub version: u8,
1057 pub inputs: Vec<String>,
1059 pub environment: Vec<String>,
1061 pub compiler_duration_ns: u64,
1064 pub crate_name: String,
1066}
1067
1068#[derive(Serialize, Deserialize)]
1069#[serde(deny_unknown_fields)]
1070struct RustcInputPredictionWire {
1071 version: u8,
1072 inputs: Vec<String>,
1073 environment: Vec<String>,
1074 #[serde(default, skip_serializing_if = "is_zero")]
1075 compiler_duration_ns: u64,
1076 #[serde(default, skip_serializing_if = "String::is_empty")]
1077 crate_name: String,
1078}
1079
1080impl Serialize for RustcInputPrediction {
1081 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1082 where
1083 S: Serializer,
1084 {
1085 RustcInputPredictionWire {
1086 version: self.version,
1087 inputs: if self.version == 4 {
1088 compact_prediction_inputs(&self.inputs)
1089 } else {
1090 self.inputs.clone()
1091 },
1092 environment: self.environment.clone(),
1093 compiler_duration_ns: self.compiler_duration_ns,
1094 crate_name: self.crate_name.clone(),
1095 }
1096 .serialize(serializer)
1097 }
1098}
1099
1100impl<'de> Deserialize<'de> for RustcInputPrediction {
1101 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1102 where
1103 D: Deserializer<'de>,
1104 {
1105 let wire = RustcInputPredictionWire::deserialize(deserializer)?;
1106 let inputs = if wire.version == 4 {
1107 expand_prediction_inputs(&wire.inputs).map_err(serde::de::Error::custom)?
1108 } else {
1109 wire.inputs
1110 };
1111 Ok(Self {
1112 version: wire.version,
1113 inputs,
1114 environment: wire.environment,
1115 compiler_duration_ns: wire.compiler_duration_ns,
1116 crate_name: wire.crate_name,
1117 })
1118 }
1119}
1120
1121fn compact_prediction_inputs(inputs: &[String]) -> Vec<String> {
1122 let mut previous = "";
1123 inputs
1124 .iter()
1125 .map(|input| {
1126 let mut shared = previous
1127 .bytes()
1128 .zip(input.bytes())
1129 .take_while(|(left, right)| left == right)
1130 .count();
1131 while !input.is_char_boundary(shared) {
1132 shared -= 1;
1133 }
1134 let compact = format!("{shared}:{}", &input[shared..]);
1135 previous = input;
1136 compact
1137 })
1138 .collect()
1139}
1140
1141fn expand_prediction_inputs(inputs: &[String]) -> Result<Vec<String>, &'static str> {
1142 let mut expanded: Vec<String> = Vec::with_capacity(inputs.len());
1143 let mut decoded_bytes = 0_usize;
1144 for input in inputs {
1145 let (shared_text, suffix) = input
1146 .split_once(':')
1147 .ok_or("compact rustc prediction input has no prefix length")?;
1148 let shared: usize = shared_text
1149 .parse()
1150 .map_err(|_| "compact rustc prediction prefix length is invalid")?;
1151 if shared.to_string() != shared_text
1152 || shared > expanded.last().map_or(0, String::len)
1153 || expanded
1154 .last()
1155 .is_some_and(|previous| !previous.is_char_boundary(shared))
1156 {
1157 return Err("compact rustc prediction prefix is not canonical");
1158 }
1159 let mut path = expanded
1160 .last()
1161 .map_or_else(String::new, |previous| previous[..shared].to_string());
1162 path.push_str(suffix);
1163 decoded_bytes = decoded_bytes
1164 .checked_add(path.len())
1165 .ok_or("compact rustc prediction is too large")?;
1166 if decoded_bytes > MAX_DECODED_PREDICTION_BYTES {
1167 return Err("compact rustc prediction is too large");
1168 }
1169 expanded.push(path);
1170 }
1171 Ok(expanded)
1172}
1173
1174fn is_zero(value: &u64) -> bool {
1175 *value == 0
1176}
1177
1178impl RustcInputPrediction {
1179 pub fn discover(
1182 &self,
1183 working_dir: &Path,
1184 path_mappings: &[PathMapping],
1185 digests: &dyn FileDigestCache,
1186 ) -> Result<DiscoveredInputs, BypassReason> {
1187 if !matches!(self.version, 2..=4) {
1188 return Err(BypassReason::UnsupportedPrediction);
1189 }
1190 if self.inputs.len() > MAX_PREDICTED_INPUTS || self.environment.len() > 4 * 1024 {
1191 return Err(BypassReason::UnsupportedPrediction);
1192 }
1193 let mut paths = BTreeSet::new();
1194 let mut named = BTreeSet::new();
1195 let admitted_roots = dep_info::native_input_roots(working_dir, path_mappings);
1196 let mut native_bytes = 0_u64;
1197 let mut counted = BTreeSet::new();
1198 for path in &self.inputs {
1199 if self.version >= 3
1200 && let Some(path) = path.strip_prefix(NATIVE_DIRECTORY_PREDICTION_PREFIX)
1201 {
1202 let directory = denormalize_path(path, path_mappings)?;
1203 dep_info::collect_native_directory(
1204 &directory,
1205 &admitted_roots,
1206 &mut paths,
1207 &mut native_bytes,
1208 &mut counted,
1209 )?;
1210 } else {
1211 let path = denormalize_path(path, path_mappings)?;
1212 named.insert(path.clone());
1213 paths.insert(path);
1214 }
1215 }
1216 let native_only = paths.difference(&named).cloned().collect();
1217 let environment = self
1218 .environment
1219 .iter()
1220 .map(|name| {
1221 if name.is_empty() || name.contains(['=', '\0']) {
1222 return Err(BypassReason::UnsupportedPrediction);
1223 }
1224 let value = std::env::var_os(name)
1225 .map(|value| {
1226 value
1227 .into_string()
1228 .map_err(|_| BypassReason::UnsupportedPrediction)
1229 })
1230 .transpose()?;
1231 Ok((name.clone(), value))
1232 })
1233 .collect::<Result<BTreeMap<_, _>, _>>()?;
1234 Ok(
1235 DiscoveredInputs::from_paths(working_dir, paths, environment, digests)?
1236 .with_native_only(native_only),
1237 )
1238 }
1239}
1240
1241#[derive(Serialize)]
1242struct ActionDescriptor {
1243 version: u8,
1244 kind: &'static str,
1245 adapter_version: u8,
1246 compiler: CompilerDescriptor,
1247 arguments: Vec<String>,
1248 environment: BTreeMap<String, Option<String>>,
1249 inputs: Vec<InputDescriptor>,
1250 #[serde(skip_serializing_if = "Option::is_none")]
1253 linker: Option<LinkerIdentity>,
1254}
1255
1256#[derive(Serialize)]
1257struct InvocationDescriptor {
1258 version: u8,
1259 kind: &'static str,
1260 adapter_version: u8,
1261 compiler: CompilerDescriptor,
1262 arguments: Vec<String>,
1263 required_inputs: Vec<String>,
1264}
1265
1266#[derive(Serialize)]
1267struct CompilerDescriptor {
1268 toolchain: String,
1269 rustc_version: String,
1270 host: String,
1271 #[serde(skip_serializing_if = "Option::is_none")]
1272 driver: Option<String>,
1273}
1274
1275#[derive(Debug, Serialize, PartialEq, Eq, PartialOrd, Ord)]
1276struct InputDescriptor {
1277 path: String,
1278 digest: CacheDigest,
1279}
1280
1281#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1283enum StaticLibraryNaming {
1284 Msvc,
1286 Unix,
1288}
1289
1290struct Parser<'a> {
1291 arguments: &'a [OsString],
1292 index: usize,
1293 parsed: Vec<Argument>,
1294 source: Option<PathBuf>,
1295 crate_types: Vec<String>,
1296 emits: Vec<Emit>,
1297 required_inputs: Vec<PathBuf>,
1298 native_libraries: Vec<String>,
1299 test: bool,
1300 crate_name: Option<String>,
1301 extra_filename: String,
1302 out_dir: Option<PathBuf>,
1303 explicit_output: Option<PathBuf>,
1304 target: Option<String>,
1305 sysroot_backend: Option<String>,
1306 options: ParseOptions,
1307}
1308
1309struct ExpandedArguments {
1310 arguments: Vec<OsString>,
1311}
1312
1313#[derive(Default)]
1314struct ResponseExpander {
1315 shell_argfiles: bool,
1316 next_is_unstable_option: bool,
1317 arguments: Vec<OsString>,
1318}
1319
1320impl ResponseExpander {
1321 fn push(&mut self, argument: String) {
1322 if self.next_is_unstable_option {
1323 self.shell_argfiles |= argument == "shell-argfiles";
1324 self.next_is_unstable_option = false;
1325 } else if let Some(option) = argument.strip_prefix("-Z") {
1326 if option.is_empty() {
1327 self.next_is_unstable_option = true;
1328 } else {
1329 self.shell_argfiles |= option == "shell-argfiles";
1330 }
1331 }
1332 self.arguments.push(argument.into());
1333 }
1334}
1335
1336fn expand_response_files(arguments: &[OsString]) -> Result<ExpandedArguments, BypassReason> {
1339 let mut expanded = ResponseExpander::default();
1340 for (index, argument) in arguments.iter().enumerate() {
1341 let argument = argument
1342 .to_str()
1343 .ok_or(BypassReason::NonUtf8Argument { index })?;
1344 let Some(argfile) = argument.strip_prefix('@') else {
1345 expanded.push(argument.to_string());
1346 continue;
1347 };
1348 let (path, shell) = match argfile.split_once(':') {
1349 Some(("shell", path)) if expanded.shell_argfiles => (path, true),
1350 _ => (argfile, false),
1351 };
1352 let contents = std::fs::read_to_string(path).map_err(|error| {
1353 BypassReason::ResponseFile(format!("{}: {error}", Path::new(path).display()))
1354 })?;
1355 if shell {
1356 let arguments = shlex::split(&contents).ok_or_else(|| {
1357 BypassReason::ResponseFile(format!(
1358 "invalid shell-style arguments in {}",
1359 Path::new(path).display()
1360 ))
1361 })?;
1362 for argument in arguments {
1363 expanded.push(argument);
1364 }
1365 } else {
1366 for argument in contents.lines() {
1367 expanded.push(argument.to_string());
1368 }
1369 }
1370 }
1371 Ok(ExpandedArguments {
1372 arguments: expanded.arguments,
1373 })
1374}
1375
1376impl<'a> Parser<'a> {
1377 fn new(arguments: &'a [OsString], options: ParseOptions) -> Self {
1378 Self {
1379 arguments,
1380 options,
1381 index: 0,
1382 parsed: Vec::new(),
1383 source: None,
1384 crate_types: Vec::new(),
1385 emits: Vec::new(),
1386 required_inputs: Vec::new(),
1387 native_libraries: Vec::new(),
1388 test: false,
1389 crate_name: None,
1390 extra_filename: String::new(),
1391 out_dir: None,
1392 explicit_output: None,
1393 target: None,
1394 sysroot_backend: None,
1395 }
1396 }
1397
1398 fn parse(mut self) -> Result<RustcInvocation, BypassReason> {
1399 while self.index < self.arguments.len() {
1400 let value = self.current()?.to_string();
1401 self.index += 1;
1402 if let Some(long) = value.strip_prefix("--") {
1403 self.parse_long(long)?;
1404 } else if value.starts_with('-') && value != "-" {
1405 self.parse_short(&value)?;
1406 } else {
1407 self.parse_input(&value)?;
1408 }
1409 }
1410
1411 if let Some(backend) = self.sysroot_backend.take()
1413 && self.parsed.iter().any(
1414 |argument| matches!(argument, Argument::Path { flag, .. } if flag == "--sysroot"),
1415 )
1416 {
1417 return Err(BypassReason::UnknownFlag(backend));
1418 }
1419 let source = self.source.clone().ok_or(BypassReason::MissingInput)?;
1420 let link_output = self.classify()?;
1421 self.require_native_libraries(link_output)?;
1422 let crate_name = self.crate_name.clone().map_or_else(
1423 || {
1424 source
1425 .file_stem()
1426 .and_then(|name| name.to_str())
1427 .map(|name| name.replace('-', "_"))
1428 .ok_or_else(|| BypassReason::NonUtf8Path(source.clone()))
1429 },
1430 Ok,
1431 )?;
1432 self.required_inputs.push(source.clone());
1433 self.drop_unobservable_diagnostic_width();
1434 Ok(RustcInvocation {
1435 arguments: self.parsed,
1436 source,
1437 required_inputs: self.required_inputs,
1438 crate_name,
1439 extra_filename: self.extra_filename,
1440 out_dir: self.out_dir,
1441 explicit_output: self.explicit_output,
1442 emits: self.emits,
1443 target: self.target,
1444 link_output,
1445 })
1446 }
1447
1448 fn current(&self) -> Result<&str, BypassReason> {
1449 self.arguments[self.index]
1450 .to_str()
1451 .ok_or(BypassReason::NonUtf8Argument { index: self.index })
1452 }
1453
1454 fn take_value(&mut self, flag: &str, inline: Option<&str>) -> Result<String, BypassReason> {
1455 if let Some(value) = inline {
1456 if value.is_empty() {
1457 return Err(BypassReason::MissingValue(flag.into()));
1458 }
1459 return Ok(value.into());
1460 }
1461 if self.index >= self.arguments.len() {
1462 return Err(BypassReason::MissingValue(flag.into()));
1463 }
1464 let value = self.current()?.to_string();
1465 self.index += 1;
1466 Ok(value)
1467 }
1468
1469 fn drop_unobservable_diagnostic_width(&mut self) {
1480 fn widths(argument: &Argument) -> Option<&str> {
1481 match argument {
1482 Argument::Plain(value) => value.strip_prefix("--diagnostic-width="),
1483 _ => None,
1484 }
1485 }
1486 let mut found = self.parsed.iter().filter_map(widths);
1487 let valid = matches!(
1488 (found.next(), found.next()),
1489 (Some(width), None) if width.parse::<usize>().is_ok()
1490 );
1491 if valid {
1492 self.parsed.retain(|argument| widths(argument).is_none());
1493 }
1494 }
1495
1496 fn parse_long(&mut self, value: &str) -> Result<(), BypassReason> {
1497 let (flag, inline) = value
1498 .split_once('=')
1499 .map_or((value, None), |(flag, value)| (flag, Some(value)));
1500 let rendered_flag = format!("--{flag}");
1501 match flag {
1502 "help" | "version" | "explain" | "print" => Err(BypassReason::CompilerQuery),
1503 "test" => {
1504 self.test = true;
1505 self.parsed.push(Argument::Plain(rendered_flag));
1506 Ok(())
1507 }
1508 "verbose" => {
1509 self.parsed.push(Argument::Plain(rendered_flag));
1510 Ok(())
1511 }
1512 "crate-name" => {
1513 let value = self.take_value(&rendered_flag, inline)?;
1514 self.crate_name = Some(value.clone());
1515 self.parsed
1516 .push(Argument::Plain(format!("{rendered_flag}={value}")));
1517 Ok(())
1518 }
1519 "cfg" | "check-cfg" | "edition" | "error-format" | "json" | "color"
1520 | "diagnostic-width" | "remap-path-scope" | "allow" | "warn" | "force-warn"
1521 | "deny" | "forbid" | "cap-lints" => {
1522 let value = self.take_value(&rendered_flag, inline)?;
1523 self.parsed
1524 .push(Argument::Plain(format!("{rendered_flag}={value}")));
1525 Ok(())
1526 }
1527 "target" => {
1528 let value = self.take_value(&rendered_flag, inline)?;
1529 let effective = self.target.is_none();
1533 if effective {
1534 self.target = Some(value.clone());
1535 }
1536 if value.ends_with(".json") || value.contains(['/', '\\']) {
1537 let path = PathBuf::from(value);
1538 if effective {
1539 self.required_inputs.push(path.clone());
1540 }
1541 self.parsed.push(Argument::Path {
1542 flag: rendered_flag,
1543 path,
1544 });
1545 } else {
1546 self.parsed
1547 .push(Argument::Plain(format!("{rendered_flag}={value}")));
1548 }
1549 Ok(())
1550 }
1551 "crate-type" => {
1552 let value = self.take_value(&rendered_flag, inline)?;
1553 self.crate_types
1554 .extend(value.split(',').map(ToOwned::to_owned));
1555 self.parsed
1556 .push(Argument::Plain(format!("{rendered_flag}={value}")));
1557 Ok(())
1558 }
1559 "emit" => {
1560 let value = self.take_value(&rendered_flag, inline)?;
1561 let emits = parse_emits(&value);
1562 self.emits.extend(emits.clone());
1563 self.parsed.push(Argument::Emit(emits));
1564 Ok(())
1565 }
1566 "out-dir" => {
1567 let path = PathBuf::from(self.take_value(&rendered_flag, inline)?);
1568 self.out_dir = Some(path.clone());
1569 self.parsed.push(Argument::Path {
1570 flag: rendered_flag,
1571 path,
1572 });
1573 Ok(())
1574 }
1575 "sysroot" => {
1576 let path = self.take_value(&rendered_flag, inline)?;
1577 self.parsed.push(Argument::Path {
1578 flag: rendered_flag,
1579 path: path.into(),
1580 });
1581 Ok(())
1582 }
1583 "extern" => {
1584 let value = self.take_value(&rendered_flag, inline)?;
1585 let (name, path) = value
1586 .split_once('=')
1587 .map_or((value.as_str(), None), |(name, path)| {
1588 (name, Some(PathBuf::from(path)))
1589 });
1590 if let Some(path) = &path {
1591 self.required_inputs.push(path.clone());
1592 }
1593 self.parsed.push(Argument::Extern {
1594 name: name.into(),
1595 path,
1596 });
1597 Ok(())
1598 }
1599 "remap-path-prefix" => {
1600 let value = self.take_value(&rendered_flag, inline)?;
1601 let Some((from, to)) = value.split_once('=') else {
1602 return Err(BypassReason::MissingValue(rendered_flag));
1603 };
1604 self.parsed.push(Argument::RemapPath {
1605 from: from.into(),
1606 to: to.into(),
1607 });
1608 Ok(())
1609 }
1610 "codegen" => {
1611 let value = self.take_value(&rendered_flag, inline)?;
1612 self.parse_codegen(&value)
1613 }
1614 "jobs-frontend" => {
1615 let value = self.take_value(&rendered_flag, inline)?;
1616 self.parsed
1617 .push(Argument::Plain(format!("{rendered_flag}={value}")));
1618 Ok(())
1619 }
1620 _ => Err(BypassReason::UnknownFlag(rendered_flag)),
1621 }
1622 }
1623
1624 fn parse_short(&mut self, value: &str) -> Result<(), BypassReason> {
1625 if let Some(attached) = value.strip_prefix("-Z") {
1626 let option = self.take_value("-Z", (!attached.is_empty()).then_some(attached))?;
1627 match option.as_str() {
1628 "embed-metadata=no"
1632 | "embed-metadata=yes"
1633 | "force-unstable-if-unmarked"
1634 | "shell-argfiles"
1635 | "unstable-options" => {
1636 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1637 return Ok(());
1638 }
1639 "use-sync-unwind=yes" | "use-sync-unwind=no" => {
1642 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1643 return Ok(());
1644 }
1645 "threads" | "threads=" => {
1646 return Err(BypassReason::MissingValue("-Zthreads".into()));
1647 }
1648 "remap-cwd-prefix" | "remap-cwd-prefix=" => {
1649 return Err(BypassReason::MissingValue("-Zremap-cwd-prefix".into()));
1650 }
1651 _ => {}
1652 }
1653 if option.starts_with("remap-cwd-prefix=") {
1659 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1660 return Ok(());
1661 }
1662 if option == "share-generics" {
1663 return Err(BypassReason::MissingValue("-Zshare-generics".into()));
1664 }
1665 if let Some(value) = option.strip_prefix("share-generics=") {
1666 if matches!(
1667 value,
1668 "y" | "yes" | "on" | "true" | "n" | "no" | "off" | "false"
1669 ) {
1670 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1671 return Ok(());
1672 }
1673 return Err(if value.is_empty() {
1674 BypassReason::MissingValue("-Zshare-generics".into())
1675 } else {
1676 BypassReason::UnknownFlag(format!("-Z{option}"))
1677 });
1678 }
1679 if option == "always-encode-mir" {
1683 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1684 return Ok(());
1685 }
1686 if let Some(level) = option.strip_prefix("mir-opt-level=") {
1687 if matches!(level, "0" | "1" | "2" | "3" | "4") {
1688 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1689 return Ok(());
1690 }
1691 return Err(if level.is_empty() {
1692 BypassReason::MissingValue("-Zmir-opt-level".into())
1693 } else {
1694 BypassReason::UnknownFlag(format!("-Z{option}"))
1695 });
1696 }
1697 if option == "mir-opt-level" {
1698 return Err(BypassReason::MissingValue("-Zmir-opt-level".into()));
1699 }
1700 if option == "inline-mir" {
1701 return Err(BypassReason::MissingValue("-Zinline-mir".into()));
1702 }
1703 if let Some(value) = option.strip_prefix("inline-mir=") {
1704 if matches!(
1705 value,
1706 "y" | "yes" | "on" | "true" | "n" | "no" | "off" | "false"
1707 ) {
1708 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1709 return Ok(());
1710 }
1711 return Err(if value.is_empty() {
1712 BypassReason::MissingValue("-Zinline-mir".into())
1713 } else {
1714 BypassReason::UnknownFlag(format!("-Z{option}"))
1715 });
1716 }
1717 if option.starts_with("threads=") {
1718 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1719 return Ok(());
1720 }
1721 if let Some(backend) = option.strip_prefix("codegen-backend=")
1723 && !backend.is_empty()
1724 && !backend.contains(['.', '/', '\\'])
1725 {
1726 self.sysroot_backend = Some(format!("-Z{option}"));
1727 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1728 return Ok(());
1729 }
1730 return Err(BypassReason::UnknownFlag(format!("-Z{option}")));
1731 }
1732 match value {
1733 "-h" | "-V" | "-vV" => return Err(BypassReason::CompilerQuery),
1736 "-g" | "-O" | "-v" => {
1737 self.parsed.push(Argument::Plain(value.into()));
1738 return Ok(());
1739 }
1740 _ => {}
1741 }
1742 for (short, long) in [
1743 ("-A", "--allow"),
1744 ("-W", "--warn"),
1745 ("-D", "--deny"),
1746 ("-F", "--forbid"),
1747 ] {
1748 if let Some(attached) = value.strip_prefix(short) {
1749 let lint = self.take_value(short, (!attached.is_empty()).then_some(attached))?;
1750 self.parsed.push(Argument::Plain(format!("{long}={lint}")));
1751 return Ok(());
1752 }
1753 }
1754 if let Some(attached) = value.strip_prefix("-C") {
1755 let option = self.take_value("-C", (!attached.is_empty()).then_some(attached))?;
1756 return self.parse_codegen(&option);
1757 }
1758 if let Some(attached) = value.strip_prefix("-L") {
1759 let search = self.take_value("-L", (!attached.is_empty()).then_some(attached))?;
1760 let (kind, path) = search
1761 .split_once('=')
1762 .map_or(("all", search.as_str()), |(kind, path)| (kind, path));
1763 if kind != "dependency" && !searches_native(kind) {
1764 return Err(BypassReason::UnsupportedSearchPath(kind.into()));
1765 }
1766 self.parsed.push(Argument::SearchPath {
1767 kind: kind.into(),
1768 path: path.into(),
1769 });
1770 return Ok(());
1771 }
1772 if let Some(attached) = value.strip_prefix("-l") {
1773 let library = self.take_value("-l", (!attached.is_empty()).then_some(attached))?;
1774 self.parsed.push(Argument::Plain(format!("-l{library}")));
1775 self.native_libraries.push(library);
1776 return Ok(());
1777 }
1778 if let Some(attached) = value.strip_prefix("-o") {
1779 let path = self.take_value("-o", (!attached.is_empty()).then_some(attached))?;
1780 self.explicit_output = Some(path.clone().into());
1781 self.parsed.push(Argument::Path {
1782 flag: "-o".into(),
1783 path: path.into(),
1784 });
1785 return Ok(());
1786 }
1787 Err(BypassReason::UnknownFlag(value.into()))
1788 }
1789
1790 fn parse_codegen(&mut self, value: &str) -> Result<(), BypassReason> {
1791 let name = value.split_once('=').map_or(value, |(name, _)| name);
1792 if name == "incremental" {
1793 return Err(BypassReason::Incremental);
1794 }
1795 if name == "profile-use" {
1796 let Some((_, profile)) = value.split_once('=') else {
1797 return Err(BypassReason::MissingValue("-Cprofile-use".into()));
1798 };
1799 if profile.is_empty() {
1800 return Err(BypassReason::MissingValue("-Cprofile-use".into()));
1801 }
1802 let path = PathBuf::from(profile);
1803 self.required_inputs.push(path.clone());
1804 self.parsed.push(Argument::Path {
1805 flag: "-Cprofile-use".into(),
1806 path,
1807 });
1808 return Ok(());
1809 }
1810 if SUPPORTED_CODEGEN_OPTIONS.binary_search(&name).is_err()
1811 && !matches!(name, "linker" | "linker-flavor")
1812 {
1813 return Err(BypassReason::UnknownCodegenOption(name.into()));
1814 }
1815 if name == "linker-plugin-lto"
1821 && let Some((_, selection)) = value.split_once('=')
1822 && !matches!(
1823 selection,
1824 "" | "y" | "yes" | "on" | "true" | "n" | "no" | "off" | "false"
1825 )
1826 {
1827 return Err(BypassReason::UnknownCodegenOption(format!(
1828 "linker-plugin-lto={selection}"
1829 )));
1830 }
1831 if name == "link-arg"
1838 && let Some((_, option)) = value.split_once('=')
1839 && let Some(selection) = option.strip_prefix("-fuse-ld=")
1840 && !selection.is_empty()
1841 && !selection.contains(',')
1842 && !self.parsed.iter().any(
1843 |argument| matches!(argument, Argument::FuseLd(existing) if existing != selection),
1844 )
1845 {
1846 if !self.parsed.iter().any(
1847 |argument| matches!(argument, Argument::FuseLd(existing) if existing == selection),
1848 ) {
1849 self.parsed.push(Argument::FuseLd(selection.to_owned()));
1850 }
1851 return Ok(());
1852 }
1853 if name == "link-arg"
1856 && let Some(option) = value.strip_prefix("link-arg=-Wl,-install_name,@rpath/")
1857 && safe_install_name(option)
1858 {
1859 self.parsed.push(Argument::InstallName(option.to_owned()));
1860 return Ok(());
1861 }
1862 if name == "link-arg"
1866 && let Some(directory) = value.strip_prefix("link-arg=-Wl,-rpath,")
1867 && directory.starts_with('/')
1868 && !directory.contains(',')
1869 {
1870 self.parsed.push(Argument::Rpath(directory.to_owned()));
1871 return Ok(());
1872 }
1873 if matches!(name, "link-arg" | "link-args")
1878 && let Some((_, option)) = value.split_once('=')
1879 && let Some(prefix) = option.strip_prefix("-Wl,-oso_prefix,")
1880 && !prefix.trim_end_matches('/').is_empty()
1881 && !prefix.contains(',')
1882 {
1883 let trailing_slash = prefix.ends_with('/');
1884 self.parsed.push(Argument::OsoPrefix {
1885 path: PathBuf::from(prefix.trim_end_matches('/')),
1886 trailing_slash,
1887 });
1888 return Ok(());
1889 }
1890 self.parsed
1891 .push(Argument::Plain(format!("--codegen={value}")));
1892 if name == "extra-filename" {
1893 self.extra_filename = value
1894 .split_once('=')
1895 .map_or(String::new(), |(_, value)| value.to_string());
1896 }
1897 Ok(())
1898 }
1899
1900 fn require_native_libraries(&mut self, link_output: LinkOutput) -> Result<(), BypassReason> {
1915 for library in std::mem::take(&mut self.native_libraries) {
1916 if link_output != LinkOutput::Library {
1917 return Err(BypassReason::NativeLibrary(library));
1918 }
1919 let Some((kind, name)) = library.split_once('=') else {
1927 continue;
1928 };
1929 let (kind, modifiers) = kind.split_once(':').unwrap_or((kind, ""));
1930 match kind {
1931 "static" => {}
1932 "dylib" | "framework" | "link-arg" => continue,
1933 _ => return Err(BypassReason::UnknownFlag(format!("-l{library}"))),
1934 }
1935 let name = name.split_once(':').map_or(name, |(_, renamed)| renamed);
1938 let (mut verbatim, mut bundle) = (false, true);
1939 for modifier in modifiers.split(',') {
1940 match modifier {
1941 "+verbatim" => verbatim = true,
1942 "-verbatim" => verbatim = false,
1943 "+bundle" => bundle = true,
1944 "-bundle" => bundle = false,
1945 _ => {}
1946 }
1947 }
1948 if !bundle {
1949 continue;
1950 }
1951 let archive = self
1952 .find_native_static_library(name, verbatim)
1953 .map_err(|()| BypassReason::CustomTargetNativeLibrary(library.clone()))?
1954 .ok_or_else(|| BypassReason::MissingNativeLibrary(library.clone()))?;
1955 self.required_inputs.push(archive);
1956 }
1957 Ok(())
1958 }
1959
1960 fn find_native_static_library(
1972 &self,
1973 name: &str,
1974 verbatim: bool,
1975 ) -> Result<Option<PathBuf>, ()> {
1976 let file_names = if verbatim {
1977 vec![name.to_owned()]
1978 } else {
1979 match self.static_library_naming() {
1980 Some(StaticLibraryNaming::Msvc) => {
1981 vec![format!("{name}.lib"), format!("lib{name}.a")]
1982 }
1983 Some(StaticLibraryNaming::Unix) => vec![format!("lib{name}.a")],
1984 None => return Err(()),
1985 }
1986 };
1987 Ok(self
1988 .parsed
1989 .iter()
1990 .filter_map(|argument| match argument {
1991 Argument::SearchPath { kind, path } if searches_native(kind) => Some(path),
1992 _ => None,
1993 })
1994 .flat_map(|directory| {
1995 file_names
1996 .iter()
1997 .map(move |file_name| directory.join(file_name))
1998 })
1999 .find(|candidate| candidate.is_file()))
2000 }
2001
2002 fn static_library_naming(&self) -> Option<StaticLibraryNaming> {
2010 let Some(target) = self.target.as_deref() else {
2011 return Some(if cfg!(any(target_env = "msvc", target_os = "uefi")) {
2012 StaticLibraryNaming::Msvc
2013 } else {
2014 StaticLibraryNaming::Unix
2015 });
2016 };
2017 if target.ends_with(".json")
2018 || target.contains(['/', '\\'])
2019 || self.options.custom_target_search
2020 {
2021 return None;
2022 }
2023 Some(if target.contains("msvc") || target.ends_with("-uefi") {
2026 StaticLibraryNaming::Msvc
2027 } else {
2028 StaticLibraryNaming::Unix
2029 })
2030 }
2031
2032 fn parse_input(&mut self, value: &str) -> Result<(), BypassReason> {
2033 if value == "-" {
2034 return Err(BypassReason::StandardInput);
2035 }
2036 if self.source.replace(value.into()).is_some() {
2037 return Err(BypassReason::MultipleInputs);
2038 }
2039 Ok(())
2040 }
2041
2042 fn classify(&self) -> Result<LinkOutput, BypassReason> {
2043 let never_links = !self.emits.iter().any(|emit| emit.kind == "link");
2052 let builds_a_library = !self.test
2053 && !self.crate_types.is_empty()
2054 && self
2055 .crate_types
2056 .iter()
2057 .all(|crate_type| matches!(crate_type.as_str(), "lib" | "rlib"));
2058 let link_output = if never_links || builds_a_library {
2059 LinkOutput::Library
2060 } else if self
2061 .target
2062 .as_deref()
2063 .is_some_and(compiler_bundled_wasm_target)
2064 && ((self.test && self.crate_types.is_empty())
2065 || matches!(self.crate_types.as_slice(), [kind] if kind == "bin" || kind == "cdylib"))
2066 {
2067 if self.parsed.iter().any(|argument| match argument {
2068 Argument::Plain(value) if value == "--codegen=link-self-contained" => false,
2069 Argument::Plain(value) if value.starts_with("--codegen=link-self-contained=") => {
2070 !matches!(
2071 value.rsplit_once('=').map(|(_, value)| value),
2072 Some("y" | "yes" | "on" | "true")
2073 )
2074 }
2075 _ => false,
2076 }) {
2077 return Err(BypassReason::UnknownCodegenOption(
2078 "link-self-contained".into(),
2079 ));
2080 }
2081 if self.target.as_deref().is_some_and(|target| target.contains("wasi"))
2082 && self.parsed.iter().any(|argument| {
2083 matches!(argument, Argument::Plain(value) if value.strip_prefix("--codegen=target-feature=").is_some_and(|features| features.split(',').any(|feature| feature == "-crt-static")))
2084 })
2085 {
2086 return Err(BypassReason::UnknownCodegenOption(
2087 "target-feature=-crt-static".into(),
2088 ));
2089 }
2090 LinkOutput::WasmExecutable
2094 } else if self.options.cache_native_links && self.links_a_native_artifact() {
2095 self.check_native_link_is_portable()?;
2096 if matches!(self.crate_types.as_slice(), [kind] if kind == "proc-macro") {
2097 LinkOutput::NativeProcMacro
2098 } else if matches!(self.crate_types.as_slice(), [kind] if kind == "cdylib") {
2099 LinkOutput::NativeSharedLibrary
2100 } else {
2101 LinkOutput::NativeExecutable
2102 }
2103 } else if self.test {
2104 return Err(BypassReason::UnsupportedCrateType("test".into()));
2105 } else {
2106 return Err(BypassReason::UnsupportedCrateType(
2107 self.crate_types
2108 .iter()
2109 .find(|crate_type| !matches!(crate_type.as_str(), "lib" | "rlib"))
2110 .cloned()
2111 .unwrap_or_else(|| "bin".into()),
2112 ));
2113 };
2114 if link_output != LinkOutput::Library
2123 && let Some(option) = self.first_link_argument(link_output)
2124 {
2125 return Err(BypassReason::UnmodeledLinkArgument(option.to_owned()));
2126 }
2127 if self
2128 .parsed
2129 .iter()
2130 .any(|arg| matches!(arg, Argument::InstallName(_)))
2131 && !(cfg!(target_os = "macos") && link_output == LinkOutput::NativeProcMacro)
2132 {
2133 return Err(BypassReason::UnmodeledLinkArgument(
2134 "link-arg=-Wl,-install_name".into(),
2135 ));
2136 }
2137 if self
2141 .parsed
2142 .iter()
2143 .any(|argument| matches!(argument, Argument::Rpath(_)))
2144 && !(link_output == LinkOutput::Library
2145 || cfg!(target_os = "macos")
2146 && matches!(
2147 link_output,
2148 LinkOutput::NativeExecutable
2149 | LinkOutput::NativeProcMacro
2150 | LinkOutput::NativeSharedLibrary
2151 ))
2152 {
2153 return Err(BypassReason::UnmodeledLinkArgument(
2154 "link-arg=-Wl,-rpath".into(),
2155 ));
2156 }
2157 if let Some(selection) = self.parsed.iter().find_map(|argument| {
2164 let Argument::FuseLd(selection) = argument else {
2165 return None;
2166 };
2167 Some(selection.as_str())
2168 }) && !matches!(
2169 link_output,
2170 LinkOutput::Library
2171 | LinkOutput::NativeExecutable
2172 | LinkOutput::NativeProcMacro
2173 | LinkOutput::NativeSharedLibrary
2174 ) {
2175 return Err(BypassReason::UnmodeledLinkArgument(format!(
2176 "link-arg=-fuse-ld={selection}"
2177 )));
2178 }
2179 if self.parsed.iter().any(|argument| {
2180 matches!(argument, Argument::Plain(value) if value.starts_with("--codegen=linker="))
2181 }) && !matches!(
2182 link_output,
2183 LinkOutput::Library
2184 | LinkOutput::NativeExecutable
2185 | LinkOutput::NativeProcMacro
2186 | LinkOutput::NativeSharedLibrary
2187 ) {
2188 return Err(BypassReason::UnknownCodegenOption("linker".into()));
2189 }
2190 if link_output != LinkOutput::Library
2195 && self.parsed.iter().any(|argument| {
2196 matches!(argument, Argument::Plain(value) if value.starts_with("--codegen=linker-flavor="))
2197 })
2198 {
2199 return Err(BypassReason::UnknownCodegenOption("linker-flavor".into()));
2200 }
2201 if !matches!(
2205 link_output,
2206 LinkOutput::Library
2207 | LinkOutput::NativeExecutable
2208 | LinkOutput::NativeProcMacro
2209 | LinkOutput::NativeSharedLibrary
2210 ) && self
2211 .parsed
2212 .iter()
2213 .any(|argument| matches!(argument, Argument::OsoPrefix { .. }))
2214 {
2215 return Err(BypassReason::UnmodeledLinkArgument(
2216 "link-arg=-Wl,-oso_prefix".into(),
2217 ));
2218 }
2219 if let Some(name) = self.parsed.iter().find_map(|argument| match argument {
2220 Argument::Extern { name, path: None } if name != "proc_macro" => Some(name),
2221 _ => None,
2222 }) {
2223 return Err(BypassReason::UnresolvedExtern(name.clone()));
2224 }
2225 if let Some(emit) = self
2226 .emits
2227 .iter()
2228 .find(|emit| !matches!(emit.kind.as_str(), "dep-info" | "link" | "metadata"))
2229 {
2230 return Err(BypassReason::UnsupportedEmit(emit.kind.clone()));
2231 }
2232 if !self
2233 .emits
2234 .iter()
2235 .any(|emit| matches!(emit.kind.as_str(), "link" | "metadata"))
2236 {
2237 return Err(BypassReason::NoCacheableOutput);
2238 }
2239 Ok(link_output)
2240 }
2241}
2242
2243impl Parser<'_> {
2244 fn first_link_argument(&self, link_output: LinkOutput) -> Option<&str> {
2247 self.parsed.iter().find_map(|argument| {
2248 let Argument::Plain(value) = argument else {
2249 return None;
2250 };
2251 let option = value.strip_prefix("--codegen=")?;
2252 let (name, value) = option.split_once('=').unwrap_or((option, ""));
2253 (matches!(name, "link-arg" | "link-args")
2254 && !(name == "link-arg" && elf_keyword_is_modeled(link_output, value))
2255 && !msvc_options_are_modeled(link_output, name, value))
2256 .then_some(option)
2257 })
2258 }
2259
2260 fn oso_prefix_covers_outputs(&self) -> bool {
2269 let Some(directory) = self
2270 .out_dir
2271 .as_deref()
2272 .or_else(|| self.explicit_output.as_deref().and_then(Path::parent))
2273 else {
2274 return false;
2275 };
2276 if !directory.is_absolute() {
2277 return false;
2278 }
2279 let directory = normalize_components(directory);
2280 self.parsed.iter().any(|argument| {
2281 let Argument::OsoPrefix { path, .. } = argument else {
2282 return false;
2283 };
2284 path.is_absolute()
2285 && (directory.starts_with(normalize_components(path))
2286 || std::fs::canonicalize(&directory)
2287 .ok()
2288 .zip(std::fs::canonicalize(path).ok())
2289 .is_some_and(|(directory, prefix)| directory.starts_with(prefix)))
2290 })
2291 }
2292
2293 fn links_a_native_artifact(&self) -> bool {
2300 self.target.is_none()
2301 && self.emits.iter().any(|emit| emit.kind == "link")
2306 && ((self.test && self.crate_types.is_empty())
2307 || matches!(self.crate_types.as_slice(), [kind] if matches!(kind.as_str(), "bin" | "proc-macro"))
2308 || (cfg!(target_os = "linux")
2309 && matches!(self.crate_types.as_slice(), [kind] if kind == "cdylib")))
2310 }
2311
2312 fn check_native_link_is_portable(&self) -> Result<(), BypassReason> {
2319 for argument in &self.parsed {
2320 let Argument::Plain(value) = argument else {
2321 continue;
2322 };
2323 let (name, value) = if value == "-g" {
2326 ("debuginfo", Some("2"))
2327 } else if let Some(option) = value.strip_prefix("--codegen=") {
2328 match option.split_once('=') {
2329 Some((name, value)) => (name, Some(value)),
2330 None => (option, None),
2334 }
2335 } else {
2336 continue;
2337 };
2338 let unportable = match name {
2339 "split-debuginfo" => match value {
2345 Some("off") => false,
2346 Some("unpacked") if cfg!(target_os = "macos") => {
2347 !self.oso_prefix_covers_outputs()
2348 }
2349 _ => true,
2350 },
2351 "debuginfo" if cfg!(target_os = "macos") => {
2360 !matches!(value, Some("0" | "none")) && !self.oso_prefix_covers_outputs()
2361 }
2362 "rpath" => is_enabled(value),
2370 "prefer-dynamic" => {
2371 is_enabled(value)
2372 && !matches!(self.crate_types.as_slice(), [kind] if kind == "proc-macro")
2373 }
2374 "link-self-contained" => true,
2377 _ => false,
2378 };
2379 if unportable {
2380 return Err(BypassReason::UnportableNativeLink(match value {
2381 Some(value) => format!("{name}={value}"),
2382 None => name.to_owned(),
2383 }));
2384 }
2385 }
2386 Ok(())
2387 }
2388}
2389
2390fn safe_install_name(name: &str) -> bool {
2391 !name.is_empty()
2392 && name
2393 .bytes()
2394 .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))
2395}
2396
2397fn is_enabled(value: Option<&str>) -> bool {
2400 matches!(value, None | Some("y" | "yes" | "on" | "true"))
2401}
2402
2403fn elf_keyword_is_modeled(link_output: LinkOutput, value: &str) -> bool {
2413 cfg!(target_os = "linux")
2414 && matches!(
2415 link_output,
2416 LinkOutput::NativeExecutable
2417 | LinkOutput::NativeProcMacro
2418 | LinkOutput::NativeSharedLibrary
2419 )
2420 && value.strip_prefix("-Wl,-z,").is_some_and(|keyword| {
2421 matches!(
2422 keyword,
2423 "defs"
2424 | "lazy"
2425 | "nodelete"
2426 | "nodlopen"
2427 | "noexecstack"
2428 | "norelro"
2429 | "now"
2430 | "origin"
2431 | "relro"
2432 )
2433 })
2434}
2435
2436fn msvc_options_are_modeled(link_output: LinkOutput, name: &str, value: &str) -> bool {
2452 cfg!(target_env = "msvc")
2453 && matches!(
2454 link_output,
2455 LinkOutput::NativeExecutable
2456 | LinkOutput::NativeProcMacro
2457 | LinkOutput::NativeSharedLibrary
2458 )
2459 && match name {
2460 "link-arg" => msvc_option_reads_no_file(value),
2461 "link-args" => {
2464 let mut options = value.split_ascii_whitespace().peekable();
2465 options.peek().is_some() && options.all(msvc_option_reads_no_file)
2466 }
2467 _ => false,
2468 }
2469}
2470
2471fn msvc_option_reads_no_file(option: &str) -> bool {
2475 let Some(option) = option.strip_prefix(['/', '-']) else {
2476 return false;
2477 };
2478 if option.eq_ignore_ascii_case("brepro") {
2479 return true;
2480 }
2481 let Some((name, sizes)) = option.split_once(':') else {
2482 return false;
2483 };
2484 let is_size = |size: &str| match size.strip_prefix("0x").or_else(|| size.strip_prefix("0X")) {
2487 Some(hex) => !hex.is_empty() && hex.bytes().all(|byte| byte.is_ascii_hexdigit()),
2488 None => !size.is_empty() && size.bytes().all(|byte| byte.is_ascii_digit()),
2489 };
2490 name.eq_ignore_ascii_case("stack")
2491 && sizes.split(',').count() <= 2
2492 && sizes.split(',').all(is_size)
2493}
2494
2495fn compiler_bundled_wasm_target(target: &str) -> bool {
2496 COMPILER_BUNDLED_WASM_TARGETS.binary_search(&target).is_ok()
2497}
2498
2499fn parse_emits(value: &str) -> Vec<Emit> {
2500 value
2501 .split(',')
2502 .map(|emit| {
2503 let (kind, path) = emit
2504 .split_once('=')
2505 .map_or((emit, None), |(kind, path)| (kind, Some(path.into())));
2506 Emit {
2507 kind: kind.into(),
2508 path,
2509 }
2510 })
2511 .collect()
2512}
2513
2514struct ActionBuilder<'a> {
2515 invocation: &'a RustcInvocation,
2516 context: ActionContext,
2517 mappings: Vec<SharedPathMapping>,
2518 aliases: PathAliases,
2522 linker: Option<LinkerIdentity>,
2523}
2524
2525impl<'a> ActionBuilder<'a> {
2526 fn new(invocation: &'a RustcInvocation, mut context: ActionContext) -> Self {
2527 context.path_mappings = PathMapping::ordered(&context.path_mappings);
2528 let mappings = resolve_path_mappings(&shared_path_mappings(&context.path_mappings));
2529 Self {
2530 linker: None,
2531 invocation,
2532 mappings,
2533 aliases: PathAliases::default(),
2534 context,
2535 }
2536 }
2537
2538 fn linked_by(mut self, linker: Option<LinkerIdentity>) -> Self {
2539 self.linker = linker;
2540 self
2541 }
2542
2543 fn build(self) -> Result<RustcAction, BypassReason> {
2544 self.validate_mappings()?;
2545 let invocation = self.invocation_descriptor()?;
2546 let environment = self.environment_descriptor()?;
2547
2548 let mut inputs = BTreeMap::<String, CacheDigest>::new();
2549 for input in &self.context.inputs {
2550 input
2551 .digest
2552 .validate()
2553 .map_err(|_| BypassReason::InvalidInputDigest(input.path.display().to_string()))?;
2554 let path = self.normalize_input_path(&input.path)?;
2555 if inputs
2556 .insert(path.clone(), input.digest.clone())
2557 .is_some_and(|existing| existing != input.digest)
2558 {
2559 return Err(BypassReason::ConflictingInput(path));
2560 }
2561 }
2562 let required = self
2563 .invocation
2564 .required_inputs
2565 .iter()
2566 .map(|path| self.normalize_input_path(path))
2567 .collect::<Result<BTreeSet<_>, _>>()?;
2568 if let Some(missing) = required.iter().find(|path| !inputs.contains_key(*path)) {
2569 return Err(BypassReason::MissingRequiredInput(missing.clone()));
2570 }
2571 let inputs = inputs
2572 .into_iter()
2573 .map(|(path, digest)| InputDescriptor { path, digest })
2574 .collect();
2575 if self.invocation.links_natively() && self.linker.is_none() {
2578 return Err(BypassReason::UnportableNativeLink(
2579 "linker identity is unknown".into(),
2580 ));
2581 }
2582 let descriptor = ActionDescriptor {
2583 version: ACTION_SCHEMA_VERSION,
2584 kind: "rustc",
2585 adapter_version: ADAPTER_VERSION,
2586 compiler: invocation.compiler,
2587 arguments: invocation.arguments,
2588 environment,
2589 inputs,
2590 linker: self.linker.clone(),
2591 };
2592 let bytes = canonical_json(&descriptor)
2593 .map_err(|error| BypassReason::Serialization(error.to_string()))?;
2594 let digest = CacheDigest::blake3(&bytes);
2595 Ok(RustcAction { digest, bytes })
2596 }
2597
2598 fn invocation_descriptor(&self) -> Result<InvocationDescriptor, BypassReason> {
2599 self.validate_mappings()?;
2600 let arguments = self
2601 .invocation
2602 .arguments
2603 .iter()
2604 .map(|argument| self.normalize_argument(argument))
2605 .collect::<Result<Vec<_>, _>>()?;
2606 let required_inputs = self
2607 .invocation
2608 .required_inputs
2609 .iter()
2610 .map(|path| self.normalize_path(path))
2611 .collect::<Result<BTreeSet<_>, _>>()?
2612 .into_iter()
2613 .collect();
2614 Ok(InvocationDescriptor {
2615 version: ACTION_SCHEMA_VERSION,
2616 kind: "rustc",
2617 adapter_version: ADAPTER_VERSION,
2618 compiler: CompilerDescriptor {
2619 toolchain: self.context.compiler.toolchain.clone(),
2620 rustc_version: self.context.compiler.rustc_version.clone(),
2621 host: self.context.compiler.host.clone(),
2622 driver: self.context.compiler.driver.clone(),
2623 },
2624 arguments,
2625 required_inputs,
2626 })
2627 }
2628
2629 fn validate_mappings(&self) -> Result<(), BypassReason> {
2630 if !self.context.working_dir.is_absolute() {
2631 return Err(BypassReason::RelativeWorkingDirectory(
2632 self.context.working_dir.clone(),
2633 ));
2634 }
2635 let mut roots = BTreeSet::new();
2636 let mut placeholders = BTreeSet::new();
2637 for mapping in &self.mappings {
2638 if !mapping.root.is_absolute() {
2639 return Err(BypassReason::RelativePathMapping(mapping.root.clone()));
2640 }
2641 if mapping.placeholder.is_empty()
2642 || !mapping
2643 .placeholder
2644 .bytes()
2645 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
2646 || !roots.insert(normalize_components(&mapping.root))
2647 || !placeholders.insert(&mapping.placeholder)
2648 {
2649 return Err(BypassReason::InvalidPathPlaceholder(
2650 mapping.placeholder.clone(),
2651 ));
2652 }
2653 }
2654 Ok(())
2655 }
2656
2657 fn normalize_argument(&self, argument: &Argument) -> Result<String, BypassReason> {
2658 match argument {
2659 Argument::Plain(value) => Ok(value.clone()),
2660 Argument::Path { flag, path } => Ok(format!("{flag}={}", self.normalize_path(path)?)),
2661 Argument::SearchPath { kind, path } => {
2662 let text = self.normalize_path(path)?;
2663 Ok(format!("-L{kind}={text}"))
2664 }
2665 Argument::Extern { name, path } => match path {
2666 Some(path) => Ok(format!("--extern={name}={}", self.normalize_path(path)?)),
2667 None => Ok(format!("--extern={name}")),
2668 },
2669 Argument::Emit(emits) => Ok(format!(
2670 "--emit={}",
2671 emits
2672 .iter()
2673 .map(|emit| match &emit.path {
2674 Some(path) => self
2675 .normalize_path(path)
2676 .map(|path| format!("{}={path}", emit.kind)),
2677 None => Ok(emit.kind.clone()),
2678 })
2679 .collect::<Result<Vec<_>, _>>()?
2680 .join(",")
2681 )),
2682 Argument::RemapPath { from, to } => Ok(format!(
2683 "--remap-path-prefix={}={}",
2684 self.normalize_path(from)?,
2685 to
2686 )),
2687 Argument::InstallName(name) => Ok(format!(
2688 "--codegen=link-arg=-Wl,-install_name,@rpath/{name}"
2689 )),
2690 Argument::OsoPrefix {
2691 path,
2692 trailing_slash,
2693 } => Ok(format!(
2694 "--codegen=link-arg=-Wl,-oso_prefix,{}{}",
2695 self.normalize_path(path)?,
2696 if *trailing_slash { "/" } else { "" }
2697 )),
2698 Argument::FuseLd(selection) => Ok(format!("--codegen=link-arg=-fuse-ld={selection}")),
2699 Argument::Rpath(directory) => Ok(format!("--codegen=link-arg=-Wl,-rpath,{directory}")),
2701 }
2702 }
2703
2704 fn environment_descriptor(&self) -> Result<BTreeMap<String, Option<String>>, BypassReason> {
2711 self.context
2712 .environment
2713 .iter()
2714 .map(|(name, value)| {
2715 let value = match value {
2716 Some(value) if self.context.portable_environment.contains(name) => {
2717 Some(self.normalize_path(Path::new(value))?)
2718 }
2719 value => value.clone(),
2720 };
2721 Ok((name.clone(), value))
2722 })
2723 .collect()
2724 }
2725
2726 fn normalize_input_path(&self, path: &Path) -> Result<String, BypassReason> {
2727 let absolute = normalize_components(&self.context.working_dir.join(path));
2728 for directory in self.invocation.native_search_paths() {
2729 let directory = normalize_components(&self.context.working_dir.join(directory));
2730 if let Ok(relative) = absolute.strip_prefix(&directory) {
2731 let suffix = relative
2737 .components()
2738 .map(|component| {
2739 component
2740 .as_os_str()
2741 .to_str()
2742 .ok_or_else(|| BypassReason::NonUtf8Path(path.to_path_buf()))
2743 })
2744 .collect::<Result<Vec<_>, _>>()?
2745 .join("/");
2746 if !suffix.is_empty() {
2747 return Ok(format!("{}/{}", self.normalize_path(&directory)?, suffix));
2748 }
2749 }
2750 }
2751 self.normalize_path(path)
2752 }
2753
2754 fn normalize_path(&self, path: &Path) -> Result<String, BypassReason> {
2755 normalize_resolved_shared_path_with(
2756 &self.aliases,
2757 path,
2758 &self.context.working_dir,
2759 &self.mappings,
2760 )
2761 .map_err(Into::into)
2762 }
2763}
2764
2765fn under_any_directory(path: &str, directories: &BTreeSet<String>) -> bool {
2769 directories.iter().any(|directory| {
2770 path.len() > directory.len()
2771 && path.as_bytes()[directory.len()] == b'/'
2772 && path.starts_with(directory)
2773 })
2774}
2775
2776fn denormalize_path(value: &str, mappings: &[PathMapping]) -> Result<PathBuf, BypassReason> {
2777 for mapping in mappings {
2778 let prefix = format!("${{{}}}", mapping.placeholder);
2779 let suffix = if value == prefix {
2780 ""
2781 } else if let Some(suffix) = value.strip_prefix(&format!("{prefix}/")) {
2782 suffix
2783 } else {
2784 continue;
2785 };
2786 if !mapping.root.is_absolute()
2787 || (!suffix.is_empty()
2788 && suffix.split('/').any(|component| {
2789 component.is_empty()
2790 || matches!(component, "." | "..")
2791 || component.contains('\\')
2792 }))
2793 {
2794 return Err(BypassReason::InvalidPredictedInput(value.into()));
2795 }
2796 let mut path = normalize_components(&mapping.root);
2797 path.extend(suffix.split('/').filter(|component| !component.is_empty()));
2798 return Ok(path);
2799 }
2800 Err(BypassReason::InvalidPredictedInput(value.into()))
2801}
2802
2803fn normalize_components(path: &Path) -> PathBuf {
2804 let mut normalized = PathBuf::new();
2805 for component in path.components() {
2806 match component {
2807 Component::CurDir => {}
2808 Component::ParentDir => {
2809 normalized.pop();
2810 }
2811 component => normalized.push(component.as_os_str()),
2812 }
2813 }
2814 normalized
2815}
2816
2817fn absolute_path(path: &Path, working_dir: &Path) -> PathBuf {
2818 if path.is_absolute() {
2819 normalize_components(path)
2820 } else {
2821 normalize_components(&working_dir.join(path))
2822 }
2823}
2824
2825#[cfg(test)]
2826#[path = "rustc_cache_tests.rs"]
2827mod tests;