No public description PiperOrigin-RevId: 1021880911
diff --git a/centipede/engine_abi.h b/centipede/engine_abi.h index cdb1f84..1fce55a 100644 --- a/centipede/engine_abi.h +++ b/centipede/engine_abi.h
@@ -28,6 +28,10 @@ // Opaque handles for in-memory input objects used by the test, which // may be serialized/deserialized by the engine. +// +// The engine never inspects or fabricates handle values. It only passes back +// handles that the adapter emitted through a `FuzzTestInputSink` and that the +// engine has not yet passed to `FuzzTestAdapter::FreeInput`. typedef uintptr_t FuzzTestInputHandle; typedef struct { @@ -141,6 +145,21 @@ const FuzzTestCoverageDomain* domain); } FuzzTestCoverageDomainRegistry; +// Test adapter callbacks. +// +// The engine upholds the following when it invokes the callbacks of a +// `FuzzTestAdapter` and of its `FuzzTestAdapterManager`: +// +// - Callbacks are invoked sequentially, on the thread that called into the +// engine with the manager (e.g. `FuzzTestWorkerMaybeRun`). A callback is +// never invoked while another one is running. +// - Pointer arguments (sinks, views and registries) are non-null and remain +// valid until the callback returns. Calling a method of a sink or registry +// passed to a callback never invokes an adapter or manager callback. +// - Before `FreeCtx` is called, every input emitted by the adapter has been +// passed to `FreeInput` exactly once. An input is not used after that. +// - A callback is invoked with the `ctx` of the struct that holds it. Once +// `FreeCtx` is called, no callback is invoked with that `ctx` again. typedef struct FuzzTestAdapterCtx FuzzTestAdapterCtx; typedef struct FuzzTestAdapter { FuzzTestAdapterCtx* ctx; @@ -169,7 +188,7 @@ int shrink, const FuzzTestInputSink* sink); // [Optional] Performs cross-over mutation using `origin` and `other`, and - // emits the mutant using `sink`. + // emits the mutant using `sink`. `origin` and `other` may be the same input. // // It should not change the content/metadata of `origin` or `other`. void (*CrossOver)(FuzzTestAdapterCtx* ctx, FuzzTestInputHandle origin,
diff --git a/centipede/engine_controller_abi.h b/centipede/engine_controller_abi.h index 74b2714..181d92b 100644 --- a/centipede/engine_controller_abi.h +++ b/centipede/engine_controller_abi.h
@@ -36,6 +36,9 @@ } FuzzTestBytesViews; // Run the FuzzTest controller with `flags` and `manager`. +// +// `manager` and `flags` are only used during the call: the engine does not +// retain them after this function returns. FuzzTestControllerStatus FuzzTestControllerRun( const FuzzTestAdapterManager* manager, const FuzzTestBytesViews* flags);
diff --git a/centipede/engine_worker_abi.h b/centipede/engine_worker_abi.h index 6d79441..079122c 100644 --- a/centipede/engine_worker_abi.h +++ b/centipede/engine_worker_abi.h
@@ -40,6 +40,9 @@ } FuzzTestWorkerStatus; // Try to run as a FuzzTest worker with `manager` if needed. +// +// `manager` and its context are only used during the call: the engine does not +// retain them after this function returns. FuzzTestWorkerStatus FuzzTestWorkerMaybeRun( const FuzzTestAdapterManager* manager);
diff --git a/rust/engine/src/engine_ffi.rs b/rust/engine/src/engine_ffi.rs index 276b3e1..a510857 100644 --- a/rust/engine/src/engine_ffi.rs +++ b/rust/engine/src/engine_ffi.rs
@@ -24,8 +24,12 @@ use core::marker::PhantomPinned; use core::ptr; -// Opaque handles for in-memory input objects used by the test, which -// may be serialized/deserialized by the engine. +/// Opaque handles for in-memory input objects used by the test, which +/// may be serialized/deserialized by the engine. +/// +/// The engine never inspects or fabricates handle values. It only passes back +/// handles that the adapter emitted through a `FuzzTestInputSink` and that the +/// engine has not yet passed to `FuzzTestAdapter::FreeInput`. #[repr(transparent)] pub struct FuzzTestInputHandle(pub usize); @@ -192,12 +196,10 @@ /// Constants for the layout of the coverage feature as a 64-bit unsigned /// integer: /// -/// - Bits 63..59: 5-bit domain ID of the feature. Each domain is a -/// logically independent feature namespace registered in -/// `FuzzTestAdapter::SetUpCoverageDomains`. +/// - Bits 63..59: 5-bit domain ID of the feature. Each domain is a logically independent feature +/// namespace registered in `FuzzTestAdapter::SetUpCoverageDomains`. /// - Bits 58..32: 27-bit feature ID within the domain. /// - Bits 31..0: 32-bit counter value of the feature. -/// pub struct FuzzTestCoverageFeatureLayout; impl FuzzTestCoverageFeatureLayout { @@ -276,6 +278,21 @@ _not_unpin: PhantomPinned, } +/// Test adapter callbacks. +/// +/// The engine upholds the following when it invokes the callbacks of a +/// `FuzzTestAdapter` and of its `FuzzTestAdapterManager`: +/// +/// - Callbacks are invoked sequentially, on the thread that called into the engine with the +/// manager (e.g. `FuzzTestWorkerMaybeRun`). A callback is never invoked while another one is +/// running. +/// - Pointer arguments (sinks, views and registries) are non-null and remain valid until the +/// callback returns. Calling a method of a sink or registry passed to a callback never invokes +/// an adapter or manager callback. +/// - Before `FreeCtx` is called, every input emitted by the adapter has been passed to +/// `FreeInput` exactly once. An input is not used after that. +/// - A callback is invoked with the `ctx` of the struct that holds it. Once `FreeCtx` is called, +/// no callback is invoked with that `ctx` again. #[repr(C)] pub struct FuzzTestAdapter { pub ctx: *mut FuzzTestAdapterCtx, @@ -314,7 +331,7 @@ >, /// [Optional] Performs cross-over mutation using `origin` and `other`, and - /// emits the mutant using `sink`. + /// emits the mutant using `sink`. `origin` and `other` may be the same input. /// /// It should not change the content/metadata of `origin` or `other`. pub cross_over: Option< @@ -438,6 +455,9 @@ #[allow(improper_ctypes)] unsafe extern "C" { /// Try to run as a FuzzTest worker with `manager` if needed. + /// + /// `manager` and its context are only used during the call: the engine does not + /// retain them after this function returns. pub fn FuzzTestWorkerMaybeRun(manager: *const FuzzTestAdapterManager) -> FuzzTestWorkerStatus; /// Returns whether the current process is running as a FuzzTest worker - @@ -445,6 +465,9 @@ pub fn FuzzTestWorkerIsRequired() -> c_int; /// Run the FuzzTest controller with `flags` and `manager`. + /// + /// `manager` and `flags` are only used during the call: the engine does not + /// retain them after this function returns. pub fn FuzzTestControllerRun( manager: *const FuzzTestAdapterManager, flags: *const FuzzTestBytesViews,
diff --git a/rust/src/worker.rs b/rust/src/worker.rs index fcfbd6a..04acf9f 100644 --- a/rust/src/worker.rs +++ b/rust/src/worker.rs
@@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use super::domains::GenericCorpusValue; +use super::domains::{GenericCorpusValue, GenericDomain}; use super::internal::{BoxedFuzzTest, FuzzTest}; use super::options::{self, CentipedeArgs, ExecutionAction}; use ::engine::engine_ffi; @@ -22,12 +22,10 @@ use spin::Mutex; use std::env; use std::ffi::c_int; -use std::ffi::CString; use std::fs; use std::path::Path; use std::process; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::LazyLock; use std::time::Duration; use std::time::Instant; @@ -92,7 +90,6 @@ /// - it could not get the lock on DiagnosticSink. /// - it got the lock but the global DiagnosticSink was not set. /// - diagnostic sink was set but the test was not executing. -#[allow(dead_code)] pub(crate) fn try_emit_finding(description: &str, signature: &str) -> bool { let Some(diagnostic_guard) = DIAGNOSTIC_SINK.try_lock() else { return false; @@ -110,9 +107,9 @@ true } -// We double-box the input because `GenericCorpusValue` is a fat pointer (`Box<dyn Any>`), +// We double-box the input because `GenericCorpusValue` is a fat pointer (`Box<dyn CloneAny>`), // which cannot be directly represented as a single `usize` in `FuzzTestInputHandle` for FFI. -// By boxing it again, we get a thin pointer (`Box<Box<dyn Any>>`) that can be safely cast +// By boxing it again, we get a thin pointer (`Box<Box<dyn CloneAny>>`) that can be safely cast // to `usize`. // The memory is reclaimed when the engine calls `free_input`, which reconstructs the outer // box using `Box::from_raw` and drops it, thereby dropping the inner box and the value. @@ -143,54 +140,42 @@ } } +/// Drives one [`FuzzTest`] instance for the fuzzing engine. pub struct RustFuzzTestAdapter { fuzz_test: BoxedFuzzTest, } impl RustFuzzTestAdapter { + /// Runs `f` with the domains of the fuzz test locked. + /// + /// The lock is released before this returns, so callers never hold it while they call back + /// into the engine. + fn with_domains<R>(&self, f: impl FnOnce(&mut dyn GenericDomain) -> R) -> R { + let domains = self.fuzz_test.domains(); + // The lock is only poisoned if a `Domain` method panicked while holding it. In worker + // mode that panic already aborted the process, because it unwound into an `extern "C"` + // callback. + let mut guard = domains.lock().expect("a Domain method panicked while holding the lock"); + f(&mut *guard) + } + pub fn set_up_coverage_domains(&self, registry: &mut CoverageDomainRegistry) { registry.set_up_sancov_domains(); } - pub fn get_preset_seed_inputs(&self, _sink: &mut InputSink) { - // TODO(the-shank): implement this once the macro has support for specifying preset seed - // inputs - } - pub fn get_random_seed_input(&self, sink: &mut InputSink) { - let domains = self.fuzz_test.domains(); - let mut domains_guard = domains.lock().expect("Failed to lock domains"); - match domains_guard.init(&mut rand::rng()) { - Ok(val) => { - sink.emit(pack_input(val)); - } - Err(e) => { - emit_error(&format!("Failed to initialize random seed: {:?}", e)); - } + match self.with_domains(|domains| domains.init(&mut rand::rng())) { + Ok(value) => sink.emit(pack_input(value)), + Err(e) => emit_error(&format!("Failed to initialize random seed: {:?}", e)), } } pub fn mutate(&self, origin: &GenericCorpusValue, shrink: bool, sink: &mut InputSink) { let mut mutant = origin.clone(); - let domains = self.fuzz_test.domains(); - let mut domains_guard = domains.lock().expect("Failed to lock domains"); - - if let Err(e) = domains_guard.mutate(&mut mutant, &mut rand::rng(), shrink) { - emit_error(&format!("Failed to mutate: {:?}", e)); - return; + match self.with_domains(|domains| domains.mutate(&mut mutant, &mut rand::rng(), shrink)) { + Ok(()) => sink.emit(pack_input(mutant)), + Err(e) => emit_error(&format!("Failed to mutate: {:?}", e)), } - - sink.emit(pack_input(mutant)); - } - - pub fn cross_over( - &self, - origin: &GenericCorpusValue, - _other: &GenericCorpusValue, - sink: &mut InputSink, - ) { - // TODO(the-shank): implement cross_over. Currently we are just calling mutate. - self.mutate(origin, false, sink); } pub fn execute(&self, input: &GenericCorpusValue, sink: &mut FeedbackSink) { @@ -218,39 +203,19 @@ } pub fn serialize_input_content(&self, input: &GenericCorpusValue, sink: &mut BytesSink) { - let domains = self.fuzz_test.domains(); - let domains_guard = domains.lock().expect("Failed to lock domains"); - match domains_guard.serialize_corpus(input) { - Ok(serialized) => { - sink.emit(&serialized); - } - Err(e) => { - emit_error(&format!("Failed to serialize input: {:?}", e)); - } + match self.with_domains(|domains| domains.serialize_corpus(input)) { + Ok(serialized) => sink.emit(&serialized), + Err(e) => emit_error(&format!("Failed to serialize input: {:?}", e)), } } pub fn deserialize_input_content(&self, content: &[u8], sink: &mut InputSink) { - let domains = self.fuzz_test.domains(); - let domains_guard = domains.lock().expect("Failed to lock domains"); - match domains_guard.parse_corpus(content) { - Ok(val) => { - sink.emit(pack_input(val)); - } - Err(e) => { - emit_error(&format!("Failed to deserialize input: {:?}", e)); - } + match self.with_domains(|domains| domains.parse_corpus(content)) { + Ok(value) => sink.emit(pack_input(value)), + Err(e) => emit_error(&format!("Failed to deserialize input: {:?}", e)), } } - pub fn serialize_input_metadata(&self, _input: &GenericCorpusValue, _sink: &mut BytesSink) { - // TODO(the-shank): to be implemented - } - - pub fn update_input_metadata(&self, _metadata: &[u8], _input: &mut GenericCorpusValue) { - // TODO(the-shank): to be implemented - } - pub fn free_input(&self, input: engine_ffi::FuzzTestInputHandle) { if input.0 != 0 { // SAFETY: The engine guarantees `input` was created by @@ -263,23 +228,22 @@ } } +/// Identifies a registered fuzz test and constructs its [`FuzzTest`] instances. pub struct RustFuzzTestAdapterManager { + /// Rust module-qualified name of the fuzz test. pub test_name: &'static str, + /// Factory that constructs a fresh [`BoxedFuzzTest`] for the test. pub fuzz_test_factory: fn() -> BoxedFuzzTest, } impl RustFuzzTestAdapterManager { pub fn get_binary_id(&self, sink: &mut BytesSink) { - static ARGV0: LazyLock<CString> = LazyLock::new(|| { - CString::new( - Path::new(&env::args().next().unwrap()) - .file_name() - .and_then(|f| f.to_str()) - .unwrap_or(""), - ) - .expect("argv[0] should not contain null bytes") - }); - sink.emit(ARGV0.as_bytes()); + // The engine asks for the binary ID at most once per process, so nothing is cached. A + // missing `argv[0]` yields an empty ID and a non-UTF-8 one is emitted as is: this runs + // inside an `extern "C"` callback and must not panic. + let argv0 = env::args_os().next().unwrap_or_default(); + let file_name = Path::new(&argv0).file_name().unwrap_or_default(); + sink.emit(file_name.as_encoded_bytes()); } // Replaces "::" with "." to avoid parsing issues in Centipede. Centipede uses ":" as a @@ -291,10 +255,10 @@ } pub fn construct_adapter(&self) -> RustFuzzTestAdapter { - let fuzz_test = (self.fuzz_test_factory)(); - RustFuzzTestAdapter { fuzz_test } + RustFuzzTestAdapter { fuzz_test: self.construct_fuzz_test() } } + /// Constructs a new [`BoxedFuzzTest`] instance for this test. pub fn construct_fuzz_test(&self) -> BoxedFuzzTest { (self.fuzz_test_factory)() } @@ -372,15 +336,18 @@ *adapter_out = engine_ffi::FuzzTestAdapter { ctx: Box::into_raw(boxed_adapter) as *mut engine_ffi::FuzzTestAdapterCtx, set_up_coverage_domains: Some(set_up_coverage_domains_callback), - get_preset_seed_inputs: Some(get_preset_seed_inputs_callback), + // The optional callbacks that have no implementation yet stay null. The engine then + // uses its own fallback: no preset seeds, `mutate` instead of `cross_over`, and no + // input metadata. + get_preset_seed_inputs: None, get_random_seed_input: Some(get_random_seed_input_callback), mutate: Some(mutate_callback), - cross_over: Some(cross_over_callback), + cross_over: None, execute: Some(execute_callback), serialize_input_content: Some(serialize_input_content_callback), deserialize_input_content: Some(deserialize_input_content_callback), - serialize_input_metadata: Some(serialize_input_metadata_callback), - update_input_metadata: Some(update_input_metadata_callback), + serialize_input_metadata: None, + update_input_metadata: None, free_input: Some(free_input_callback), free_ctx: Some(free_ctx_callback), }; @@ -410,23 +377,6 @@ /// The caller must ensure that: /// * `ctx` is a valid pointer to the `RustFuzzTestAdapter` created by `construct_adapter_callback`. /// * `sink` is a valid pointer to `FuzzTestInputSink`. -pub unsafe extern "C" fn get_preset_seed_inputs_callback( - ctx: *mut engine_ffi::FuzzTestAdapterCtx, - sink: *const engine_ffi::FuzzTestInputSink, -) { - // SAFETY: The engine guarantees `ctx` is a valid pointer to the `RustFuzzTestAdapter` - // created by `construct_adapter_callback`. - let adapter = unsafe { &*(ctx as *const RustFuzzTestAdapter) }; - // SAFETY: The engine guarantees `sink` is a valid pointer to `FuzzTestInputSink`. - let mut safe_sink = unsafe { InputSink::from_raw(sink) }; - adapter.get_preset_seed_inputs(&mut safe_sink); -} - -/// # Safety -/// -/// The caller must ensure that: -/// * `ctx` is a valid pointer to the `RustFuzzTestAdapter` created by `construct_adapter_callback`. -/// * `sink` is a valid pointer to `FuzzTestInputSink`. pub unsafe extern "C" fn get_random_seed_input_callback( ctx: *mut engine_ffi::FuzzTestAdapterCtx, sink: *const engine_ffi::FuzzTestInputSink, @@ -467,35 +417,6 @@ /// /// The caller must ensure that: /// * `ctx` is a valid pointer to the `RustFuzzTestAdapter` created by `construct_adapter_callback`. -/// * `origin` is a valid `FuzzTestInputHandle` pointing to a heap-allocated `GenericCorpusValue` -/// managed by the framework. -/// * `other` is a valid `FuzzTestInputHandle` pointing to a heap-allocated `GenericCorpusValue` -/// managed by the framework. -/// * `sink` is a valid pointer to `FuzzTestInputSink`. -pub unsafe extern "C" fn cross_over_callback( - ctx: *mut engine_ffi::FuzzTestAdapterCtx, - origin: engine_ffi::FuzzTestInputHandle, - other: engine_ffi::FuzzTestInputHandle, - sink: *const engine_ffi::FuzzTestInputSink, -) { - // SAFETY: The engine guarantees `ctx` is a valid pointer to the `RustFuzzTestAdapter` - // created by `construct_adapter_callback`. - let adapter = unsafe { &*(ctx as *const RustFuzzTestAdapter) }; - // SAFETY: The engine guarantees `origin` is a valid `FuzzTestInputHandle` pointing to - // a heap-allocated `GenericCorpusValue` managed by the framework. - let origin_ref = unsafe { &*(origin.0 as *const GenericCorpusValue) }; - // SAFETY: The engine guarantees `other` is a valid `FuzzTestInputHandle` pointing to - // a heap-allocated `GenericCorpusValue` managed by the framework. - let other_ref = unsafe { &*(other.0 as *const GenericCorpusValue) }; - // SAFETY: The engine guarantees `sink` is a valid pointer to `FuzzTestInputSink`. - let mut safe_sink = unsafe { InputSink::from_raw(sink) }; - adapter.cross_over(origin_ref, other_ref, &mut safe_sink); -} - -/// # Safety -/// -/// The caller must ensure that: -/// * `ctx` is a valid pointer to the `RustFuzzTestAdapter` created by `construct_adapter_callback`. /// * `input` is a valid `FuzzTestInputHandle` pointing to a heap-allocated `GenericCorpusValue` /// managed by the framework. /// * `sink` is a valid pointer to `FuzzTestFeedbackSink`. @@ -566,55 +487,6 @@ /// The caller must ensure that: /// * `ctx` is a valid pointer to the `RustFuzzTestAdapter` created by `construct_adapter_callback`. /// * `input` is a valid `FuzzTestInputHandle` pointing to a heap-allocated `GenericCorpusValue` -/// managed by the framework. -/// * `sink` is a valid pointer to `FuzzTestBytesSink`. -pub unsafe extern "C" fn serialize_input_metadata_callback( - ctx: *mut engine_ffi::FuzzTestAdapterCtx, - input: engine_ffi::FuzzTestInputHandle, - sink: *const engine_ffi::FuzzTestBytesSink, -) { - // SAFETY: The engine guarantees `ctx` is a valid pointer to the `RustFuzzTestAdapter` - // created by `construct_adapter_callback`. - let adapter = unsafe { &*(ctx as *const RustFuzzTestAdapter) }; - // SAFETY: The engine guarantees `input` is a valid `FuzzTestInputHandle` pointing to - // a heap-allocated `GenericCorpusValue` managed by the framework. - let input_ref = unsafe { &*(input.0 as *const GenericCorpusValue) }; - // SAFETY: The engine guarantees `sink` is a valid pointer to `FuzzTestBytesSink`. - let mut safe_sink = unsafe { BytesSink::from_raw(sink) }; - adapter.serialize_input_metadata(input_ref, &mut safe_sink); -} - -/// # Safety -/// -/// The caller must ensure that: -/// * `ctx` is a valid pointer to the `RustFuzzTestAdapter` created by `construct_adapter_callback`. -/// * `metadata` is a valid pointer to `FuzzTestBytesView` containing serialized input metadata. -/// * `input` is a valid `FuzzTestInputHandle` pointing to a heap-allocated `GenericCorpusValue` -/// managed by the framework, and the engine guarantees exclusive access to it for the call -/// duration. -pub unsafe extern "C" fn update_input_metadata_callback( - ctx: *mut engine_ffi::FuzzTestAdapterCtx, - metadata: *const engine_ffi::FuzzTestBytesView, - input: engine_ffi::FuzzTestInputHandle, -) { - // SAFETY: The engine guarantees `ctx` is a valid pointer to the `RustFuzzTestAdapter` - // created by `construct_adapter_callback`. - let adapter = unsafe { &*(ctx as *const RustFuzzTestAdapter) }; - // SAFETY: The engine guarantees `metadata` is a valid pointer to `FuzzTestBytesView` - // containing serialized input metadata. - let bytes = unsafe { &*(*metadata).to_bytes() }; - // SAFETY: The engine guarantees `input` is a valid `FuzzTestInputHandle` pointing to - // a heap-allocated `GenericCorpusValue` managed by the framework, and provides exclusive - // access to it. - let input_ref = unsafe { &mut *(input.0 as *mut GenericCorpusValue) }; - adapter.update_input_metadata(bytes, input_ref); -} - -/// # Safety -/// -/// The caller must ensure that: -/// * `ctx` is a valid pointer to the `RustFuzzTestAdapter` created by `construct_adapter_callback`. -/// * `input` is a valid `FuzzTestInputHandle` pointing to a heap-allocated `GenericCorpusValue` /// managed by the framework that has not been freed yet. pub unsafe extern "C" fn free_input_callback( ctx: *mut engine_ffi::FuzzTestAdapterCtx, @@ -641,37 +513,41 @@ } } +/// Runs `fuzztest` locally with random mutations for a short fixed duration. +/// +/// # Panics +/// +/// Panics if locking, initializing, or mutating the test domains fails, or if the property +/// function fails on a generated input. pub fn run_smoke_test(fuzztest: &dyn FuzzTest) { - let start_time = Instant::now(); - // TODO(the-shank): these should be configurable externally. - let smoke_test_duration = Duration::from_secs(1); - let only_shrink = false; + const SMOKE_TEST_DURATION: Duration = Duration::from_secs(1); + const ONLY_SHRINK: bool = false; + let deadline = Instant::now() + SMOKE_TEST_DURATION; + let domains = fuzztest.domains(); // TODO(the-shank): the rng seed should be configurable let mut rng = rand::rng(); - let mut generic_corpus_value = fuzztest - .domains() + let mut corpus_value = domains .lock() .expect("Failed to lock domains") .init(&mut rng) .expect("domain initialization should succeed to provide an initial corpus value"); - - let result = fuzztest.execute(&generic_corpus_value); - // DISCUSS: probably need a more "googletest" approach to handling the result here? - assert!(result); - - while start_time.elapsed() < smoke_test_duration { - fuzztest - .domains() + loop { + // DISCUSS: probably need a more "googletest" approach to handling the result here? + assert!( + fuzztest.execute(&corpus_value), + "the property function failed; see the counterexample reported above" + ); + if Instant::now() >= deadline { + break; + } + domains .lock() .expect("Failed to lock domains") - .mutate(&mut generic_corpus_value, &mut rng, only_shrink) + .mutate(&mut corpus_value, &mut rng, ONLY_SHRINK) .expect("domain mutation should succeed"); - let result = fuzztest.execute(&generic_corpus_value); - // DISCUSS: probably need a more "googletest" approach to handling the result here? - assert!(result); } } @@ -682,74 +558,38 @@ /// Processes and executes a fuzz test using the provided [`RustFuzzTestAdapterManager`]. /// -/// This function serves as the primary entry point for running a fuzz test. It manages test -/// execution across two operational modes: +/// This function serves as the primary entry point for running a fuzz test: /// -/// 1. Worker Mode: Registers signal/sanitizer crash handlers and attempts to hand off execution to -/// the external fuzzing engine (e.g., Centipede) via [`maybe_run_as_worker`]. +/// 1. Worker mode: registers the sanitizer crash handler and offers the test to the fuzzing engine +/// (e.g., Centipede) via [`maybe_run_as_worker`]. /// - If the binary was spawned as a worker process by the fuzzing engine, control remains in the -/// engine loop until complete. -/// - Returns cleanly on [`WorkerStatus::Success`], or panics on [`WorkerStatus::Failure`] to -/// signal test failure to the harness. -/// 2. Smoke Test Mode: If worker mode is not active (e.g., during standard `blaze test` or `cargo -/// test` unit test runs), falls back to executing a short local smoke test using sample inputs -/// and mutation iterations to verify property function sanity. +/// engine loop until it completes. +/// - Returns cleanly on [`WorkerStatus::Success`], so that the harness continues with the next +/// test, and exits the process with status 1 on [`WorkerStatus::Failure`]. +/// 2. Otherwise, the action selected by the FuzzTest options: run the fuzzing controller +/// (standalone fuzzing or crash replay), or fall back to a short local smoke test, as in +/// standard `blaze test` or `cargo test` runs. +/// +/// # Panics +/// +/// Panics if the controller reports a failure in standalone mode, or if the smoke test finds a +/// failing input. pub fn process(manager: RustFuzzTestAdapterManager) { super::crash_handler::register_crash_handler(); - // box it to get a stable heap address. - let manager = Box::new(manager); - - if let Some(status) = maybe_run_as_worker(&manager) { - match status { - WorkerStatus::Success => { - // do nothing, the harness would continue to the next test - return; - } - WorkerStatus::Failure => { - process::exit(1); - } - } + match maybe_run_as_worker(&manager) { + // The harness continues with the next test. + Some(WorkerStatus::Success) => return, + Some(WorkerStatus::Failure) => process::exit(1), + // Worker mode was not requested. + None => {} } - // worker mode was not run -- determine what to do next. match options::determine_execution_action(manager.test_name) { - ExecutionAction::Standalone(centipede_args) => { - let status = run_standalone_mode(&manager, centipede_args); - if status == engine_ffi::FuzzTestControllerStatus::Failure { - panic!("FuzzTest controller reported failure"); - } - } + ExecutionAction::Standalone(args) => run_controller(&manager, args), ExecutionAction::ReplayAllCrashes { args, list_file } => { - let status = run_standalone_mode(&manager, args); - if status == engine_ffi::FuzzTestControllerStatus::Failure { - panic!("FuzzTest controller reported failure"); - } - - // Now read the file and replay each crash - if let Ok(contents) = fs::read_to_string(list_file.path()) { - let options = options::get_fuzztest_options(); - for crash_id in contents.lines() { - let crash_id = crash_id.trim(); - if crash_id.is_empty() { - continue; - } - let replay_mode = - options::ExecutionMode::ReplayCrash(options::ReplayCrashOptions { - replay_id: crash_id.to_string(), - }); - if let Ok(Some(replay_args)) = CentipedeArgs::from_execution_mode( - &replay_mode, - options, - manager.test_name, - None, - ) { - // We ignore the result here because replaying a crash is expected to fail - // (report failure). We want to continue replaying other crashes. - let _ = run_standalone_mode(&manager, replay_args); - } - } - } + run_controller(&manager, args); + replay_listed_crashes(&manager, list_file.path()); } ExecutionAction::SmokeTest => { let fuzz_test = manager.construct_fuzz_test(); @@ -758,6 +598,49 @@ } } +/// Runs the controller and panics if it reports a failure, which fails the test in the harness. +fn run_controller(manager: &RustFuzzTestAdapterManager, args: CentipedeArgs) { + let status = run_standalone_mode(manager, args); + if status == engine_ffi::FuzzTestControllerStatus::Failure { + panic!("FuzzTest controller reported failure"); + } +} + +/// Replays every crash listed in `list_file`, with one controller run per crash ID. +/// +/// A list that cannot be read and a replay that cannot be prepared are reported as warnings. +/// They do not fail the test, in the same way that a crash that reproduces does not: this mode +/// replays as much as it can. +fn replay_listed_crashes(manager: &RustFuzzTestAdapterManager, list_file: &Path) { + let crash_ids = match fs::read_to_string(list_file) { + Ok(crash_ids) => crash_ids, + Err(e) => { + eprintln!( + "warning: no crash was replayed, cannot read the crash list {}: {e}", + list_file.display() + ); + return; + } + }; + let options = options::get_fuzztest_options(); + for crash_id in crash_ids.lines().map(str::trim).filter(|crash_id| !crash_id.is_empty()) { + let replay_mode = options::ExecutionMode::ReplayCrash(options::ReplayCrashOptions { + replay_id: crash_id.to_string(), + }); + match CentipedeArgs::from_execution_mode(&replay_mode, options, manager.test_name, None) { + Ok(Some(replay_args)) => { + // The status is ignored: replaying a crash is expected to report a failure, and + // the remaining crashes should still be replayed. + let _ = run_standalone_mode(manager, replay_args); + } + Ok(None) => { + eprintln!("warning: crash {crash_id} was not replayed: nothing to run for it") + } + Err(e) => eprintln!("warning: crash {crash_id} was not replayed: {e:#}"), + } + } +} + fn make_ffi_manager(manager: &RustFuzzTestAdapterManager) -> engine_ffi::FuzzTestAdapterManager { let ctx = manager as *const RustFuzzTestAdapterManager as *mut engine_ffi::FuzzTestAdapterManagerCtx; @@ -780,8 +663,8 @@ /// # Returns /// - `Some(WorkerStatus::Success)`: The process ran in worker mode and completed successfully. /// - `Some(WorkerStatus::Failure)`: The process ran in worker mode and encountered a failure. -/// - `None`: Worker mode was not requested (`kFuzzTestWorkerNotRequired`). The caller should fall -/// back to standalone smoke-test execution. +/// - `None`: Worker mode was not requested (`kFuzzTestWorkerNotRequired`). The caller decides what +/// to run instead. fn maybe_run_as_worker(manager: &RustFuzzTestAdapterManager) -> Option<WorkerStatus> { let ffi_manager = make_ffi_manager(manager);