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
347#[derive(Debug, Clone, PartialEq, Eq)]
348enum Argument {
349 Plain(String),
350 Path {
351 flag: String,
352 path: PathBuf,
353 },
354 SearchPath {
355 kind: String,
356 path: PathBuf,
357 },
358 Extern {
359 name: String,
360 path: Option<PathBuf>,
361 },
362 Emit(Vec<Emit>),
363 RemapPath {
364 from: PathBuf,
365 to: String,
366 },
367 InstallName(String),
369 OsoPrefix {
372 path: PathBuf,
373 trailing_slash: bool,
374 },
375 FuseLd(String),
379}
380
381#[derive(Debug, Clone, PartialEq, Eq)]
382struct Emit {
383 kind: String,
384 path: Option<PathBuf>,
385}
386
387#[derive(Debug, Clone, PartialEq, Eq)]
388pub struct RustcInvocation {
393 arguments: Vec<Argument>,
394 source: PathBuf,
395 required_inputs: Vec<PathBuf>,
396 crate_name: String,
397 extra_filename: String,
398 out_dir: Option<PathBuf>,
399 explicit_output: Option<PathBuf>,
400 emits: Vec<Emit>,
401 target: Option<String>,
402 link_output: LinkOutput,
403}
404
405#[derive(Debug, Clone, Copy, PartialEq, Eq)]
406enum LinkOutput {
407 Library,
408 WasmExecutable,
409 NativeExecutable,
410 NativeProcMacro,
411 NativeSharedLibrary,
416}
417
418#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
424#[non_exhaustive]
425pub struct ParseOptions {
426 pub cache_native_links: bool,
429 pub custom_target_search: bool,
435}
436
437impl ParseOptions {
438 pub fn caching_native_links(enabled: bool) -> Self {
440 Self {
441 cache_native_links: enabled,
442 ..Self::default()
443 }
444 }
445
446 pub fn with_custom_target_search(mut self, enabled: bool) -> Self {
449 self.custom_target_search = enabled;
450 self
451 }
452}
453
454#[derive(Debug, Clone, PartialEq, Eq)]
456pub struct RustcOutputs {
457 pub directory: PathBuf,
459 pub files: Vec<PathBuf>,
461 pub dep_info: PathBuf,
463}
464
465impl RustcInvocation {
466 pub fn parse(arguments: &[OsString]) -> Result<Self, BypassReason> {
475 Self::parse_with(arguments, ParseOptions::default())
476 }
477
478 pub fn expand_arguments(arguments: &[OsString]) -> Result<Vec<OsString>, BypassReason> {
483 Ok(expand_response_files(arguments)?.arguments)
484 }
485
486 pub fn parse_with(arguments: &[OsString], options: ParseOptions) -> Result<Self, BypassReason> {
489 let expanded = expand_response_files(arguments)?;
490 Parser::new(&expanded.arguments, options).parse()
491 }
492
493 pub fn links_natively(&self) -> bool {
496 matches!(
497 self.link_output,
498 LinkOutput::NativeExecutable
499 | LinkOutput::NativeProcMacro
500 | LinkOutput::NativeSharedLibrary
501 )
502 }
503
504 pub fn portable_install_name(&self, outputs: &RustcOutputs) -> Option<String> {
508 if !cfg!(target_os = "macos")
509 || self.link_output != LinkOutput::NativeProcMacro
510 || self
511 .arguments
512 .iter()
513 .any(|arg| matches!(arg, Argument::InstallName(_)))
514 {
515 return None;
516 }
517 let file = outputs
518 .files
519 .iter()
520 .find(|path| path.extension().is_some_and(|ext| ext == "dylib"))?;
521 let name = file.file_name()?.to_str()?;
522 if !safe_install_name(name) {
523 return None;
524 }
525 Some(format!("-Clink-arg=-Wl,-install_name,@rpath/{name}"))
526 }
527
528 pub fn linker_override(&self) -> Option<&Path> {
531 self.arguments.iter().find_map(|argument| {
532 let Argument::Plain(value) = argument else {
533 return None;
534 };
535 value.strip_prefix("--codegen=linker=").map(Path::new)
536 })
537 }
538
539 pub fn fuse_ld(&self) -> Option<&str> {
542 self.arguments.iter().find_map(|argument| {
543 let Argument::FuseLd(selection) = argument else {
544 return None;
545 };
546 Some(selection.as_str())
547 })
548 }
549
550 fn emits_windows_pdb(&self) -> bool {
551 if !cfg!(windows) || !self.links_natively() {
552 return false;
553 }
554 let mut enabled = false;
555 for argument in &self.arguments {
556 let Argument::Plain(value) = argument else {
557 continue;
558 };
559 if value == "-g" {
560 enabled = true;
561 } else if let Some(value) = value.strip_prefix("--codegen=debuginfo=") {
562 enabled = !matches!(value, "0" | "none");
563 }
564 }
565 enabled
566 }
567
568 pub fn native_search_paths(&self) -> impl Iterator<Item = &Path> {
572 self.arguments.iter().filter_map(|argument| match argument {
573 Argument::SearchPath { kind, path } if kind == "native" => Some(path.as_path()),
574 _ => None,
575 })
576 }
577
578 pub fn source(&self) -> &Path {
580 &self.source
581 }
582
583 pub fn required_inputs_in(&self, working_dir: &Path) -> Vec<PathBuf> {
589 self.required_inputs
590 .iter()
591 .map(|path| absolute_path(path, working_dir))
592 .collect()
593 }
594
595 pub fn target(&self) -> Option<&str> {
597 self.target.as_deref()
598 }
599
600 pub fn crate_name(&self) -> &str {
602 &self.crate_name
603 }
604
605 pub fn remaps_working_directory(&self) -> bool {
614 self.arguments.iter().any(|argument| {
615 matches!(argument, Argument::Plain(flag) if flag.starts_with("-Zremap-cwd-prefix="))
616 })
617 }
618
619 pub fn source_fingerprint(&self, discovered: &DiscoveredInputs) -> CacheDigest {
632 let linked = self
633 .arguments
634 .iter()
635 .filter_map(|argument| match argument {
636 Argument::Extern {
637 path: Some(path), ..
638 } => Some(path.as_path()),
639 _ => None,
640 })
641 .collect::<BTreeSet<_>>();
642 let owned = discovered
643 .inputs
644 .iter()
645 .filter(|input| {
646 !linked.contains(input.path.as_path()) && !discovered.is_native_only(&input.path)
647 })
648 .map(|input| (input.path.as_path(), &input.digest))
649 .collect::<BTreeMap<_, _>>();
650 let mut bytes = Vec::new();
651 for (path, digest) in owned {
652 bytes.extend_from_slice(path.as_os_str().as_encoded_bytes());
653 bytes.push(0);
654 bytes.extend_from_slice(digest.key().as_bytes());
655 bytes.push(0);
656 }
657 CacheDigest::blake3(&bytes)
658 }
659
660 pub fn outputs(&self, working_dir: &Path) -> Result<RustcOutputs, BypassReason> {
665 if !working_dir.is_absolute() {
666 return Err(BypassReason::RelativeWorkingDirectory(
667 working_dir.to_path_buf(),
668 ));
669 }
670 let explicit_output = self
671 .explicit_output
672 .as_deref()
673 .map(|path| absolute_path(path, working_dir));
674 let output_directory = explicit_output
675 .as_deref()
676 .and_then(Path::parent)
677 .map(Path::to_path_buf)
678 .or_else(|| {
679 self.out_dir
680 .as_deref()
681 .map(|path| absolute_path(path, working_dir))
682 })
683 .unwrap_or_else(|| normalize_components(working_dir));
684 if let Some(output) = &explicit_output
688 && self.emits.iter().any(|emit| {
689 emit.path.is_none()
690 && matches!(emit.kind.as_str(), "dep-info" | "link" | "metadata")
691 })
692 {
693 return Err(BypassReason::ImplicitEmitWithOutputFile(output.clone()));
694 }
695 let mut files = BTreeSet::new();
696 let mut dep_info = None;
697 for emit in &self.emits {
698 if emit.kind == "dep-info" {
699 let path = emit.path.as_ref().map_or_else(
700 || {
701 explicit_output.clone().map_or_else(
702 || {
703 output_directory
704 .join(format!("{}{}.d", self.crate_name, self.extra_filename))
705 },
706 |path| path.with_extension("d"),
707 )
708 },
709 |path| absolute_path(path, working_dir),
710 );
711 if path.file_name().is_none() {
712 return Err(BypassReason::InvalidOutputPath(path));
713 }
714 dep_info = Some(path);
715 continue;
716 }
717 let (prefix, extension) = match emit.kind.as_str() {
718 "link" => match self.link_output {
719 LinkOutput::Library => ("lib", "rlib"),
720 LinkOutput::WasmExecutable => ("", "wasm"),
721 LinkOutput::NativeExecutable => ("", std::env::consts::EXE_EXTENSION),
722 LinkOutput::NativeProcMacro | LinkOutput::NativeSharedLibrary => (
723 std::env::consts::DLL_PREFIX,
724 std::env::consts::DLL_SUFFIX.trim_start_matches('.'),
725 ),
726 },
727 "metadata" => ("lib", "rmeta"),
728 _ => continue,
729 };
730 let path = if let Some(path) = &emit.path {
731 absolute_path(path, working_dir)
732 } else {
733 let name = format!("{prefix}{}{}", self.crate_name, self.extra_filename);
734 output_directory.join(if extension.is_empty() {
735 name
736 } else {
737 format!("{name}.{extension}")
738 })
739 };
740 if path.file_name().is_none() {
741 return Err(BypassReason::InvalidOutputPath(path));
742 }
743 if path.parent() != Some(output_directory.as_path()) {
744 return Err(BypassReason::SplitOutputDirectories);
745 }
746 let has_library_extension = path
751 .extension()
752 .and_then(|extension| extension.to_str())
753 .is_some_and(|extension| matches!(extension, "rlib" | "rmeta"))
754 || (cfg!(windows)
755 && path
756 .file_stem()
757 .and_then(|stem| Path::new(stem).extension())
758 .and_then(|extension| extension.to_str())
759 .is_some_and(|extension| matches!(extension, "rlib" | "rmeta")));
760 if emit.kind == "link"
761 && !matches!(self.link_output, LinkOutput::Library)
762 && has_library_extension
763 {
764 return Err(BypassReason::AmbiguousOutputName(path));
765 }
766 if emit.kind == "link" && self.emits_windows_pdb() {
767 files.insert(path.with_extension("pdb"));
768 }
769 files.insert(path);
770 }
771 let dep_info = dep_info.ok_or(BypassReason::NoDepInfo)?;
772 if dep_info.parent() != Some(output_directory.as_path()) {
773 return Err(BypassReason::SplitOutputDirectories);
774 }
775 Ok(RustcOutputs {
776 directory: output_directory,
777 files: files.into_iter().collect(),
778 dep_info,
779 })
780 }
781
782 pub fn action(&self, context: ActionContext) -> Result<RustcAction, BypassReason> {
788 self.action_linked_by(context, None)
789 }
790
791 pub fn action_linked_by(
800 &self,
801 context: ActionContext,
802 linker: Option<LinkerIdentity>,
803 ) -> Result<RustcAction, BypassReason> {
804 ActionBuilder::new(self, context).linked_by(linker).build()
805 }
806
807 pub fn invocation_digest(&self, context: &ActionContext) -> Result<CacheDigest, BypassReason> {
809 let descriptor = ActionBuilder::new(self, context.clone()).invocation_descriptor()?;
810 let bytes = canonical_json(&descriptor)
811 .map_err(|error| BypassReason::Serialization(error.to_string()))?;
812 Ok(CacheDigest::blake3(&bytes))
813 }
814
815 pub fn prediction(
818 &self,
819 context: &ActionContext,
820 discovered: &DiscoveredInputs,
821 ) -> Result<RustcInputPrediction, BypassReason> {
822 let builder = ActionBuilder::new(self, context.clone());
823 builder.validate_mappings()?;
824 let mut native_directories = BTreeSet::new();
825 for argument in &self.arguments {
826 if let Argument::SearchPath { kind, path } = argument
827 && kind == "native"
828 {
829 native_directories.insert(builder.normalize_path(path)?);
830 }
831 }
832 let mut inputs = BTreeSet::new();
844 for input in &discovered.inputs {
845 let normalized = builder.normalize_path(&input.path)?;
846 if !under_any_directory(&normalized, &native_directories)
847 || !discovered.is_native_only(&input.path)
848 {
849 inputs.insert(normalized);
850 }
851 }
852 inputs.extend(
853 native_directories
854 .into_iter()
855 .map(|directory| format!("{NATIVE_DIRECTORY_PREDICTION_PREFIX}{directory}")),
856 );
857 Ok(RustcInputPrediction {
858 version: 4,
859 inputs: inputs.into_iter().collect(),
860 environment: discovered.environment.keys().cloned().collect(),
861 compiler_duration_ns: 0,
862 crate_name: String::new(),
863 })
864 }
865}
866
867pub fn is_build_script_crate_name(crate_name: &str) -> bool {
871 crate_name
872 .strip_prefix("build_script_")
873 .is_some_and(|stem| !stem.is_empty())
874}
875
876impl RustcOutputs {
877 pub fn build_script_executable(&self, crate_name: &str) -> Option<&Path> {
887 is_build_script_crate_name(crate_name)
888 .then(|| self.files.iter().find(|path| self.is_executable(path)))
889 .flatten()
890 .map(PathBuf::as_path)
891 }
892
893 pub fn is_executable(&self, path: &Path) -> bool {
901 self.files.iter().any(|output| output == path)
902 && !matches!(
903 path.extension().and_then(|extension| extension.to_str()),
904 Some("rlib" | "rmeta")
905 )
906 }
907}
908
909#[derive(Debug, Clone, PartialEq, Eq)]
910pub struct PathMapping {
912 pub root: PathBuf,
914 pub placeholder: String,
916}
917
918impl PathMapping {
919 pub fn new(root: impl Into<PathBuf>, placeholder: impl Into<String>) -> Self {
921 Self {
922 root: root.into(),
923 placeholder: placeholder.into(),
924 }
925 }
926
927 pub fn ordered(mappings: &[PathMapping]) -> Vec<PathMapping> {
930 let mut ordered = mappings.to_vec();
931 ordered.sort_by_key(|mapping| std::cmp::Reverse(mapping.root.components().count()));
932 ordered
933 }
934}
935
936fn shared_path_mappings(mappings: &[PathMapping]) -> Vec<SharedPathMapping> {
937 mappings
938 .iter()
939 .map(|mapping| SharedPathMapping::new(&mapping.root, &mapping.placeholder))
940 .collect()
941}
942
943pub fn normalize_mapped_path(
950 path: &Path,
951 working_dir: &Path,
952 mappings: &[PathMapping],
953) -> Result<String, BypassReason> {
954 normalize_shared_path(path, working_dir, &shared_path_mappings(mappings)).map_err(Into::into)
955}
956
957#[derive(Debug, Clone, PartialEq, Eq)]
958pub struct CompilerIdentity {
960 pub toolchain: String,
962 pub rustc_version: String,
964 pub host: String,
966 pub driver: Option<String>,
968}
969
970#[derive(Debug, Clone, PartialEq, Eq)]
972pub struct ActionInput {
973 pub path: PathBuf,
975 pub digest: CacheDigest,
977}
978
979#[derive(Debug, Clone, PartialEq, Eq)]
981pub struct ActionContext {
982 pub compiler: CompilerIdentity,
984 pub working_dir: PathBuf,
986 pub path_mappings: Vec<PathMapping>,
988 pub environment: BTreeMap<String, Option<String>>,
990 pub portable_environment: BTreeSet<String>,
997 pub inputs: Vec<ActionInput>,
999}
1000
1001#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1011#[serde(deny_unknown_fields)]
1012pub struct LinkerIdentity {
1013 pub driver: String,
1015 pub driver_version: String,
1017 pub linker_version: String,
1019 #[serde(skip_serializing_if = "BTreeMap::is_empty", default)]
1021 pub crt_objects: BTreeMap<String, CacheDigest>,
1022 #[serde(skip_serializing_if = "Option::is_none", default)]
1024 pub sdk: Option<String>,
1025 #[serde(skip_serializing_if = "Option::is_none", default)]
1027 pub deployment_target: Option<String>,
1028}
1029
1030#[derive(Debug, Clone, PartialEq, Eq)]
1032pub struct RustcAction {
1033 pub digest: CacheDigest,
1035 pub bytes: Vec<u8>,
1037}
1038
1039#[derive(Debug, Clone, PartialEq, Eq)]
1042pub struct RustcInputPrediction {
1043 pub version: u8,
1045 pub inputs: Vec<String>,
1047 pub environment: Vec<String>,
1049 pub compiler_duration_ns: u64,
1052 pub crate_name: String,
1054}
1055
1056#[derive(Serialize, Deserialize)]
1057#[serde(deny_unknown_fields)]
1058struct RustcInputPredictionWire {
1059 version: u8,
1060 inputs: Vec<String>,
1061 environment: Vec<String>,
1062 #[serde(default, skip_serializing_if = "is_zero")]
1063 compiler_duration_ns: u64,
1064 #[serde(default, skip_serializing_if = "String::is_empty")]
1065 crate_name: String,
1066}
1067
1068impl Serialize for RustcInputPrediction {
1069 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1070 where
1071 S: Serializer,
1072 {
1073 RustcInputPredictionWire {
1074 version: self.version,
1075 inputs: if self.version == 4 {
1076 compact_prediction_inputs(&self.inputs)
1077 } else {
1078 self.inputs.clone()
1079 },
1080 environment: self.environment.clone(),
1081 compiler_duration_ns: self.compiler_duration_ns,
1082 crate_name: self.crate_name.clone(),
1083 }
1084 .serialize(serializer)
1085 }
1086}
1087
1088impl<'de> Deserialize<'de> for RustcInputPrediction {
1089 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1090 where
1091 D: Deserializer<'de>,
1092 {
1093 let wire = RustcInputPredictionWire::deserialize(deserializer)?;
1094 let inputs = if wire.version == 4 {
1095 expand_prediction_inputs(&wire.inputs).map_err(serde::de::Error::custom)?
1096 } else {
1097 wire.inputs
1098 };
1099 Ok(Self {
1100 version: wire.version,
1101 inputs,
1102 environment: wire.environment,
1103 compiler_duration_ns: wire.compiler_duration_ns,
1104 crate_name: wire.crate_name,
1105 })
1106 }
1107}
1108
1109fn compact_prediction_inputs(inputs: &[String]) -> Vec<String> {
1110 let mut previous = "";
1111 inputs
1112 .iter()
1113 .map(|input| {
1114 let mut shared = previous
1115 .bytes()
1116 .zip(input.bytes())
1117 .take_while(|(left, right)| left == right)
1118 .count();
1119 while !input.is_char_boundary(shared) {
1120 shared -= 1;
1121 }
1122 let compact = format!("{shared}:{}", &input[shared..]);
1123 previous = input;
1124 compact
1125 })
1126 .collect()
1127}
1128
1129fn expand_prediction_inputs(inputs: &[String]) -> Result<Vec<String>, &'static str> {
1130 let mut expanded: Vec<String> = Vec::with_capacity(inputs.len());
1131 let mut decoded_bytes = 0_usize;
1132 for input in inputs {
1133 let (shared_text, suffix) = input
1134 .split_once(':')
1135 .ok_or("compact rustc prediction input has no prefix length")?;
1136 let shared: usize = shared_text
1137 .parse()
1138 .map_err(|_| "compact rustc prediction prefix length is invalid")?;
1139 if shared.to_string() != shared_text
1140 || shared > expanded.last().map_or(0, String::len)
1141 || expanded
1142 .last()
1143 .is_some_and(|previous| !previous.is_char_boundary(shared))
1144 {
1145 return Err("compact rustc prediction prefix is not canonical");
1146 }
1147 let mut path = expanded
1148 .last()
1149 .map_or_else(String::new, |previous| previous[..shared].to_string());
1150 path.push_str(suffix);
1151 decoded_bytes = decoded_bytes
1152 .checked_add(path.len())
1153 .ok_or("compact rustc prediction is too large")?;
1154 if decoded_bytes > MAX_DECODED_PREDICTION_BYTES {
1155 return Err("compact rustc prediction is too large");
1156 }
1157 expanded.push(path);
1158 }
1159 Ok(expanded)
1160}
1161
1162fn is_zero(value: &u64) -> bool {
1163 *value == 0
1164}
1165
1166impl RustcInputPrediction {
1167 pub fn discover(
1170 &self,
1171 working_dir: &Path,
1172 path_mappings: &[PathMapping],
1173 digests: &dyn FileDigestCache,
1174 ) -> Result<DiscoveredInputs, BypassReason> {
1175 if !matches!(self.version, 2..=4) {
1176 return Err(BypassReason::UnsupportedPrediction);
1177 }
1178 if self.inputs.len() > MAX_PREDICTED_INPUTS || self.environment.len() > 4 * 1024 {
1179 return Err(BypassReason::UnsupportedPrediction);
1180 }
1181 let mut paths = BTreeSet::new();
1182 let mut named = BTreeSet::new();
1183 let admitted_roots = dep_info::native_input_roots(working_dir, path_mappings);
1184 let mut native_bytes = 0_u64;
1185 let mut counted = BTreeSet::new();
1186 for path in &self.inputs {
1187 if self.version >= 3
1188 && let Some(path) = path.strip_prefix(NATIVE_DIRECTORY_PREDICTION_PREFIX)
1189 {
1190 let directory = denormalize_path(path, path_mappings)?;
1191 dep_info::collect_native_directory(
1192 &directory,
1193 &admitted_roots,
1194 &mut paths,
1195 &mut native_bytes,
1196 &mut counted,
1197 )?;
1198 } else {
1199 let path = denormalize_path(path, path_mappings)?;
1200 named.insert(path.clone());
1201 paths.insert(path);
1202 }
1203 }
1204 let native_only = paths.difference(&named).cloned().collect();
1205 let environment = self
1206 .environment
1207 .iter()
1208 .map(|name| {
1209 if name.is_empty() || name.contains(['=', '\0']) {
1210 return Err(BypassReason::UnsupportedPrediction);
1211 }
1212 let value = std::env::var_os(name)
1213 .map(|value| {
1214 value
1215 .into_string()
1216 .map_err(|_| BypassReason::UnsupportedPrediction)
1217 })
1218 .transpose()?;
1219 Ok((name.clone(), value))
1220 })
1221 .collect::<Result<BTreeMap<_, _>, _>>()?;
1222 Ok(
1223 DiscoveredInputs::from_paths(working_dir, paths, environment, digests)?
1224 .with_native_only(native_only),
1225 )
1226 }
1227}
1228
1229#[derive(Serialize)]
1230struct ActionDescriptor {
1231 version: u8,
1232 kind: &'static str,
1233 adapter_version: u8,
1234 compiler: CompilerDescriptor,
1235 arguments: Vec<String>,
1236 environment: BTreeMap<String, Option<String>>,
1237 inputs: Vec<InputDescriptor>,
1238 #[serde(skip_serializing_if = "Option::is_none")]
1241 linker: Option<LinkerIdentity>,
1242}
1243
1244#[derive(Serialize)]
1245struct InvocationDescriptor {
1246 version: u8,
1247 kind: &'static str,
1248 adapter_version: u8,
1249 compiler: CompilerDescriptor,
1250 arguments: Vec<String>,
1251 required_inputs: Vec<String>,
1252}
1253
1254#[derive(Serialize)]
1255struct CompilerDescriptor {
1256 toolchain: String,
1257 rustc_version: String,
1258 host: String,
1259 #[serde(skip_serializing_if = "Option::is_none")]
1260 driver: Option<String>,
1261}
1262
1263#[derive(Debug, Serialize, PartialEq, Eq, PartialOrd, Ord)]
1264struct InputDescriptor {
1265 path: String,
1266 digest: CacheDigest,
1267}
1268
1269#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1271enum StaticLibraryNaming {
1272 Msvc,
1274 Unix,
1276}
1277
1278struct Parser<'a> {
1279 arguments: &'a [OsString],
1280 index: usize,
1281 parsed: Vec<Argument>,
1282 source: Option<PathBuf>,
1283 crate_types: Vec<String>,
1284 emits: Vec<Emit>,
1285 required_inputs: Vec<PathBuf>,
1286 native_libraries: Vec<String>,
1287 test: bool,
1288 crate_name: Option<String>,
1289 extra_filename: String,
1290 out_dir: Option<PathBuf>,
1291 explicit_output: Option<PathBuf>,
1292 target: Option<String>,
1293 sysroot_backend: Option<String>,
1294 options: ParseOptions,
1295}
1296
1297struct ExpandedArguments {
1298 arguments: Vec<OsString>,
1299}
1300
1301#[derive(Default)]
1302struct ResponseExpander {
1303 shell_argfiles: bool,
1304 next_is_unstable_option: bool,
1305 arguments: Vec<OsString>,
1306}
1307
1308impl ResponseExpander {
1309 fn push(&mut self, argument: String) {
1310 if self.next_is_unstable_option {
1311 self.shell_argfiles |= argument == "shell-argfiles";
1312 self.next_is_unstable_option = false;
1313 } else if let Some(option) = argument.strip_prefix("-Z") {
1314 if option.is_empty() {
1315 self.next_is_unstable_option = true;
1316 } else {
1317 self.shell_argfiles |= option == "shell-argfiles";
1318 }
1319 }
1320 self.arguments.push(argument.into());
1321 }
1322}
1323
1324fn expand_response_files(arguments: &[OsString]) -> Result<ExpandedArguments, BypassReason> {
1327 let mut expanded = ResponseExpander::default();
1328 for (index, argument) in arguments.iter().enumerate() {
1329 let argument = argument
1330 .to_str()
1331 .ok_or(BypassReason::NonUtf8Argument { index })?;
1332 let Some(argfile) = argument.strip_prefix('@') else {
1333 expanded.push(argument.to_string());
1334 continue;
1335 };
1336 let (path, shell) = match argfile.split_once(':') {
1337 Some(("shell", path)) if expanded.shell_argfiles => (path, true),
1338 _ => (argfile, false),
1339 };
1340 let contents = std::fs::read_to_string(path).map_err(|error| {
1341 BypassReason::ResponseFile(format!("{}: {error}", Path::new(path).display()))
1342 })?;
1343 if shell {
1344 let arguments = shlex::split(&contents).ok_or_else(|| {
1345 BypassReason::ResponseFile(format!(
1346 "invalid shell-style arguments in {}",
1347 Path::new(path).display()
1348 ))
1349 })?;
1350 for argument in arguments {
1351 expanded.push(argument);
1352 }
1353 } else {
1354 for argument in contents.lines() {
1355 expanded.push(argument.to_string());
1356 }
1357 }
1358 }
1359 Ok(ExpandedArguments {
1360 arguments: expanded.arguments,
1361 })
1362}
1363
1364impl<'a> Parser<'a> {
1365 fn new(arguments: &'a [OsString], options: ParseOptions) -> Self {
1366 Self {
1367 arguments,
1368 options,
1369 index: 0,
1370 parsed: Vec::new(),
1371 source: None,
1372 crate_types: Vec::new(),
1373 emits: Vec::new(),
1374 required_inputs: Vec::new(),
1375 native_libraries: Vec::new(),
1376 test: false,
1377 crate_name: None,
1378 extra_filename: String::new(),
1379 out_dir: None,
1380 explicit_output: None,
1381 target: None,
1382 sysroot_backend: None,
1383 }
1384 }
1385
1386 fn parse(mut self) -> Result<RustcInvocation, BypassReason> {
1387 while self.index < self.arguments.len() {
1388 let value = self.current()?.to_string();
1389 self.index += 1;
1390 if let Some(long) = value.strip_prefix("--") {
1391 self.parse_long(long)?;
1392 } else if value.starts_with('-') && value != "-" {
1393 self.parse_short(&value)?;
1394 } else {
1395 self.parse_input(&value)?;
1396 }
1397 }
1398
1399 if let Some(backend) = self.sysroot_backend.take()
1401 && self.parsed.iter().any(
1402 |argument| matches!(argument, Argument::Path { flag, .. } if flag == "--sysroot"),
1403 )
1404 {
1405 return Err(BypassReason::UnknownFlag(backend));
1406 }
1407 let source = self.source.clone().ok_or(BypassReason::MissingInput)?;
1408 let link_output = self.classify()?;
1409 self.require_native_libraries(link_output)?;
1410 let crate_name = self.crate_name.clone().map_or_else(
1411 || {
1412 source
1413 .file_stem()
1414 .and_then(|name| name.to_str())
1415 .map(|name| name.replace('-', "_"))
1416 .ok_or_else(|| BypassReason::NonUtf8Path(source.clone()))
1417 },
1418 Ok,
1419 )?;
1420 self.required_inputs.push(source.clone());
1421 self.drop_unobservable_diagnostic_width();
1422 Ok(RustcInvocation {
1423 arguments: self.parsed,
1424 source,
1425 required_inputs: self.required_inputs,
1426 crate_name,
1427 extra_filename: self.extra_filename,
1428 out_dir: self.out_dir,
1429 explicit_output: self.explicit_output,
1430 emits: self.emits,
1431 target: self.target,
1432 link_output,
1433 })
1434 }
1435
1436 fn current(&self) -> Result<&str, BypassReason> {
1437 self.arguments[self.index]
1438 .to_str()
1439 .ok_or(BypassReason::NonUtf8Argument { index: self.index })
1440 }
1441
1442 fn take_value(&mut self, flag: &str, inline: Option<&str>) -> Result<String, BypassReason> {
1443 if let Some(value) = inline {
1444 if value.is_empty() {
1445 return Err(BypassReason::MissingValue(flag.into()));
1446 }
1447 return Ok(value.into());
1448 }
1449 if self.index >= self.arguments.len() {
1450 return Err(BypassReason::MissingValue(flag.into()));
1451 }
1452 let value = self.current()?.to_string();
1453 self.index += 1;
1454 Ok(value)
1455 }
1456
1457 fn drop_unobservable_diagnostic_width(&mut self) {
1468 fn widths(argument: &Argument) -> Option<&str> {
1469 match argument {
1470 Argument::Plain(value) => value.strip_prefix("--diagnostic-width="),
1471 _ => None,
1472 }
1473 }
1474 let mut found = self.parsed.iter().filter_map(widths);
1475 let valid = matches!(
1476 (found.next(), found.next()),
1477 (Some(width), None) if width.parse::<usize>().is_ok()
1478 );
1479 if valid {
1480 self.parsed.retain(|argument| widths(argument).is_none());
1481 }
1482 }
1483
1484 fn parse_long(&mut self, value: &str) -> Result<(), BypassReason> {
1485 let (flag, inline) = value
1486 .split_once('=')
1487 .map_or((value, None), |(flag, value)| (flag, Some(value)));
1488 let rendered_flag = format!("--{flag}");
1489 match flag {
1490 "help" | "version" | "explain" | "print" => Err(BypassReason::CompilerQuery),
1491 "test" => {
1492 self.test = true;
1493 self.parsed.push(Argument::Plain(rendered_flag));
1494 Ok(())
1495 }
1496 "verbose" => {
1497 self.parsed.push(Argument::Plain(rendered_flag));
1498 Ok(())
1499 }
1500 "crate-name" => {
1501 let value = self.take_value(&rendered_flag, inline)?;
1502 self.crate_name = Some(value.clone());
1503 self.parsed
1504 .push(Argument::Plain(format!("{rendered_flag}={value}")));
1505 Ok(())
1506 }
1507 "cfg" | "check-cfg" | "edition" | "error-format" | "json" | "color"
1508 | "diagnostic-width" | "remap-path-scope" | "allow" | "warn" | "force-warn"
1509 | "deny" | "forbid" | "cap-lints" => {
1510 let value = self.take_value(&rendered_flag, inline)?;
1511 self.parsed
1512 .push(Argument::Plain(format!("{rendered_flag}={value}")));
1513 Ok(())
1514 }
1515 "target" => {
1516 let value = self.take_value(&rendered_flag, inline)?;
1517 let effective = self.target.is_none();
1521 if effective {
1522 self.target = Some(value.clone());
1523 }
1524 if value.ends_with(".json") || value.contains(['/', '\\']) {
1525 let path = PathBuf::from(value);
1526 if effective {
1527 self.required_inputs.push(path.clone());
1528 }
1529 self.parsed.push(Argument::Path {
1530 flag: rendered_flag,
1531 path,
1532 });
1533 } else {
1534 self.parsed
1535 .push(Argument::Plain(format!("{rendered_flag}={value}")));
1536 }
1537 Ok(())
1538 }
1539 "crate-type" => {
1540 let value = self.take_value(&rendered_flag, inline)?;
1541 self.crate_types
1542 .extend(value.split(',').map(ToOwned::to_owned));
1543 self.parsed
1544 .push(Argument::Plain(format!("{rendered_flag}={value}")));
1545 Ok(())
1546 }
1547 "emit" => {
1548 let value = self.take_value(&rendered_flag, inline)?;
1549 let emits = parse_emits(&value);
1550 self.emits.extend(emits.clone());
1551 self.parsed.push(Argument::Emit(emits));
1552 Ok(())
1553 }
1554 "out-dir" => {
1555 let path = PathBuf::from(self.take_value(&rendered_flag, inline)?);
1556 self.out_dir = Some(path.clone());
1557 self.parsed.push(Argument::Path {
1558 flag: rendered_flag,
1559 path,
1560 });
1561 Ok(())
1562 }
1563 "sysroot" => {
1564 let path = self.take_value(&rendered_flag, inline)?;
1565 self.parsed.push(Argument::Path {
1566 flag: rendered_flag,
1567 path: path.into(),
1568 });
1569 Ok(())
1570 }
1571 "extern" => {
1572 let value = self.take_value(&rendered_flag, inline)?;
1573 let (name, path) = value
1574 .split_once('=')
1575 .map_or((value.as_str(), None), |(name, path)| {
1576 (name, Some(PathBuf::from(path)))
1577 });
1578 if let Some(path) = &path {
1579 self.required_inputs.push(path.clone());
1580 }
1581 self.parsed.push(Argument::Extern {
1582 name: name.into(),
1583 path,
1584 });
1585 Ok(())
1586 }
1587 "remap-path-prefix" => {
1588 let value = self.take_value(&rendered_flag, inline)?;
1589 let Some((from, to)) = value.split_once('=') else {
1590 return Err(BypassReason::MissingValue(rendered_flag));
1591 };
1592 self.parsed.push(Argument::RemapPath {
1593 from: from.into(),
1594 to: to.into(),
1595 });
1596 Ok(())
1597 }
1598 "codegen" => {
1599 let value = self.take_value(&rendered_flag, inline)?;
1600 self.parse_codegen(&value)
1601 }
1602 "jobs-frontend" => {
1603 let value = self.take_value(&rendered_flag, inline)?;
1604 self.parsed
1605 .push(Argument::Plain(format!("{rendered_flag}={value}")));
1606 Ok(())
1607 }
1608 _ => Err(BypassReason::UnknownFlag(rendered_flag)),
1609 }
1610 }
1611
1612 fn parse_short(&mut self, value: &str) -> Result<(), BypassReason> {
1613 if let Some(attached) = value.strip_prefix("-Z") {
1614 let option = self.take_value("-Z", (!attached.is_empty()).then_some(attached))?;
1615 match option.as_str() {
1616 "embed-metadata=no"
1620 | "embed-metadata=yes"
1621 | "force-unstable-if-unmarked"
1622 | "shell-argfiles"
1623 | "unstable-options" => {
1624 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1625 return Ok(());
1626 }
1627 "use-sync-unwind=yes" | "use-sync-unwind=no" => {
1630 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1631 return Ok(());
1632 }
1633 "threads" | "threads=" => {
1634 return Err(BypassReason::MissingValue("-Zthreads".into()));
1635 }
1636 "remap-cwd-prefix" | "remap-cwd-prefix=" => {
1637 return Err(BypassReason::MissingValue("-Zremap-cwd-prefix".into()));
1638 }
1639 _ => {}
1640 }
1641 if option.starts_with("remap-cwd-prefix=") {
1647 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1648 return Ok(());
1649 }
1650 if option == "share-generics" {
1651 return Err(BypassReason::MissingValue("-Zshare-generics".into()));
1652 }
1653 if let Some(value) = option.strip_prefix("share-generics=") {
1654 if matches!(
1655 value,
1656 "y" | "yes" | "on" | "true" | "n" | "no" | "off" | "false"
1657 ) {
1658 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1659 return Ok(());
1660 }
1661 return Err(if value.is_empty() {
1662 BypassReason::MissingValue("-Zshare-generics".into())
1663 } else {
1664 BypassReason::UnknownFlag(format!("-Z{option}"))
1665 });
1666 }
1667 if option.starts_with("threads=") {
1668 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1669 return Ok(());
1670 }
1671 if let Some(backend) = option.strip_prefix("codegen-backend=")
1673 && !backend.is_empty()
1674 && !backend.contains(['.', '/', '\\'])
1675 {
1676 self.sysroot_backend = Some(format!("-Z{option}"));
1677 self.parsed.push(Argument::Plain(format!("-Z{option}")));
1678 return Ok(());
1679 }
1680 return Err(BypassReason::UnknownFlag(format!("-Z{option}")));
1681 }
1682 match value {
1683 "-h" | "-V" | "-vV" => return Err(BypassReason::CompilerQuery),
1686 "-g" | "-O" | "-v" => {
1687 self.parsed.push(Argument::Plain(value.into()));
1688 return Ok(());
1689 }
1690 _ => {}
1691 }
1692 for (short, long) in [
1693 ("-A", "--allow"),
1694 ("-W", "--warn"),
1695 ("-D", "--deny"),
1696 ("-F", "--forbid"),
1697 ] {
1698 if let Some(attached) = value.strip_prefix(short) {
1699 let lint = self.take_value(short, (!attached.is_empty()).then_some(attached))?;
1700 self.parsed.push(Argument::Plain(format!("{long}={lint}")));
1701 return Ok(());
1702 }
1703 }
1704 if let Some(attached) = value.strip_prefix("-C") {
1705 let option = self.take_value("-C", (!attached.is_empty()).then_some(attached))?;
1706 return self.parse_codegen(&option);
1707 }
1708 if let Some(attached) = value.strip_prefix("-L") {
1709 let search = self.take_value("-L", (!attached.is_empty()).then_some(attached))?;
1710 let (kind, path) = search
1711 .split_once('=')
1712 .map_or(("all", search.as_str()), |(kind, path)| (kind, path));
1713 if !matches!(kind, "dependency" | "native") {
1714 return Err(BypassReason::UnsupportedSearchPath(kind.into()));
1715 }
1716 self.parsed.push(Argument::SearchPath {
1717 kind: kind.into(),
1718 path: path.into(),
1719 });
1720 return Ok(());
1721 }
1722 if let Some(attached) = value.strip_prefix("-l") {
1723 let library = self.take_value("-l", (!attached.is_empty()).then_some(attached))?;
1724 self.parsed.push(Argument::Plain(format!("-l{library}")));
1725 self.native_libraries.push(library);
1726 return Ok(());
1727 }
1728 if let Some(attached) = value.strip_prefix("-o") {
1729 let path = self.take_value("-o", (!attached.is_empty()).then_some(attached))?;
1730 self.explicit_output = Some(path.clone().into());
1731 self.parsed.push(Argument::Path {
1732 flag: "-o".into(),
1733 path: path.into(),
1734 });
1735 return Ok(());
1736 }
1737 Err(BypassReason::UnknownFlag(value.into()))
1738 }
1739
1740 fn parse_codegen(&mut self, value: &str) -> Result<(), BypassReason> {
1741 let name = value.split_once('=').map_or(value, |(name, _)| name);
1742 if name == "incremental" {
1743 return Err(BypassReason::Incremental);
1744 }
1745 if name == "profile-use" {
1746 let Some((_, profile)) = value.split_once('=') else {
1747 return Err(BypassReason::MissingValue("-Cprofile-use".into()));
1748 };
1749 if profile.is_empty() {
1750 return Err(BypassReason::MissingValue("-Cprofile-use".into()));
1751 }
1752 let path = PathBuf::from(profile);
1753 self.required_inputs.push(path.clone());
1754 self.parsed.push(Argument::Path {
1755 flag: "-Cprofile-use".into(),
1756 path,
1757 });
1758 return Ok(());
1759 }
1760 if SUPPORTED_CODEGEN_OPTIONS.binary_search(&name).is_err()
1761 && !matches!(name, "linker" | "linker-flavor")
1762 {
1763 return Err(BypassReason::UnknownCodegenOption(name.into()));
1764 }
1765 if name == "linker-plugin-lto"
1771 && let Some((_, selection)) = value.split_once('=')
1772 && !matches!(
1773 selection,
1774 "" | "y" | "yes" | "on" | "true" | "n" | "no" | "off" | "false"
1775 )
1776 {
1777 return Err(BypassReason::UnknownCodegenOption(format!(
1778 "linker-plugin-lto={selection}"
1779 )));
1780 }
1781 if name == "link-arg"
1788 && let Some((_, option)) = value.split_once('=')
1789 && let Some(selection) = option.strip_prefix("-fuse-ld=")
1790 && !selection.is_empty()
1791 && !selection.contains(',')
1792 && !self.parsed.iter().any(
1793 |argument| matches!(argument, Argument::FuseLd(existing) if existing != selection),
1794 )
1795 {
1796 if !self.parsed.iter().any(
1797 |argument| matches!(argument, Argument::FuseLd(existing) if existing == selection),
1798 ) {
1799 self.parsed.push(Argument::FuseLd(selection.to_owned()));
1800 }
1801 return Ok(());
1802 }
1803 if name == "link-arg"
1806 && let Some(option) = value.strip_prefix("link-arg=-Wl,-install_name,@rpath/")
1807 && safe_install_name(option)
1808 {
1809 self.parsed.push(Argument::InstallName(option.to_owned()));
1810 return Ok(());
1811 }
1812 if matches!(name, "link-arg" | "link-args")
1817 && let Some((_, option)) = value.split_once('=')
1818 && let Some(prefix) = option.strip_prefix("-Wl,-oso_prefix,")
1819 && !prefix.trim_end_matches('/').is_empty()
1820 && !prefix.contains(',')
1821 {
1822 let trailing_slash = prefix.ends_with('/');
1823 self.parsed.push(Argument::OsoPrefix {
1824 path: PathBuf::from(prefix.trim_end_matches('/')),
1825 trailing_slash,
1826 });
1827 return Ok(());
1828 }
1829 self.parsed
1830 .push(Argument::Plain(format!("--codegen={value}")));
1831 if name == "extra-filename" {
1832 self.extra_filename = value
1833 .split_once('=')
1834 .map_or(String::new(), |(_, value)| value.to_string());
1835 }
1836 Ok(())
1837 }
1838
1839 fn require_native_libraries(&mut self, link_output: LinkOutput) -> Result<(), BypassReason> {
1854 for library in std::mem::take(&mut self.native_libraries) {
1855 if link_output != LinkOutput::Library {
1856 return Err(BypassReason::NativeLibrary(library));
1857 }
1858 let Some((kind, name)) = library.split_once('=') else {
1866 continue;
1867 };
1868 let (kind, modifiers) = kind.split_once(':').unwrap_or((kind, ""));
1869 match kind {
1870 "static" => {}
1871 "dylib" | "framework" | "link-arg" => continue,
1872 _ => return Err(BypassReason::UnknownFlag(format!("-l{library}"))),
1873 }
1874 let name = name.split_once(':').map_or(name, |(_, renamed)| renamed);
1877 let (mut verbatim, mut bundle) = (false, true);
1878 for modifier in modifiers.split(',') {
1879 match modifier {
1880 "+verbatim" => verbatim = true,
1881 "-verbatim" => verbatim = false,
1882 "+bundle" => bundle = true,
1883 "-bundle" => bundle = false,
1884 _ => {}
1885 }
1886 }
1887 if !bundle {
1888 continue;
1889 }
1890 let archive = self
1891 .find_native_static_library(name, verbatim)
1892 .map_err(|()| BypassReason::CustomTargetNativeLibrary(library.clone()))?
1893 .ok_or_else(|| BypassReason::MissingNativeLibrary(library.clone()))?;
1894 self.required_inputs.push(archive);
1895 }
1896 Ok(())
1897 }
1898
1899 fn find_native_static_library(
1911 &self,
1912 name: &str,
1913 verbatim: bool,
1914 ) -> Result<Option<PathBuf>, ()> {
1915 let file_names = if verbatim {
1916 vec![name.to_owned()]
1917 } else {
1918 match self.static_library_naming() {
1919 Some(StaticLibraryNaming::Msvc) => {
1920 vec![format!("{name}.lib"), format!("lib{name}.a")]
1921 }
1922 Some(StaticLibraryNaming::Unix) => vec![format!("lib{name}.a")],
1923 None => return Err(()),
1924 }
1925 };
1926 Ok(self
1927 .parsed
1928 .iter()
1929 .filter_map(|argument| match argument {
1930 Argument::SearchPath { kind, path } if kind == "native" => Some(path),
1931 _ => None,
1932 })
1933 .flat_map(|directory| {
1934 file_names
1935 .iter()
1936 .map(move |file_name| directory.join(file_name))
1937 })
1938 .find(|candidate| candidate.is_file()))
1939 }
1940
1941 fn static_library_naming(&self) -> Option<StaticLibraryNaming> {
1949 let Some(target) = self.target.as_deref() else {
1950 return Some(if cfg!(any(target_env = "msvc", target_os = "uefi")) {
1951 StaticLibraryNaming::Msvc
1952 } else {
1953 StaticLibraryNaming::Unix
1954 });
1955 };
1956 if target.ends_with(".json")
1957 || target.contains(['/', '\\'])
1958 || self.options.custom_target_search
1959 {
1960 return None;
1961 }
1962 Some(if target.contains("msvc") || target.ends_with("-uefi") {
1965 StaticLibraryNaming::Msvc
1966 } else {
1967 StaticLibraryNaming::Unix
1968 })
1969 }
1970
1971 fn parse_input(&mut self, value: &str) -> Result<(), BypassReason> {
1972 if value == "-" {
1973 return Err(BypassReason::StandardInput);
1974 }
1975 if self.source.replace(value.into()).is_some() {
1976 return Err(BypassReason::MultipleInputs);
1977 }
1978 Ok(())
1979 }
1980
1981 fn classify(&self) -> Result<LinkOutput, BypassReason> {
1982 let never_links = !self.emits.iter().any(|emit| emit.kind == "link");
1991 let builds_a_library = !self.test
1992 && !self.crate_types.is_empty()
1993 && self
1994 .crate_types
1995 .iter()
1996 .all(|crate_type| matches!(crate_type.as_str(), "lib" | "rlib"));
1997 let link_output = if never_links || builds_a_library {
1998 LinkOutput::Library
1999 } else if self
2000 .target
2001 .as_deref()
2002 .is_some_and(compiler_bundled_wasm_target)
2003 && ((self.test && self.crate_types.is_empty())
2004 || matches!(self.crate_types.as_slice(), [kind] if kind == "bin" || kind == "cdylib"))
2005 {
2006 if self.parsed.iter().any(|argument| match argument {
2007 Argument::Plain(value) if value == "--codegen=link-self-contained" => false,
2008 Argument::Plain(value) if value.starts_with("--codegen=link-self-contained=") => {
2009 !matches!(
2010 value.rsplit_once('=').map(|(_, value)| value),
2011 Some("y" | "yes" | "on" | "true")
2012 )
2013 }
2014 _ => false,
2015 }) {
2016 return Err(BypassReason::UnknownCodegenOption(
2017 "link-self-contained".into(),
2018 ));
2019 }
2020 if self.target.as_deref().is_some_and(|target| target.contains("wasi"))
2021 && self.parsed.iter().any(|argument| {
2022 matches!(argument, Argument::Plain(value) if value.strip_prefix("--codegen=target-feature=").is_some_and(|features| features.split(',').any(|feature| feature == "-crt-static")))
2023 })
2024 {
2025 return Err(BypassReason::UnknownCodegenOption(
2026 "target-feature=-crt-static".into(),
2027 ));
2028 }
2029 LinkOutput::WasmExecutable
2033 } else if self.options.cache_native_links && self.links_a_native_artifact() {
2034 self.check_native_link_is_portable()?;
2035 if matches!(self.crate_types.as_slice(), [kind] if kind == "proc-macro") {
2036 LinkOutput::NativeProcMacro
2037 } else if matches!(self.crate_types.as_slice(), [kind] if kind == "cdylib") {
2038 LinkOutput::NativeSharedLibrary
2039 } else {
2040 LinkOutput::NativeExecutable
2041 }
2042 } else if self.test {
2043 return Err(BypassReason::UnsupportedCrateType("test".into()));
2044 } else {
2045 return Err(BypassReason::UnsupportedCrateType(
2046 self.crate_types
2047 .iter()
2048 .find(|crate_type| !matches!(crate_type.as_str(), "lib" | "rlib"))
2049 .cloned()
2050 .unwrap_or_else(|| "bin".into()),
2051 ));
2052 };
2053 if link_output != LinkOutput::Library
2062 && let Some(option) = self.first_link_argument(link_output)
2063 {
2064 return Err(BypassReason::UnmodeledLinkArgument(option.to_owned()));
2065 }
2066 if self
2067 .parsed
2068 .iter()
2069 .any(|arg| matches!(arg, Argument::InstallName(_)))
2070 && !(cfg!(target_os = "macos") && link_output == LinkOutput::NativeProcMacro)
2071 {
2072 return Err(BypassReason::UnmodeledLinkArgument(
2073 "link-arg=-Wl,-install_name".into(),
2074 ));
2075 }
2076 if let Some(selection) = self.parsed.iter().find_map(|argument| {
2083 let Argument::FuseLd(selection) = argument else {
2084 return None;
2085 };
2086 Some(selection.as_str())
2087 }) && !matches!(
2088 link_output,
2089 LinkOutput::Library
2090 | LinkOutput::NativeExecutable
2091 | LinkOutput::NativeProcMacro
2092 | LinkOutput::NativeSharedLibrary
2093 ) {
2094 return Err(BypassReason::UnmodeledLinkArgument(format!(
2095 "link-arg=-fuse-ld={selection}"
2096 )));
2097 }
2098 if self.parsed.iter().any(|argument| {
2099 matches!(argument, Argument::Plain(value) if value.starts_with("--codegen=linker="))
2100 }) && !matches!(
2101 link_output,
2102 LinkOutput::Library
2103 | LinkOutput::NativeExecutable
2104 | LinkOutput::NativeProcMacro
2105 | LinkOutput::NativeSharedLibrary
2106 ) {
2107 return Err(BypassReason::UnknownCodegenOption("linker".into()));
2108 }
2109 if link_output != LinkOutput::Library
2114 && self.parsed.iter().any(|argument| {
2115 matches!(argument, Argument::Plain(value) if value.starts_with("--codegen=linker-flavor="))
2116 })
2117 {
2118 return Err(BypassReason::UnknownCodegenOption("linker-flavor".into()));
2119 }
2120 if !matches!(
2124 link_output,
2125 LinkOutput::Library
2126 | LinkOutput::NativeExecutable
2127 | LinkOutput::NativeProcMacro
2128 | LinkOutput::NativeSharedLibrary
2129 ) && self
2130 .parsed
2131 .iter()
2132 .any(|argument| matches!(argument, Argument::OsoPrefix { .. }))
2133 {
2134 return Err(BypassReason::UnmodeledLinkArgument(
2135 "link-arg=-Wl,-oso_prefix".into(),
2136 ));
2137 }
2138 if let Some(name) = self.parsed.iter().find_map(|argument| match argument {
2139 Argument::Extern { name, path: None } if name != "proc_macro" => Some(name),
2140 _ => None,
2141 }) {
2142 return Err(BypassReason::UnresolvedExtern(name.clone()));
2143 }
2144 if let Some(emit) = self
2145 .emits
2146 .iter()
2147 .find(|emit| !matches!(emit.kind.as_str(), "dep-info" | "link" | "metadata"))
2148 {
2149 return Err(BypassReason::UnsupportedEmit(emit.kind.clone()));
2150 }
2151 if !self
2152 .emits
2153 .iter()
2154 .any(|emit| matches!(emit.kind.as_str(), "link" | "metadata"))
2155 {
2156 return Err(BypassReason::NoCacheableOutput);
2157 }
2158 Ok(link_output)
2159 }
2160}
2161
2162impl Parser<'_> {
2163 fn first_link_argument(&self, link_output: LinkOutput) -> Option<&str> {
2166 self.parsed.iter().find_map(|argument| {
2167 let Argument::Plain(value) = argument else {
2168 return None;
2169 };
2170 let option = value.strip_prefix("--codegen=")?;
2171 let (name, value) = option.split_once('=').unwrap_or((option, ""));
2172 (matches!(name, "link-arg" | "link-args")
2173 && !(name == "link-arg" && elf_keyword_is_modeled(link_output, value))
2174 && !msvc_options_are_modeled(link_output, name, value))
2175 .then_some(option)
2176 })
2177 }
2178
2179 fn oso_prefix_covers_outputs(&self) -> bool {
2188 let Some(directory) = self
2189 .out_dir
2190 .as_deref()
2191 .or_else(|| self.explicit_output.as_deref().and_then(Path::parent))
2192 else {
2193 return false;
2194 };
2195 if !directory.is_absolute() {
2196 return false;
2197 }
2198 let directory = normalize_components(directory);
2199 self.parsed.iter().any(|argument| {
2200 let Argument::OsoPrefix { path, .. } = argument else {
2201 return false;
2202 };
2203 path.is_absolute()
2204 && (directory.starts_with(normalize_components(path))
2205 || std::fs::canonicalize(&directory)
2206 .ok()
2207 .zip(std::fs::canonicalize(path).ok())
2208 .is_some_and(|(directory, prefix)| directory.starts_with(prefix)))
2209 })
2210 }
2211
2212 fn links_a_native_artifact(&self) -> bool {
2219 self.target.is_none()
2220 && self.emits.iter().any(|emit| emit.kind == "link")
2225 && ((self.test && self.crate_types.is_empty())
2226 || matches!(self.crate_types.as_slice(), [kind] if matches!(kind.as_str(), "bin" | "proc-macro"))
2227 || (cfg!(target_os = "linux")
2228 && matches!(self.crate_types.as_slice(), [kind] if kind == "cdylib")))
2229 }
2230
2231 fn check_native_link_is_portable(&self) -> Result<(), BypassReason> {
2238 for argument in &self.parsed {
2239 let Argument::Plain(value) = argument else {
2240 continue;
2241 };
2242 let (name, value) = if value == "-g" {
2245 ("debuginfo", Some("2"))
2246 } else if let Some(option) = value.strip_prefix("--codegen=") {
2247 match option.split_once('=') {
2248 Some((name, value)) => (name, Some(value)),
2249 None => (option, None),
2253 }
2254 } else {
2255 continue;
2256 };
2257 let unportable = match name {
2258 "split-debuginfo" => match value {
2264 Some("off") => false,
2265 Some("unpacked") if cfg!(target_os = "macos") => {
2266 !self.oso_prefix_covers_outputs()
2267 }
2268 _ => true,
2269 },
2270 "debuginfo" if cfg!(target_os = "macos") => {
2279 !matches!(value, Some("0" | "none")) && !self.oso_prefix_covers_outputs()
2280 }
2281 "rpath" => is_enabled(value),
2289 "prefer-dynamic" => {
2290 is_enabled(value)
2291 && !matches!(self.crate_types.as_slice(), [kind] if kind == "proc-macro")
2292 }
2293 "link-self-contained" => true,
2296 _ => false,
2297 };
2298 if unportable {
2299 return Err(BypassReason::UnportableNativeLink(match value {
2300 Some(value) => format!("{name}={value}"),
2301 None => name.to_owned(),
2302 }));
2303 }
2304 }
2305 Ok(())
2306 }
2307}
2308
2309fn safe_install_name(name: &str) -> bool {
2310 !name.is_empty()
2311 && name
2312 .bytes()
2313 .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))
2314}
2315
2316fn is_enabled(value: Option<&str>) -> bool {
2319 matches!(value, None | Some("y" | "yes" | "on" | "true"))
2320}
2321
2322fn elf_keyword_is_modeled(link_output: LinkOutput, value: &str) -> bool {
2332 cfg!(target_os = "linux")
2333 && matches!(
2334 link_output,
2335 LinkOutput::NativeExecutable
2336 | LinkOutput::NativeProcMacro
2337 | LinkOutput::NativeSharedLibrary
2338 )
2339 && value.strip_prefix("-Wl,-z,").is_some_and(|keyword| {
2340 matches!(
2341 keyword,
2342 "defs"
2343 | "lazy"
2344 | "nodelete"
2345 | "nodlopen"
2346 | "noexecstack"
2347 | "norelro"
2348 | "now"
2349 | "origin"
2350 | "relro"
2351 )
2352 })
2353}
2354
2355fn msvc_options_are_modeled(link_output: LinkOutput, name: &str, value: &str) -> bool {
2371 cfg!(target_env = "msvc")
2372 && matches!(
2373 link_output,
2374 LinkOutput::NativeExecutable
2375 | LinkOutput::NativeProcMacro
2376 | LinkOutput::NativeSharedLibrary
2377 )
2378 && match name {
2379 "link-arg" => msvc_option_reads_no_file(value),
2380 "link-args" => {
2383 let mut options = value.split_ascii_whitespace().peekable();
2384 options.peek().is_some() && options.all(msvc_option_reads_no_file)
2385 }
2386 _ => false,
2387 }
2388}
2389
2390fn msvc_option_reads_no_file(option: &str) -> bool {
2394 let Some(option) = option.strip_prefix(['/', '-']) else {
2395 return false;
2396 };
2397 if option.eq_ignore_ascii_case("brepro") {
2398 return true;
2399 }
2400 let Some((name, sizes)) = option.split_once(':') else {
2401 return false;
2402 };
2403 let is_size = |size: &str| match size.strip_prefix("0x").or_else(|| size.strip_prefix("0X")) {
2406 Some(hex) => !hex.is_empty() && hex.bytes().all(|byte| byte.is_ascii_hexdigit()),
2407 None => !size.is_empty() && size.bytes().all(|byte| byte.is_ascii_digit()),
2408 };
2409 name.eq_ignore_ascii_case("stack")
2410 && sizes.split(',').count() <= 2
2411 && sizes.split(',').all(is_size)
2412}
2413
2414fn compiler_bundled_wasm_target(target: &str) -> bool {
2415 COMPILER_BUNDLED_WASM_TARGETS.binary_search(&target).is_ok()
2416}
2417
2418fn parse_emits(value: &str) -> Vec<Emit> {
2419 value
2420 .split(',')
2421 .map(|emit| {
2422 let (kind, path) = emit
2423 .split_once('=')
2424 .map_or((emit, None), |(kind, path)| (kind, Some(path.into())));
2425 Emit {
2426 kind: kind.into(),
2427 path,
2428 }
2429 })
2430 .collect()
2431}
2432
2433struct ActionBuilder<'a> {
2434 invocation: &'a RustcInvocation,
2435 context: ActionContext,
2436 mappings: Vec<SharedPathMapping>,
2437 aliases: PathAliases,
2441 linker: Option<LinkerIdentity>,
2442}
2443
2444impl<'a> ActionBuilder<'a> {
2445 fn new(invocation: &'a RustcInvocation, mut context: ActionContext) -> Self {
2446 context.path_mappings = PathMapping::ordered(&context.path_mappings);
2447 let mappings = resolve_path_mappings(&shared_path_mappings(&context.path_mappings));
2448 Self {
2449 linker: None,
2450 invocation,
2451 mappings,
2452 aliases: PathAliases::default(),
2453 context,
2454 }
2455 }
2456
2457 fn linked_by(mut self, linker: Option<LinkerIdentity>) -> Self {
2458 self.linker = linker;
2459 self
2460 }
2461
2462 fn build(self) -> Result<RustcAction, BypassReason> {
2463 self.validate_mappings()?;
2464 let invocation = self.invocation_descriptor()?;
2465 let environment = self.environment_descriptor()?;
2466
2467 let mut inputs = BTreeMap::<String, CacheDigest>::new();
2468 for input in &self.context.inputs {
2469 input
2470 .digest
2471 .validate()
2472 .map_err(|_| BypassReason::InvalidInputDigest(input.path.display().to_string()))?;
2473 let path = self.normalize_input_path(&input.path)?;
2474 if inputs
2475 .insert(path.clone(), input.digest.clone())
2476 .is_some_and(|existing| existing != input.digest)
2477 {
2478 return Err(BypassReason::ConflictingInput(path));
2479 }
2480 }
2481 let required = self
2482 .invocation
2483 .required_inputs
2484 .iter()
2485 .map(|path| self.normalize_input_path(path))
2486 .collect::<Result<BTreeSet<_>, _>>()?;
2487 if let Some(missing) = required.iter().find(|path| !inputs.contains_key(*path)) {
2488 return Err(BypassReason::MissingRequiredInput(missing.clone()));
2489 }
2490 let inputs = inputs
2491 .into_iter()
2492 .map(|(path, digest)| InputDescriptor { path, digest })
2493 .collect();
2494 if self.invocation.links_natively() && self.linker.is_none() {
2497 return Err(BypassReason::UnportableNativeLink(
2498 "linker identity is unknown".into(),
2499 ));
2500 }
2501 let descriptor = ActionDescriptor {
2502 version: ACTION_SCHEMA_VERSION,
2503 kind: "rustc",
2504 adapter_version: ADAPTER_VERSION,
2505 compiler: invocation.compiler,
2506 arguments: invocation.arguments,
2507 environment,
2508 inputs,
2509 linker: self.linker.clone(),
2510 };
2511 let bytes = canonical_json(&descriptor)
2512 .map_err(|error| BypassReason::Serialization(error.to_string()))?;
2513 let digest = CacheDigest::blake3(&bytes);
2514 Ok(RustcAction { digest, bytes })
2515 }
2516
2517 fn invocation_descriptor(&self) -> Result<InvocationDescriptor, BypassReason> {
2518 self.validate_mappings()?;
2519 let arguments = self
2520 .invocation
2521 .arguments
2522 .iter()
2523 .map(|argument| self.normalize_argument(argument))
2524 .collect::<Result<Vec<_>, _>>()?;
2525 let required_inputs = self
2526 .invocation
2527 .required_inputs
2528 .iter()
2529 .map(|path| self.normalize_path(path))
2530 .collect::<Result<BTreeSet<_>, _>>()?
2531 .into_iter()
2532 .collect();
2533 Ok(InvocationDescriptor {
2534 version: ACTION_SCHEMA_VERSION,
2535 kind: "rustc",
2536 adapter_version: ADAPTER_VERSION,
2537 compiler: CompilerDescriptor {
2538 toolchain: self.context.compiler.toolchain.clone(),
2539 rustc_version: self.context.compiler.rustc_version.clone(),
2540 host: self.context.compiler.host.clone(),
2541 driver: self.context.compiler.driver.clone(),
2542 },
2543 arguments,
2544 required_inputs,
2545 })
2546 }
2547
2548 fn validate_mappings(&self) -> Result<(), BypassReason> {
2549 if !self.context.working_dir.is_absolute() {
2550 return Err(BypassReason::RelativeWorkingDirectory(
2551 self.context.working_dir.clone(),
2552 ));
2553 }
2554 let mut roots = BTreeSet::new();
2555 let mut placeholders = BTreeSet::new();
2556 for mapping in &self.mappings {
2557 if !mapping.root.is_absolute() {
2558 return Err(BypassReason::RelativePathMapping(mapping.root.clone()));
2559 }
2560 if mapping.placeholder.is_empty()
2561 || !mapping
2562 .placeholder
2563 .bytes()
2564 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
2565 || !roots.insert(normalize_components(&mapping.root))
2566 || !placeholders.insert(&mapping.placeholder)
2567 {
2568 return Err(BypassReason::InvalidPathPlaceholder(
2569 mapping.placeholder.clone(),
2570 ));
2571 }
2572 }
2573 Ok(())
2574 }
2575
2576 fn normalize_argument(&self, argument: &Argument) -> Result<String, BypassReason> {
2577 match argument {
2578 Argument::Plain(value) => Ok(value.clone()),
2579 Argument::Path { flag, path } => Ok(format!("{flag}={}", self.normalize_path(path)?)),
2580 Argument::SearchPath { kind, path } => {
2581 let text = self.normalize_path(path)?;
2582 Ok(format!("-L{kind}={text}"))
2583 }
2584 Argument::Extern { name, path } => match path {
2585 Some(path) => Ok(format!("--extern={name}={}", self.normalize_path(path)?)),
2586 None => Ok(format!("--extern={name}")),
2587 },
2588 Argument::Emit(emits) => Ok(format!(
2589 "--emit={}",
2590 emits
2591 .iter()
2592 .map(|emit| match &emit.path {
2593 Some(path) => self
2594 .normalize_path(path)
2595 .map(|path| format!("{}={path}", emit.kind)),
2596 None => Ok(emit.kind.clone()),
2597 })
2598 .collect::<Result<Vec<_>, _>>()?
2599 .join(",")
2600 )),
2601 Argument::RemapPath { from, to } => Ok(format!(
2602 "--remap-path-prefix={}={}",
2603 self.normalize_path(from)?,
2604 to
2605 )),
2606 Argument::InstallName(name) => Ok(format!(
2607 "--codegen=link-arg=-Wl,-install_name,@rpath/{name}"
2608 )),
2609 Argument::OsoPrefix {
2610 path,
2611 trailing_slash,
2612 } => Ok(format!(
2613 "--codegen=link-arg=-Wl,-oso_prefix,{}{}",
2614 self.normalize_path(path)?,
2615 if *trailing_slash { "/" } else { "" }
2616 )),
2617 Argument::FuseLd(selection) => Ok(format!("--codegen=link-arg=-fuse-ld={selection}")),
2618 }
2619 }
2620
2621 fn environment_descriptor(&self) -> Result<BTreeMap<String, Option<String>>, BypassReason> {
2628 self.context
2629 .environment
2630 .iter()
2631 .map(|(name, value)| {
2632 let value = match value {
2633 Some(value) if self.context.portable_environment.contains(name) => {
2634 Some(self.normalize_path(Path::new(value))?)
2635 }
2636 value => value.clone(),
2637 };
2638 Ok((name.clone(), value))
2639 })
2640 .collect()
2641 }
2642
2643 fn normalize_input_path(&self, path: &Path) -> Result<String, BypassReason> {
2644 let absolute = normalize_components(&self.context.working_dir.join(path));
2645 for directory in self.invocation.native_search_paths() {
2646 let directory = normalize_components(&self.context.working_dir.join(directory));
2647 if let Ok(relative) = absolute.strip_prefix(&directory) {
2648 let suffix = relative
2654 .components()
2655 .map(|component| {
2656 component
2657 .as_os_str()
2658 .to_str()
2659 .ok_or_else(|| BypassReason::NonUtf8Path(path.to_path_buf()))
2660 })
2661 .collect::<Result<Vec<_>, _>>()?
2662 .join("/");
2663 if !suffix.is_empty() {
2664 return Ok(format!("{}/{}", self.normalize_path(&directory)?, suffix));
2665 }
2666 }
2667 }
2668 self.normalize_path(path)
2669 }
2670
2671 fn normalize_path(&self, path: &Path) -> Result<String, BypassReason> {
2672 normalize_resolved_shared_path_with(
2673 &self.aliases,
2674 path,
2675 &self.context.working_dir,
2676 &self.mappings,
2677 )
2678 .map_err(Into::into)
2679 }
2680}
2681
2682fn under_any_directory(path: &str, directories: &BTreeSet<String>) -> bool {
2686 directories.iter().any(|directory| {
2687 path.len() > directory.len()
2688 && path.as_bytes()[directory.len()] == b'/'
2689 && path.starts_with(directory)
2690 })
2691}
2692
2693fn denormalize_path(value: &str, mappings: &[PathMapping]) -> Result<PathBuf, BypassReason> {
2694 for mapping in mappings {
2695 let prefix = format!("${{{}}}", mapping.placeholder);
2696 let suffix = if value == prefix {
2697 ""
2698 } else if let Some(suffix) = value.strip_prefix(&format!("{prefix}/")) {
2699 suffix
2700 } else {
2701 continue;
2702 };
2703 if !mapping.root.is_absolute()
2704 || (!suffix.is_empty()
2705 && suffix.split('/').any(|component| {
2706 component.is_empty()
2707 || matches!(component, "." | "..")
2708 || component.contains('\\')
2709 }))
2710 {
2711 return Err(BypassReason::InvalidPredictedInput(value.into()));
2712 }
2713 let mut path = normalize_components(&mapping.root);
2714 path.extend(suffix.split('/').filter(|component| !component.is_empty()));
2715 return Ok(path);
2716 }
2717 Err(BypassReason::InvalidPredictedInput(value.into()))
2718}
2719
2720fn normalize_components(path: &Path) -> PathBuf {
2721 let mut normalized = PathBuf::new();
2722 for component in path.components() {
2723 match component {
2724 Component::CurDir => {}
2725 Component::ParentDir => {
2726 normalized.pop();
2727 }
2728 component => normalized.push(component.as_os_str()),
2729 }
2730 }
2731 normalized
2732}
2733
2734fn absolute_path(path: &Path, working_dir: &Path) -> PathBuf {
2735 if path.is_absolute() {
2736 normalize_components(path)
2737 } else {
2738 normalize_components(&working_dir.join(path))
2739 }
2740}
2741
2742#[cfg(test)]
2743#[path = "rustc_cache_tests.rs"]
2744mod tests;