| // 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. | |
| //! Reference-oracle runner invoking Miri on staged differential fixtures. | |
| //! | |
| //! Uses a file-locked offline `cargo miri setup` cache configured with | |
| //! `CARGO_NET_OFFLINE=true` and vendored crates from | |
| //! `<rust_sysroot>/lib/rustlib/src/rust/library/vendor` inside an isolated | |
| //! scratch `CARGO_HOME/config.toml` unless `ANNEAL_MIRI_SYSROOT` explicitly | |
| //! provides a valid prepared non-symlink sysroot. | |
| use std::{ | |
| collections::{BTreeMap, BTreeSet, hash_map::RandomState}, | |
| env, | |
| ffi::{OsStr, OsString}, | |
| fmt::Write as _, | |
| fs::{self, File}, | |
| hash::{BuildHasher as _, Hasher as _}, | |
| io::Read as _, | |
| path::{Component, Path, PathBuf}, | |
| sync::{ | |
| Arc, | |
| atomic::{AtomicU64, Ordering}, | |
| }, | |
| thread, | |
| time::{Duration, Instant, SystemTime, UNIX_EPOCH}, | |
| }; | |
| use anneal_testkit::{Invocation, Termination}; | |
| use serde::{Deserialize, Serialize}; | |
| use serde_json::Value; | |
| use sha2::{Digest, Sha256}; | |
| use crate::{ | |
| corpus::LitmusCase, | |
| r#gen::{GenProgram, render_batch_crate}, | |
| lean_runner::{ | |
| effective_timeout_duration, effective_timeout_secs, sha256_bytes_hex, sha256_file_hex, | |
| }, | |
| rustc_runner::{ | |
| FuzzExecCase, ImmutableStagingDir, PinnedPrivateDir, STORE_PREFIX, TRUSTED_CHILD_PATH_DIRS, | |
| build_child_path_with_bins, collect_rel_file_sha256s_nofollow, copy_opened_file_to_new_dst, | |
| copy_validated_subtree, copy_verified_regular_file, is_global_compiler_or_sysroot_stderr, | |
| prepare_sysroot_binary, prepare_sysroot_binary_in, run_supervised_in_tmp, | |
| sha256_opened_file_hex, try_validate_store_contained_path, | |
| validate_store_contained_dir_tree, validate_store_contained_entry, | |
| }, | |
| verdict::{Expectation, IntKind, MirValue, ObservedOutcome, OrderingKind}, | |
| }; | |
| mod parse; | |
| mod sysroot; | |
| use parse::*; | |
| pub use parse::{parse_miri_output, parse_miri_ret_line}; | |
| use sysroot::*; | |
| const MIRI_RET_STEM: &str = "ANNEAL_MIRI_RET"; | |
| const MIRI_RET_PREFIX: &str = "ANNEAL_MIRI_RET="; | |
| static MIRI_MARKER_SEQ: AtomicU64 = AtomicU64::new(0); | |
| const MIRI_BATCH_CASE_PREFIX: &str = "ANNEAL_MIRI_CASE:"; | |
| const MIRI_RUN_PREFIX: &str = "ANNEAL_MIRI_RUN:"; | |
| const MIRI_BATCH_CHUNK_SIZE: usize = 32; | |
| const PINNED_MIRI_TARGET: &str = "x86_64-unknown-linux-gnu"; | |
| const MIRI_SETUP_TIMEOUT_SECS: u64 = 300; | |
| const MIRI_CASE_TIMEOUT_SECS: u64 = 120; | |
| const RUSTC_PROBE_TIMEOUT_SECS: u64 = 30; | |
| /// Prepared Miri binary and sysroot coordinates for executing reference checks. | |
| #[derive(Clone, Debug)] | |
| pub struct MiriSession { | |
| pub miri_bin: PathBuf, | |
| pub rust_sysroot: PathBuf, | |
| pub miri_sysroot: PathBuf, | |
| pub ld_library_path: String, | |
| pub(crate) validated_tmpdir: Option<PathBuf>, | |
| pub(crate) _sysroot_staging: Option<Arc<ImmutableStagingDir>>, | |
| pub(crate) _miri_sysroot_staging: Option<Arc<ImmutableStagingDir>>, | |
| } | |
| #[derive(Clone, Copy)] | |
| struct MiriChildEnv<'a> { | |
| ld_path: &'a str, | |
| path_env: &'a OsStr, | |
| tmpdir: Option<&'a Path>, | |
| } | |
| #[derive(Clone, Copy)] | |
| enum MiriCacheRoot<'a> { | |
| Path(&'a Path), | |
| Pinned(&'a PinnedPrivateDir), | |
| } | |
| impl MiriSession { | |
| /// Locate `miri` alongside `rust_sysroot` and resolve or offline-prepare | |
| /// a Miri target sysroot under `cache_root`. | |
| pub fn prepare(rust_sysroot: &Path, cache_root: &Path) -> Result<Self, String> { | |
| Self::prepare_with_env(rust_sysroot, cache_root, |k| env::var_os(k)) | |
| } | |
| pub fn prepare_with_env( | |
| rust_sysroot: &Path, | |
| cache_root: &Path, | |
| get_env: impl Fn(&str) -> Option<OsString>, | |
| ) -> Result<Self, String> { | |
| let caller_cwd = | |
| env::current_dir().map_err(|e| format!("determine caller working directory: {e}"))?; | |
| Self::prepare_with_env_at(rust_sysroot, cache_root, &caller_cwd, get_env) | |
| } | |
| fn prepare_with_env_at( | |
| rust_sysroot: &Path, | |
| cache_root: &Path, | |
| caller_cwd: &Path, | |
| get_env: impl Fn(&str) -> Option<OsString>, | |
| ) -> Result<Self, String> { | |
| let validated_tmpdir = crate::mir_eval_runner::validate_optional_existing_dir_env( | |
| get_env("TMPDIR").as_deref(), | |
| caller_cwd, | |
| "TMPDIR", | |
| )?; | |
| let prepared = prepare_sysroot_binary_in( | |
| rust_sysroot, | |
| "bin/miri", | |
| Path::new(STORE_PREFIX), | |
| validated_tmpdir.as_deref(), | |
| "Miri binary", | |
| )?; | |
| Self::prepare_from_sysroot_at_cache( | |
| prepared, | |
| MiriCacheRoot::Path(cache_root), | |
| caller_cwd, | |
| validated_tmpdir, | |
| get_env, | |
| ) | |
| } | |
| pub(crate) fn prepare_from_sysroot( | |
| prepared: crate::rustc_runner::PreparedSysroot, | |
| cache_root: &Path, | |
| ) -> Result<Self, String> { | |
| let caller_cwd = | |
| env::current_dir().map_err(|e| format!("determine caller working directory: {e}"))?; | |
| let get_env = |k: &str| env::var_os(k); | |
| let validated_tmpdir = crate::mir_eval_runner::validate_optional_existing_dir_env( | |
| get_env("TMPDIR").as_deref(), | |
| &caller_cwd, | |
| "TMPDIR", | |
| )?; | |
| Self::prepare_from_sysroot_at_cache( | |
| prepared, | |
| MiriCacheRoot::Path(cache_root), | |
| &caller_cwd, | |
| validated_tmpdir, | |
| get_env, | |
| ) | |
| } | |
| pub(crate) fn prepare_from_sysroot_pinned( | |
| prepared: crate::rustc_runner::PreparedSysroot, | |
| cache_root: &PinnedPrivateDir, | |
| ) -> Result<Self, String> { | |
| let caller_cwd = | |
| env::current_dir().map_err(|e| format!("determine caller working directory: {e}"))?; | |
| let get_env = |k: &str| env::var_os(k); | |
| let validated_tmpdir = crate::mir_eval_runner::validate_optional_existing_dir_env( | |
| get_env("TMPDIR").as_deref(), | |
| &caller_cwd, | |
| "TMPDIR", | |
| )?; | |
| Self::prepare_from_sysroot_at_cache( | |
| prepared, | |
| MiriCacheRoot::Pinned(cache_root), | |
| &caller_cwd, | |
| validated_tmpdir, | |
| get_env, | |
| ) | |
| } | |
| fn prepare_from_sysroot_at_cache( | |
| prepared: crate::rustc_runner::PreparedSysroot, | |
| cache: MiriCacheRoot<'_>, | |
| caller_cwd: &Path, | |
| validated_tmpdir: Option<PathBuf>, | |
| get_env: impl Fn(&str) -> Option<OsString>, | |
| ) -> Result<Self, String> { | |
| let raw_sysroot = prepared.sysroot; | |
| let raw_miri_bin = if let Some(ref staging) = prepared._staging { | |
| let _ = staging.open_verified_rel_file(Path::new("bin/miri"), "Miri binary")?; | |
| raw_sysroot.join("bin/miri") | |
| } else { | |
| crate::rustc_runner::validated_store_aware_executable( | |
| &raw_sysroot.join("bin/miri"), | |
| Path::new(STORE_PREFIX), | |
| caller_cwd, | |
| "Miri binary", | |
| )? | |
| }; | |
| let raw_ld = prepared.ld_library_path; | |
| let rust_sysroot = | |
| ImmutableStagingDir::pin_path_with_guards(&[prepared._staging.as_ref()], &raw_sysroot); | |
| let miri_bin = | |
| ImmutableStagingDir::pin_path_with_guards(&[prepared._staging.as_ref()], &raw_miri_bin); | |
| let ld_library_path = if raw_ld.is_empty() { | |
| String::new() | |
| } else { | |
| ImmutableStagingDir::pin_env_paths_with_guards( | |
| &[prepared._staging.as_ref()], | |
| OsStr::new(&raw_ld), | |
| )? | |
| .to_string_lossy() | |
| .into_owned() | |
| }; | |
| if let Some(explicit) = | |
| get_env("ANNEAL_MIRI_SYSROOT").filter(|v| !v.is_empty()).map(PathBuf::from) | |
| { | |
| let (raw_miri_sysroot, miri_staging) = stage_miri_sysroot_dir_in( | |
| &explicit, | |
| caller_cwd, | |
| Path::new(STORE_PREFIX), | |
| validated_tmpdir.as_deref(), | |
| "ANNEAL_MIRI_SYSROOT", | |
| )?; | |
| let ver_tag = rustc_version_tag( | |
| &rust_sysroot, | |
| &ld_library_path, | |
| get_env("PATH").as_deref(), | |
| validated_tmpdir.as_deref(), | |
| caller_cwd, | |
| )?; | |
| let setup_sha = compute_miri_setup_input_sha256_inner( | |
| &raw_sysroot, | |
| &ver_tag, | |
| prepared._staging.as_deref(), | |
| )?; | |
| verify_miri_sysroot_stamp_with_store( | |
| &raw_miri_sysroot, | |
| miri_staging.as_deref(), | |
| Path::new(STORE_PREFIX), | |
| &ver_tag, | |
| &setup_sha, | |
| )?; | |
| let miri_sysroot = ImmutableStagingDir::pin_path_with_guards( | |
| &[miri_staging.as_ref()], | |
| &raw_miri_sysroot, | |
| ); | |
| return Ok(Self { | |
| miri_bin, | |
| rust_sysroot, | |
| miri_sysroot, | |
| ld_library_path, | |
| validated_tmpdir, | |
| _sysroot_staging: prepared._staging, | |
| _miri_sysroot_staging: miri_staging, | |
| }); | |
| } | |
| let ver_tag = rustc_version_tag( | |
| &rust_sysroot, | |
| &ld_library_path, | |
| get_env("PATH").as_deref(), | |
| validated_tmpdir.as_deref(), | |
| caller_cwd, | |
| )?; | |
| let setup_sha = compute_miri_setup_input_sha256_inner( | |
| &raw_sysroot, | |
| &ver_tag, | |
| prepared._staging.as_deref(), | |
| )?; | |
| let cache_id = format!("{ver_tag}-{}", &setup_sha[..16]); | |
| let target_rel = PathBuf::from(format!("miri-sysroot-{cache_id}")); | |
| let lock_rel = PathBuf::from(format!("miri-sysroot-{cache_id}.setup.lock")); | |
| let (canon_cache_root, target_dir, lock_path) = match cache { | |
| MiriCacheRoot::Path(cache_root) => { | |
| fs::create_dir_all(cache_root) | |
| .map_err(|e| format!("create cache dir {}: {e}", cache_root.display()))?; | |
| let canon = fs::canonicalize(cache_root) | |
| .map_err(|e| format!("canonicalize cache dir {}: {e}", cache_root.display()))?; | |
| let t = canon.join(&target_rel); | |
| let l = canon.join(&lock_rel); | |
| (Some(canon), t, l) | |
| } | |
| MiriCacheRoot::Pinned(pinned) => { | |
| (None, pinned.pin_path(&target_rel), pinned.pin_path(&lock_rel)) | |
| } | |
| }; | |
| let lock_file = File::options() | |
| .create(true) | |
| .read(true) | |
| .write(true) | |
| .truncate(false) | |
| .open(&lock_path) | |
| .map_err(|e| format!("open Miri lock {}: {e}", lock_path.display()))?; | |
| lock_file | |
| .lock() | |
| .map_err(|e| format!("acquire Miri setup lock {}: {e}", lock_path.display()))?; | |
| let cached_ready = match cache { | |
| MiriCacheRoot::Path(_) => { | |
| let caller = canon_cache_root.as_deref().unwrap_or(caller_cwd); | |
| if fs::symlink_metadata(&target_dir).is_ok() { | |
| stage_and_verify_miri_sysroot_in( | |
| &target_dir, | |
| caller, | |
| Path::new(STORE_PREFIX), | |
| validated_tmpdir.as_deref(), | |
| &ver_tag, | |
| &setup_sha, | |
| "cached Miri sysroot", | |
| ) | |
| .ok() | |
| } else { | |
| None | |
| } | |
| } | |
| MiriCacheRoot::Pinned(pinned) => { | |
| if pinned.has_rel_dir(&target_rel, "cached Miri sysroot") { | |
| stage_and_verify_miri_sysroot_from_pinned_in( | |
| pinned, | |
| &target_rel, | |
| Path::new(STORE_PREFIX), | |
| validated_tmpdir.as_deref(), | |
| &ver_tag, | |
| &setup_sha, | |
| "cached Miri sysroot", | |
| ) | |
| .ok() | |
| } else { | |
| None | |
| } | |
| } | |
| }; | |
| let (raw_miri_sysroot, miri_staging) = match cached_ready { | |
| Some(pair) => pair, | |
| None => { | |
| build_offline_miri_sysroot_in( | |
| cache, | |
| &rust_sysroot, | |
| &miri_bin, | |
| &target_dir, | |
| &ver_tag, | |
| &setup_sha, | |
| &ld_library_path, | |
| get_env("PATH").as_deref(), | |
| validated_tmpdir.as_deref(), | |
| caller_cwd, | |
| )?; | |
| match cache { | |
| MiriCacheRoot::Path(_) => { | |
| let caller = canon_cache_root.as_deref().unwrap_or(caller_cwd); | |
| stage_and_verify_miri_sysroot_in( | |
| &target_dir, | |
| caller, | |
| Path::new(STORE_PREFIX), | |
| validated_tmpdir.as_deref(), | |
| &ver_tag, | |
| &setup_sha, | |
| "cached Miri sysroot", | |
| )? | |
| } | |
| MiriCacheRoot::Pinned(pinned) => stage_and_verify_miri_sysroot_from_pinned_in( | |
| pinned, | |
| &target_rel, | |
| Path::new(STORE_PREFIX), | |
| validated_tmpdir.as_deref(), | |
| &ver_tag, | |
| &setup_sha, | |
| "cached Miri sysroot", | |
| )?, | |
| } | |
| } | |
| }; | |
| drop(lock_file); | |
| let miri_sysroot = | |
| ImmutableStagingDir::pin_path_with_guards(&[miri_staging.as_ref()], &raw_miri_sysroot); | |
| Ok(Self { | |
| miri_bin, | |
| rust_sysroot, | |
| miri_sysroot, | |
| ld_library_path, | |
| validated_tmpdir, | |
| _sysroot_staging: prepared._staging, | |
| _miri_sysroot_staging: miri_staging, | |
| }) | |
| } | |
| fn resolve_miri_rustc_bin( | |
| &self, | |
| ) -> Result<(PathBuf, Option<Arc<ImmutableStagingDir>>), String> { | |
| if let Some(ref staging) = self._sysroot_staging { | |
| let _ = staging.open_verified_rel_file(Path::new("bin/rustc"), "Miri rustc binary")?; | |
| return Ok((staging.pin_path(Path::new("bin/rustc")), None)); | |
| } | |
| let prepared = prepare_sysroot_binary( | |
| &self.rust_sysroot, | |
| "bin/rustc", | |
| Path::new(STORE_PREFIX), | |
| "Miri rustc binary", | |
| )?; | |
| let pinned_bin = ImmutableStagingDir::pin_path_with_guards( | |
| &[prepared._staging.as_ref()], | |
| &prepared.binary, | |
| ); | |
| Ok((pinned_bin, prepared._staging)) | |
| } | |
| /// Execute all litmus cases under Miri, grouping harness generation by | |
| /// fixture source file and running cases across bounded worker threads. | |
| pub fn run_cases( | |
| &self, | |
| cases: &[LitmusCase], | |
| ) -> Result<BTreeMap<String, ObservedOutcome>, String> { | |
| let mut by_source: BTreeMap<PathBuf, Vec<&LitmusCase>> = BTreeMap::new(); | |
| for case in cases { | |
| by_source.entry(case.source_abs.clone()).or_default().push(case); | |
| } | |
| let workers = thread::available_parallelism().map(|n| n.get().clamp(1, 4)).unwrap_or(1); | |
| let ld_path = &self.ld_library_path; | |
| let path_env = | |
| build_child_path(&self.rust_sysroot.join("bin"), env::var_os("PATH").as_deref())?; | |
| let (rustc_bin, _rustc_staging) = self.resolve_miri_rustc_bin()?; | |
| let setup_timeout = effective_timeout_secs(MIRI_SETUP_TIMEOUT_SECS)?; | |
| let work_root = crate::mir_eval_runner::build_temp_dir( | |
| "anneal-miri-work-", | |
| self.validated_tmpdir.as_deref(), | |
| )?; | |
| let child_env = | |
| MiriChildEnv { ld_path, path_env: &path_env, tmpdir: self.validated_tmpdir.as_deref() }; | |
| let mut results = BTreeMap::new(); | |
| struct MiriWorkItem { | |
| case_id: String, | |
| harness_path: PathBuf, | |
| bridge_rlib: PathBuf, | |
| corpus_dir: PathBuf, | |
| selector: String, | |
| token: String, | |
| } | |
| let mut work_items: Vec<MiriWorkItem> = Vec::with_capacity(cases.len()); | |
| for (group_idx, (source_abs, group_cases)) in by_source.iter().enumerate() { | |
| let source_text = fs::read_to_string(source_abs) | |
| .map_err(|e| format!("read fixture {}: {e}", source_abs.display()))?; | |
| let bundle_res = build_isolated_miri_group( | |
| work_root.path(), | |
| group_idx, | |
| &source_text, | |
| group_cases, | |
| &rustc_bin, | |
| &self.miri_sysroot, | |
| child_env, | |
| Duration::from_secs(setup_timeout), | |
| ); | |
| match bundle_res { | |
| Ok(bundle) => { | |
| for case in group_cases { | |
| work_items.push(MiriWorkItem { | |
| case_id: case.id.clone(), | |
| harness_path: bundle.harness_path.clone(), | |
| bridge_rlib: bundle.bridge_rlib.clone(), | |
| corpus_dir: bundle.corpus_dir.clone(), | |
| selector: case.id.clone(), | |
| token: bundle.token.clone(), | |
| }); | |
| } | |
| } | |
| Err(detail) => { | |
| for case in group_cases { | |
| results.insert( | |
| case.id.clone(), | |
| ObservedOutcome::ToolError { detail: detail.clone() }, | |
| ); | |
| } | |
| } | |
| } | |
| } | |
| for chunk in work_items.chunks(workers) { | |
| let outcomes = thread::scope(|scope| { | |
| let mut handles = Vec::with_capacity(chunk.len()); | |
| for item in chunk { | |
| let miri_bin = &self.miri_bin; | |
| let miri_sysroot = &self.miri_sysroot; | |
| handles.push(scope.spawn(move || { | |
| let out = run_single_miri( | |
| miri_bin, | |
| miri_sysroot, | |
| child_env, | |
| &item.harness_path, | |
| &item.bridge_rlib, | |
| &item.corpus_dir, | |
| &item.selector, | |
| Some(item.token.as_str()), | |
| ); | |
| (item.case_id.clone(), out) | |
| })); | |
| } | |
| handles | |
| .into_iter() | |
| .map(|h| { | |
| h.join().unwrap_or_else(|_| { | |
| ( | |
| "<panicked>".to_owned(), | |
| ObservedOutcome::ToolError { | |
| detail: "Miri worker thread panicked".to_owned(), | |
| }, | |
| ) | |
| }) | |
| }) | |
| .collect::<Vec<_>>() | |
| }); | |
| for (case_id, outcome) in outcomes { | |
| results.insert(case_id, outcome); | |
| } | |
| } | |
| Ok(results) | |
| } | |
| /// Execute a Stage-2 fuzz batch under Miri (`-Zmiri-tree-borrows`) using | |
| /// batched execution for expected-clean cases with automatic recursive | |
| /// bisection down to isolated single-case runs on any UB/panic/error, and | |
| /// isolated parallel worker runs for expected-UB/scope cases. | |
| pub fn run_fuzz_batch( | |
| &self, | |
| source_text: &str, | |
| cases: &[crate::rustc_runner::FuzzExecCase], | |
| ) -> Result<BTreeMap<String, ObservedOutcome>, String> { | |
| self.run_fuzz_batch_until(source_text, cases, None) | |
| } | |
| /// Deadline-clamped variant of [`Self::run_fuzz_batch`] used by the | |
| /// shrinker so stalled candidates cannot run past `max_duration_secs`. | |
| pub fn run_fuzz_batch_until( | |
| &self, | |
| source_text: &str, | |
| cases: &[crate::rustc_runner::FuzzExecCase], | |
| deadline: Option<Instant>, | |
| ) -> Result<BTreeMap<String, ObservedOutcome>, String> { | |
| let with_ev = self.run_fuzz_batch_with_evidence_until(source_text, cases, deadline)?; | |
| Ok(with_ev.into_iter().map(|(id, (outcome, _ev))| (id, outcome)).collect()) | |
| } | |
| /// Deadline-clamped execution returning `(outcome, case_bound_evidence)` | |
| /// for every case in `cases`. | |
| pub fn run_fuzz_batch_with_evidence_until( | |
| &self, | |
| source_text: &str, | |
| cases: &[FuzzExecCase], | |
| deadline: Option<Instant>, | |
| ) -> Result<BTreeMap<String, (ObservedOutcome, Option<String>)>, String> { | |
| self.run_fuzz_crate_with_evidence_impl(source_text, None, cases, deadline) | |
| } | |
| /// Program-aware deadline-clamped execution preserving single-crate Miri | |
| /// batching on the happy path while isolating ordinary compiler diagnostics | |
| /// (`error[E...]`, syntax errors) via subset-specific harnesses. | |
| pub fn run_fuzz_crate_with_evidence_until( | |
| &self, | |
| source_text: &str, | |
| programs: &[&GenProgram], | |
| cases: &[FuzzExecCase], | |
| deadline: Option<Instant>, | |
| ) -> Result<BTreeMap<String, (ObservedOutcome, Option<String>)>, String> { | |
| if programs.len() != cases.len() { | |
| return Err(format!( | |
| "Miri crate program count ({}) does not match case count ({})", | |
| programs.len(), | |
| cases.len() | |
| )); | |
| } | |
| let pairs: Vec<(&GenProgram, &FuzzExecCase)> = | |
| programs.iter().copied().zip(cases.iter()).collect(); | |
| for (prog, case) in &pairs { | |
| if prog.case_id != case.case_id { | |
| return Err(format!( | |
| "Miri crate program `{}` does not match case `{}`", | |
| prog.case_id, case.case_id | |
| )); | |
| } | |
| } | |
| self.run_fuzz_crate_with_evidence_impl(source_text, Some(&pairs), cases, deadline) | |
| } | |
| fn run_fuzz_crate_with_evidence_impl( | |
| &self, | |
| source_text: &str, | |
| programs: Option<&[(&GenProgram, &FuzzExecCase)]>, | |
| cases: &[FuzzExecCase], | |
| deadline: Option<Instant>, | |
| ) -> Result<BTreeMap<String, (ObservedOutcome, Option<String>)>, String> { | |
| if cases.is_empty() { | |
| return Ok(BTreeMap::new()); | |
| } | |
| let ld_path = &self.ld_library_path; | |
| let path_env = | |
| build_child_path(&self.rust_sysroot.join("bin"), env::var_os("PATH").as_deref())?; | |
| let (rustc_bin, _rustc_staging) = self.resolve_miri_rustc_bin()?; | |
| let work_root = crate::mir_eval_runner::build_temp_dir( | |
| "anneal-miri-fuzz-", | |
| self.validated_tmpdir.as_deref(), | |
| )?; | |
| let child_env = | |
| MiriChildEnv { ld_path, path_env: &path_env, tmpdir: self.validated_tmpdir.as_deref() }; | |
| let bundle = match build_isolated_miri_fuzz_group( | |
| work_root.path(), | |
| "fuzz", | |
| source_text, | |
| cases, | |
| &rustc_bin, | |
| &self.miri_sysroot, | |
| child_env, | |
| deadline, | |
| ) { | |
| Ok(b) => b, | |
| Err(MiriBatchFailure::Global(detail)) => { | |
| return Ok(cases | |
| .iter() | |
| .map(|c| { | |
| ( | |
| c.case_id.clone(), | |
| (ObservedOutcome::ToolError { detail: detail.clone() }, None), | |
| ) | |
| }) | |
| .collect()); | |
| } | |
| Err(MiriBatchFailure::CompileDiagnostic(detail)) => { | |
| if let Some(items) = programs | |
| && items.len() > 1 | |
| { | |
| let mid = items.len() / 2; | |
| let mut combined = run_miri_compile_bisect_slice( | |
| &self.miri_bin, | |
| &rustc_bin, | |
| &self.miri_sysroot, | |
| child_env, | |
| &items[..mid], | |
| deadline, | |
| ); | |
| combined.extend(run_miri_compile_bisect_slice( | |
| &self.miri_bin, | |
| &rustc_bin, | |
| &self.miri_sysroot, | |
| child_env, | |
| &items[mid..], | |
| deadline, | |
| )); | |
| return Ok(combined); | |
| } | |
| return Ok(cases | |
| .iter() | |
| .map(|c| { | |
| ( | |
| c.case_id.clone(), | |
| (ObservedOutcome::ToolError { detail: detail.clone() }, None), | |
| ) | |
| }) | |
| .collect()); | |
| } | |
| }; | |
| let mut results = BTreeMap::new(); | |
| let clean_pairs: Vec<(String, String)> = cases | |
| .iter() | |
| .filter(|c| c.expected_clean_batch) | |
| .map(|c| (c.case_id.clone(), c.fn_name.clone())) | |
| .collect(); | |
| let clean_progs: Vec<(&GenProgram, &FuzzExecCase)> = programs | |
| .map(|ps| ps.iter().copied().filter(|(_, c)| c.expected_clean_batch).collect()) | |
| .unwrap_or_default(); | |
| let isolated_pairs: Vec<(String, String)> = cases | |
| .iter() | |
| .filter(|c| !c.expected_clean_batch) | |
| .map(|c| (c.case_id.clone(), c.fn_name.clone())) | |
| .collect(); | |
| let isolated_progs: Vec<(&GenProgram, &FuzzExecCase)> = programs | |
| .map(|ps| ps.iter().copied().filter(|(_, c)| !c.expected_clean_batch).collect()) | |
| .unwrap_or_default(); | |
| // Execute clean chunks in parallel (up to 4 chunks at once), bisecting | |
| // any chunk that faults so verdict accuracy matches per-case execution. | |
| let workers = thread::available_parallelism().map(|n| n.get().clamp(1, 4)).unwrap_or(1); | |
| let chunks: Vec<&[(String, String)]> = clean_pairs.chunks(MIRI_BATCH_CHUNK_SIZE).collect(); | |
| let prog_chunks: Vec<&[(&GenProgram, &FuzzExecCase)]> = if programs.is_some() { | |
| clean_progs.chunks(MIRI_BATCH_CHUNK_SIZE).collect() | |
| } else { | |
| Vec::new() | |
| }; | |
| for (group_idx, group) in chunks.chunks(workers).enumerate() { | |
| let group_base = group_idx * workers; | |
| let group_maps = thread::scope(|scope| { | |
| let mut handles = Vec::with_capacity(group.len()); | |
| for (local_idx, chunk) in group.iter().enumerate() { | |
| let miri_bin = &self.miri_bin; | |
| let rustc_bin = &rustc_bin; | |
| let miri_sysroot = &self.miri_sysroot; | |
| let harness_path = &bundle.harness_path; | |
| let bridge_rlib = &bundle.bridge_rlib; | |
| let corpus_dir = &bundle.corpus_dir; | |
| let expected_token = bundle.token.as_str(); | |
| let chunk_progs = prog_chunks.get(group_base + local_idx).copied(); | |
| handles.push(scope.spawn(move || { | |
| run_miri_chunk_with_bisection( | |
| miri_bin, | |
| Some(rustc_bin.as_path()), | |
| miri_sysroot, | |
| child_env, | |
| harness_path, | |
| Some((bridge_rlib.as_path(), corpus_dir.as_path())), | |
| chunk, | |
| chunk_progs, | |
| false, | |
| Some(expected_token), | |
| deadline, | |
| ) | |
| })); | |
| } | |
| handles.into_iter().map(|h| h.join().unwrap_or_default()).collect::<Vec<_>>() | |
| }); | |
| for m in group_maps { | |
| results.extend(m); | |
| } | |
| } | |
| // Execute isolated UB / scope-control cases directly in parallel, | |
| // falling back to a standalone harness if another batch-mate failed to | |
| // compile in the shared crate. | |
| for (group_idx, chunk) in isolated_pairs.chunks(workers).enumerate() { | |
| let group_base = group_idx * workers; | |
| let outcomes = thread::scope(|scope| { | |
| let mut handles = Vec::with_capacity(chunk.len()); | |
| for (local_idx, (case_id, fn_name)) in chunk.iter().enumerate() { | |
| let miri_bin = &self.miri_bin; | |
| let rustc_bin = &rustc_bin; | |
| let miri_sysroot = &self.miri_sysroot; | |
| let harness_path = &bundle.harness_path; | |
| let bridge_rlib = &bundle.bridge_rlib; | |
| let corpus_dir = &bundle.corpus_dir; | |
| let expected_token = bundle.token.as_str(); | |
| let iso_prog = | |
| programs.and_then(|_| isolated_progs.get(group_base + local_idx).copied()); | |
| handles.push(scope.spawn(move || { | |
| let out = run_single_miri_fuzz_with_fallback( | |
| miri_bin, | |
| Some(rustc_bin.as_path()), | |
| miri_sysroot, | |
| child_env, | |
| harness_path, | |
| Some((bridge_rlib.as_path(), corpus_dir.as_path())), | |
| (case_id, fn_name), | |
| iso_prog, | |
| Some(expected_token), | |
| deadline, | |
| ); | |
| (case_id.clone(), out) | |
| })); | |
| } | |
| handles | |
| .into_iter() | |
| .map(|h| { | |
| h.join().unwrap_or_else(|_| { | |
| ( | |
| "<panicked>".to_owned(), | |
| ( | |
| ObservedOutcome::ToolError { | |
| detail: "Miri fuzz worker thread panicked".to_owned(), | |
| }, | |
| None, | |
| ), | |
| ) | |
| }) | |
| }) | |
| .collect::<Vec<_>>() | |
| }); | |
| for (id, outcome) in outcomes { | |
| results.insert(id, outcome); | |
| } | |
| } | |
| Ok(results) | |
| } | |
| } | |
| fn fresh_miri_marker_token(disallowed_haystack: &str) -> String { | |
| loop { | |
| let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0); | |
| let seq = MIRI_MARKER_SEQ.fetch_add(1, Ordering::Relaxed); | |
| let mut h = Sha256::new(); | |
| h.update(b"anneal-miri-marker-v2\0"); | |
| h.update(nanos.to_le_bytes()); | |
| h.update(std::process::id().to_le_bytes()); | |
| h.update(seq.to_le_bytes()); | |
| h.update((disallowed_haystack.len() as u64).to_le_bytes()); | |
| let mut rs = RandomState::new().build_hasher(); | |
| rs.write_u64(seq); | |
| h.update(rs.finish().to_le_bytes()); | |
| if let Ok(mut urand) = File::open("/dev/urandom") { | |
| let mut buf = [0u8; 16]; | |
| if urand.read_exact(&mut buf).is_ok() { | |
| h.update(buf); | |
| } | |
| } | |
| let digest = h.finalize(); | |
| let mut tok = String::with_capacity(32); | |
| for b in &digest[..16] { | |
| let _ = write!(tok, "{b:02x}"); | |
| } | |
| if !disallowed_haystack.contains(&tok) { | |
| return tok; | |
| } | |
| } | |
| } | |
| fn validate_rust_ident(ident: &str, label: &str) -> Result<(), String> { | |
| let mut bytes = ident.bytes(); | |
| let Some(first) = bytes.next() else { | |
| return Err(format!("empty {label}")); | |
| }; | |
| if !(first.is_ascii_alphabetic() || first == b'_') | |
| || !bytes.all(|b| b.is_ascii_alphanumeric() || b == b'_') | |
| { | |
| return Err(format!("invalid {label} `{ident}`")); | |
| } | |
| Ok(()) | |
| } | |
| fn validate_rust_fn_path(path: &str) -> Result<(), String> { | |
| if path.is_empty() | |
| || path.split("::").any(|seg| validate_rust_ident(seg, "fixture function segment").is_err()) | |
| { | |
| return Err(format!("invalid fixture function path `{path}`")); | |
| } | |
| Ok(()) | |
| } | |
| struct IsolatedMiriBundle { | |
| token: String, | |
| harness_path: PathBuf, | |
| bridge_rlib: PathBuf, | |
| corpus_dir: PathBuf, | |
| } | |
| #[derive(Clone, Debug, PartialEq, Eq)] | |
| enum MiriBatchFailure { | |
| /// Genuine Miri/rustc/sysroot/timeout/launch failure affecting all cases. | |
| Global(String), | |
| /// Ordinary compilation diagnostic (e.g., `error[E0308]`, syntax error) | |
| /// that can be isolated cleanly using subset-specific crates/harnesses. | |
| CompileDiagnostic(String), | |
| } | |
| impl MiriBatchFailure { | |
| fn into_detail(self) -> String { | |
| match self { | |
| Self::Global(d) | Self::CompileDiagnostic(d) => d, | |
| } | |
| } | |
| } | |
| #[allow(clippy::too_many_arguments)] | |
| fn compile_miri_rlib_status( | |
| rustc_bin: &Path, | |
| miri_sysroot: &Path, | |
| child_env: MiriChildEnv<'_>, | |
| crate_name: &str, | |
| src_path: &Path, | |
| out_rlib: &Path, | |
| extra_extern: Option<(&str, &Path)>, | |
| extra_lib_dir: Option<&Path>, | |
| timeout: Duration, | |
| ) -> Result<(), MiriBatchFailure> { | |
| let mut inv = Invocation::new(rustc_bin, &["--edition=2024", "--target", PINNED_MIRI_TARGET]) | |
| .arg("--sysroot") | |
| .arg(miri_sysroot) | |
| .arg("--cfg") | |
| .arg("miri") | |
| .arg("-Zalways-encode-mir") | |
| .arg("-C") | |
| .arg("opt-level=0") | |
| .arg("-C") | |
| .arg("debug-assertions=no") | |
| .arg("-C") | |
| .arg("overflow-checks=no") | |
| .arg("-A") | |
| .arg("dead_code") | |
| .arg("--crate-type=lib") | |
| .arg("--crate-name") | |
| .arg(crate_name); | |
| if let Some((dep_name, dep_rlib)) = extra_extern { | |
| inv = inv.arg("--extern").arg(format!("{dep_name}={}", dep_rlib.display())); | |
| } | |
| if let Some(lib_dir) = extra_lib_dir { | |
| inv = inv.arg("-L").arg(lib_dir); | |
| } | |
| inv = inv | |
| .arg("-o") | |
| .arg(out_rlib) | |
| .arg(src_path) | |
| .env("LD_LIBRARY_PATH", child_env.ld_path) | |
| .env("PATH", child_env.path_env); | |
| if let Some(td) = child_env.tmpdir { | |
| inv = inv.env("TMPDIR", td); | |
| } | |
| let work_dir = src_path.parent().unwrap_or_else(|| Path::new("/")); | |
| let out = run_supervised_in_tmp(&inv, work_dir, timeout, child_env.tmpdir, crate_name) | |
| .map_err(MiriBatchFailure::Global)?; | |
| match out.termination { | |
| Termination::Exited(status) if status.success() => Ok(()), | |
| other => { | |
| let stderr = String::from_utf8_lossy(&out.stderr); | |
| let snippet = stderr.lines().take(6).collect::<Vec<_>>().join(" | "); | |
| let msg = format!( | |
| "compile Miri `{crate_name}` crate failed ({}): {snippet}", | |
| other.describe() | |
| ); | |
| if matches!(other, Termination::Exited(_)) && !is_miri_global_stderr(&stderr) { | |
| Err(MiriBatchFailure::CompileDiagnostic(msg)) | |
| } else { | |
| Err(MiriBatchFailure::Global(msg)) | |
| } | |
| } | |
| } | |
| } | |
| #[allow(clippy::too_many_arguments)] | |
| fn compile_isolated_miri_crates( | |
| work_root: &Path, | |
| group_rel: &str, | |
| source_text: &str, | |
| bridge_code: String, | |
| render_harness: impl FnOnce(&str) -> Result<String, String>, | |
| rustc_bin: &Path, | |
| miri_sysroot: &Path, | |
| child_env: MiriChildEnv<'_>, | |
| deadline: Option<Instant>, | |
| ) -> Result<IsolatedMiriBundle, MiriBatchFailure> { | |
| let group_dir = work_root.join(group_rel); | |
| let corpus_dir = group_dir.join("c"); | |
| let bridge_dir = group_dir.join("b"); | |
| fs::create_dir_all(&corpus_dir).map_err(|e| { | |
| MiriBatchFailure::Global(format!("create Miri corpus dir {}: {e}", corpus_dir.display())) | |
| })?; | |
| fs::create_dir_all(&bridge_dir).map_err(|e| { | |
| MiriBatchFailure::Global(format!("create Miri bridge dir {}: {e}", bridge_dir.display())) | |
| })?; | |
| // Compile `corpus` and `bridge` into separate `.rlib` crates BEFORE | |
| // generating the secret token or writing `h/harness.rs`, keeping the | |
| // token strictly inside `h/harness.rs` source literals (never in paths, | |
| // symbols, args, or stack frame metadata). | |
| let corpus_src = corpus_dir.join("corpus.rs"); | |
| fs::write(&corpus_src, source_text).map_err(|e| { | |
| MiriBatchFailure::Global(format!("write Miri corpus {}: {e}", corpus_src.display())) | |
| })?; | |
| let corpus_rlib = corpus_dir.join("libcorpus.rlib"); | |
| let corpus_timeout = effective_timeout_duration(MIRI_SETUP_TIMEOUT_SECS, deadline) | |
| .map_err(MiriBatchFailure::Global)?; | |
| compile_miri_rlib_status( | |
| rustc_bin, | |
| miri_sysroot, | |
| child_env, | |
| "corpus", | |
| &corpus_src, | |
| &corpus_rlib, | |
| None, | |
| None, | |
| corpus_timeout, | |
| )?; | |
| let bridge_src = bridge_dir.join("bridge.rs"); | |
| fs::write(&bridge_src, &bridge_code).map_err(|e| { | |
| MiriBatchFailure::Global(format!("write Miri bridge {}: {e}", bridge_src.display())) | |
| })?; | |
| let bridge_rlib = bridge_dir.join("libbridge.rlib"); | |
| let bridge_timeout = effective_timeout_duration(MIRI_SETUP_TIMEOUT_SECS, deadline) | |
| .map_err(MiriBatchFailure::Global)?; | |
| compile_miri_rlib_status( | |
| rustc_bin, | |
| miri_sysroot, | |
| child_env, | |
| "bridge", | |
| &bridge_src, | |
| &bridge_rlib, | |
| Some(("corpus", &corpus_rlib)), | |
| Some(&corpus_dir), | |
| bridge_timeout, | |
| )?; | |
| let mut disallowed = String::with_capacity(source_text.len() + bridge_code.len() + 1); | |
| disallowed.push_str(source_text); | |
| disallowed.push('\n'); | |
| disallowed.push_str(&bridge_code); | |
| let token = fresh_miri_marker_token(&disallowed); | |
| let harness_code = render_harness(&token).map_err(MiriBatchFailure::CompileDiagnostic)?; | |
| let harness_dir = group_dir.join("h"); | |
| fs::create_dir_all(&harness_dir).map_err(|e| { | |
| MiriBatchFailure::Global(format!("create Miri harness dir {}: {e}", harness_dir.display())) | |
| })?; | |
| let harness_path = harness_dir.join("harness.rs"); | |
| fs::write(&harness_path, harness_code).map_err(|e| { | |
| MiriBatchFailure::Global(format!("write Miri harness {}: {e}", harness_path.display())) | |
| })?; | |
| Ok(IsolatedMiriBundle { token, harness_path, bridge_rlib, corpus_dir }) | |
| } | |
| #[allow(clippy::too_many_arguments)] | |
| fn build_isolated_miri_group( | |
| work_root: &Path, | |
| group_idx: usize, | |
| source_text: &str, | |
| group_cases: &[&LitmusCase], | |
| rustc_bin: &Path, | |
| miri_sysroot: &Path, | |
| child_env: MiriChildEnv<'_>, | |
| setup_timeout: Duration, | |
| ) -> Result<IsolatedMiriBundle, String> { | |
| let bridge_code = generate_miri_bridge(group_cases)?; | |
| let deadline = Instant::now().checked_add(setup_timeout); | |
| compile_isolated_miri_crates( | |
| work_root, | |
| &format!("group_{group_idx}"), | |
| source_text, | |
| bridge_code, | |
| |tok| generate_miri_harness_with_token(group_cases, Some(tok)), | |
| rustc_bin, | |
| miri_sysroot, | |
| child_env, | |
| deadline, | |
| ) | |
| .map_err(MiriBatchFailure::into_detail) | |
| } | |
| #[allow(clippy::too_many_arguments)] | |
| fn build_isolated_miri_fuzz_group( | |
| work_root: &Path, | |
| group_rel: &str, | |
| source_text: &str, | |
| cases: &[FuzzExecCase], | |
| rustc_bin: &Path, | |
| miri_sysroot: &Path, | |
| child_env: MiriChildEnv<'_>, | |
| deadline: Option<Instant>, | |
| ) -> Result<IsolatedMiriBundle, MiriBatchFailure> { | |
| let bridge_code = | |
| generate_miri_fuzz_bridge(cases).map_err(MiriBatchFailure::CompileDiagnostic)?; | |
| compile_isolated_miri_crates( | |
| work_root, | |
| group_rel, | |
| source_text, | |
| bridge_code, | |
| |tok| generate_miri_fuzz_harness_with_token(cases, Some(tok)), | |
| rustc_bin, | |
| miri_sysroot, | |
| child_env, | |
| deadline, | |
| ) | |
| } | |
| fn miri_marker_prefix(stem_with_sep: &str, token: Option<&str>) -> String { | |
| match token { | |
| Some(tok) => { | |
| if let Some(stem) = stem_with_sep.strip_suffix('=') { | |
| format!("{stem}:{tok}=") | |
| } else { | |
| format!("{stem_with_sep}{tok}:") | |
| } | |
| } | |
| None => stem_with_sep.to_owned(), | |
| } | |
| } | |
| fn miri_ret_prefix_for_token(token: Option<&str>) -> String { | |
| miri_marker_prefix(MIRI_RET_PREFIX, token) | |
| } | |
| fn generate_miri_bridge(cases: &[&LitmusCase]) -> Result<String, String> { | |
| let mut out = String::from("#![allow(unused_unsafe)]\nextern crate corpus;\n\n"); | |
| for (idx, case) in cases.iter().enumerate() { | |
| validate_rust_fn_path(&case.function)?; | |
| let arg_exprs = | |
| case.args.iter().map(rust_arg_expr).collect::<Result<Vec<_>, _>>()?.join(", "); | |
| let call = format!("unsafe {{ corpus::{}({arg_exprs}) }}", case.function); | |
| match (&case.expected, &case.expected_return) { | |
| (Expectation::Pass, Some(exp)) => { | |
| let ret_ty = rust_ret_type(exp)?; | |
| let _ = writeln!( | |
| out, | |
| "#[inline(never)]\npub fn call_case_{idx}() -> {ret_ty} {{\n {call}\n}}\n" | |
| ); | |
| } | |
| _ => { | |
| let _ = writeln!( | |
| out, | |
| "#[inline(never)]\npub fn call_case_{idx}() {{\n let _ret = {call};\n}}\n" | |
| ); | |
| } | |
| } | |
| } | |
| Ok(out) | |
| } | |
| fn generate_miri_fuzz_bridge(cases: &[FuzzExecCase]) -> Result<String, String> { | |
| let mut out = String::from("#![allow(unused_unsafe)]\nextern crate corpus;\n\n"); | |
| for (idx, case) in cases.iter().enumerate() { | |
| validate_rust_fn_path(&case.fn_name)?; | |
| let arg_exprs = | |
| case.args.iter().map(rust_arg_expr).collect::<Result<Vec<_>, _>>()?.join(", "); | |
| let ret_ty = rust_ret_type(&case.ret_shape)?; | |
| let _ = writeln!( | |
| out, | |
| "#[inline(never)]\npub fn call_fuzz_case_{idx}() -> {ret_ty} {{\n unsafe {{ corpus::{}({arg_exprs}) }}\n}}\n", | |
| case.fn_name | |
| ); | |
| } | |
| Ok(out) | |
| } | |
| #[cfg_attr(not(test), allow(dead_code))] | |
| fn generate_miri_harness(cases: &[&LitmusCase]) -> Result<String, String> { | |
| generate_miri_harness_with_token(cases, None) | |
| } | |
| fn generate_miri_harness_with_token( | |
| cases: &[&LitmusCase], | |
| token: Option<&str>, | |
| ) -> Result<String, String> { | |
| let ret_prefix = miri_ret_prefix_for_token(token); | |
| let mut out = String::from("extern crate bridge;\n\nfn main() {\n"); | |
| out.push_str(" let selector = std::env::args().nth(1).expect(\"missing case selector\");\n"); | |
| out.push_str(" match selector.as_str() {\n"); | |
| for (idx, case) in cases.iter().enumerate() { | |
| out.push_str(&format!(" {:?} => {{\n", case.id)); | |
| match (&case.expected, &case.expected_return) { | |
| (Expectation::Pass, Some(exp)) => { | |
| let ret_ty = rust_ret_type(exp)?; | |
| out.push_str(&format!( | |
| " match std::panic::catch_unwind(std::panic::AssertUnwindSafe(bridge::call_case_{idx})) {{\n\ | |
| \x20 Ok(ret) => {{ let ret: {ret_ty} = ret; {}; }}\n\ | |
| \x20 Err(_) => println!(\"{ret_prefix}PANICKED\"),\n\ | |
| \x20 }}\n", | |
| rust_print_ret_stmt(exp, "ret", &ret_prefix)? | |
| )); | |
| } | |
| _ => { | |
| out.push_str(&format!( | |
| " match std::panic::catch_unwind(std::panic::AssertUnwindSafe(bridge::call_case_{idx})) {{\n\ | |
| \x20 Ok(()) => println!(\"{ret_prefix}UNEXPECTED_RETURN\"),\n\ | |
| \x20 Err(_) => println!(\"{ret_prefix}PANICKED\"),\n\ | |
| \x20 }}\n" | |
| )); | |
| } | |
| } | |
| out.push_str(" }\n"); | |
| } | |
| out.push_str(" other => panic!(\"unknown differential case selector: {other}\"),\n"); | |
| out.push_str(" }\n}\n"); | |
| Ok(out) | |
| } | |
| pub(crate) fn rust_arg_expr_pub(val: &MirValue) -> Result<String, String> { | |
| rust_arg_expr(val) | |
| } | |
| pub(crate) fn rust_ret_type_pub(shape: &MirValue) -> Result<String, String> { | |
| rust_ret_type(shape) | |
| } | |
| /// Format a Rust expression producing a `String` matching | |
| /// `parse_miri_ret_line`. | |
| pub(crate) fn rust_print_ret_payload_expr(shape: &MirValue, var: &str) -> Result<String, String> { | |
| match shape { | |
| MirValue::Int { int_kind, .. } => { | |
| Ok(format!("format!(\"INT:{}:{{}}\", {var})", int_kind.rust_name())) | |
| } | |
| MirValue::Bool { .. } => Ok(format!("format!(\"BOOL:{{}}\", {var})")), | |
| MirValue::Char { .. } => Ok(format!("format!(\"CHAR:{{}}\", {var} as u32)")), | |
| MirValue::Ordering { .. } => Ok(format!( | |
| "format!(\"ORDERING:{{}}\", match {var} {{ \ | |
| core::cmp::Ordering::Less => \"less\", \ | |
| core::cmp::Ordering::Equal => \"equal\", \ | |
| core::cmp::Ordering::Greater => \"greater\" }})" | |
| )), | |
| MirValue::Unit => Ok(format!("{{ let () = {var}; \"UNIT\".to_owned() }}")), | |
| MirValue::OverflowPair { int_kind, .. } => { | |
| Ok(format!("format!(\"OVF:{}:{{}}:{{}}\", {var}.0, {var}.1)", int_kind.rust_name())) | |
| } | |
| MirValue::Enum { .. } => Err("Enum expected_return is not supported".to_owned()), | |
| } | |
| } | |
| /// Partition crate-level inner attributes (`#![...]`, including multi-line | |
| /// attributes) from module body lines, dropping `#![no_std]` so std harnesses | |
| /// compile cleanly. | |
| pub(crate) fn split_crate_attrs(source_text: &str) -> (Vec<String>, Vec<String>) { | |
| let mut crate_attrs = Vec::new(); | |
| let mut mod_lines = Vec::new(); | |
| let mut in_attr = false; | |
| let mut bracket_depth: i32 = 0; | |
| for line in source_text.lines() { | |
| let trimmed = line.trim(); | |
| if !in_attr && trimmed == "#![no_std]" { | |
| continue; | |
| } | |
| if !in_attr && trimmed.starts_with("#![") { | |
| in_attr = true; | |
| bracket_depth = 0; | |
| } | |
| if in_attr { | |
| crate_attrs.push(line.to_owned()); | |
| for ch in line.chars() { | |
| match ch { | |
| '[' => bracket_depth += 1, | |
| ']' => bracket_depth -= 1, | |
| _ => {} | |
| } | |
| } | |
| if bracket_depth <= 0 { | |
| in_attr = false; | |
| bracket_depth = 0; | |
| } | |
| } else { | |
| mod_lines.push(line.to_owned()); | |
| } | |
| } | |
| (crate_attrs, mod_lines) | |
| } | |
| fn generate_miri_fuzz_harness_with_token( | |
| cases: &[FuzzExecCase], | |
| token: Option<&str>, | |
| ) -> Result<String, String> { | |
| let run_prefix = miri_marker_prefix(MIRI_RUN_PREFIX, token); | |
| let case_prefix = miri_marker_prefix(MIRI_BATCH_CASE_PREFIX, token); | |
| let ret_prefix = miri_ret_prefix_for_token(token); | |
| let mut out = | |
| String::from("extern crate bridge;\n\nfn run_one(selector: &str, batch_mode: bool) {\n"); | |
| out.push_str(" use std::io::Write;\n"); | |
| out.push_str(" match selector {\n"); | |
| for (idx, case) in cases.iter().enumerate() { | |
| let ret_ty = rust_ret_type(&case.ret_shape)?; | |
| let payload_expr = rust_print_ret_payload_expr(&case.ret_shape, "ret")?; | |
| let _ = writeln!(out, " {:?} => {{", case.case_id); | |
| let _ = writeln!( | |
| out, | |
| " println!(\"{run_prefix}{}:{}\");", | |
| case.case_id, case.fn_name | |
| ); | |
| out.push_str(" let _ = std::io::stdout().flush();\n"); | |
| out.push_str(" if !batch_mode {\n"); | |
| let _ = writeln!( | |
| out, | |
| " match std::panic::catch_unwind(std::panic::AssertUnwindSafe(bridge::call_fuzz_case_{idx})) {{\n\ | |
| \x20 Ok(ret) => {{\n\ | |
| \x20 let ret: {ret_ty} = ret;\n\ | |
| \x20 let payload = {payload_expr};\n\ | |
| \x20 println!(\"{case_prefix}{}:{{payload}}\");\n\ | |
| \x20 println!(\"{ret_prefix}{{payload}}\");\n\ | |
| \x20 }}\n\ | |
| \x20 Err(_) => println!(\"{ret_prefix}PANICKED\"),\n\ | |
| \x20 }}", | |
| case.case_id | |
| ); | |
| out.push_str(" } else {\n"); | |
| let _ = | |
| writeln!(out, " let ret: {ret_ty} = bridge::call_fuzz_case_{idx}();"); | |
| let _ = writeln!(out, " let payload = {payload_expr};"); | |
| let _ = writeln!( | |
| out, | |
| " println!(\"{case_prefix}{}:{{payload}}\");", | |
| case.case_id | |
| ); | |
| out.push_str(" }\n"); | |
| out.push_str(" let _ = std::io::stdout().flush();\n"); | |
| out.push_str(" }\n"); | |
| } | |
| out.push_str(" other => panic!(\"unknown differential fuzz selector: {other}\"),\n"); | |
| out.push_str(" }\n}\n\nfn main() {\n"); | |
| out.push_str(" let args: Vec<String> = std::env::args().skip(1).collect();\n"); | |
| out.push_str(" if args.first().map(String::as_str) == Some(\"__BATCH__\") {\n"); | |
| out.push_str(" for sel in &args[1..] {\n"); | |
| out.push_str(" run_one(sel, true);\n"); | |
| out.push_str(" }\n"); | |
| out.push_str(" } else if let Some(sel) = args.first() {\n"); | |
| out.push_str(" run_one(sel, false);\n"); | |
| out.push_str(" } else {\n"); | |
| out.push_str(" panic!(\"missing case selector\");\n"); | |
| out.push_str(" }\n}\n"); | |
| Ok(out) | |
| } | |
| fn tool_error_map( | |
| case_pairs: &[(String, String)], | |
| detail: &str, | |
| ) -> BTreeMap<String, (ObservedOutcome, Option<String>)> { | |
| case_pairs | |
| .iter() | |
| .map(|(id, _)| { | |
| (id.clone(), (ObservedOutcome::ToolError { detail: detail.to_owned() }, None)) | |
| }) | |
| .collect() | |
| } | |
| fn add_miri_crate_args(mut inv: Invocation, miri_deps: Option<(&Path, &Path)>) -> Invocation { | |
| if let Some((bridge_rlib, corpus_dir)) = miri_deps { | |
| let bridge_dir = bridge_rlib.parent().unwrap_or_else(|| Path::new("/")); | |
| inv = inv | |
| .arg("--crate-name") | |
| .arg("harness") | |
| .arg("--extern") | |
| .arg(format!("bridge={}", bridge_rlib.display())) | |
| .arg("-L") | |
| .arg(bridge_dir) | |
| .arg("-L") | |
| .arg(corpus_dir); | |
| } | |
| inv | |
| } | |
| #[expect(clippy::too_many_arguments)] | |
| fn run_miri_chunk_with_bisection( | |
| miri_bin: &Path, | |
| rustc_bin: Option<&Path>, | |
| miri_sysroot: &Path, | |
| child_env: MiriChildEnv<'_>, | |
| harness_path: &Path, | |
| miri_deps: Option<(&Path, &Path)>, | |
| case_pairs: &[(String, String)], | |
| prog_items: Option<&[(&GenProgram, &FuzzExecCase)]>, | |
| harness_is_exact_subset: bool, | |
| expected_token: Option<&str>, | |
| deadline: Option<Instant>, | |
| ) -> BTreeMap<String, (ObservedOutcome, Option<String>)> { | |
| if case_pairs.is_empty() { | |
| return BTreeMap::new(); | |
| } | |
| if case_pairs.len() == 1 { | |
| let mut out = BTreeMap::new(); | |
| let standalone = prog_items.and_then(|ps| (!harness_is_exact_subset).then_some(ps[0])); | |
| out.insert( | |
| case_pairs[0].0.clone(), | |
| run_single_miri_fuzz_with_fallback( | |
| miri_bin, | |
| rustc_bin, | |
| miri_sysroot, | |
| child_env, | |
| harness_path, | |
| miri_deps, | |
| (&case_pairs[0].0, &case_pairs[0].1), | |
| standalone, | |
| expected_token, | |
| deadline, | |
| ), | |
| ); | |
| return out; | |
| } | |
| let inv = Invocation::new( | |
| miri_bin, | |
| &["--edition=2024", "--target", PINNED_MIRI_TARGET, "--error-format=json"], | |
| ) | |
| .arg("--sysroot") | |
| .arg(miri_sysroot) | |
| .arg("-C") | |
| .arg("opt-level=0") | |
| .arg("-C") | |
| .arg("debug-assertions=no") | |
| .arg("-C") | |
| .arg("overflow-checks=no") | |
| .arg("-Zmiri-tree-borrows") | |
| .arg("-Zmiri-seed=0"); | |
| let mut inv = add_miri_crate_args(inv, miri_deps) | |
| .arg(harness_path) | |
| .arg("--") | |
| .arg("__BATCH__") | |
| .env("LD_LIBRARY_PATH", child_env.ld_path) | |
| .env("PATH", child_env.path_env); | |
| for (id, _) in case_pairs { | |
| inv = inv.arg(id); | |
| } | |
| if let Some(td) = child_env.tmpdir { | |
| inv = inv.env("TMPDIR", td); | |
| } | |
| let work_dir = harness_path.parent().unwrap_or_else(|| Path::new("/")); | |
| let batch_timeout = match effective_timeout_duration(240, deadline) { | |
| Ok(t) => t, | |
| Err(detail) => return tool_error_map(case_pairs, &detail), | |
| }; | |
| match run_supervised_in_tmp(&inv, work_dir, batch_timeout, child_env.tmpdir, "miri batch") { | |
| Ok(proc_out) => { | |
| if matches!(proc_out.termination, Termination::Exited(s) if s.success()) { | |
| let stdout = String::from_utf8_lossy(&proc_out.stdout); | |
| if let Some(parsed) = | |
| parse_miri_batch_stdout_with_token(&stdout, case_pairs, expected_token) | |
| { | |
| return parsed; | |
| } | |
| } | |
| let stderr = String::from_utf8_lossy(&proc_out.stderr); | |
| match classify_miri_batch_failure(&proc_out.termination, &stderr) { | |
| Some(MiriBatchFailure::Global(detail)) => { | |
| return tool_error_map(case_pairs, &detail); | |
| } | |
| Some(MiriBatchFailure::CompileDiagnostic(detail)) => { | |
| if let (Some(items), Some(r_bin)) = (prog_items, rustc_bin) | |
| && items.len() > 1 | |
| { | |
| let mid = items.len() / 2; | |
| let mut combined = run_miri_compile_bisect_slice( | |
| miri_bin, | |
| r_bin, | |
| miri_sysroot, | |
| child_env, | |
| &items[..mid], | |
| deadline, | |
| ); | |
| combined.extend(run_miri_compile_bisect_slice( | |
| miri_bin, | |
| r_bin, | |
| miri_sysroot, | |
| child_env, | |
| &items[mid..], | |
| deadline, | |
| )); | |
| return combined; | |
| } | |
| return tool_error_map(case_pairs, &detail); | |
| } | |
| None => {} | |
| } | |
| } | |
| Err(err) => { | |
| let detail = format!("Miri batch supervisor error: {err}"); | |
| return tool_error_map(case_pairs, &detail); | |
| } | |
| } | |
| // Runtime-local faults (UB, panic, abort, unsupported, or partial output) | |
| // bisect down on the already-compiling shared harness. | |
| let mid = case_pairs.len() / 2; | |
| let left_progs = prog_items.map(|ps| &ps[..mid]); | |
| let right_progs = prog_items.map(|ps| &ps[mid..]); | |
| let mut combined = run_miri_chunk_with_bisection( | |
| miri_bin, | |
| rustc_bin, | |
| miri_sysroot, | |
| child_env, | |
| harness_path, | |
| miri_deps, | |
| &case_pairs[..mid], | |
| left_progs, | |
| false, | |
| expected_token, | |
| deadline, | |
| ); | |
| combined.extend(run_miri_chunk_with_bisection( | |
| miri_bin, | |
| rustc_bin, | |
| miri_sysroot, | |
| child_env, | |
| harness_path, | |
| miri_deps, | |
| &case_pairs[mid..], | |
| right_progs, | |
| false, | |
| expected_token, | |
| deadline, | |
| )); | |
| combined | |
| } | |
| fn run_miri_compile_bisect_slice( | |
| miri_bin: &Path, | |
| rustc_bin: &Path, | |
| miri_sysroot: &Path, | |
| child_env: MiriChildEnv<'_>, | |
| items: &[(&GenProgram, &FuzzExecCase)], | |
| deadline: Option<Instant>, | |
| ) -> BTreeMap<String, (ObservedOutcome, Option<String>)> { | |
| if items.is_empty() { | |
| return BTreeMap::new(); | |
| } | |
| let sub_pairs: Vec<(String, String)> = | |
| items.iter().map(|(_, c)| (c.case_id.clone(), c.fn_name.clone())).collect(); | |
| let sub_progs: Vec<&GenProgram> = items.iter().map(|(p, _)| *p).collect(); | |
| let sub_cases: Vec<FuzzExecCase> = items.iter().map(|(_, c)| (*c).clone()).collect(); | |
| let sub_src = if sub_progs.len() == 1 { | |
| sub_progs[0].render_standalone() | |
| } else { | |
| render_batch_crate(&sub_progs) | |
| }; | |
| let work_dir = | |
| match crate::mir_eval_runner::build_temp_dir("anneal-miri-bisect-", child_env.tmpdir) { | |
| Ok(d) => d, | |
| Err(e) => return tool_error_map(&sub_pairs, &e), | |
| }; | |
| let bundle = match build_isolated_miri_fuzz_group( | |
| work_dir.path(), | |
| "slice", | |
| &sub_src, | |
| &sub_cases, | |
| rustc_bin, | |
| miri_sysroot, | |
| child_env, | |
| deadline, | |
| ) { | |
| Ok(b) => b, | |
| Err(MiriBatchFailure::Global(detail)) => return tool_error_map(&sub_pairs, &detail), | |
| Err(MiriBatchFailure::CompileDiagnostic(detail)) => { | |
| drop(work_dir); | |
| if items.len() > 1 { | |
| let mid = items.len() / 2; | |
| let mut combined = run_miri_compile_bisect_slice( | |
| miri_bin, | |
| rustc_bin, | |
| miri_sysroot, | |
| child_env, | |
| &items[..mid], | |
| deadline, | |
| ); | |
| combined.extend(run_miri_compile_bisect_slice( | |
| miri_bin, | |
| rustc_bin, | |
| miri_sysroot, | |
| child_env, | |
| &items[mid..], | |
| deadline, | |
| )); | |
| return combined; | |
| } | |
| return tool_error_map(&sub_pairs, &detail); | |
| } | |
| }; | |
| let slice_items: Vec<(&GenProgram, &FuzzExecCase)> = | |
| sub_progs.into_iter().zip(sub_cases.iter()).collect(); | |
| run_miri_chunk_with_bisection( | |
| miri_bin, | |
| Some(rustc_bin), | |
| miri_sysroot, | |
| child_env, | |
| &bundle.harness_path, | |
| Some((&bundle.bridge_rlib, &bundle.corpus_dir)), | |
| &sub_pairs, | |
| Some(&slice_items), | |
| true, | |
| Some(&bundle.token), | |
| deadline, | |
| ) | |
| } | |
| fn is_miri_global_stderr(stderr: &str) -> bool { | |
| if is_global_compiler_or_sysroot_stderr(stderr) { | |
| return true; | |
| } | |
| for line in stderr.lines() { | |
| let trimmed = line.trim(); | |
| if let Ok(val) = serde_json::from_str::<Value>(trimmed) | |
| && val.get("$message_type").and_then(Value::as_str) == Some("diagnostic") | |
| { | |
| if let Some(code) = val.get("code").and_then(|c| c.get("code")).and_then(Value::as_str) | |
| && code == "E0463" | |
| { | |
| return true; | |
| } | |
| if let Some(msg) = val.get("message").and_then(Value::as_str) | |
| && (msg.starts_with("internal compiler error:") | |
| || msg.contains("can't find crate for") | |
| || msg.contains("could not execute process")) | |
| { | |
| return true; | |
| } | |
| if let Some(rendered) = val.get("rendered").and_then(Value::as_str) | |
| && is_global_compiler_or_sysroot_stderr(rendered) | |
| { | |
| return true; | |
| } | |
| } | |
| } | |
| false | |
| } | |
| fn is_case_local_runtime_stderr(stderr: &str) -> bool { | |
| for line in stderr.lines() { | |
| let trimmed = line.trim(); | |
| if let Ok(val) = serde_json::from_str::<Value>(trimmed) | |
| && val.get("$message_type").and_then(Value::as_str) == Some("diagnostic") | |
| { | |
| if val.get("level").and_then(Value::as_str) == Some("error") | |
| && let Some(msg) = val.get("message").and_then(Value::as_str) | |
| && (msg.starts_with("Undefined Behavior:") | |
| || msg.starts_with("abnormal termination:") | |
| || msg.starts_with("unsupported operation:")) | |
| { | |
| return true; | |
| } | |
| continue; | |
| } | |
| } | |
| stderr.contains("error: Undefined Behavior:") | |
| || stderr.contains("error: abnormal termination:") | |
| || stderr.contains("error: unsupported operation:") | |
| || stderr.contains("panicked at ") | |
| } | |
| fn classify_miri_batch_failure( | |
| termination: &Termination, | |
| stderr: &str, | |
| ) -> Option<MiriBatchFailure> { | |
| let snippet = || stderr.lines().take(6).collect::<Vec<_>>().join(" | "); | |
| match termination { | |
| Termination::TimedOut(_) => Some(MiriBatchFailure::Global(format!( | |
| "Miri batch timed out ({}): {}", | |
| termination.describe(), | |
| snippet() | |
| ))), | |
| Termination::LaunchFailed(msg) => { | |
| Some(MiriBatchFailure::Global(format!("Miri batch launch failed: {msg}"))) | |
| } | |
| Termination::Exited(status) => { | |
| if is_miri_global_stderr(stderr) { | |
| return Some(MiriBatchFailure::Global(format!( | |
| "Miri batch compiler/sysroot failure ({}): {}", | |
| termination.describe(), | |
| snippet() | |
| ))); | |
| } | |
| if !status.success() && !is_case_local_runtime_stderr(stderr) { | |
| return Some(MiriBatchFailure::CompileDiagnostic(format!( | |
| "Miri batch compile failure ({}): {}", | |
| termination.describe(), | |
| snippet() | |
| ))); | |
| } | |
| None | |
| } | |
| } | |
| } | |
| fn parse_miri_batch_stdout_with_token( | |
| stdout: &str, | |
| case_pairs: &[(String, String)], | |
| expected_token: Option<&str>, | |
| ) -> Option<BTreeMap<String, (ObservedOutcome, Option<String>)>> { | |
| let run_pfx = miri_marker_prefix(MIRI_RUN_PREFIX, expected_token); | |
| let case_pfx = miri_marker_prefix(MIRI_BATCH_CASE_PREFIX, expected_token); | |
| let ret_pfx_tok = format!("{MIRI_RET_STEM}:"); | |
| let mut run_seen = BTreeMap::new(); | |
| let mut raw = BTreeMap::new(); | |
| for line in stdout.lines() { | |
| let trimmed = line.trim(); | |
| if let Some(rest) = trimmed.strip_prefix(&run_pfx) | |
| && let Some((id, fn_name)) = rest.split_once(':') | |
| { | |
| if run_seen.insert(id.to_owned(), fn_name.to_owned()).is_some() { | |
| return None; | |
| } | |
| } else if let Some(rest) = trimmed.strip_prefix(&case_pfx) | |
| && let Some((id, payload)) = rest.split_once(':') | |
| { | |
| let value = parse_miri_ret_line(payload).ok()?; | |
| if raw | |
| .insert(id.to_owned(), (ObservedOutcome::Returned { value }, payload.to_owned())) | |
| .is_some() | |
| { | |
| return None; | |
| } | |
| } else if expected_token.is_some() | |
| && (trimmed.starts_with(MIRI_RUN_PREFIX) | |
| || trimmed.starts_with(MIRI_BATCH_CASE_PREFIX) | |
| || trimmed.starts_with(MIRI_RET_PREFIX) | |
| || trimmed.starts_with(&ret_pfx_tok)) | |
| { | |
| return None; | |
| } | |
| } | |
| if raw.len() != case_pairs.len() || run_seen.len() != case_pairs.len() { | |
| return None; | |
| } | |
| let mut out = BTreeMap::new(); | |
| for (id, fn_name) in case_pairs { | |
| if run_seen.get(id).map(String::as_str) != Some(fn_name.as_str()) { | |
| return None; | |
| } | |
| let (outcome, payload) = raw.remove(id)?; | |
| let evidence = | |
| format!("{MIRI_RUN_PREFIX}{id}:{fn_name}|{MIRI_BATCH_CASE_PREFIX}{id}:{payload}"); | |
| out.insert(id.clone(), (outcome, Some(evidence))); | |
| } | |
| Some(out) | |
| } | |
| fn rust_arg_expr(val: &MirValue) -> Result<String, String> { | |
| match val { | |
| MirValue::Int { int_kind, bits } => Ok(int_kind.format_rust_literal(*bits)), | |
| MirValue::Bool { value } => Ok(value.to_string()), | |
| MirValue::Char { scalar } => { | |
| char::from_u32(*scalar).ok_or_else(|| format!("invalid Unicode scalar {scalar}"))?; | |
| Ok(format!("char::from_u32({scalar}u32).unwrap()")) | |
| } | |
| MirValue::Ordering { value } => Ok(value.to_rust_expr().to_owned()), | |
| MirValue::Unit => Ok("()".to_owned()), | |
| MirValue::Enum { enum_type, variant, .. } => { | |
| validate_rust_ident(enum_type, "enum name")?; | |
| validate_rust_ident(variant, "enum variant")?; | |
| Ok(format!("corpus::{enum_type}::{variant}")) | |
| } | |
| MirValue::OverflowPair { .. } => { | |
| Err("OverflowPair is not a supported Miri harness input type in Stage 1".to_owned()) | |
| } | |
| } | |
| } | |
| fn rust_ret_type(shape: &MirValue) -> Result<String, String> { | |
| match shape { | |
| MirValue::Int { int_kind, .. } => Ok(int_kind.rust_name().to_owned()), | |
| MirValue::Bool { .. } => Ok("bool".to_owned()), | |
| MirValue::Char { .. } => Ok("char".to_owned()), | |
| MirValue::Ordering { .. } => Ok("core::cmp::Ordering".to_owned()), | |
| MirValue::Unit => Ok("()".to_owned()), | |
| MirValue::OverflowPair { int_kind, .. } => Ok(format!("({}, bool)", int_kind.rust_name())), | |
| MirValue::Enum { .. } => Err("Enum expected_return is not supported in Stage 1".to_owned()), | |
| } | |
| } | |
| fn rust_print_ret_stmt(shape: &MirValue, var: &str, ret_prefix: &str) -> Result<String, String> { | |
| match shape { | |
| MirValue::Int { int_kind, .. } => { | |
| Ok(format!("println!(\"{ret_prefix}INT:{}:{{}}\", {var})", int_kind.rust_name())) | |
| } | |
| MirValue::Bool { .. } => Ok(format!("println!(\"{ret_prefix}BOOL:{{}}\", {var})")), | |
| MirValue::Char { .. } => Ok(format!("println!(\"{ret_prefix}CHAR:{{}}\", {var} as u32)")), | |
| MirValue::Ordering { .. } => Ok(format!( | |
| "println!(\"{ret_prefix}ORDERING:{{}}\", match {var} {{ \ | |
| core::cmp::Ordering::Less => \"less\", \ | |
| core::cmp::Ordering::Equal => \"equal\", \ | |
| core::cmp::Ordering::Greater => \"greater\" }})" | |
| )), | |
| MirValue::Unit => Ok(format!("let () = {var}; println!(\"{ret_prefix}UNIT\")")), | |
| MirValue::OverflowPair { int_kind, .. } => Ok(format!( | |
| "println!(\"{ret_prefix}OVF:{}:{{}}:{{}}\", {var}.0, {var}.1)", | |
| int_kind.rust_name() | |
| )), | |
| MirValue::Enum { .. } => Err("Enum expected_return is not supported in Stage 1".to_owned()), | |
| } | |
| } | |
| #[allow(clippy::too_many_arguments)] | |
| fn run_single_miri( | |
| miri_bin: &Path, | |
| miri_sysroot: &Path, | |
| child_env: MiriChildEnv<'_>, | |
| harness_path: &Path, | |
| bridge_rlib: &Path, | |
| corpus_dir: &Path, | |
| selector: &str, | |
| expected_token: Option<&str>, | |
| ) -> ObservedOutcome { | |
| run_single_miri_until( | |
| miri_bin, | |
| miri_sysroot, | |
| child_env, | |
| harness_path, | |
| Some((bridge_rlib, corpus_dir)), | |
| selector, | |
| expected_token, | |
| None, | |
| ) | |
| } | |
| #[expect(clippy::too_many_arguments)] | |
| fn invoke_single_miri_until( | |
| miri_bin: &Path, | |
| miri_sysroot: &Path, | |
| child_env: MiriChildEnv<'_>, | |
| harness_path: &Path, | |
| miri_deps: Option<(&Path, &Path)>, | |
| selector: &str, | |
| mute_target_io: bool, | |
| deadline: Option<Instant>, | |
| ) -> Result<(Option<i32>, String, String), ObservedOutcome> { | |
| let mut inv = Invocation::new( | |
| miri_bin, | |
| &["--edition=2024", "--target", PINNED_MIRI_TARGET, "--error-format=json"], | |
| ) | |
| .arg("--sysroot") | |
| .arg(miri_sysroot) | |
| .arg("-C") | |
| .arg("opt-level=0") | |
| .arg("-C") | |
| .arg("debug-assertions=no") | |
| .arg("-C") | |
| .arg("overflow-checks=no") | |
| .arg("-Zmiri-tree-borrows") | |
| .arg("-Zmiri-seed=0"); | |
| if mute_target_io { | |
| inv = inv.arg("-Zmiri-mute-stdout-stderr"); | |
| } | |
| let mut inv = add_miri_crate_args(inv, miri_deps) | |
| .arg(harness_path) | |
| .arg("--") | |
| .arg(selector) | |
| .env("LD_LIBRARY_PATH", child_env.ld_path) | |
| .env("PATH", child_env.path_env); | |
| if let Some(td) = child_env.tmpdir { | |
| inv = inv.env("TMPDIR", td); | |
| } | |
| let case_timeout = effective_timeout_duration(MIRI_CASE_TIMEOUT_SECS, deadline) | |
| .map_err(|detail| ObservedOutcome::ToolError { detail })?; | |
| let work_dir = harness_path.parent().unwrap_or_else(|| Path::new("/")); | |
| let out = run_supervised_in_tmp(&inv, work_dir, case_timeout, child_env.tmpdir, selector) | |
| .map_err(|detail| ObservedOutcome::ToolError { detail })?; | |
| let exit_code = match out.termination { | |
| Termination::Exited(status) => status.code(), | |
| Termination::TimedOut(status) => { | |
| return Err(ObservedOutcome::ToolError { | |
| detail: format!( | |
| "miri timed out after {:.3}s for {selector} ({status})", | |
| case_timeout.as_secs_f64() | |
| ), | |
| }); | |
| } | |
| Termination::LaunchFailed(err) => { | |
| return Err(ObservedOutcome::ToolError { | |
| detail: format!("spawn miri for {selector}: {err}"), | |
| }); | |
| } | |
| }; | |
| Ok(( | |
| exit_code, | |
| String::from_utf8_lossy(&out.stdout).into_owned(), | |
| String::from_utf8_lossy(&out.stderr).into_owned(), | |
| )) | |
| } | |
| fn invoke_single_miri_verified_until( | |
| miri_bin: &Path, | |
| miri_sysroot: &Path, | |
| child_env: MiriChildEnv<'_>, | |
| harness_path: &Path, | |
| miri_deps: Option<(&Path, &Path)>, | |
| selector: &str, | |
| deadline: Option<Instant>, | |
| ) -> Result<(Option<i32>, String, String), ObservedOutcome> { | |
| let (exit_code, stdout, stderr) = invoke_single_miri_until( | |
| miri_bin, | |
| miri_sysroot, | |
| child_env, | |
| harness_path, | |
| miri_deps, | |
| selector, | |
| false, | |
| deadline, | |
| )?; | |
| if exit_code == Some(0) { | |
| return Ok((exit_code, stdout, stderr)); | |
| } | |
| // Non-zero exits re-run with `-Zmiri-mute-stdout-stderr` so Miri's host | |
| // diagnostics arrive over a channel fixture code cannot write. | |
| let (muted_exit, _muted_stdout, muted_stderr) = invoke_single_miri_until( | |
| miri_bin, | |
| miri_sysroot, | |
| child_env, | |
| harness_path, | |
| miri_deps, | |
| selector, | |
| true, | |
| deadline, | |
| )?; | |
| if muted_exit == Some(0) { | |
| return Err(ObservedOutcome::ToolError { | |
| detail: format!( | |
| "Miri non-zero exit ({exit_code:?}) for {selector} did not reproduce under -Zmiri-mute-stdout-stderr" | |
| ), | |
| }); | |
| } | |
| Ok((muted_exit, stdout, muted_stderr)) | |
| } | |
| #[expect(clippy::too_many_arguments)] | |
| fn run_single_miri_until( | |
| miri_bin: &Path, | |
| miri_sysroot: &Path, | |
| child_env: MiriChildEnv<'_>, | |
| harness_path: &Path, | |
| miri_deps: Option<(&Path, &Path)>, | |
| selector: &str, | |
| expected_token: Option<&str>, | |
| deadline: Option<Instant>, | |
| ) -> ObservedOutcome { | |
| match invoke_single_miri_verified_until( | |
| miri_bin, | |
| miri_sysroot, | |
| child_env, | |
| harness_path, | |
| miri_deps, | |
| selector, | |
| deadline, | |
| ) { | |
| Ok((exit_code, stdout, stderr)) => { | |
| parse_miri_output_with_token(exit_code, &stdout, &stderr, expected_token) | |
| } | |
| Err(err_outcome) => err_outcome, | |
| } | |
| } | |
| #[expect(clippy::too_many_arguments)] | |
| fn run_single_miri_fuzz_with_fallback( | |
| miri_bin: &Path, | |
| rustc_bin: Option<&Path>, | |
| miri_sysroot: &Path, | |
| child_env: MiriChildEnv<'_>, | |
| harness_path: &Path, | |
| miri_deps: Option<(&Path, &Path)>, | |
| (case_id, fn_name): (&str, &str), | |
| standalone_item: Option<(&GenProgram, &FuzzExecCase)>, | |
| expected_token: Option<&str>, | |
| deadline: Option<Instant>, | |
| ) -> (ObservedOutcome, Option<String>) { | |
| let (exit_code, stdout, stderr) = match invoke_single_miri_verified_until( | |
| miri_bin, | |
| miri_sysroot, | |
| child_env, | |
| harness_path, | |
| miri_deps, | |
| case_id, | |
| deadline, | |
| ) { | |
| Ok(res) => res, | |
| Err(err_outcome) => return (err_outcome, None), | |
| }; | |
| let parsed = parse_miri_fuzz_single_output_with_token( | |
| exit_code, | |
| case_id, | |
| fn_name, | |
| &stdout, | |
| &stderr, | |
| expected_token, | |
| ); | |
| if matches!(&parsed.0, ObservedOutcome::ToolError { .. }) | |
| && let Some(item) = standalone_item | |
| && let Some(rustc_bin) = rustc_bin | |
| && exit_code.is_some_and(|c| c != 0) | |
| && !is_miri_global_stderr(&stderr) | |
| && !is_case_local_runtime_stderr(&stderr) | |
| { | |
| let mut isolated = run_miri_compile_bisect_slice( | |
| miri_bin, | |
| rustc_bin, | |
| miri_sysroot, | |
| child_env, | |
| &[item], | |
| deadline, | |
| ); | |
| if let Some(res) = isolated.remove(case_id) { | |
| return res; | |
| } | |
| } | |
| parsed | |
| } | |
| fn parse_miri_fuzz_single_output_with_token( | |
| exit_code: Option<i32>, | |
| case_id: &str, | |
| fn_name: &str, | |
| stdout: &str, | |
| stderr: &str, | |
| expected_token: Option<&str>, | |
| ) -> (ObservedOutcome, Option<String>) { | |
| let run_pfx = miri_marker_prefix(MIRI_RUN_PREFIX, expected_token); | |
| let case_pfx = miri_marker_prefix(MIRI_BATCH_CASE_PREFIX, expected_token); | |
| let run_marker = format!("{run_pfx}{case_id}:{fn_name}"); | |
| let case_prefix = format!("{case_pfx}{case_id}:"); | |
| let canonical_run = format!("{MIRI_RUN_PREFIX}{case_id}:{fn_name}"); | |
| let canonical_case_prefix = format!("{MIRI_BATCH_CASE_PREFIX}{case_id}:"); | |
| let mut run_count = 0usize; | |
| let mut matched_payload: Option<&str> = None; | |
| for line in stdout.lines() { | |
| let trimmed = line.trim(); | |
| if trimmed == run_marker { | |
| run_count += 1; | |
| if run_count > 1 { | |
| return ( | |
| ObservedOutcome::ToolError { | |
| detail: format!("Miri output contained duplicate `{run_marker}` marker"), | |
| }, | |
| None, | |
| ); | |
| } | |
| } else if let Some(payload) = trimmed.strip_prefix(&case_prefix) { | |
| if matched_payload.is_some() { | |
| return ( | |
| ObservedOutcome::ToolError { | |
| detail: format!("Miri output contained duplicate `{case_prefix}` payload"), | |
| }, | |
| None, | |
| ); | |
| } | |
| matched_payload = Some(payload); | |
| } else if expected_token.is_some() | |
| && (trimmed.starts_with(MIRI_RUN_PREFIX) || trimmed.starts_with(MIRI_BATCH_CASE_PREFIX)) | |
| { | |
| return ( | |
| ObservedOutcome::ToolError { | |
| detail: format!( | |
| "Miri output contained unauthenticated case/run marker: {trimmed:?}" | |
| ), | |
| }, | |
| None, | |
| ); | |
| } | |
| } | |
| let has_run = run_count == 1; | |
| let outcome = parse_miri_output_with_token(exit_code, stdout, stderr, expected_token); | |
| match outcome { | |
| ObservedOutcome::Returned { value } => { | |
| if !has_run { | |
| return ( | |
| ObservedOutcome::ToolError { | |
| detail: format!("Miri output missing case marker `{run_marker}`"), | |
| }, | |
| None, | |
| ); | |
| } | |
| let Some(payload) = matched_payload else { | |
| return ( | |
| ObservedOutcome::ToolError { | |
| detail: format!("Miri output missing `{case_prefix}` payload"), | |
| }, | |
| None, | |
| ); | |
| }; | |
| ( | |
| ObservedOutcome::Returned { value }, | |
| Some(format!("{canonical_run}|{canonical_case_prefix}{payload}")), | |
| ) | |
| } | |
| ObservedOutcome::UndefinedBehavior { ref detail } => { | |
| if has_run { | |
| let ev = format!("{canonical_run}|UB|{detail}"); | |
| (outcome, Some(ev)) | |
| } else { | |
| ( | |
| ObservedOutcome::ToolError { | |
| detail: format!("Miri UB lacked `{run_marker}`: {detail}"), | |
| }, | |
| None, | |
| ) | |
| } | |
| } | |
| ObservedOutcome::AbnormalAbort { ref detail } => { | |
| if has_run { | |
| let ev = format!("{canonical_run}|ABORT|{detail}"); | |
| (outcome, Some(ev)) | |
| } else { | |
| ( | |
| ObservedOutcome::ToolError { | |
| detail: format!("Miri abort lacked `{run_marker}`: {detail}"), | |
| }, | |
| None, | |
| ) | |
| } | |
| } | |
| ObservedOutcome::Panic { ref detail } => { | |
| if has_run { | |
| let ev = format!("{canonical_run}|PANIC|{detail}"); | |
| (outcome, Some(ev)) | |
| } else { | |
| ( | |
| ObservedOutcome::ToolError { | |
| detail: format!("Miri panic lacked `{run_marker}`: {detail}"), | |
| }, | |
| None, | |
| ) | |
| } | |
| } | |
| ObservedOutcome::Unsupported { ref detail } => { | |
| if has_run { | |
| let ev = format!("{canonical_run}|UNSUPPORTED|{detail}"); | |
| (outcome, Some(ev)) | |
| } else { | |
| ( | |
| ObservedOutcome::ToolError { | |
| detail: format!("Miri unsupported lacked `{run_marker}`: {detail}"), | |
| }, | |
| None, | |
| ) | |
| } | |
| } | |
| other => (other, None), | |
| } | |
| } | |
| #[cfg(test)] | |
| mod tests; |