| // Copyright 2026 The Fuchsia Authors | |
| // | |
| // Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 | |
| // <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT | |
| // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. | |
| // This file may not be copied, modified, or distributed except according to | |
| // those terms. | |
| //! Offline Miri sysroot preparation, its readiness stamp, and the | |
| //! supervised child processes that build it. | |
| use super::*; | |
| #[derive(Serialize)] | |
| struct ScratchCargoConfig { | |
| source: ScratchCargoSources, | |
| } | |
| #[derive(Serialize)] | |
| struct ScratchCargoSources { | |
| #[serde(rename = "crates-io")] | |
| crates_io: ScratchCratesIoReplace, | |
| #[serde(rename = "vendored-sources")] | |
| vendored_sources: ScratchVendorDir, | |
| } | |
| #[derive(Serialize)] | |
| struct ScratchCratesIoReplace { | |
| #[serde(rename = "replace-with")] | |
| replace_with: &'static str, | |
| } | |
| #[derive(Serialize)] | |
| struct ScratchVendorDir { | |
| directory: String, | |
| } | |
| pub(super) fn render_vendored_cargo_config(vendor_dir: &Path) -> Result<String, String> { | |
| let cfg = ScratchCargoConfig { | |
| source: ScratchCargoSources { | |
| crates_io: ScratchCratesIoReplace { replace_with: "vendored-sources" }, | |
| vendored_sources: ScratchVendorDir { | |
| directory: vendor_dir.to_string_lossy().into_owned(), | |
| }, | |
| }, | |
| }; | |
| toml::to_string(&cfg).map_err(|e| format!("serialize offline Miri Cargo config: {e}")) | |
| } | |
| pub(super) fn build_child_path( | |
| primary_bin: &Path, | |
| ambient_path: Option<&OsStr>, | |
| ) -> Result<OsString, String> { | |
| let caller_cwd = | |
| env::current_dir().map_err(|e| format!("resolve current working directory: {e}"))?; | |
| let store_prefix = Path::new(STORE_PREFIX); | |
| let trusted_dirs: Vec<&Path> = TRUSTED_CHILD_PATH_DIRS.iter().map(Path::new).collect(); | |
| build_child_path_with_bins( | |
| &[primary_bin], | |
| None, | |
| store_prefix, | |
| &trusted_dirs, | |
| ambient_path, | |
| &caller_cwd, | |
| ) | |
| } | |
| pub(super) fn parse_rustc_version_tag(rustc: &Path, text: &str) -> Result<String, String> { | |
| let commit = text | |
| .lines() | |
| .find_map(|line| line.strip_prefix("commit-hash: ")) | |
| .map(str::trim) | |
| .filter(|s| !s.is_empty()) | |
| .ok_or_else(|| format!("`{} -vV` output missing `commit-hash:` line", rustc.display()))?; | |
| let short: String = commit.chars().take(12).collect(); | |
| let host = text | |
| .lines() | |
| .find_map(|line| line.strip_prefix("host: ")) | |
| .map(str::trim) | |
| .filter(|s| !s.is_empty()) | |
| .ok_or_else(|| format!("`{} -vV` output missing `host:` line", rustc.display()))?; | |
| let rustc_sha = sha256_file_hex(rustc)?; | |
| Ok(format!("{short}-{host}-{}", &rustc_sha[..12])) | |
| } | |
| pub(super) const MIRI_SYSROOT_STAMP_VERSION: u32 = 3; | |
| #[derive(Debug, Deserialize, Serialize)] | |
| pub(super) struct MiriSysrootStamp { | |
| pub(super) version: u32, | |
| pub(super) ver_tag: String, | |
| pub(super) setup_sha: String, | |
| pub(super) files: BTreeMap<String, String>, | |
| } | |
| pub(super) fn expected_miri_ready_stamp_json( | |
| ver_tag: &str, | |
| setup_sha: &str, | |
| files: BTreeMap<String, String>, | |
| ) -> Result<String, String> { | |
| let mut payload = serde_json::to_string_pretty(&MiriSysrootStamp { | |
| version: MIRI_SYSROOT_STAMP_VERSION, | |
| ver_tag: ver_tag.to_owned(), | |
| setup_sha: setup_sha.to_owned(), | |
| files, | |
| }) | |
| .map_err(|e| format!("serialize Miri ready stamp: {e}"))?; | |
| payload.push('\n'); | |
| Ok(payload) | |
| } | |
| #[cfg(test)] | |
| pub(super) fn expected_miri_ready_stamp_for_dir( | |
| miri_sysroot: &Path, | |
| ver_tag: &str, | |
| setup_sha: &str, | |
| ) -> String { | |
| let rustlib = miri_sysroot.join("lib/rustlib"); | |
| let files = collect_rel_file_sha256s_nofollow(&rustlib, None, "test Miri lib/rustlib") | |
| .unwrap_or_default(); | |
| expected_miri_ready_stamp_json(ver_tag, setup_sha, files).unwrap() | |
| } | |
| pub(super) fn stage_miri_sysroot_dir_in( | |
| raw_dir: &Path, | |
| caller_cwd: &Path, | |
| store_prefix: &Path, | |
| tmp_parent: Option<&Path>, | |
| label: &str, | |
| ) -> Result<(PathBuf, Option<Arc<ImmutableStagingDir>>), String> { | |
| if raw_dir.components().any(|c| matches!(c, Component::ParentDir)) { | |
| return Err(format!( | |
| "{label} must not contain `..` path traversal segments: {}", | |
| raw_dir.display() | |
| )); | |
| } | |
| let abs_dir = | |
| if raw_dir.is_absolute() { raw_dir.to_path_buf() } else { caller_cwd.join(raw_dir) }; | |
| if let Some(res) = | |
| try_validate_store_contained_path(&abs_dir, store_prefix, caller_cwd, true, label) | |
| { | |
| let canon_sysroot = res?; | |
| let canon_store = | |
| crate::mir_eval_runner::validate_dir_path_no_symlinks(store_prefix, caller_cwd)?; | |
| let rustlib_dir = canon_sysroot.join("lib/rustlib"); | |
| if fs::symlink_metadata(canon_sysroot.join("lib")).is_err() | |
| || fs::symlink_metadata(&rustlib_dir).is_err() | |
| { | |
| return Err(format!("{label}={} does not contain `lib/rustlib`", raw_dir.display())); | |
| } | |
| let canon_rustlib = validate_store_contained_entry( | |
| &rustlib_dir, | |
| &canon_store, | |
| &canon_store, | |
| true, | |
| &format!("{label} lib/rustlib"), | |
| )?; | |
| validate_store_contained_dir_tree( | |
| &canon_rustlib, | |
| &canon_store, | |
| &canon_store, | |
| &format!("{label} lib/rustlib"), | |
| )?; | |
| let stamp_path = canon_sysroot.join(".anneal-miri-ready"); | |
| let _ = validate_store_contained_entry( | |
| &stamp_path, | |
| &canon_store, | |
| &canon_store, | |
| false, | |
| &format!("{label} .anneal-miri-ready"), | |
| ) | |
| .map_err(|e| { | |
| format!( | |
| "{label}={} lacks verifiable `.anneal-miri-ready` setup stamp ({e})", | |
| raw_dir.display() | |
| ) | |
| })?; | |
| return Ok((canon_sysroot, None)); | |
| } | |
| let canon_sysroot = crate::mir_eval_runner::validate_dir_path_no_symlinks(&abs_dir, caller_cwd) | |
| .map_err(|e| format!("{label}={} must not be a symlink: {e}", raw_dir.display()))?; | |
| let lib_dir = canon_sysroot.join("lib"); | |
| let rustlib_dir = lib_dir.join("rustlib"); | |
| if fs::symlink_metadata(&lib_dir).is_err() || fs::symlink_metadata(&rustlib_dir).is_err() { | |
| return Err(format!("{label}={} does not contain `lib/rustlib`", raw_dir.display())); | |
| } | |
| let canon_rustlib = | |
| crate::mir_eval_runner::validate_dir_path_no_symlinks(&rustlib_dir, &canon_sysroot) | |
| .map_err(|e| format!("{label}={} invalid `lib/rustlib`: {e}", raw_dir.display()))?; | |
| let stamp_src = canon_sysroot.join(".anneal-miri-ready"); | |
| if let Err(e) = fs::symlink_metadata(&stamp_src) { | |
| return Err(format!( | |
| "{label}={} lacks verifiable `.anneal-miri-ready` setup stamp ({e})", | |
| raw_dir.display() | |
| )); | |
| } | |
| let temp = crate::mir_eval_runner::build_temp_dir("anneal-miri-sys-", tmp_parent)?; | |
| let (_, staging) = ImmutableStagingDir::build_and_pin(temp, label, |_, pinned_root| { | |
| copy_verified_regular_file( | |
| &stamp_src, | |
| &pinned_root.join(".anneal-miri-ready"), | |
| false, | |
| &format!("{label} .anneal-miri-ready"), | |
| )?; | |
| copy_validated_subtree( | |
| &canon_rustlib, | |
| &pinned_root.join("lib/rustlib"), | |
| None, | |
| false, | |
| &format!("{label} lib/rustlib"), | |
| ) | |
| })?; | |
| Ok((staging.root().to_path_buf(), Some(staging))) | |
| } | |
| fn collect_store_rel_file_sha256s( | |
| root_dir: &Path, | |
| store_prefix: &Path, | |
| canon_store: &Path, | |
| label: &str, | |
| ) -> Result<BTreeMap<String, String>, String> { | |
| validate_store_contained_dir_tree(root_dir, store_prefix, canon_store, label)?; | |
| let mut files = BTreeMap::new(); | |
| let mut visited = BTreeSet::new(); | |
| let mut stack = vec![(root_dir.to_path_buf(), PathBuf::new())]; | |
| visited.insert(root_dir.to_path_buf()); | |
| while let Some((cur_dir, rel_prefix)) = stack.pop() { | |
| let mut entries: Vec<_> = fs::read_dir(&cur_dir) | |
| .map_err(|e| format!("read {label} dir {}: {e}", cur_dir.display()))? | |
| .collect::<Result<Vec<_>, _>>() | |
| .map_err(|e| format!("iterate {label} dir {}: {e}", cur_dir.display()))?; | |
| entries.sort_by_key(|e| e.file_name()); | |
| for entry in entries { | |
| let path = entry.path(); | |
| let next_rel = rel_prefix.join(entry.file_name()); | |
| let meta = fs::symlink_metadata(&path) | |
| .map_err(|e| format!("stat {label} {}: {e}", path.display()))?; | |
| let target = if meta.file_type().is_symlink() { | |
| let canon_target = fs::canonicalize(&path) | |
| .map_err(|e| format!("canonicalize {label} {}: {e}", path.display()))?; | |
| let cmeta = fs::symlink_metadata(&canon_target) | |
| .map_err(|e| format!("stat {label} {}: {e}", canon_target.display()))?; | |
| validate_store_contained_entry( | |
| &path, | |
| store_prefix, | |
| canon_store, | |
| cmeta.is_dir(), | |
| label, | |
| )? | |
| } else { | |
| path | |
| }; | |
| let tmeta = fs::symlink_metadata(&target) | |
| .map_err(|e| format!("stat {label} {}: {e}", target.display()))?; | |
| if tmeta.is_dir() { | |
| if visited.insert(target.clone()) { | |
| stack.push((target, next_rel)); | |
| } | |
| } else if tmeta.is_file() { | |
| let mut segs = Vec::new(); | |
| for comp in next_rel.components() { | |
| let Component::Normal(os) = comp else { | |
| return Err(format!("invalid relative component in {label}")); | |
| }; | |
| segs.push(os.to_str().ok_or_else(|| { | |
| format!("non-UTF-8 path in {label}: {}", next_rel.display()) | |
| })?); | |
| } | |
| files.insert(segs.join("/"), sha256_file_hex(&target)?); | |
| } | |
| } | |
| } | |
| Ok(files) | |
| } | |
| pub(super) fn verify_miri_sysroot_stamp_with_store( | |
| miri_sysroot: &Path, | |
| staging: Option<&ImmutableStagingDir>, | |
| store_prefix: &Path, | |
| ver_tag: &str, | |
| setup_sha: &str, | |
| ) -> Result<(), String> { | |
| let mut stamp_file = if let Some(stage) = staging { | |
| stage | |
| .open_verified_rel_file( | |
| Path::new(".anneal-miri-ready"), | |
| "ANNEAL_MIRI_SYSROOT .anneal-miri-ready", | |
| ) | |
| .map_err(|e| { | |
| format!( | |
| "ANNEAL_MIRI_SYSROOT={} lacks verifiable `.anneal-miri-ready` setup stamp ({e})", | |
| miri_sysroot.display() | |
| ) | |
| })? | |
| } else { | |
| let ready_stamp = miri_sysroot.join(".anneal-miri-ready"); | |
| let canon_stamp = if let Some(res) = try_validate_store_contained_path( | |
| &ready_stamp, | |
| store_prefix, | |
| miri_sysroot, | |
| false, | |
| "ANNEAL_MIRI_SYSROOT .anneal-miri-ready", | |
| ) { | |
| res | |
| } else { | |
| crate::mir_eval_runner::validate_executable_no_links( | |
| &ready_stamp, | |
| miri_sysroot, | |
| "ANNEAL_MIRI_SYSROOT .anneal-miri-ready", | |
| ) | |
| } | |
| .map_err(|e| { | |
| format!( | |
| "ANNEAL_MIRI_SYSROOT={} lacks verifiable `.anneal-miri-ready` setup stamp ({e})", | |
| miri_sysroot.display() | |
| ) | |
| })?; | |
| let f = File::open(&canon_stamp).map_err(|e| { | |
| format!("open ANNEAL_MIRI_SYSROOT stamp {}: {e}", canon_stamp.display()) | |
| })?; | |
| #[cfg(unix)] | |
| { | |
| use std::os::unix::fs::MetadataExt as _; | |
| let opened = f.metadata().map_err(|e| { | |
| format!("fstat ANNEAL_MIRI_SYSROOT stamp {}: {e}", canon_stamp.display()) | |
| })?; | |
| if !opened.is_file() || opened.nlink() > 1 { | |
| return Err(format!( | |
| "ANNEAL_MIRI_SYSROOT={} `.anneal-miri-ready` must not be a hardlink (nlink={})", | |
| miri_sysroot.display(), | |
| opened.nlink() | |
| )); | |
| } | |
| } | |
| f | |
| }; | |
| let mut raw = String::new(); | |
| std::io::Read::read_to_string(&mut stamp_file, &mut raw).map_err(|e| { | |
| format!("read ANNEAL_MIRI_SYSROOT stamp in {}: {e}", miri_sysroot.display()) | |
| })?; | |
| let stamp: MiriSysrootStamp = serde_json::from_str(&raw).map_err(|_| { | |
| format!( | |
| "ANNEAL_MIRI_SYSROOT={} setup stamp does not match current Miri/rust-src inputs", | |
| miri_sysroot.display() | |
| ) | |
| })?; | |
| if stamp.version != MIRI_SYSROOT_STAMP_VERSION | |
| || stamp.ver_tag != ver_tag | |
| || stamp.setup_sha != setup_sha | |
| { | |
| return Err(format!( | |
| "ANNEAL_MIRI_SYSROOT={} setup stamp does not match current Miri/rust-src inputs", | |
| miri_sysroot.display() | |
| )); | |
| } | |
| let disk_files = if let Some(stage) = staging { | |
| stage.collect_rel_file_sha256s( | |
| Some(Path::new("lib/rustlib")), | |
| None, | |
| "staged Miri lib/rustlib", | |
| )? | |
| } else { | |
| let rustlib = miri_sysroot.join("lib/rustlib"); | |
| if miri_sysroot.starts_with(store_prefix) && fs::symlink_metadata(store_prefix).is_ok() { | |
| let canon_store = | |
| crate::mir_eval_runner::validate_dir_path_no_symlinks(store_prefix, miri_sysroot)?; | |
| collect_store_rel_file_sha256s( | |
| &rustlib, | |
| store_prefix, | |
| &canon_store, | |
| "store Miri lib/rustlib", | |
| )? | |
| } else { | |
| collect_rel_file_sha256s_nofollow(&rustlib, None, "Miri lib/rustlib")? | |
| } | |
| }; | |
| if disk_files.len() != stamp.files.len() { | |
| return Err(format!( | |
| "ANNEAL_MIRI_SYSROOT={} lib/rustlib file set does not match `.anneal-miri-ready` manifest", | |
| miri_sysroot.display() | |
| )); | |
| } | |
| for (rel, expected_sha) in &stamp.files { | |
| let Some(actual_sha) = disk_files.get(rel) else { | |
| return Err(format!( | |
| "ANNEAL_MIRI_SYSROOT={} missing lib/rustlib artifact listed in `.anneal-miri-ready`: {rel}", | |
| miri_sysroot.display() | |
| )); | |
| }; | |
| if !actual_sha.eq_ignore_ascii_case(expected_sha) { | |
| return Err(format!( | |
| "ANNEAL_MIRI_SYSROOT={} lib/rustlib artifact `{rel}` failed SHA-256 verification against `.anneal-miri-ready`", | |
| miri_sysroot.display() | |
| )); | |
| } | |
| } | |
| Ok(()) | |
| } | |
| #[cfg(test)] | |
| pub(super) fn verify_explicit_miri_sysroot_stamp( | |
| miri_sysroot: &Path, | |
| ver_tag: &str, | |
| setup_sha: &str, | |
| ) -> Result<(), String> { | |
| verify_miri_sysroot_stamp_with_store( | |
| miri_sysroot, | |
| None, | |
| Path::new(STORE_PREFIX), | |
| ver_tag, | |
| setup_sha, | |
| ) | |
| } | |
| #[cfg(test)] | |
| pub(super) fn stage_and_verify_miri_sysroot( | |
| raw_dir: &Path, | |
| caller_cwd: &Path, | |
| store_prefix: &Path, | |
| ver_tag: &str, | |
| setup_sha: &str, | |
| label: &str, | |
| ) -> Result<(PathBuf, Option<Arc<ImmutableStagingDir>>), String> { | |
| stage_and_verify_miri_sysroot_in( | |
| raw_dir, | |
| caller_cwd, | |
| store_prefix, | |
| None, | |
| ver_tag, | |
| setup_sha, | |
| label, | |
| ) | |
| } | |
| pub(super) fn stage_and_verify_miri_sysroot_in( | |
| raw_dir: &Path, | |
| caller_cwd: &Path, | |
| store_prefix: &Path, | |
| tmp_parent: Option<&Path>, | |
| ver_tag: &str, | |
| setup_sha: &str, | |
| label: &str, | |
| ) -> Result<(PathBuf, Option<Arc<ImmutableStagingDir>>), String> { | |
| let (miri_sysroot, miri_staging) = | |
| stage_miri_sysroot_dir_in(raw_dir, caller_cwd, store_prefix, tmp_parent, label)?; | |
| verify_miri_sysroot_stamp_with_store( | |
| &miri_sysroot, | |
| miri_staging.as_deref(), | |
| store_prefix, | |
| ver_tag, | |
| setup_sha, | |
| )?; | |
| Ok((miri_sysroot, miri_staging)) | |
| } | |
| #[cfg(test)] | |
| pub(super) fn stage_and_verify_miri_sysroot_from_pinned( | |
| pinned: &PinnedPrivateDir, | |
| rel_dir: &Path, | |
| store_prefix: &Path, | |
| ver_tag: &str, | |
| setup_sha: &str, | |
| label: &str, | |
| ) -> Result<(PathBuf, Option<Arc<ImmutableStagingDir>>), String> { | |
| stage_and_verify_miri_sysroot_from_pinned_in( | |
| pinned, | |
| rel_dir, | |
| store_prefix, | |
| None, | |
| ver_tag, | |
| setup_sha, | |
| label, | |
| ) | |
| } | |
| pub(super) fn stage_and_verify_miri_sysroot_from_pinned_in( | |
| pinned: &PinnedPrivateDir, | |
| rel_dir: &Path, | |
| store_prefix: &Path, | |
| tmp_parent: Option<&Path>, | |
| ver_tag: &str, | |
| setup_sha: &str, | |
| label: &str, | |
| ) -> Result<(PathBuf, Option<Arc<ImmutableStagingDir>>), String> { | |
| if !pinned.has_rel_dir(&rel_dir.join("lib/rustlib"), &format!("{label} lib/rustlib")) { | |
| return Err(format!("{label}={} does not contain `lib/rustlib`", rel_dir.display())); | |
| } | |
| let mut stamp_file = pinned | |
| .open_verified_rel_file( | |
| &rel_dir.join(".anneal-miri-ready"), | |
| &format!("{label} .anneal-miri-ready"), | |
| ) | |
| .map_err(|e| { | |
| format!( | |
| "{label}={} lacks verifiable `.anneal-miri-ready` setup stamp ({e})", | |
| rel_dir.display() | |
| ) | |
| })?; | |
| let temp = crate::mir_eval_runner::build_temp_dir("anneal-miri-sys-", tmp_parent)?; | |
| let (_, miri_staging) = ImmutableStagingDir::build_and_pin(temp, label, |_, pinned_root| { | |
| copy_opened_file_to_new_dst( | |
| &mut stamp_file, | |
| false, | |
| &pinned_root.join(".anneal-miri-ready"), | |
| false, | |
| &format!("{label} .anneal-miri-ready"), | |
| )?; | |
| pinned.copy_rel_subtree_to( | |
| &rel_dir.join("lib/rustlib"), | |
| &pinned_root.join("lib/rustlib"), | |
| false, | |
| &format!("{label} lib/rustlib"), | |
| ) | |
| })?; | |
| let priv_root = miri_staging.root().to_path_buf(); | |
| verify_miri_sysroot_stamp_with_store( | |
| &priv_root, | |
| Some(&miri_staging), | |
| store_prefix, | |
| ver_tag, | |
| setup_sha, | |
| )?; | |
| Ok((priv_root, Some(miri_staging))) | |
| } | |
| #[path = "sysroot/hashing_and_stamp.rs"] | |
| mod hashing_and_stamp; | |
| #[path = "sysroot/offline_build.rs"] | |
| mod offline_build; | |
| #[cfg(test)] | |
| pub(super) use hashing_and_stamp::compute_miri_setup_input_sha256; | |
| pub(super) use hashing_and_stamp::{ | |
| compute_miri_setup_input_sha256_inner, rustc_version_tag, write_new_miri_ready_stamp, | |
| }; | |
| pub(super) use offline_build::build_offline_miri_sysroot_in; |