No public description PiperOrigin-RevId: 1021880917
diff --git a/Cargo.lock b/Cargo.lock index 62d9daa..1a615de 100644 --- a/Cargo.lock +++ b/Cargo.lock
@@ -226,6 +226,10 @@ [[package]] name = "engine-ffi" version = "0.1.0" +dependencies = [ + "googletest", + "spin 0.10.1", +] [[package]] name = "equivalent" @@ -267,7 +271,6 @@ "postcard", "rand", "serde", - "spin 0.10.1", "tempfile", "trybuild", ]
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/BUILD b/rust/BUILD index fd4502f..e65c96b 100644 --- a/rust/BUILD +++ b/rust/BUILD
@@ -43,7 +43,6 @@ "@crate_index//:postcard", # v1 "@crate_index//:rand", # v0_10 "@crate_index//:serde", # v1 - "@crate_index//:spin", # v0_10 "@crate_index//:tempfile", # v3 ], )
diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 1f60eb2..fcf27d4 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml
@@ -35,7 +35,6 @@ postcard.workspace = true rand.workspace = true serde.workspace = true -spin.workspace = true tempfile.workspace = true [dev-dependencies]
diff --git a/rust/engine/BUILD b/rust/engine/BUILD index 8603658..7d99b62 100644 --- a/rust/engine/BUILD +++ b/rust/engine/BUILD
@@ -12,15 +12,18 @@ # See the License for the specific language governing permissions and # limitations under the License. -load("@rules_rust//rust:defs.bzl", "rust_library") +load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test") licenses(["notice"]) rust_library( name = "engine", srcs = [ + "src/adapter.rs", + "src/diagnostics.rs", "src/engine_ffi.rs", "src/lib.rs", + "src/worker.rs", ], edition = "2024", visibility = ["@com_google_fuzztest//rust:__subpackages__"], @@ -28,5 +31,15 @@ "@com_google_fuzztest//centipede:engine_abi", "@com_google_fuzztest//centipede:engine_controller_with_subprocess", "@com_google_fuzztest//centipede:engine_worker", + "@crate_index//:spin", # v0_10 + ], +) + +rust_test( + name = "engine_test", + crate = ":engine", + edition = "2024", + deps = [ + "@crate_index//:googletest", ], )
diff --git a/rust/engine/Cargo.toml b/rust/engine/Cargo.toml index d92f6c9..c0e37c3 100644 --- a/rust/engine/Cargo.toml +++ b/rust/engine/Cargo.toml
@@ -19,5 +19,9 @@ build = "build.rs" [dependencies] +spin.workspace = true + +[dev-dependencies] +googletest.workspace = true
diff --git a/rust/engine/src/adapter.rs b/rust/engine/src/adapter.rs new file mode 100644 index 0000000..5333fb7 --- /dev/null +++ b/rust/engine/src/adapter.rs
@@ -0,0 +1,81 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The traits that a test framework implements to be driven by the FuzzTest engine. +//! +//! They mirror the callback tables of `engine_abi.h`. The engine calls the methods one at a +//! time, on the thread that called [`run_worker_if_requested`](crate::run_worker_if_requested). +//! A method runs inside an `extern "C"` callback, so a panic that unwinds out of it aborts the +//! process. + +use crate::CoverageDomainRegistry; +use crate::ExecuteContext; +use crate::FeedbackSink; +use std::fmt::Debug; + +/// Identifies one test to the engine, and constructs its adapters. +/// +/// Corresponds to `FuzzTestAdapterManager` in `engine_abi.h`. +pub trait AdapterManager { + /// The adapter of the test. + type Adapter: Adapter; + + /// Returns the ID of the current binary. + fn binary_id(&self) -> Vec<u8>; + + /// Returns the name of the test. + fn test_name(&self) -> String; + + /// Constructs an adapter of the test. + fn construct_adapter(&self) -> Self::Adapter; +} + +/// The operations that the engine needs on the inputs of one test. +/// +/// Corresponds to `FuzzTestAdapter` in `engine_abi.h`. The optional callbacks of that table +/// (preset seeds, cross-over and input metadata) have no method here yet, and the engine uses +/// its fallback for them. +/// +/// An error that a method returns is reported to the engine as an unrecoverable error. +pub trait Adapter { + /// An in-memory input of the test. + /// + /// The engine keeps the inputs that the adapter returns and passes them back by reference. + /// An input is dropped when the engine is done with it. + type Input; + + /// Why an operation failed. It is reported to the engine in its `Debug` format. + type Error: Debug; + + /// Registers the coverage domains of the test with `registry`. + /// + /// The registrations must be the same for all the adapters of the same test. + fn set_up_coverage_domains(&self, registry: &CoverageDomainRegistry); + + /// Returns a randomly generated seed input. + fn random_seed_input(&self) -> Result<Self::Input, Self::Error>; + + /// Returns a mutant of `origin`, a smaller one if `shrink` is set. + fn mutate(&self, origin: &Self::Input, shrink: bool) -> Result<Self::Input, Self::Error>; + + /// Executes `input` for testing. Emits the feedback of the execution to `feedback`, and + /// reports its findings through `cx`. + fn execute(&self, cx: &ExecuteContext<'_>, input: &Self::Input, feedback: &FeedbackSink); + + /// Serializes the content of `input`. + fn serialize_input(&self, input: &Self::Input) -> Result<Vec<u8>, Self::Error>; + + /// Deserializes an input from its serialized `content`. + fn deserialize_input(&self, content: &[u8]) -> Result<Self::Input, Self::Error>; +}
diff --git a/rust/engine/src/diagnostics.rs b/rust/engine/src/diagnostics.rs new file mode 100644 index 0000000..ea69c25 --- /dev/null +++ b/rust/engine/src/diagnostics.rs
@@ -0,0 +1,395 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The diagnostic sink of the engine, and the process-wide state that lets crash hooks use it. +//! +//! A sanitizer or signal hook has no adapter pointer, may run on any thread, and may run inside +//! a signal handler. The diagnostic sink of the adapter is therefore published here for as long +//! as the engine is inside `Execute`, which is the only time a finding may be emitted. + +use crate::engine_ffi::FuzzTestBytesView; +use crate::engine_ffi::FuzzTestDiagnosticSink; +use crate::engine_ffi::FuzzTestDiagnosticSinkCtx; +use spin::Mutex as SpinMutex; +use std::marker::PhantomData; +#[cfg(test)] +use std::sync::Mutex; + +/// A copy of the diagnostic sink of an adapter, which outlives the call that lent the sink. +/// +/// Copies only the fields that this crate reads (`ctx`, `emit_error`, `emit_finding`), so +/// `retain` never reads `emit_warning`. +/// +/// The copy is inert: holding it calls nothing. Every call through it is vouched for where it +/// is made, by [`DiagnosticSink::assume_live`] or by [`execute_scope`]. +pub(crate) struct DiagnosticSink { + ctx: *mut FuzzTestDiagnosticSinkCtx, + emit_error: Option< + unsafe extern "C" fn(ctx: *mut FuzzTestDiagnosticSinkCtx, message: &FuzzTestBytesView<'_>), + >, + emit_finding: Option< + unsafe extern "C" fn( + ctx: *mut FuzzTestDiagnosticSinkCtx, + description: &FuzzTestBytesView<'_>, + signature: &FuzzTestBytesView<'_>, + ), + >, +} + +// SAFETY: the value is a context pointer and function pointers, and holding it calls nothing. +// The `unsafe` function that leads to a call states which threads may make it. +unsafe impl Send for DiagnosticSink {} +// SAFETY: as above. +unsafe impl Sync for DiagnosticSink {} + +/// A witness that errors can be reported to a diagnostic sink. +/// +/// [`DiagnosticSink::assume_live`] creates it, and its caller vouches for the sink for as long +/// as the witness exists. +pub(crate) struct LiveSink<'sink> { + // Safety invariant: for as long as this value exists, the `emit_error` function of `sink` + // is null, or it may be called with the `ctx` of `sink` and a view that is valid for the + // call, from the thread that created this value. Only `assume_live` creates one. + sink: &'sink DiagnosticSink, + // The invariant is about one thread, so the witness stays on it. + _not_send_nor_sync: PhantomData<*const ()>, +} + +impl LiveSink<'_> { + /// Reports an unrecoverable error to the engine. + pub(crate) fn emit_error(&self, message: &str) { + let emit = self.sink.emit_error.expect("EmitError is required by ABI"); + // SAFETY: by the struct invariant `emit`, which is not null, may be called with `ctx` + // from this thread. The view borrows `message` for the duration of the call. + unsafe { emit(self.sink.ctx, &FuzzTestBytesView::from_bytes(message.as_bytes())) } + } +} + +impl DiagnosticSink { + /// Copies the fields used from `raw`, so that the copy can outlive the call that lent `raw`. + pub(crate) fn retain(raw: &FuzzTestDiagnosticSink) -> Self { + Self { ctx: raw.ctx, emit_error: raw.emit_error, emit_finding: raw.emit_finding } + } + + /// Returns a witness that errors can be reported to this sink. + /// + /// # Safety + /// + /// For as long as the returned [`LiveSink`] exists, the `emit_error` function that this sink + /// retained must be null, or a function that may be called from the current thread with the + /// `ctx` of the same sink and a view that is valid for the call. + pub(crate) unsafe fn assume_live(&self) -> LiveSink<'_> { + LiveSink { sink: self, _not_send_nor_sync: PhantomData } + } + + /// Reports a finding to the engine. + /// + /// # Safety + /// + /// This sink must accept findings, as [`execute_scope`] defines it, until this function + /// returns. + unsafe fn emit_finding_unchecked(&self, description: &str, signature: &str) { + let emit = self.emit_finding.expect("EmitFinding is required by ABI"); + let description = FuzzTestBytesView::from_bytes(description.as_bytes()); + let signature = FuzzTestBytesView::from_bytes(signature.as_bytes()); + // SAFETY: by this function's contract `emit`, which is not null, may be called with + // `ctx` from this thread. Both views borrow a `&str` for the duration of the call. + unsafe { emit(self.ctx, &description, &signature) } + } +} + +/// A witness that the diagnostic sink of an adapter accepts findings, which the engine only +/// does while it is inside `Execute`. +/// +/// [`Adapter::execute`](crate::Adapter::execute) borrows this value for the duration of the +/// call, and reports the findings of the execution through it. +pub struct ExecuteContext<'exec> { + // Safety invariant: `sink` accepts findings, as `execute_scope` defines it, for as long as + // this value exists. Only `execute_scope` creates one. + sink: &'exec DiagnosticSink, +} + +impl ExecuteContext<'_> { + /// Reports a finding for the input that is being executed, with a human-readable + /// `description` and a `signature` for deduplication. + /// + /// If several findings are reported for one execution, the engine keeps one of them. + pub fn emit_finding(&self, description: &str, signature: &str) { + // SAFETY: by the struct invariant `sink` accepts findings for as long as `self` is + // borrowed. + unsafe { self.sink.emit_finding_unchecked(description, signature) } + } +} + +/// What this module keeps for the whole process. +struct Process { + // Whether an adapter is alive. No `unsafe` code relies on this field: it only makes + // `claim_adapter` refuse a second adapter. + adapter_alive: bool, + // Safety invariant: `Some` only while the `execute_scope` call that stored the sink is + // running. The caller of that call vouched that the sink accepts findings until the call + // returns. + executing: Option<DiagnosticSink>, +} + +// A spin lock, because `try_emit_finding` may run inside a signal handler: it must not block, +// and it only ever uses `try_lock`. Everything else that takes the lock runs on the thread on +// which the engine calls the adapter. +// +// The lock is held across the call into the sink on purpose. The end of `execute_scope` takes +// it too, so the engine cannot leave `Execute` while another thread is in the middle of an +// emission. +static PROCESS: SpinMutex<Process> = + SpinMutex::new(Process { adapter_alive: false, executing: None }); + +/// The state in this module is process-wide, so the tests that use it take turns. +#[cfg(test)] +pub(crate) static TEST_TURN: Mutex<()> = Mutex::new(()); + +/// Records that an adapter is about to be constructed. +/// +/// Returns `false` and records nothing if another adapter is still alive. A crash hook could +/// not tell which of two live adapters a crash belongs to, so the caller must not construct a +/// second one. +#[must_use] +pub(crate) fn claim_adapter() -> bool { + let mut process = PROCESS.lock(); + if process.adapter_alive { + return false; + } + process.adapter_alive = true; + true +} + +/// Records that the engine freed the adapter that [`claim_adapter`] recorded. +pub(crate) fn release_adapter() { + PROCESS.lock().adapter_alive = false; +} + +/// Runs `f` with a witness that `sink` accepts findings, and lets [`try_emit_finding`] report +/// findings to `sink` for as long as `f` runs. +/// +/// # Panics +/// +/// Panics if another `execute_scope` call is already running. +/// +/// # Safety +/// +/// `sink` must *accept findings* until this function returns. A sink accepts findings when the +/// `emit_finding` function that it retained is null, or may be called with the `ctx` of +/// the same sink and two views that are valid for the call, from any thread and from several +/// threads at once. If the program calls [`try_emit_finding`] from a signal handler, that +/// function must be async-signal-safe too. +pub(crate) unsafe fn execute_scope<R>( + sink: &DiagnosticSink, + f: impl FnOnce(&ExecuteContext<'_>) -> R, +) -> R { + /// Takes the published sink back. + struct Withdraw; + impl Drop for Withdraw { + fn drop(&mut self) { + // This waits for a crash hook that is in the middle of an emission. + PROCESS.lock().executing = None; + } + } + + { + let mut process = PROCESS.lock(); + assert!(process.executing.is_none(), "overlapping execute_scope calls are not supported"); + // By this function's contract `sink` accepts findings until `_withdraw` is dropped, which + // is what the invariant of `executing` requires. + process.executing = Some(DiagnosticSink { + ctx: sink.ctx, + emit_error: sink.emit_error, + emit_finding: sink.emit_finding, + }); + // The lock is released at the end of this block: `f` and the crash hooks take it again. + } + // Dropped when `f` returns or unwinds, before this function returns. + let _withdraw = Withdraw; + // By this function's contract `sink` accepts findings for as long as the witness exists. + f(&ExecuteContext { sink }) +} + +/// Reports a finding from a crash hook, and returns whether it was emitted. +/// +/// This function never blocks, so it can be called from a signal handler. It returns `false` +/// without emitting if the state is locked (for example because the crash interrupted this +/// thread inside this module), or if the engine is not inside `Execute`. +pub fn try_emit_finding(description: &str, signature: &str) -> bool { + let Some(process) = PROCESS.try_lock() else { + return false; + }; + let Some(sink) = process.executing.as_ref() else { + return false; + }; + // SAFETY: by the invariant of `executing`, the `execute_scope` call that stored `sink` is + // running, and its caller vouched that `sink` accepts findings until that call returns. + // This thread holds the lock that the call takes before it returns, so `sink` keeps + // accepting them until `emit_finding_unchecked` returns. + unsafe { sink.emit_finding_unchecked(description, signature) }; + true +} + +#[cfg(test)] +mod tests { + use super::*; + use googletest::prelude::*; + use std::mem; + use std::ptr; + + /// What the recording sink received. + #[derive(Debug, PartialEq, Eq)] + enum Emitted { + Error(String), + Finding { description: String, signature: String }, + } + + fn finding(description: &str, signature: &str) -> Emitted { + Emitted::Finding { description: description.to_string(), signature: signature.to_string() } + } + + // Not thread-local: a crash hook may emit from any thread. + static EMITTED: Mutex<Vec<Emitted>> = Mutex::new(Vec::new()); + + fn text(view: &FuzzTestBytesView<'_>) -> String { + String::from_utf8_lossy(view.as_bytes()).into_owned() + } + + extern "C" fn record_error( + _ctx: *mut FuzzTestDiagnosticSinkCtx, + message: &FuzzTestBytesView<'_>, + ) { + EMITTED.lock().expect("an earlier test panicked").push(Emitted::Error(text(message))); + } + + extern "C" fn record_finding( + _ctx: *mut FuzzTestDiagnosticSinkCtx, + description: &FuzzTestBytesView<'_>, + signature: &FuzzTestBytesView<'_>, + ) { + EMITTED + .lock() + .expect("an earlier test panicked") + .push(finding(&text(description), &text(signature))); + } + + /// Returns a sink that appends what it receives to `EMITTED`. + /// + /// # Safety-usable invariant + /// + /// Its callbacks are safe functions that ignore `ctx`, so the returned sink may be called at + /// any time and from any thread, and it accepts findings at any time. + fn recording_sink() -> DiagnosticSink { + let sink = FuzzTestDiagnosticSink { + ctx: ptr::null_mut(), + emit_error: Some(record_error), + emit_warning: None, + emit_finding: Some(record_finding), + }; + // The callbacks of `sink` are safe functions that ignore `ctx`, so they may be called + // at any time and from any thread. + DiagnosticSink::retain(&sink) + } + + /// Runs `f` inside [`execute_scope`] with `sink`. + fn in_execute_scope(sink: &DiagnosticSink, f: impl FnOnce(&ExecuteContext<'_>)) { + // SAFETY: `sink` is a recording sink, which accepts findings at any time and from any + // thread, see `recording_sink`. No test reports a finding from a signal handler. + unsafe { execute_scope(sink, f) } + } + + /// Runs `test` with no adapter claimed at the start, and returns what the recording sink + /// received. + fn emitted_by(test: impl FnOnce()) -> Vec<Emitted> { + let _turn = TEST_TURN.lock().expect("an earlier test panicked"); + release_adapter(); + EMITTED.lock().expect("an earlier test panicked").clear(); + + test(); + + release_adapter(); + mem::take(&mut *EMITTED.lock().expect("an earlier test panicked")) + } + + #[gtest] + fn try_emit_finding_is_refused_outside_execute() { + let emitted = emitted_by(|| { + expect_true!(claim_adapter()); + + expect_false!(try_emit_finding("description", "signature")); + }); + + expect_that!(emitted, is_empty()); + } + + #[gtest] + fn findings_are_emitted_inside_execute_only() { + let emitted = emitted_by(|| { + let sink = recording_sink(); + + in_execute_scope(&sink, |cx| { + expect_true!(try_emit_finding("crash", "crash signature")); + cx.emit_finding("panic", "panic signature"); + }); + + expect_false!(try_emit_finding("late", "late signature")); + }); + + expect_eq!( + emitted, + vec![finding("crash", "crash signature"), finding("panic", "panic signature")] + ); + } + + #[gtest] + fn a_second_adapter_is_refused_until_the_first_is_released() { + let emitted = emitted_by(|| { + expect_true!(claim_adapter()); + expect_false!(claim_adapter()); + + release_adapter(); + + expect_true!(claim_adapter()); + }); + + expect_that!(emitted, is_empty()); + } + + #[gtest] + fn emit_error_reaches_the_sink() { + let emitted = emitted_by(|| { + let sink = recording_sink(); + // SAFETY: the callbacks of a recording sink may be called at any time. + unsafe { sink.assume_live() }.emit_error("message"); + }); + + expect_eq!(emitted, vec![Emitted::Error("message".to_string())]); + } + + #[gtest] + fn try_emit_finding_returns_false_without_blocking_when_state_is_locked() { + let emitted = emitted_by(|| { + let sink = recording_sink(); + in_execute_scope(&sink, |_| { + let guard = PROCESS.lock(); + expect_false!(try_emit_finding("contended", "sig")); + drop(guard); + expect_true!(try_emit_finding("uncontended", "sig")); + }); + }); + + expect_eq!(emitted, vec![finding("uncontended", "sig")]); + } +}
diff --git a/rust/engine/src/engine_ffi.rs b/rust/engine/src/engine_ffi.rs index 276b3e1..54be757 100644 --- a/rust/engine/src/engine_ffi.rs +++ b/rust/engine/src/engine_ffi.rs
@@ -12,62 +12,72 @@ // See the License for the specific language governing permissions and // limitations under the License. -// The source of truth for the FFI definitions in this file are these C++ header files: -// - engine_abi.h -// - engine_worker_abi.h -// - engine_controller_abi.h -// TODO(b/540347807): use crubit +//! Rust definitions of the FuzzTest engine ABI. +//! +//! The source of truth for the definitions in this file are these C headers: +//! - `engine_abi.h` +//! - `engine_worker_abi.h` +//! - `engine_controller_abi.h` +//! +//! The types are spelled so that the compiler checks what the headers say in comments. A +//! pointer that the engine lends for the duration of a callback is an `Option<&T>`. A struct +//! whose fields are only usable under a condition keeps them private, states the condition as +//! a safety invariant, and offers safe methods that rely on it. -use core::ffi::c_int; +use std::ffi::c_int; +use std::marker::PhantomData; +use std::marker::PhantomPinned; +use std::mem::MaybeUninit; +#[cfg(test)] +use std::ptr; +use std::slice; -use core::marker::PhantomData; -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 handle for an in-memory input object used by the test. #[repr(transparent)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct FuzzTestInputHandle(pub usize); +/// A borrowed buffer of bytes. #[repr(C)] #[derive(Debug, Copy, Clone)] -pub struct FuzzTestBytesView { - pub data: *const u8, - pub size: usize, +pub struct FuzzTestBytesView<'a> { + // Safety invariant: `size` is 0, or `data` is non-null and points within a single allocated + // object to `size` initialized bytes that are valid for reads and are not written to for `'a`, + // with `size <= isize::MAX as usize`. + data: *const u8, + size: usize, + _buffer: PhantomData<&'a [u8]>, } -impl FuzzTestBytesView { - pub fn from_bytes(bytes: &[u8]) -> Self { - Self { data: bytes.as_ptr(), size: bytes.len() } +impl<'a> FuzzTestBytesView<'a> { + pub fn from_bytes(bytes: &'a [u8]) -> Self { + Self { data: bytes.as_ptr(), size: bytes.len(), _buffer: PhantomData } } - pub fn to_bytes(&self) -> *const [u8] { - if self.data.is_null() { - &[] - } else { - ptr::slice_from_raw_parts(self.data, self.size) + pub fn as_bytes(&self) -> &'a [u8] { + if self.size == 0 { + return &[]; } + // SAFETY: `size` is not 0, so by the struct invariant `data` is non-null and points within + // a single allocated object to `size` initialized bytes that are valid for reads and are + // not written to for `'a`, with `size <= isize::MAX as usize`, and `u8` has alignment 1. + unsafe { slice::from_raw_parts(self.data, self.size) } } } +/// A borrowed array of byte buffers. #[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct FuzzTestBytesViews { - pub views: *const FuzzTestBytesView, - pub count: usize, +pub struct FuzzTestBytesViews<'a> { + // Safety invariant: `count` is 0, or `views` points to an array of `count` views that is + // valid for reads and is not written to for `'a`. + views: *const FuzzTestBytesView<'a>, + count: usize, + _views: PhantomData<&'a [FuzzTestBytesView<'a>]>, } -impl FuzzTestBytesViews { - pub fn from_slice(views: &[FuzzTestBytesView]) -> Self { - Self { views: views.as_ptr(), count: views.len() } - } - - pub fn as_slice(&self) -> *const [FuzzTestBytesView] { - if self.views.is_null() { - &[] - } else { - ptr::slice_from_raw_parts(self.views, self.count) - } +impl<'a> FuzzTestBytesViews<'a> { + pub fn from_slice(views: &'a [FuzzTestBytesView<'a>]) -> Self { + Self { views: views.as_ptr(), count: views.len(), _views: PhantomData } } } @@ -80,27 +90,23 @@ /// Sink for diagnostics during the setup and execution of the test /// methods. Methods in this sink are async-safe and thread-safe. +/// +/// The fields are only used by the `diagnostics` module, whose `unsafe` functions state when +/// they may be called. #[repr(C)] -#[derive(Copy, Clone)] pub struct FuzzTestDiagnosticSink { pub ctx: *mut FuzzTestDiagnosticSinkCtx, /// Emits an unrecoverable error with a human-readable `message`. Engine would /// propagate the error to the controller command when in the worker mode. pub emit_error: Option< - unsafe extern "C" fn( - ctx: *mut FuzzTestDiagnosticSinkCtx, - message: *const FuzzTestBytesView, - ), + unsafe extern "C" fn(ctx: *mut FuzzTestDiagnosticSinkCtx, message: &FuzzTestBytesView<'_>), >, /// Emits a warning with a human-readable `message`. Engine would log /// the warning and continue gracefully when in the worker mode. pub emit_warning: Option< - unsafe extern "C" fn( - ctx: *mut FuzzTestDiagnosticSinkCtx, - message: *const FuzzTestBytesView, - ), + unsafe extern "C" fn(ctx: *mut FuzzTestDiagnosticSinkCtx, message: &FuzzTestBytesView<'_>), >, /// Emits a finding for running a test input within `Execute()` with a @@ -112,17 +118,12 @@ pub emit_finding: Option< unsafe extern "C" fn( ctx: *mut FuzzTestDiagnosticSinkCtx, - description: *const FuzzTestBytesView, - signature: *const FuzzTestBytesView, + description: &FuzzTestBytesView<'_>, + signature: &FuzzTestBytesView<'_>, ), >, } -// SAFETY: The engine guarantees that the diagnostic sink and its context are -// thread-safe and async-safe. -unsafe impl Send for FuzzTestDiagnosticSink {} -unsafe impl Sync for FuzzTestDiagnosticSink {} - #[repr(C)] pub struct FuzzTestBytesSinkCtx { _opaque: (), @@ -132,14 +133,32 @@ /// Sink for bytes data. #[repr(C)] -#[derive(Copy, Clone)] pub struct FuzzTestBytesSink { - pub ctx: *mut FuzzTestBytesSinkCtx, + // Safety invariant: `emit` is null, or it may be called with `ctx` and a valid view for as + // long as this value is borrowed. + ctx: *mut FuzzTestBytesSinkCtx, + emit: + Option<unsafe extern "C" fn(ctx: *mut FuzzTestBytesSinkCtx, view: &FuzzTestBytesView<'_>)>, +} +impl FuzzTestBytesSink { /// Emits a byte buffer. Multiple emissions are concatenated. - pub emit: Option< - unsafe extern "C" fn(ctx: *mut FuzzTestBytesSinkCtx, view: *const FuzzTestBytesView), - >, + pub fn emit(&self, bytes: &[u8]) { + let emit = self.emit.expect("Emit is required by ABI"); + // SAFETY: `emit` is not null, so by the struct invariant it may be called with `ctx` + // while `self` is borrowed. The view borrows `bytes` for the duration of the call. + unsafe { emit(self.ctx, &FuzzTestBytesView::from_bytes(bytes)) } + } + + /// Creates a sink with a null context that forwards to `emit`. + /// + /// `emit` is a safe function, so it upholds the struct invariant whatever it is called with. + #[cfg(test)] + pub fn for_test( + emit: extern "C" fn(ctx: *mut FuzzTestBytesSinkCtx, view: &FuzzTestBytesView<'_>), + ) -> Self { + Self { ctx: ptr::null_mut(), emit: Some(emit) } + } } #[repr(C)] @@ -151,61 +170,85 @@ /// Sink for seed inputs. #[repr(C)] -#[derive(Copy, Clone)] pub struct FuzzTestInputSink { - pub ctx: *mut FuzzTestInputSinkCtx, + // Safety invariant: `emit` is null, or it may be called with `ctx` for as long as this + // value is borrowed. + ctx: *mut FuzzTestInputSinkCtx, + emit: Option<unsafe extern "C" fn(ctx: *mut FuzzTestInputSinkCtx, input: FuzzTestInputHandle)>, +} +impl FuzzTestInputSink { /// Emits a test `input` to the engine. Engine would call /// `FuzzTestAdapter::FreeInput` on the emitted input after the engine is /// done with it. - pub emit: - Option<unsafe extern "C" fn(ctx: *mut FuzzTestInputSinkCtx, input: FuzzTestInputHandle)>, + pub fn emit(&self, input: FuzzTestInputHandle) { + let emit = self.emit.expect("Emit is required by ABI"); + // SAFETY: `emit` is not null, so by the struct invariant it may be called with `ctx` + // while `self` is borrowed. + unsafe { emit(self.ctx, input) } + } + + /// Creates a sink with a null context that forwards to `emit`. + /// + /// `emit` is a safe function, so it upholds the struct invariant whatever it is called with. + #[cfg(test)] + pub fn for_test( + emit: extern "C" fn(ctx: *mut FuzzTestInputSinkCtx, input: FuzzTestInputHandle), + ) -> Self { + Self { ctx: ptr::null_mut(), emit: Some(emit) } + } } +/// A borrowed array of 64-bit integers. #[repr(C)] -pub struct FuzzTestUint64sView { - pub data: *const u64, - pub size: usize, +pub struct FuzzTestUint64sView<'a> { + // Safety invariant: `size` is 0, or `data` is non-null, aligned, and points within a single + // allocated object to `size` initialized integers that are valid for reads and are not + // written to for `'a`, with `size * size_of::<u64>() <= isize::MAX as usize`. + data: *const u64, + size: usize, + _buffer: PhantomData<&'a [u64]>, } -impl FuzzTestUint64sView { - pub fn from_slice(slice: &[u64]) -> Self { - Self { data: slice.as_ptr(), size: slice.len() } +impl<'a> FuzzTestUint64sView<'a> { + pub fn from_slice(slice: &'a [u64]) -> Self { + Self { data: slice.as_ptr(), size: slice.len(), _buffer: PhantomData } } - pub fn as_slice(&self) -> *const [u64] { - if self.data.is_null() || self.size == 0 { - &[] - } else { - ptr::slice_from_raw_parts(self.data, self.size) + #[cfg(test)] + pub fn as_slice(&self) -> &'a [u64] { + if self.size == 0 { + return &[]; } - } - - pub fn to_bytes(&self) -> *const [u8] { - if self.data.is_null() { - &[] - } else { - ptr::slice_from_raw_parts(self.data as *const u8, self.size * size_of::<u64>()) - } + // SAFETY: `size` is not 0, so by the struct invariant `data` is non-null, aligned, and + // points within a single allocated object to `size` initialized integers that are valid + // for reads and are not written to for `'a`, with `size * size_of::<u64>() <= isize::MAX + // as usize`. + unsafe { slice::from_raw_parts(self.data, self.size) } } } + /// 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 { + /// Bit offset of the feature counter value within a packed 64-bit coverage feature. pub const COUNTER_START_BIT: u32 = 0; + /// Maximum number of bits used for the feature counter value. pub const COUNTER_BIT_SIZE: u32 = 32; + /// Bit offset of the per-domain feature ID within a packed 64-bit coverage feature. pub const FEATURE_ID_START_BIT: u32 = 32; + /// Maximum number of bits used for the feature ID within a domain. pub const FEATURE_ID_BIT_SIZE: u32 = 27; + /// Bit offset of the coverage domain ID within a packed 64-bit coverage feature. pub const DOMAIN_ID_START_BIT: u32 = 59; + /// Number of bits used for the coverage domain ID. pub const DOMAIN_ID_BIT_SIZE: u32 = 5; } @@ -218,30 +261,60 @@ /// Sink for execution feedback. #[repr(C)] -#[derive(Copy, Clone)] pub struct FuzzTestFeedbackSink { - pub ctx: *mut FuzzTestFeedbackSinkCtx, + // Safety invariant: `emit_coverage_features` is null, or it may be called with `ctx` and a + // valid view for as long as this value is borrowed. + ctx: *mut FuzzTestFeedbackSinkCtx, + emit_coverage_features: Option< + unsafe extern "C" fn(ctx: *mut FuzzTestFeedbackSinkCtx, features: &FuzzTestUint64sView<'_>), + >, +} +impl FuzzTestFeedbackSink { /// Emits an array of coverage features captured from the execution /// inside `Execute` call. See `FuzzTestCoverageFeatureLayout` for the feature /// layout. /// /// Multiple emissions are concatenated. - pub emit_coverage_features: Option< - unsafe extern "C" fn( + pub fn emit_coverage_features(&self, features: &[u64]) { + let emit = self.emit_coverage_features.expect("EmitCoverageFeatures is required by ABI"); + // SAFETY: `emit` is not null, so by the struct invariant it may be called with `ctx` + // while `self` is borrowed. The view borrows `features` for the duration of the call. + unsafe { emit(self.ctx, &FuzzTestUint64sView::from_slice(features)) } + } + + /// Emits the SanitizerCoverage features of the execution. + pub fn emit_sancov_features(&self) { + // `SanCovRuntimeEmitFeatures` calls the callback without checking it. + assert!(self.emit_coverage_features.is_some(), "EmitCoverageFeatures is required by ABI"); + // SAFETY: `SanCovRuntimeEmitFeatures` only uses the sink during the call. It calls + // `emit_coverage_features`, which is not null, with `ctx` and a valid view, which the + // struct invariant allows while `self` is borrowed. + unsafe { SanCovRuntimeEmitFeatures(self) } + } + + /// Creates a sink with a null context that forwards to `emit_coverage_features`. + /// + /// `emit_coverage_features` is a safe function, so it upholds the struct invariant whatever + /// it is called with. + #[cfg(test)] + pub fn for_test( + emit_coverage_features: extern "C" fn( ctx: *mut FuzzTestFeedbackSinkCtx, - features: *const FuzzTestUint64sView, + features: &FuzzTestUint64sView<'_>, ), - >, + ) -> Self { + Self { ctx: ptr::null_mut(), emit_coverage_features: Some(emit_coverage_features) } + } } /// Information of a coverage domain. #[repr(C)] -pub struct FuzzTestCoverageDomain { +pub struct FuzzTestCoverageDomain<'a> { /// 5-bit domain ID. pub domain_id: u8, /// Human-readable name of the domain for logging. - pub name: FuzzTestBytesView, + pub name: FuzzTestBytesView<'a>, /// Number of bits used for the feature IDs in this domain, must be <= 27. pub feature_id_bit_size: u8, /// Number of bits used for the counter values in this domain, must be <= 32. @@ -255,20 +328,111 @@ _not_unpin: PhantomPinned, } -#[repr(C)] -#[derive(Copy, Clone)] -pub struct FuzzTestCoverageDomainRegistry { - pub ctx: *mut FuzzTestDomainRegistryCtx, +/// Information describing a coverage feature domain. +/// +/// This is a high-level wrapper for `FuzzTestCoverageDomain`, the Rust representation of the C +/// struct of the same name defined in `engine_abi.h` (the source of truth for the ABI). +/// +/// Unlike the FFI representation, which uses `FuzzTestBytesView`, this type uses a Rust string +/// slice (`&str`) for safety and convenience. `CoverageDomainRegistry::register` takes it. +/// +/// A coverage domain represents a logically independent feature namespace registered in +/// `CoverageDomainRegistry`. FuzzTest packs 64-bit coverage features into three parts: +/// * Bits 63..59 (5 bits): 5-bit domain ID (`domain_id`, up to 32 domains). +/// * Bits 58..32 (27 bits): Feature ID within the domain (`feature_id_bit_size` <= 27). +/// * Bits 31..0 (32 bits): Feature counter value (`counter_bit_size` <= 32). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CoverageDomain<'name> { + /// 5-bit unique domain identifier (must be < 32). + pub domain_id: u8, + /// Human-readable name of the domain for logging and debugging. + pub name: &'name str, + /// Number of bits used for feature IDs in this domain (must be <= 27). + pub feature_id_bit_size: u8, + /// Number of bits used for feature counter values in this domain (must be <= 32). + pub counter_bit_size: u8, +} - /// Registers a new coverage `domain`. - pub register: Option< +/// Registry of the coverage domains of a test. +#[repr(C)] +pub struct FuzzTestCoverageDomainRegistry { + // Safety invariant: `register` is null, or it may be called with `ctx` and a valid domain + // for as long as this value is borrowed. A domain is valid if its name is valid for the + // call and its numbers are within the ranges of `FuzzTestCoverageFeatureLayout`. + ctx: *mut FuzzTestDomainRegistryCtx, + register: Option< unsafe extern "C" fn( ctx: *mut FuzzTestDomainRegistryCtx, - domain: *const FuzzTestCoverageDomain, + domain: &FuzzTestCoverageDomain<'_>, ), >, } +impl FuzzTestCoverageDomainRegistry { + /// Registers a coverage domain of the test. + /// + /// # Panics + /// + /// Panics if the ID of `domain` or one of its bit sizes does not fit in the layout of a + /// coverage feature, see [`FuzzTestCoverageFeatureLayout`]. + pub fn register(&self, domain: CoverageDomain<'_>) { + assert!( + u32::from(domain.domain_id) < (1 << FuzzTestCoverageFeatureLayout::DOMAIN_ID_BIT_SIZE), + "the domain ID {} does not fit in {} bits", + domain.domain_id, + FuzzTestCoverageFeatureLayout::DOMAIN_ID_BIT_SIZE + ); + assert!( + u32::from(domain.feature_id_bit_size) + <= FuzzTestCoverageFeatureLayout::FEATURE_ID_BIT_SIZE, + "the feature ID bit size {} is larger than {}", + domain.feature_id_bit_size, + FuzzTestCoverageFeatureLayout::FEATURE_ID_BIT_SIZE + ); + assert!( + u32::from(domain.counter_bit_size) <= FuzzTestCoverageFeatureLayout::COUNTER_BIT_SIZE, + "the counter bit size {} is larger than {}", + domain.counter_bit_size, + FuzzTestCoverageFeatureLayout::COUNTER_BIT_SIZE + ); + let register = self.register.expect("Register is required by ABI"); + let domain = FuzzTestCoverageDomain { + domain_id: domain.domain_id, + name: FuzzTestBytesView::from_bytes(domain.name.as_bytes()), + feature_id_bit_size: domain.feature_id_bit_size, + counter_bit_size: domain.counter_bit_size, + }; + // SAFETY: `register` is not null, so by the struct invariant it may be called with + // `ctx` and a valid domain while `self` is borrowed. `domain` is valid: its numbers + // were checked above, and its name borrows a `&str` for the duration of the call. + unsafe { register(self.ctx, &domain) } + } + + /// Sets up the SanitizerCoverage domains. + pub fn set_up_sancov_domains(&self) { + // `SanCovRuntimeSetUpCoverageDomains` calls the callback without checking it. + assert!(self.register.is_some(), "Register is required by ABI"); + // SAFETY: `SanCovRuntimeSetUpCoverageDomains` only uses the registry during the call. + // It calls `register`, which is not null, with `ctx` and a valid domain, which the + // struct invariant allows while `self` is borrowed. + unsafe { SanCovRuntimeSetUpCoverageDomains(self) }; + } + + /// Creates a registry with a null context that forwards to `register`. + /// + /// `register` is a safe function, so it upholds the struct invariant whatever it is called + /// with. + #[cfg(test)] + pub fn for_test( + register: extern "C" fn( + ctx: *mut FuzzTestDomainRegistryCtx, + domain: &FuzzTestCoverageDomain<'_>, + ), + ) -> Self { + Self { ctx: ptr::null_mut(), register: Some(register) } + } +} + #[repr(C)] pub struct FuzzTestAdapterCtx { _opaque: (), @@ -276,6 +440,7 @@ _not_unpin: PhantomPinned, } +/// The callbacks of a test adapter. `engine_abi.h` documents how the engine calls them. #[repr(C)] pub struct FuzzTestAdapter { pub ctx: *mut FuzzTestAdapterCtx, @@ -286,19 +451,21 @@ pub set_up_coverage_domains: Option< unsafe extern "C" fn( ctx: *mut FuzzTestAdapterCtx, - registry: *const FuzzTestCoverageDomainRegistry, + registry: Option<&FuzzTestCoverageDomainRegistry>, ), >, /// [Optional] Emits any preset seed inputs of the test using `sink`. /// The output must be the same for the all the test adapters of the same test /// (identified by the test name and the binary). - pub get_preset_seed_inputs: - Option<unsafe extern "C" fn(ctx: *mut FuzzTestAdapterCtx, sink: *const FuzzTestInputSink)>, + pub get_preset_seed_inputs: Option< + unsafe extern "C" fn(ctx: *mut FuzzTestAdapterCtx, sink: Option<&FuzzTestInputSink>), + >, /// Emits a randomly generated seed input using `sink`. - pub get_random_seed_input: - Option<unsafe extern "C" fn(ctx: *mut FuzzTestAdapterCtx, sink: *const FuzzTestInputSink)>, + pub get_random_seed_input: Option< + unsafe extern "C" fn(ctx: *mut FuzzTestAdapterCtx, sink: Option<&FuzzTestInputSink>), + >, /// Mutates from `origin`, and emits the mutant using `sink`. `shrink` != 0 /// means to generate smaller mutant. @@ -309,12 +476,12 @@ ctx: *mut FuzzTestAdapterCtx, origin: FuzzTestInputHandle, shrink: c_int, - sink: *const FuzzTestInputSink, + sink: Option<&FuzzTestInputSink>, ), >, /// [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< @@ -322,7 +489,7 @@ ctx: *mut FuzzTestAdapterCtx, origin: FuzzTestInputHandle, other: FuzzTestInputHandle, - sink: *const FuzzTestInputSink, + sink: Option<&FuzzTestInputSink>, ), >, @@ -335,7 +502,7 @@ unsafe extern "C" fn( ctx: *mut FuzzTestAdapterCtx, input: FuzzTestInputHandle, - sink: *const FuzzTestFeedbackSink, + sink: Option<&FuzzTestFeedbackSink>, ), >, @@ -344,7 +511,7 @@ unsafe extern "C" fn( ctx: *mut FuzzTestAdapterCtx, input: FuzzTestInputHandle, - sink: *const FuzzTestBytesSink, + sink: Option<&FuzzTestBytesSink>, ), >, @@ -353,8 +520,8 @@ pub deserialize_input_content: Option< unsafe extern "C" fn( ctx: *mut FuzzTestAdapterCtx, - content: *const FuzzTestBytesView, - sink: *const FuzzTestInputSink, + content: Option<&FuzzTestBytesView<'_>>, + sink: Option<&FuzzTestInputSink>, ), >, @@ -363,7 +530,7 @@ unsafe extern "C" fn( ctx: *mut FuzzTestAdapterCtx, input: FuzzTestInputHandle, - sink: *const FuzzTestBytesSink, + sink: Option<&FuzzTestBytesSink>, ), >, @@ -371,7 +538,7 @@ pub update_input_metadata: Option< unsafe extern "C" fn( ctx: *mut FuzzTestAdapterCtx, - metadata: *const FuzzTestBytesView, + metadata: Option<&FuzzTestBytesView<'_>>, input: FuzzTestInputHandle, ), >, @@ -391,18 +558,19 @@ _not_unpin: PhantomPinned, } +/// The callbacks of a test adapter manager. `engine_abi.h` documents how the engine calls them. #[repr(C)] pub struct FuzzTestAdapterManager { pub ctx: *mut FuzzTestAdapterManagerCtx, /// [Optional] Emits the ID for the current binary. pub get_binary_id: Option< - unsafe extern "C" fn(ctx: *mut FuzzTestAdapterManagerCtx, sink: *const FuzzTestBytesSink), + unsafe extern "C" fn(ctx: *mut FuzzTestAdapterManagerCtx, sink: Option<&FuzzTestBytesSink>), >, /// Emits the test name. pub get_test_name: Option< - unsafe extern "C" fn(ctx: *mut FuzzTestAdapterManagerCtx, sink: *const FuzzTestBytesSink), + unsafe extern "C" fn(ctx: *mut FuzzTestAdapterManagerCtx, sink: Option<&FuzzTestBytesSink>), >, /// Constructs an adapter of the test into `adapter_out`. Any diagnostics @@ -412,41 +580,100 @@ pub construct_adapter: Option< unsafe extern "C" fn( ctx: *mut FuzzTestAdapterManagerCtx, - diagnostic_sink: *const FuzzTestDiagnosticSink, - adapter_out: *mut FuzzTestAdapter, + diagnostic_sink: Option<&FuzzTestDiagnosticSink>, + adapter_out: Option<&mut MaybeUninit<FuzzTestAdapter>>, ), >, } -#[repr(i32)] -pub enum FuzzTestWorkerStatus { - /// Test should finish with a success. - Success = 0, - /// Test should finish with a failure. - Failure = 1, - /// Test should continue with controller commands. - NotRequired = 2, -} +/// `kFuzzTestWorkerSuccess`: the test should finish with a success. +pub const WORKER_SUCCESS: c_int = 0; +/// `kFuzzTestWorkerFailure`: the test should finish with a failure. +pub const WORKER_FAILURE: c_int = 1; +/// `kFuzzTestWorkerNotRequired`: the test should continue with controller commands. +pub const WORKER_NOT_REQUIRED: c_int = 2; +/// `kFuzzTestControllerSuccess`. +pub const CONTROLLER_SUCCESS: c_int = 0; -#[derive(PartialEq, Eq)] -#[repr(i32)] -pub enum FuzzTestControllerStatus { - Success = 0, - Failure = 1, -} - +// `improper_ctypes` flags the `PhantomPinned` marker of the opaque context structs, because its +// layout is unspecified. The marker is zero-sized, and the contexts are only used behind +// pointers. #[allow(improper_ctypes)] +// SAFETY: `FuzzTestWorkerMaybeRun` and `FuzzTestControllerRun` are defined with C linkage by the +// `cc_deps` of this crate, with the signatures of `engine_worker_abi.h` and +// `engine_controller_abi.h`. The two `SanCovRuntime*` functions are defined with C linkage by +// `//third_party/googlefuzztest/centipede:sancov_runtime`, with the signatures of +// `sancov_runtime.h`. This crate does not depend on that library: a binary that calls them links +// it through `//third_party/googlefuzztest/rust/coverage`. A reference has the ABI of the non-null +// pointer that the C signature takes. The two status enums are received as `c_int`, so that a +// value this file does not list is not undefined behavior. unsafe extern "C" { - /// Try to run as a FuzzTest worker with `manager` if needed. - pub fn FuzzTestWorkerMaybeRun(manager: *const FuzzTestAdapterManager) -> FuzzTestWorkerStatus; + /// Try to run as a FuzzTest worker with `manager` if needed. Returns a `WORKER_*` value. + /// + /// `manager` and its context are only used during the call. + pub fn FuzzTestWorkerMaybeRun(manager: &FuzzTestAdapterManager) -> c_int; - /// Returns whether the current process is running as a FuzzTest worker - - /// non-zero means yes and zero means no. It can be called outside of tests. - pub fn FuzzTestWorkerIsRequired() -> c_int; - - /// Run the FuzzTest controller with `flags` and `manager`. + /// Run the FuzzTest controller with `flags` and `manager`. Returns `CONTROLLER_SUCCESS` or + /// a failure value. + /// + /// `manager` and `flags` are only used during the call. pub fn FuzzTestControllerRun( - manager: *const FuzzTestAdapterManager, - flags: *const FuzzTestBytesViews, - ) -> FuzzTestControllerStatus; + manager: &FuzzTestAdapterManager, + flags: &FuzzTestBytesViews<'_>, + ) -> c_int; + + // TODO(b/586877694): a later CL of this chain moves the two declarations below to `coverage` + // with `# Safety` sections, states in `sancov_runtime.h` what the runtime does with the + // struct, and serializes the calls into the runtime. Until then their callers rely on + // `sancov_state.cc`, and nothing stops another thread from post-processing the coverage + // during `SanCovRuntimeEmitFeatures`, as before this CL. + fn SanCovRuntimeSetUpCoverageDomains(registry: &FuzzTestCoverageDomainRegistry) -> usize; + + fn SanCovRuntimeEmitFeatures(sink: &FuzzTestFeedbackSink); +} + +#[cfg(test)] +mod tests { + use super::*; + use googletest::prelude::*; + + extern "C" fn ignore_domain( + _ctx: *mut FuzzTestDomainRegistryCtx, + _domain: &FuzzTestCoverageDomain<'_>, + ) { + } + + /// The largest values that a registry accepts. + fn largest_domain() -> CoverageDomain<'static> { + CoverageDomain { + domain_id: 31, + name: "domain", + feature_id_bit_size: 27, + counter_bit_size: 32, + } + } + + #[gtest] + #[should_panic(expected = "the domain ID 32 does not fit in 5 bits")] + fn register_refuses_a_domain_id_that_does_not_fit() { + let registry = FuzzTestCoverageDomainRegistry::for_test(ignore_domain); + + registry.register(CoverageDomain { domain_id: 32, ..largest_domain() }); + } + + #[gtest] + #[should_panic(expected = "the feature ID bit size 28 is larger than 27")] + fn register_refuses_too_many_feature_id_bits() { + let registry = FuzzTestCoverageDomainRegistry::for_test(ignore_domain); + + registry.register(CoverageDomain { feature_id_bit_size: 28, ..largest_domain() }); + } + + #[gtest] + #[should_panic(expected = "the counter bit size 33 is larger than 32")] + fn register_refuses_too_many_counter_bits() { + let registry = FuzzTestCoverageDomainRegistry::for_test(ignore_domain); + + registry.register(CoverageDomain { counter_bit_size: 33, ..largest_domain() }); + } }
diff --git a/rust/engine/src/lib.rs b/rust/engine/src/lib.rs index f6e0bf8..04692f9 100644 --- a/rust/engine/src/lib.rs +++ b/rust/engine/src/lib.rs
@@ -12,274 +12,33 @@ // See the License for the specific language governing permissions and // limitations under the License. +//! A safe interface to the FuzzTest engine. +//! +//! A test framework implements [`AdapterManager`] and [`Adapter`], and gives the manager to +//! [`run_worker_if_requested`] or to [`run_controller`]. The `extern "C"` callbacks that the +//! engine calls, and the `unsafe` code that they need, stay inside this crate. +//! +//! A crash hook, which has no adapter at hand, reports a finding with [`try_emit_finding`]. + #![deny(clippy::absolute_paths)] #![deny(unused_imports)] +// The callbacks of `worker` are `unsafe` functions. An unsafe operation in their body still +// has to be written in an `unsafe` block, with a `SAFETY` comment of its own. +#![deny(unsafe_op_in_unsafe_fn)] -pub mod engine_ffi; +mod adapter; +mod diagnostics; +mod engine_ffi; +mod worker; -use std::marker::PhantomData; - -#[allow(improper_ctypes)] -unsafe extern "C" { - fn SanCovRuntimeSetUpCoverageDomains( - registry: *const engine_ffi::FuzzTestCoverageDomainRegistry, - ) -> usize; - - fn SanCovRuntimeEmitFeatures(sink: *const engine_ffi::FuzzTestFeedbackSink); -} - -/// A zero-sized witness token proving that a test is currently executing. -/// -/// Some of the methods on FuzzTestDiagnosticSink require that they are called only if the engine is -/// calling `Execute` callback of FuzzTestAdapter, which includes: -/// -/// * `emit_finding` -/// -/// The methods receiving this type can safely assume that the `Execute` callback is active because -/// the caller ensures this by creating this type. -pub struct ExecuteContext { - _private: PhantomData<()>, -} - -impl ExecuteContext { - /// Creates a new execution context. - /// - /// # Safety - /// - /// * The caller must ensure that it is in the `Execute` callback of FuzzTestAdapter. - pub unsafe fn new() -> Self { - Self { _private: PhantomData } - } -} - -#[derive(Clone)] -pub struct DiagnosticSink { - raw: engine_ffi::FuzzTestDiagnosticSink, -} - -impl DiagnosticSink { - /// Creates a safe wrapper from a pointer to `FuzzTestDiagnosticSink`. - /// - /// # Safety - /// - /// The caller must ensure that: - /// * `raw` is a non-null, properly aligned pointer to a valid `FuzzTestDiagnosticSink`. - /// * `(*raw).ctx` is a valid context pointer. - /// * The sink and its context remain valid for the duration of `DiagnosticSink`'s usage - /// (guaranteed by the engine until `FreeCtx` is called on the adapter). - pub unsafe fn from_raw(raw: *const engine_ffi::FuzzTestDiagnosticSink) -> Self { - // SAFETY: Caller guarantees `raw` is a valid pointer to `FuzzTestDiagnosticSink`. - let raw_sink = unsafe { *raw }; - Self { raw: raw_sink } - } - - /// Emits an unrecoverable error message to the underlying diagnostic sink. - pub fn emit_error(&self, message: &str) { - let emit = self.raw.emit_error.expect("EmitError is required by ABI"); - let view = engine_ffi::FuzzTestBytesView::from_bytes(message.as_bytes()); - // SAFETY: The presence of `self` guarantees that the context of the underlying - // `FuzzTestDiagnosticSink` remains live for the duration of this sink. - unsafe { - emit(self.raw.ctx, &view); - } - } - - /// Emits a warning message to the underlying diagnostic sink. - pub fn emit_warning(&self, message: &str) { - let emit = self.raw.emit_warning.expect("EmitWarning is required by ABI"); - let view = engine_ffi::FuzzTestBytesView::from_bytes(message.as_bytes()); - // SAFETY: The presence of `self` guarantees that the context of the underlying - // `FuzzTestDiagnosticSink` remains live for the duration of this sink. - unsafe { - emit(self.raw.ctx, &view); - } - } - - /// Emits a test finding (e.g., a crash or bug) to the underlying diagnostic sink. - /// - /// This must only be called during test execution, which is guaranteed by the - /// [`ExecuteContext`] token. - pub fn emit_finding(&self, _token: &ExecuteContext, description: &str, signature: &str) { - let emit = self.raw.emit_finding.expect("EmitFinding is required by ABI"); - let desc_view = engine_ffi::FuzzTestBytesView::from_bytes(description.as_bytes()); - let sig_view = engine_ffi::FuzzTestBytesView::from_bytes(signature.as_bytes()); - // SAFETY: The presence of `self` guarantees that the context of the underlying - // `FuzzTestDiagnosticSink` remains live for the duration of this sink. - // The witness `_token` further proves execution is currently within the `Execute` callback. - unsafe { - emit(self.raw.ctx, &desc_view, &sig_view); - } - } -} - -pub struct BytesSink { - raw: engine_ffi::FuzzTestBytesSink, -} - -impl BytesSink { - /// Creates a safe wrapper from a pointer to `FuzzTestBytesSink`. - /// - /// # Safety - /// - /// The caller must ensure that: - /// * `raw` is a non-null, properly aligned pointer to a valid `FuzzTestBytesSink`. - /// * `(*raw).ctx` is a valid context pointer. - /// * The sink and its context remain valid for the duration of `BytesSink`'s usage - /// (guaranteed by the engine until `FreeCtx` is called on the adapter). - pub unsafe fn from_raw(raw: *const engine_ffi::FuzzTestBytesSink) -> Self { - // SAFETY: Caller guarantees `raw` is a valid pointer to `FuzzTestBytesSink`. - let raw_sink = unsafe { *raw }; - Self { raw: raw_sink } - } - - /// Emits a byte slice to the underlying bytes sink. - /// - /// Multiple calls to this function will concatenate the emitted bytes. - pub fn emit(&mut self, bytes: &[u8]) { - let emit = self.raw.emit.expect("Emit is required by ABI"); - let view = engine_ffi::FuzzTestBytesView::from_bytes(bytes); - // SAFETY: The presence of `self` guarantees `from_raw` was called with a valid context - // pointer (`self.raw.ctx`) that remains live for the duration of this call. - unsafe { - emit(self.raw.ctx, &view); - } - } -} - -pub struct InputSink { - raw: engine_ffi::FuzzTestInputSink, -} - -impl InputSink { - /// Creates a safe wrapper from a pointer to `FuzzTestInputSink`. - /// - /// # Safety - /// - /// The caller must ensure that: - /// * `raw` is a non-null, properly aligned pointer to a valid `FuzzTestInputSink`. - /// * `(*raw).ctx` is a valid context pointer. - /// * The sink and its context remain valid for the duration of `InputSink`'s usage - /// (guaranteed by the engine until `FreeCtx` is called on the adapter). - pub unsafe fn from_raw(raw: *const engine_ffi::FuzzTestInputSink) -> Self { - // SAFETY: Caller guarantees `raw` is a valid pointer to `FuzzTestInputSink`. - let raw_sink = unsafe { *raw }; - Self { raw: raw_sink } - } - - /// Emits a test input handle to the underlying input sink. - /// - /// This function transfers ownership of the input represented by the handle - /// to the engine. The engine is responsible for freeing it. - pub fn emit(&mut self, input: engine_ffi::FuzzTestInputHandle) { - let emit = self.raw.emit.expect("Emit is required by ABI"); - // SAFETY: The presence of `self` guarantees `from_raw` was called with a valid context - // pointer (`self.raw.ctx`) that remains live for the duration of this call. - unsafe { - emit(self.raw.ctx, input); - } - } -} - -pub struct FeedbackSink { - raw: engine_ffi::FuzzTestFeedbackSink, -} - -impl FeedbackSink { - /// Creates a safe wrapper from a pointer to `FuzzTestFeedbackSink`. - /// - /// # Safety - /// - /// The caller must ensure that: - /// * `raw` is a non-null, properly aligned pointer to a valid `FuzzTestFeedbackSink`. - /// * `(*raw).ctx` is a valid context pointer. - /// * The sink and its context remain valid for the duration of `FeedbackSink`'s usage - /// (guaranteed by the engine until `FreeCtx` is called on the adapter). - pub unsafe fn from_raw(raw: *const engine_ffi::FuzzTestFeedbackSink) -> Self { - // SAFETY: Caller guarantees `raw` is a valid pointer to `FuzzTestFeedbackSink`. - let raw_sink = unsafe { *raw }; - Self { raw: raw_sink } - } - - /// Emits execution coverage features to the underlying feedback sink. - pub fn emit_coverage_features(&mut self, features: &[u64]) { - let emit = - self.raw.emit_coverage_features.expect("EmitCoverageFeatures is required by ABI"); - let view = engine_ffi::FuzzTestUint64sView::from_slice(features); - // SAFETY: The presence of `self` guarantees `from_raw` was called with a valid context - // pointer (`self.raw.ctx`) that remains live for the duration of this call. - unsafe { - emit(self.raw.ctx, &view); - } - } - - /// Emits SanitizerCoverage features. - pub fn emit_sancov_features(&mut self) { - // SAFETY: the sink pointer is guaranteed to be valid by the framework. - unsafe { SanCovRuntimeEmitFeatures(&self.raw) }; - } -} - -/// Information describing a coverage feature domain. -/// -/// This is a high-level wrapper for [`engine_ffi::FuzzTestCoverageDomain`], -/// which is the Rust representation of the C struct `FuzzTestCoverageDomain` -/// defined in `engine_abi.h` (the source of truth for the ABI). -/// -/// Unlike the FFI representation which uses [`engine_ffi::FuzzTestBytesView`], -/// this type uses Rust slices (`&[u8]`) for safety and convenience. It can be -/// converted to the FFI representation using `From`/`Into`. -/// -/// A coverage domain represents a logically independent feature namespace registered in -/// `CoverageDomainRegistry`. FuzzTest packs 64-bit coverage features into three parts: -/// * Bits 63..59 (5 bits): 5-bit domain ID (`domain_id`, up to 32 domains). -/// * Bits 58..32 (27 bits): Feature ID within the domain (`feature_id_bit_size` <= 27). -/// * Bits 31..0 (32 bits): Feature counter value (`counter_bit_size` <= 32). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct CoverageDomain<'a> { - /// 5-bit unique domain identifier (must be < 32). - pub domain_id: u8, - /// Human-readable name of the domain for logging and debugging. - pub name: &'a str, - /// Number of bits used for feature IDs in this domain (must be <= 27). - pub feature_id_bit_size: u8, - /// Number of bits used for feature counter values in this domain (must be <= 32). - pub counter_bit_size: u8, -} - -impl<'a> From<CoverageDomain<'a>> for engine_ffi::FuzzTestCoverageDomain { - fn from(domain: CoverageDomain<'a>) -> Self { - Self { - domain_id: domain.domain_id, - name: engine_ffi::FuzzTestBytesView::from_bytes(domain.name.as_bytes()), - feature_id_bit_size: domain.feature_id_bit_size, - counter_bit_size: domain.counter_bit_size, - } - } -} - -pub struct CoverageDomainRegistry { - raw: engine_ffi::FuzzTestCoverageDomainRegistry, -} - -impl CoverageDomainRegistry { - /// Creates a safe wrapper from a pointer to `FuzzTestCoverageDomainRegistry`. - /// - /// # Safety - /// - /// The caller must ensure that: - /// * `raw` is a non-null, properly aligned pointer to a valid `FuzzTestCoverageDomainRegistry`. - /// * `(*raw).ctx` is a valid context pointer. - /// * The registry and its context remain valid for the duration of `CoverageDomainRegistry`'s usage - /// (guaranteed by the engine until `FreeCtx` is called on the adapter). - pub unsafe fn from_raw(raw: *const engine_ffi::FuzzTestCoverageDomainRegistry) -> Self { - // SAFETY: Caller guarantees `raw` is a valid pointer to `FuzzTestCoverageDomainRegistry`. - let raw_registry = unsafe { *raw }; - Self { raw: raw_registry } - } - - /// Sets up SanitizerCoverage domains. - pub fn set_up_sancov_domains(&self) { - // SAFETY: The registry pointer is guaranteed to be valid by the framework. - unsafe { SanCovRuntimeSetUpCoverageDomains(&self.raw) }; - } -} +pub use adapter::Adapter; +pub use adapter::AdapterManager; +pub use diagnostics::try_emit_finding; +pub use diagnostics::ExecuteContext; +pub use engine_ffi::CoverageDomain; +pub use engine_ffi::FuzzTestCoverageDomainRegistry as CoverageDomainRegistry; +pub use engine_ffi::FuzzTestCoverageFeatureLayout as CoverageFeatureLayout; +pub use engine_ffi::FuzzTestFeedbackSink as FeedbackSink; +pub use worker::run_controller; +pub use worker::run_worker_if_requested; +pub use worker::RunOutcome;
diff --git a/rust/engine/src/worker.rs b/rust/engine/src/worker.rs new file mode 100644 index 0000000..8fa1749 --- /dev/null +++ b/rust/engine/src/worker.rs
@@ -0,0 +1,1161 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Runs the FuzzTest engine with an [`AdapterManager`]. +//! +//! The engine drives a test through two tables of C callbacks, `FuzzTestAdapterManager` and +//! `FuzzTestAdapter`. This module fills them in with functions that forward to an +//! [`AdapterManager`] and to its [`Adapter`], so that a test framework needs no `unsafe` code. +//! +//! One adapter is alive at a time in a process: `ConstructAdapter` reports an error instead of +//! constructing a second one. +//! +//! # Engine contract +//! +//! The callbacks are `unsafe` to call, because they rely on how the engine calls them. +//! `engine_abi.h` documents it, and the `SAFETY` comments of this module refer to these rules +//! by number: +//! +//! 1. The engine calls the callbacks of a manager, and of the adapter that it constructs, one at a +//! time. It calls them on the thread that passed the manager to `FuzzTestWorkerMaybeRun` or +//! `FuzzTestControllerRun`, and before that function returns. +//! 2. A pointer argument is null, or it meets until the callback returns what Rust requires of the +//! reference that `engine_ffi` declares it as. A view, a sink or a registry that the engine +//! passes upholds the safety invariant of its type, and calling it never calls a callback. +//! 3. A manager callback receives the `ctx` of the `FuzzTestAdapterManager` that holds it. An +//! adapter callback receives the `ctx` of the `FuzzTestAdapter` that holds it, after +//! `ConstructAdapter` filled that table in. Once the engine has called `FreeCtx`, it calls +//! nothing else with that `ctx`. +//! 4. An input handle that the engine passes was emitted through an input sink by the adapter that +//! receives it, and the engine has not passed it to `FreeInput` yet. The engine passes every +//! emitted handle to `FreeInput` once, before it calls `FreeCtx`. + +use crate::diagnostics; +use crate::diagnostics::DiagnosticSink; +use crate::diagnostics::ExecuteContext; +use crate::diagnostics::LiveSink; +use crate::engine_ffi; +use crate::engine_ffi::FuzzTestAdapter; +use crate::engine_ffi::FuzzTestAdapterCtx; +use crate::engine_ffi::FuzzTestAdapterManager; +use crate::engine_ffi::FuzzTestAdapterManagerCtx; +use crate::engine_ffi::FuzzTestBytesSink; +use crate::engine_ffi::FuzzTestBytesView; +use crate::engine_ffi::FuzzTestBytesViews; +use crate::engine_ffi::FuzzTestCoverageDomainRegistry; +use crate::engine_ffi::FuzzTestDiagnosticSink; +use crate::engine_ffi::FuzzTestFeedbackSink; +use crate::engine_ffi::FuzzTestInputHandle; +use crate::engine_ffi::FuzzTestInputSink; +use crate::Adapter; +use crate::AdapterManager; +use std::ffi::c_int; +use std::mem::MaybeUninit; +use std::ptr; + +/// What the `ctx` of a `FuzzTestAdapter` points to. +struct AdapterState<A: Adapter> { + adapter: A, + // Safety invariant: a copy of the diagnostic sink that `construct_adapter` received when + // it created this state. + diagnostics: DiagnosticSink, +} + +impl<A: Adapter> AdapterState<A> { + /// Runs `f` with the live adapter that `ctx` points to. Does nothing if `ctx` is null. + /// + /// This function picks the lifetime of what it lends to `f`, so `f` cannot keep any of it + /// after it returns. + /// + /// # Safety + /// + /// `ctx` must be null, or the `ctx` that `construct_adapter` stored in a `FuzzTestAdapter` + /// for an adapter of type `A`. `free_ctx` must not have been called with it, and must not be + /// called with it before this function returns. The caller must be on the thread that ran + /// `construct_adapter`: the state need not be `Send` or `Sync`. + unsafe fn with_live(ctx: *mut FuzzTestAdapterCtx, f: impl FnOnce(&Live<'_, A>)) { + // SAFETY: by this function's contract, a `ctx` that is not null comes from the + // `Box<Self>` that `construct_adapter` leaked, so it is aligned and it points to an + // initialized `Self`. Only `free_ctx` accesses that value other than through a shared + // reference, and it does not run before this function returns. The value stays on the + // thread that created it. + let Some(state) = (unsafe { ctx.cast::<Self>().as_ref() }) else { + return; + }; + // SAFETY: by the invariant of the field, `state.diagnostics` is a copy of the sink that + // `construct_adapter` received for this adapter, and the caller of `construct_adapter` + // keeps that sink usable on this thread until `free_ctx` is called for the adapter. By + // this function's contract that does not happen before `f` returns, and the witness + // does not outlive `f`. + let errors = unsafe { state.diagnostics.assume_live() }; + f(&Live { adapter: &state.adapter, diagnostics: &state.diagnostics, errors }); + } +} + +/// A live adapter, as one of its callbacks sees it: the engine has not freed it, and does not +/// free it while this value exists. Only `AdapterState::with_live` creates one. +struct Live<'call, A: Adapter> { + adapter: &'call A, + /// The diagnostic sink of the adapter, for `diagnostics::execute_scope`. + diagnostics: &'call DiagnosticSink, + /// The witness that errors can be reported to that sink. + errors: LiveSink<'call>, +} + +impl<A: Adapter> Live<'_, A> { + /// Reports an unrecoverable error of the adapter to the engine. + fn emit_error(&self, message: &str) { + self.errors.emit_error(message); + } + + /// Hands `input` over to the engine through `sink`, or reports why the adapter has none. + /// + /// # Safety-usable invariant + /// + /// Any non-zero handle emitted to `sink` is `Box::into_raw(Box<A::Input>).expose_provenance()` + /// allocated on the current thread. + fn emit_input( + &self, + failure: &str, + input: Result<A::Input, A::Error>, + sink: &FuzzTestInputSink, + ) { + match input { + Ok(input) => { + // The handle is the address of the input. The engine owns the input from here + // on, and `free_input` takes it back. + let input = Box::into_raw(Box::new(input)); + sink.emit(FuzzTestInputHandle(input.expose_provenance())); + } + Err(e) => self.emit_error(&format!("{failure}: {e:?}")), + } + } + + /// Returns the input that `handle` refers to, for as long as this adapter is lent. + /// + /// # Safety + /// + /// `handle` must have been emitted by `emit_input` for an adapter of type `A`. `free_input` + /// must not have been called with it, and must not be called with it while the returned + /// reference exists. The caller must be on the thread that emitted it: an input need not be + /// `Send` or `Sync`. + unsafe fn input(&self, handle: FuzzTestInputHandle) -> &A::Input { + // SAFETY: by this function's contract `handle` is the address of the `Box<A::Input>` + // that `emit_input` leaked, so it is aligned, it is not null, and it points to an + // initialized input. Only `free_input` accesses that input other than through a shared + // reference, and it does not run while the returned reference exists. The input stays + // on the thread that created it. + unsafe { &*ptr::with_exposed_provenance::<A::Input>(handle.0) } + } +} + +/// Runs `f` with the manager that `ctx` points to. Does nothing if `ctx` is null. +/// +/// This function picks the lifetime of the reference that it lends to `f`, so `f` cannot keep +/// the reference after it returns. +/// +/// # Safety +/// +/// `ctx` must be null, or the `ctx` of a table that `manager_table::<M>` built from a manager +/// that stays borrowed until this function returns. The caller must be on the thread that +/// holds that borrow: `M` need not be `Sync`. +unsafe fn with_manager<M: AdapterManager>(ctx: *mut FuzzTestAdapterManagerCtx, f: impl FnOnce(&M)) { + // SAFETY: by this function's contract, a `ctx` that is not null was derived from a `&M` + // whose borrow lasts until this function returns. It is therefore aligned, it points to an + // initialized `M`, and no exclusive reference to that `M` exists until then. The reference + // stays on the thread that holds the borrow. + if let Some(manager) = unsafe { ctx.cast::<M>().as_ref() } { + f(manager); + } +} + +/// Builds the table of callbacks that forward to `manager`. +/// +/// The table points to `manager`, so the engine must only use it while `manager` is borrowed. +/// +/// # Safety-usable invariant +/// +/// The returned table's `ctx` is derived from `manager: &M`, and only `manager_table::<M>` +/// installs `get_binary_id::<M>`, `get_test_name::<M>`, and `construct_adapter::<M>`. +fn manager_table<M: AdapterManager>(manager: &M) -> FuzzTestAdapterManager { + FuzzTestAdapterManager { + // Only ever read through, by `with_manager`. + ctx: ptr::from_ref(manager).cast_mut().cast(), + get_binary_id: Some(get_binary_id::<M>), + get_test_name: Some(get_test_name::<M>), + construct_adapter: Some(construct_adapter::<M>), + } +} + +/// `FuzzTestAdapterManager::GetBinaryId`. +/// +/// # Safety +/// +/// See the [engine contract](self#engine-contract). +unsafe extern "C" fn get_binary_id<M: AdapterManager>( + ctx: *mut FuzzTestAdapterManagerCtx, + sink: Option<&FuzzTestBytesSink>, +) { + let Some(sink) = sink else { + return; + }; + let body = |manager: &M| sink.emit(&manager.binary_id()); + // SAFETY: only `manager_table::<M>` installs this function, so by rule 3 `ctx` is the one + // that it stored. By rule 1 the engine calls this function on the thread that gave it the + // table, before `run_worker_if_requested` or `run_controller` returns, and both keep the + // manager borrowed until then. + unsafe { with_manager::<M>(ctx, body) }; +} + +/// `FuzzTestAdapterManager::GetTestName`. +/// +/// # Safety +/// +/// See the [engine contract](self#engine-contract). +unsafe extern "C" fn get_test_name<M: AdapterManager>( + ctx: *mut FuzzTestAdapterManagerCtx, + sink: Option<&FuzzTestBytesSink>, +) { + let Some(sink) = sink else { + return; + }; + let body = |manager: &M| sink.emit(manager.test_name().as_bytes()); + // SAFETY: see `get_binary_id`. + unsafe { with_manager::<M>(ctx, body) }; +} + +/// `FuzzTestAdapterManager::ConstructAdapter`. +/// +/// # Safety-usable invariant +/// +/// When this function writes to `adapter_out`, `ctx` is +/// `Box::into_raw(Box<AdapterState<M::Adapter>>)` created on the current thread with a retained +/// copy of `diagnostic_sink`, and only `construct_adapter` installs the adapter callbacks for `A = +/// M::Adapter`. +/// +/// # Safety +/// +/// See the [engine contract](self#engine-contract). In addition, `diagnostic_sink` must stay +/// usable until this function returns and, if it constructs an adapter, until `free_ctx` is +/// called with the `ctx` of that adapter: its `emit_error` function is null, or it may be +/// called on this thread with the `ctx` of the sink and a view that is valid for the call. +/// `engine_abi.h` says that the engine keeps the sink alive until then. +unsafe extern "C" fn construct_adapter<M: AdapterManager>( + ctx: *mut FuzzTestAdapterManagerCtx, + diagnostic_sink: Option<&FuzzTestDiagnosticSink>, + adapter_out: Option<&mut MaybeUninit<FuzzTestAdapter>>, +) { + let (Some(diagnostic_sink), Some(adapter_out)) = (diagnostic_sink, adapter_out) else { + return; + }; + let body = |manager: &M| { + // The copy is inert: the callback that calls the sink through it vouches for the sink at + // that moment. + let diagnostics = DiagnosticSink::retain(diagnostic_sink); + // The adapter is claimed before the manager constructs it, so that a second adapter is + // refused without running any code of the manager. If the manager panics, the process + // aborts at this `extern "C"` boundary, so no claim is left without an adapter. + if !diagnostics::claim_adapter() { + // SAFETY: by the contract of `construct_adapter`, `diagnostic_sink` is usable on this + // thread until it returns, and the witness is dropped at the end of this statement. + unsafe { diagnostics.assume_live() } + .emit_error("ConstructAdapter: another adapter is still alive in this process"); + return; + } + // `diagnostics` is the copy of the sink of this call, as the invariant of the field + // requires. + let state = Box::new(AdapterState { adapter: manager.construct_adapter(), diagnostics }); + adapter_out.write(FuzzTestAdapter { + // The engine owns the state from here on, and `free_ctx` takes it back. + ctx: Box::into_raw(state).cast(), + set_up_coverage_domains: Some(set_up_coverage_domains::<M::Adapter>), + // The optional callbacks that `Adapter` has no method for stay null. The engine then + // uses its own fallback: no preset seeds, `Mutate` instead of `CrossOver`, and no input + // metadata. + get_preset_seed_inputs: None, + get_random_seed_input: Some(get_random_seed_input::<M::Adapter>), + mutate: Some(mutate::<M::Adapter>), + cross_over: None, + execute: Some(execute::<M::Adapter>), + serialize_input_content: Some(serialize_input_content::<M::Adapter>), + deserialize_input_content: Some(deserialize_input_content::<M::Adapter>), + serialize_input_metadata: None, + update_input_metadata: None, + free_input: Some(free_input::<M::Adapter>), + free_ctx: Some(free_ctx::<M::Adapter>), + }); + }; + // SAFETY: see `get_binary_id`. + unsafe { with_manager::<M>(ctx, body) }; +} + +/// `FuzzTestAdapter::SetUpCoverageDomains`. +/// +/// # Safety +/// +/// See the [engine contract](self#engine-contract). +unsafe extern "C" fn set_up_coverage_domains<A: Adapter>( + ctx: *mut FuzzTestAdapterCtx, + registry: Option<&FuzzTestCoverageDomainRegistry>, +) { + let Some(registry) = registry else { + return; + }; + let body = |state: &Live<'_, A>| state.adapter.set_up_coverage_domains(registry); + // SAFETY: only `construct_adapter` installs this function, for the adapter type `A` of the + // state that it stores as `ctx`. By rule 3 this is that `ctx`, and the engine has not + // called `free_ctx` with it. By rule 1 it does not call `free_ctx` before this function + // returns, and this is the thread that ran `construct_adapter`. + unsafe { AdapterState::<A>::with_live(ctx, body) }; +} + +/// `FuzzTestAdapter::GetRandomSeedInput`. +/// +/// # Safety +/// +/// See the [engine contract](self#engine-contract). +unsafe extern "C" fn get_random_seed_input<A: Adapter>( + ctx: *mut FuzzTestAdapterCtx, + sink: Option<&FuzzTestInputSink>, +) { + let Some(sink) = sink else { + return; + }; + let body = |state: &Live<'_, A>| { + let input = state.adapter.random_seed_input(); + state.emit_input("Failed to initialize random seed", input, sink); + }; + // SAFETY: see `set_up_coverage_domains`. + unsafe { AdapterState::<A>::with_live(ctx, body) }; +} + +/// `FuzzTestAdapter::Mutate`. +/// +/// # Safety +/// +/// See the [engine contract](self#engine-contract). +unsafe extern "C" fn mutate<A: Adapter>( + ctx: *mut FuzzTestAdapterCtx, + origin: FuzzTestInputHandle, + shrink: c_int, + sink: Option<&FuzzTestInputSink>, +) { + let Some(sink) = sink else { + return; + }; + let body = |state: &Live<'_, A>| { + // SAFETY: only `construct_adapter` installs `mutate`, together with the callbacks that + // emit the inputs of the same adapter type `A`. By rule 4 this adapter emitted `origin` + // and the engine has not freed it. By rule 1 it does not call `free_input` before + // `mutate` returns, and this is the thread that emitted the input. + let origin = unsafe { state.input(origin) }; + state.emit_input("Failed to mutate", state.adapter.mutate(origin, shrink != 0), sink); + }; + // SAFETY: see `set_up_coverage_domains`. + unsafe { AdapterState::<A>::with_live(ctx, body) }; +} + +/// `FuzzTestAdapter::Execute`. +/// +/// # Safety +/// +/// See the [engine contract](self#engine-contract). In addition, the diagnostic sink that +/// `construct_adapter` received for this adapter must accept findings, as +/// [`diagnostics::execute_scope`] defines it, until this function returns. The engine accepts +/// findings for as long as it runs the `Execute` callback. +unsafe extern "C" fn execute<A: Adapter>( + ctx: *mut FuzzTestAdapterCtx, + input: FuzzTestInputHandle, + sink: Option<&FuzzTestFeedbackSink>, +) { + let Some(sink) = sink else { + return; + }; + let body = |state: &Live<'_, A>| { + // SAFETY: see `mutate`. + let input = unsafe { state.input(input) }; + let run = |cx: &ExecuteContext<'_>| state.adapter.execute(cx, input, sink); + // SAFETY: by the invariant of the field, `state.diagnostics` is a copy of the diagnostic + // sink that `construct_adapter` received for this adapter. By the contract of `execute` + // that sink accepts findings until `execute` returns. + unsafe { diagnostics::execute_scope(state.diagnostics, run) }; + }; + // SAFETY: see `set_up_coverage_domains`. + unsafe { AdapterState::<A>::with_live(ctx, body) }; +} + +/// `FuzzTestAdapter::SerializeInputContent`. +/// +/// # Safety +/// +/// See the [engine contract](self#engine-contract). +unsafe extern "C" fn serialize_input_content<A: Adapter>( + ctx: *mut FuzzTestAdapterCtx, + input: FuzzTestInputHandle, + sink: Option<&FuzzTestBytesSink>, +) { + let Some(sink) = sink else { + return; + }; + let body = |state: &Live<'_, A>| { + // SAFETY: see `mutate`. + let input = unsafe { state.input(input) }; + match state.adapter.serialize_input(input) { + Ok(content) => sink.emit(&content), + Err(e) => state.emit_error(&format!("Failed to serialize input: {e:?}")), + } + }; + // SAFETY: see `set_up_coverage_domains`. + unsafe { AdapterState::<A>::with_live(ctx, body) }; +} + +/// `FuzzTestAdapter::DeserializeInputContent`. +/// +/// # Safety +/// +/// See the [engine contract](self#engine-contract). +unsafe extern "C" fn deserialize_input_content<A: Adapter>( + ctx: *mut FuzzTestAdapterCtx, + content: Option<&FuzzTestBytesView<'_>>, + sink: Option<&FuzzTestInputSink>, +) { + let (Some(content), Some(sink)) = (content, sink) else { + return; + }; + let body = |state: &Live<'_, A>| { + let input = state.adapter.deserialize_input(content.as_bytes()); + state.emit_input("Failed to deserialize input", input, sink); + }; + // SAFETY: see `set_up_coverage_domains`. + unsafe { AdapterState::<A>::with_live(ctx, body) }; +} + +/// `FuzzTestAdapter::FreeInput`. +/// +/// # Safety +/// +/// See the [engine contract](self#engine-contract). +unsafe extern "C" fn free_input<A: Adapter>( + _ctx: *mut FuzzTestAdapterCtx, + input: FuzzTestInputHandle, +) { + // `emit_input` never hands out 0. + if input.0 == 0 { + return; + } + // SAFETY: only `construct_adapter` installs this function, together with the callbacks that + // emit the inputs of the same adapter type `A`. By rule 4 `input` is the address of a + // `Box<A::Input>` that `emit_input` leaked, and the engine does not pass it again, so the box + // is taken back once. By rule 1 no callback is using the input, and this is the thread that + // emitted it. + drop(unsafe { Box::from_raw(ptr::with_exposed_provenance_mut::<A::Input>(input.0)) }); +} + +/// `FuzzTestAdapter::FreeCtx`. +/// +/// # Safety +/// +/// See the [engine contract](self#engine-contract). +unsafe extern "C" fn free_ctx<A: Adapter>(ctx: *mut FuzzTestAdapterCtx) { + // A null `ctx` belongs to no adapter, and the claim of a live adapter stays. + if ctx.is_null() { + return; + } + struct ReleaseOnDrop; + impl Drop for ReleaseOnDrop { + fn drop(&mut self) { + diagnostics::release_adapter(); + } + } + let _release = ReleaseOnDrop; + // SAFETY: only `construct_adapter` installs this function, for the adapter type `A` of the + // `Box<AdapterState<A>>` that it leaked as `ctx`. By rule 3 this is that `ctx`, and the + // engine calls nothing else with it, so the box is taken back once. By rule 1 no other + // callback of the adapter is running, so `AdapterState::with_live` is not lending the + // state, and this is the thread that ran `construct_adapter`. + let state = unsafe { Box::from_raw(ctx.cast::<AdapterState<A>>()) }; + drop(state); +} + +/// How a run of the engine ended. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[must_use] +pub enum RunOutcome { + /// The test should finish with a success. + Success, + /// The test should finish with a failure. + Failure, +} + +/// Runs the test of `manager` as a FuzzTest worker, if the engine started this process as one. +/// +/// Returns `None` if it did not: the caller decides what to run instead. Otherwise the engine +/// drives the test through `manager` on this thread, and this function returns when the engine +/// is done with it. +#[must_use] +pub fn run_worker_if_requested<M: AdapterManager>(manager: &M) -> Option<RunOutcome> { + let table = manager_table(manager); + // SAFETY: + // - `table` is a manager table whose `ctx` points to `manager`. The engine only uses both + // during this call (`engine_worker_abi.h`), while `manager` is borrowed, and it calls the + // callbacks of `table` and of any constructed adapter on this thread according to the engine + // contract (`engine_abi.h`), so `M` and `M::Adapter` need not be `Send` or `Sync`. + // - `construct_adapter`: the `diagnostic_sink` passed by the engine remains usable on this + // thread (its `emit_error` is null or callable with its `ctx` and a valid view) until + // `construct_adapter` returns and, if an adapter is constructed, until `free_ctx` is called. + // - `execute`: the retained `diagnostic_sink` accepts findings (`emit_finding` is null or + // callable concurrently from any thread and async-signal-safely with its `ctx` and valid + // views) for the duration of each `Execute` call (`engine_abi.h`). + // - Other threads may be inside the engine with the manager of another test, as when a test + // harness runs tests in parallel: the engine returns early for a test whose name is not the + // one it was started for, and `construct_adapter` refuses a second adapter while one is + // alive. + let status = unsafe { engine_ffi::FuzzTestWorkerMaybeRun(&table) }; + match status { + engine_ffi::WORKER_NOT_REQUIRED => None, + engine_ffi::WORKER_SUCCESS => Some(RunOutcome::Success), + engine_ffi::WORKER_FAILURE => Some(RunOutcome::Failure), + unknown => { + eprintln!("FuzzTest worker returned the unknown status {unknown}, taken as a failure"); + Some(RunOutcome::Failure) + } + } +} + +/// Runs the FuzzTest controller with the command-line arguments `args`. +/// +/// The controller runs the test of `manager` in worker processes that it starts. +pub fn run_controller<M: AdapterManager>(manager: &M, args: &[&[u8]]) -> RunOutcome { + let table = manager_table(manager); + let views: Vec<_> = args.iter().copied().map(FuzzTestBytesView::from_bytes).collect(); + let flags = FuzzTestBytesViews::from_slice(&views); + // SAFETY: + // - `table` is a manager table whose `ctx` points to `manager`, and `flags` upholds the + // `FuzzTestBytesViews` safety invariant because `views` borrows `args` for this call. The + // engine only uses `table`, `manager`, and `flags` during this call + // (`engine_controller_abi.h`), while all of them are borrowed. + // - If the engine calls any manager or adapter callbacks, it does so on this thread according + // to the engine contract (`engine_abi.h`), keeping `diagnostic_sink` usable until `free_ctx` + // for `construct_adapter` and accepting findings concurrently/signal-safely during each + // `Execute` call. + let status = unsafe { engine_ffi::FuzzTestControllerRun(&table, &flags) }; + if status == engine_ffi::CONTROLLER_SUCCESS { + RunOutcome::Success + } else { + RunOutcome::Failure + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::diagnostics::ExecuteContext; + use crate::diagnostics::TEST_TURN; + use crate::engine_ffi::CoverageDomain; + use crate::engine_ffi::FuzzTestBytesSinkCtx; + use crate::engine_ffi::FuzzTestCoverageDomain; + use crate::engine_ffi::FuzzTestDiagnosticSinkCtx; + use crate::engine_ffi::FuzzTestDomainRegistryCtx; + use crate::engine_ffi::FuzzTestFeedbackSinkCtx; + use crate::engine_ffi::FuzzTestInputSinkCtx; + use crate::engine_ffi::FuzzTestUint64sView; + use googletest::prelude::*; + use std::cell::{Cell, RefCell}; + use std::sync::MutexGuard; + + struct TestManager; + + impl AdapterManager for TestManager { + type Adapter = TestAdapter; + + fn binary_id(&self) -> Vec<u8> { + b"test-binary".to_vec() + } + + fn test_name(&self) -> String { + "suite.test".to_string() + } + + fn construct_adapter(&self) -> TestAdapter { + TestAdapter + } + } + + /// An adapter whose inputs are byte strings, and whose behavior depends on their content. + struct TestAdapter; + + impl Adapter for TestAdapter { + type Input = Vec<u8>; + type Error = &'static str; + + fn set_up_coverage_domains(&self, registry: &FuzzTestCoverageDomainRegistry) { + // The largest values that a registry accepts. + registry.register(CoverageDomain { + domain_id: 31, + name: "test domain", + feature_id_bit_size: 27, + counter_bit_size: 32, + }); + } + + fn random_seed_input(&self) -> Result<Self::Input, Self::Error> { + if FAIL_RANDOM_SEED.get() { + return Err("Intentional seed failure"); + } + Ok(b"seed".to_vec()) + } + + fn mutate(&self, origin: &Self::Input, shrink: bool) -> Result<Self::Input, Self::Error> { + if origin == b"immutable" { + return Err("Intentional mutate failure"); + } + let mut mutant = origin.clone(); + if shrink { + mutant.pop(); + } else { + mutant.push(b'!'); + } + Ok(mutant) + } + + fn execute( + &self, + cx: &ExecuteContext<'_>, + input: &Self::Input, + feedback: &FuzzTestFeedbackSink, + ) { + let features: &[u64] = match input.as_slice() { + b"fail" => { + cx.emit_finding("the test failed", "failure signature"); + &[7, 9] + } + // What a crash hook does. The feature tells the test whether the finding was + // accepted. + b"crash" => { + if diagnostics::try_emit_finding("the test crashed", "crash signature") { + &[1] + } else { + &[0] + } + } + _ => &[7, 9], + }; + feedback.emit_coverage_features(features); + } + + fn serialize_input(&self, input: &Self::Input) -> Result<Vec<u8>, Self::Error> { + if input == b"unserializable" { + return Err("Intentional serialize failure"); + } + Ok(input.clone()) + } + + fn deserialize_input(&self, content: &[u8]) -> Result<Self::Input, Self::Error> { + if content == b"corrupt" { + return Err("Intentional deserialize failure"); + } + Ok(content.to_vec()) + } + } + + /// A coverage domain that the registry of the fake engine received. + #[derive(Debug, PartialEq, Eq)] + struct RegisteredDomain { + domain_id: u8, + name: String, + feature_id_bit_size: u8, + counter_bit_size: u8, + } + + /// What the sinks and the registry of the fake engine received. + #[derive(Debug, Default, PartialEq, Eq)] + struct Received { + errors: Vec<String>, + findings: Vec<(String, String)>, + inputs: Vec<FuzzTestInputHandle>, + bytes: Vec<u8>, + features: Vec<u64>, + domains: Vec<RegisteredDomain>, + } + + fn received_bytes(bytes: &[u8]) -> Received { + Received { bytes: bytes.to_vec(), ..Received::default() } + } + + fn received_error(message: &str) -> Received { + Received { errors: vec![message.to_string()], ..Received::default() } + } + + /// Returns the only input in `received`, or fails the test. + /// + /// This does not panic: the caller holds the turn of the tests, and a panic would poison it + /// for the tests that follow. + fn only_input(received: &Received) -> Result<FuzzTestInputHandle> { + verify_that!(received.inputs, len(eq(1)))?; + Ok(received.inputs[0]) + } + + thread_local! { + // The callbacks emit on the thread that called them, which is the thread of the test. + static RECEIVED: RefCell<Received> = RefCell::new(Received::default()); + static FAIL_RANDOM_SEED: Cell<bool> = const { Cell::new(false) }; + } + + fn text(view: &FuzzTestBytesView<'_>) -> String { + String::from_utf8_lossy(view.as_bytes()).into_owned() + } + + extern "C" fn record_error( + _ctx: *mut FuzzTestDiagnosticSinkCtx, + message: &FuzzTestBytesView<'_>, + ) { + RECEIVED.with_borrow_mut(|received| received.errors.push(text(message))); + } + + extern "C" fn record_finding( + _ctx: *mut FuzzTestDiagnosticSinkCtx, + description: &FuzzTestBytesView<'_>, + signature: &FuzzTestBytesView<'_>, + ) { + RECEIVED.with_borrow_mut(|received| { + received.findings.push((text(description), text(signature))); + }); + } + + extern "C" fn record_input(_ctx: *mut FuzzTestInputSinkCtx, input: FuzzTestInputHandle) { + RECEIVED.with_borrow_mut(|received| received.inputs.push(input)); + } + + extern "C" fn record_bytes(_ctx: *mut FuzzTestBytesSinkCtx, view: &FuzzTestBytesView<'_>) { + RECEIVED.with_borrow_mut(|received| received.bytes.extend_from_slice(view.as_bytes())); + } + + extern "C" fn record_features( + _ctx: *mut FuzzTestFeedbackSinkCtx, + features: &FuzzTestUint64sView<'_>, + ) { + RECEIVED.with_borrow_mut(|received| { + received.features.extend_from_slice(features.as_slice()); + }); + } + + extern "C" fn record_domain( + _ctx: *mut FuzzTestDomainRegistryCtx, + domain: &FuzzTestCoverageDomain<'_>, + ) { + RECEIVED.with_borrow_mut(|received| { + received.domains.push(RegisteredDomain { + domain_id: domain.domain_id, + name: text(&domain.name), + feature_id_bit_size: domain.feature_id_bit_size, + counter_bit_size: domain.counter_bit_size, + }); + }); + } + + /// The diagnostic sink of the fake engine. + /// + /// # Safety-usable invariant + /// + /// Its callbacks are safe functions that ignore `ctx`, so it may be used at any time and + /// from any thread, and it accepts findings at any time. + fn diagnostic_sink() -> FuzzTestDiagnosticSink { + FuzzTestDiagnosticSink { + ctx: ptr::null_mut(), + emit_error: Some(record_error), + emit_warning: None, + emit_finding: Some(record_finding), + } + } + + fn empty_adapter() -> FuzzTestAdapter { + FuzzTestAdapter { + ctx: ptr::null_mut(), + set_up_coverage_domains: None, + get_preset_seed_inputs: None, + get_random_seed_input: None, + mutate: None, + cross_over: None, + execute: None, + serialize_input_content: None, + deserialize_input_content: None, + serialize_input_metadata: None, + update_input_metadata: None, + free_input: None, + free_ctx: None, + } + } + + /// Asks `manager` for an adapter the way the engine does. Returns `None` if `manager` + /// constructed none. + fn construct_adapter_of(manager: &TestManager) -> Option<FuzzTestAdapter> { + let table = manager_table(manager); + let construct_adapter = table.construct_adapter.expect("installed by manager_table"); + let mut adapter = MaybeUninit::new(empty_adapter()); + // SAFETY: this follows the engine contract. `table.ctx` points to `manager`, which is + // borrowed. The sink and `adapter` are valid for the call, and the sink stays usable + // after it, see `diagnostic_sink`. + unsafe { construct_adapter(table.ctx, Some(&diagnostic_sink()), Some(&mut adapter)) }; + // SAFETY: `adapter` was initialized by `MaybeUninit::new`, and `construct_adapter` only + // ever writes a whole table to it. + let adapter = unsafe { adapter.assume_init() }; + (!adapter.ctx.is_null()).then_some(adapter) + } + + /// Plays the engine for one adapter of `TestManager`. + /// + /// Each method calls one callback of the adapter the way the engine contract requires: on + /// the thread of the test, with arguments that are valid for the call, and with sinks and a + /// registry that record what they receive in `RECEIVED` and call nothing back. It returns + /// what they received. Like the engine, it frees every input that it received before it + /// frees the adapter. + struct FakeEngine { + // Safety invariant: `construct_adapter::<TestManager>` filled this table in, and + // `free_ctx` has not been called. + adapter: FuzzTestAdapter, + // Safety invariant: the handles that `adapter` emitted and that `free_input` has not + // been called with. + inputs: RefCell<Vec<FuzzTestInputHandle>>, + // The diagnostics slot is process-wide, so the tests that have an adapter take turns. + // Released after `drop` freed the adapter. + _turn: MutexGuard<'static, ()>, + } + + impl FakeEngine { + fn start() -> Self { + let turn = TEST_TURN.lock().expect("an earlier test panicked"); + RECEIVED.take(); + FAIL_RANDOM_SEED.set(false); + let adapter = construct_adapter_of(&TestManager).expect("no other adapter is alive"); + Self { adapter, inputs: RefCell::new(Vec::new()), _turn: turn } + } + + /// Returns what the sinks received since the last call, and keeps track of the inputs. + fn received(&self) -> Received { + let received = RECEIVED.take(); + self.inputs.borrow_mut().extend_from_slice(&received.inputs); + received + } + + fn set_up_coverage_domains(&self) -> Received { + let callback = self.adapter.set_up_coverage_domains.expect("required callback"); + let registry = FuzzTestCoverageDomainRegistry::for_test(record_domain); + // SAFETY: by the struct invariant and as described on `FakeEngine`. + unsafe { callback(self.adapter.ctx, Some(®istry)) }; + self.received() + } + + fn random_seed_input(&self) -> Received { + let callback = self.adapter.get_random_seed_input.expect("required callback"); + let sink = FuzzTestInputSink::for_test(record_input); + // SAFETY: by the struct invariant and as described on `FakeEngine`. + unsafe { callback(self.adapter.ctx, Some(&sink)) }; + self.received() + } + + fn mutate(&self, origin: FuzzTestInputHandle, shrink: bool) -> Received { + let callback = self.adapter.mutate.expect("required callback"); + let sink = FuzzTestInputSink::for_test(record_input); + // SAFETY: by the struct invariant and as described on `FakeEngine`. + unsafe { callback(self.adapter.ctx, origin, c_int::from(shrink), Some(&sink)) }; + self.received() + } + + fn execute(&self, input: FuzzTestInputHandle) -> Received { + let callback = self.adapter.execute.expect("required callback"); + let sink = FuzzTestFeedbackSink::for_test(record_features); + // SAFETY: by the struct invariant and as described on `FakeEngine`. The diagnostic + // sink of the fake engine accepts findings at any time. + unsafe { callback(self.adapter.ctx, input, Some(&sink)) }; + self.received() + } + + fn serialize(&self, input: FuzzTestInputHandle) -> Received { + let callback = self.adapter.serialize_input_content.expect("required callback"); + let sink = FuzzTestBytesSink::for_test(record_bytes); + // SAFETY: by the struct invariant and as described on `FakeEngine`. + unsafe { callback(self.adapter.ctx, input, Some(&sink)) }; + self.received() + } + + fn deserialize(&self, content: &[u8]) -> Received { + let callback = self.adapter.deserialize_input_content.expect("required callback"); + let content = FuzzTestBytesView::from_bytes(content); + let sink = FuzzTestInputSink::for_test(record_input); + // SAFETY: by the struct invariant and as described on `FakeEngine`. + unsafe { callback(self.adapter.ctx, Some(&content), Some(&sink)) }; + self.received() + } + + fn free_input(&self, input: FuzzTestInputHandle) -> Received { + let callback = self.adapter.free_input.expect("required callback"); + self.inputs.borrow_mut().retain(|live| *live != input); + // SAFETY: by the struct invariants and as described on `FakeEngine`. + unsafe { callback(self.adapter.ctx, input) }; + self.received() + } + } + + impl Drop for FakeEngine { + fn drop(&mut self) { + let free_input = self.adapter.free_input.expect("required callback"); + for input in self.inputs.take() { + // SAFETY: by the struct invariants and as described on `FakeEngine`. This is + // the only `FreeInput` call with `input`. + unsafe { free_input(self.adapter.ctx, input) }; + } + let free_ctx = self.adapter.free_ctx.expect("required callback"); + // SAFETY: by the struct invariants and as described on `FakeEngine`. This is the + // last call with this `ctx`. + unsafe { free_ctx(self.adapter.ctx) }; + } + } + + #[gtest] + fn only_the_required_callbacks_are_installed() { + let engine = FakeEngine::start(); + let adapter = &engine.adapter; + + expect_false!(adapter.ctx.is_null()); + expect_true!(adapter.set_up_coverage_domains.is_some()); + expect_true!(adapter.get_random_seed_input.is_some()); + expect_true!(adapter.mutate.is_some()); + expect_true!(adapter.execute.is_some()); + expect_true!(adapter.serialize_input_content.is_some()); + expect_true!(adapter.deserialize_input_content.is_some()); + expect_true!(adapter.free_input.is_some()); + expect_true!(adapter.free_ctx.is_some()); + // The engine has a fallback for these. + expect_true!(adapter.get_preset_seed_inputs.is_none()); + expect_true!(adapter.cross_over.is_none()); + expect_true!(adapter.serialize_input_metadata.is_none()); + expect_true!(adapter.update_input_metadata.is_none()); + } + + #[gtest] + fn the_coverage_domains_of_the_adapter_reach_the_registry() { + let engine = FakeEngine::start(); + + expect_eq!( + engine.set_up_coverage_domains(), + Received { + domains: vec![RegisteredDomain { + domain_id: 31, + name: "test domain".to_string(), + feature_id_bit_size: 27, + counter_bit_size: 32, + }], + ..Received::default() + } + ); + } + + #[gtest] + fn the_manager_callbacks_emit_the_test_name_and_the_binary_id() { + let manager = TestManager; + let table = manager_table(&manager); + let get_test_name = table.get_test_name.expect("installed by manager_table"); + let get_binary_id = table.get_binary_id.expect("installed by manager_table"); + let sink = FuzzTestBytesSink::for_test(record_bytes); + RECEIVED.take(); + + // SAFETY: this follows the engine contract. `table.ctx` points to `manager`, which is + // borrowed, and `sink` is valid for the call. + unsafe { get_test_name(table.ctx, Some(&sink)) }; + let test_name = RECEIVED.take(); + // SAFETY: as above. + unsafe { get_binary_id(table.ctx, Some(&sink)) }; + let binary_id = RECEIVED.take(); + + expect_eq!(test_name, received_bytes(b"suite.test")); + expect_eq!(binary_id, received_bytes(b"test-binary")); + } + + #[gtest] + fn inputs_are_passed_back_by_handle() -> Result<()> { + let engine = FakeEngine::start(); + + let seed = only_input(&engine.random_seed_input())?; + let grown = only_input(&engine.mutate(seed, false))?; + let shrunk = only_input(&engine.mutate(seed, true))?; + + expect_eq!(engine.serialize(seed), received_bytes(b"seed")); + expect_eq!(engine.serialize(grown), received_bytes(b"seed!")); + expect_eq!(engine.serialize(shrunk), received_bytes(b"see")); + expect_eq!(engine.free_input(seed), Received::default()); + expect_eq!(engine.serialize(grown), received_bytes(b"seed!")); + Ok(()) + } + + #[gtest] + fn deserialized_content_becomes_an_input() -> Result<()> { + let engine = FakeEngine::start(); + + let input = only_input(&engine.deserialize(b"content"))?; + + expect_eq!(engine.serialize(input), received_bytes(b"content")); + Ok(()) + } + + #[gtest] + fn the_errors_of_the_adapter_are_reported_in_their_debug_format() -> Result<()> { + let engine = FakeEngine::start(); + let immutable = only_input(&engine.deserialize(b"immutable"))?; + let unserializable = only_input(&engine.deserialize(b"unserializable"))?; + + expect_eq!( + engine.mutate(immutable, false), + received_error("Failed to mutate: \"Intentional mutate failure\"") + ); + expect_eq!( + engine.serialize(unserializable), + received_error("Failed to serialize input: \"Intentional serialize failure\"") + ); + expect_eq!( + engine.deserialize(b"corrupt"), + received_error("Failed to deserialize input: \"Intentional deserialize failure\"") + ); + Ok(()) + } + + #[gtest] + fn random_seed_input_error_is_reported() { + let engine = FakeEngine::start(); + FAIL_RANDOM_SEED.set(true); + let result = engine.random_seed_input(); + FAIL_RANDOM_SEED.set(false); + + expect_eq!( + result, + received_error("Failed to initialize random seed: \"Intentional seed failure\"") + ); + } + + #[gtest] + fn execute_emits_the_feedback_and_the_findings() -> Result<()> { + let engine = FakeEngine::start(); + let passing = only_input(&engine.deserialize(b"pass"))?; + let failing = only_input(&engine.deserialize(b"fail"))?; + + expect_eq!( + engine.execute(passing), + Received { features: vec![7, 9], ..Received::default() } + ); + expect_eq!( + engine.execute(failing), + Received { + features: vec![7, 9], + findings: vec![("the test failed".to_string(), "failure signature".to_string())], + ..Received::default() + } + ); + Ok(()) + } + + #[gtest] + fn a_crash_hook_reports_findings_during_execute_only() -> Result<()> { + let engine = FakeEngine::start(); + let crashing = only_input(&engine.deserialize(b"crash"))?; + + expect_false!(diagnostics::try_emit_finding("early", "early signature")); + let during_execute = engine.execute(crashing); + expect_false!(diagnostics::try_emit_finding("late", "late signature")); + + expect_eq!( + during_execute, + Received { + features: vec![1], + findings: vec![("the test crashed".to_string(), "crash signature".to_string())], + ..Received::default() + } + ); + expect_eq!(RECEIVED.take(), Received::default()); + Ok(()) + } + + #[gtest] + fn a_second_adapter_is_refused_while_the_first_is_alive() -> Result<()> { + let engine = FakeEngine::start(); + + let second = construct_adapter_of(&TestManager); + let received = RECEIVED.take(); + + expect_true!(second.is_none()); + expect_eq!( + received, + received_error("ConstructAdapter: another adapter is still alive in this process") + ); + // The first adapter is not affected. + let seed = only_input(&engine.random_seed_input())?; + expect_eq!(engine.serialize(seed), received_bytes(b"seed")); + Ok(()) + } + + #[gtest] + fn an_adapter_can_be_constructed_once_the_previous_one_is_freed() { + drop(FakeEngine::start()); + + let engine = FakeEngine::start(); + + expect_eq!(engine.deserialize(b"corrupt").errors.len(), 1); + } + + #[gtest] + fn null_arguments_are_ignored() -> Result<()> { + let engine = FakeEngine::start(); + let adapter = &engine.adapter; + let input = only_input(&engine.random_seed_input())?; + let get_random_seed_input = adapter.get_random_seed_input.expect("required callback"); + let serialize_input_content = adapter.serialize_input_content.expect("required callback"); + let deserialize_input_content = + adapter.deserialize_input_content.expect("required callback"); + let sink = FuzzTestInputSink::for_test(record_input); + + // SAFETY: as described on `FakeEngine`, with a null `ctx`. + unsafe { get_random_seed_input(ptr::null_mut(), Some(&sink)) }; + // SAFETY: as described on `FakeEngine`, with a null sink. + unsafe { serialize_input_content(adapter.ctx, input, None) }; + // SAFETY: as described on `FakeEngine`, with a null view. + unsafe { deserialize_input_content(adapter.ctx, None, Some(&sink)) }; + + expect_eq!(RECEIVED.take(), Received::default()); + Ok(()) + } + + #[gtest] + fn free_ctx_with_a_null_ctx_keeps_the_live_adapter() -> Result<()> { + let engine = FakeEngine::start(); + let free_ctx = engine.adapter.free_ctx.expect("required callback"); + let crashing = only_input(&engine.deserialize(b"crash"))?; + + // SAFETY: as described on `FakeEngine`, with a null `ctx`. + unsafe { free_ctx(ptr::null_mut()) }; + + // A crash hook still reaches the diagnostic sink of the adapter. + expect_eq!( + engine.execute(crashing), + Received { + features: vec![1], + findings: vec![("the test crashed".to_string(), "crash signature".to_string())], + ..Received::default() + } + ); + Ok(()) + } + + #[gtest] + fn the_worker_does_not_run_in_a_process_that_the_engine_did_not_start() { + expect_true!(run_worker_if_requested(&TestManager).is_none()); + } +}
diff --git a/rust/src/crash_handler.rs b/rust/src/crash_handler.rs index 335f82a..cb0cd1f 100644 --- a/rust/src/crash_handler.rs +++ b/rust/src/crash_handler.rs
@@ -12,12 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::slice; +use std::str; + // SAFETY: // - `FuzzTestSetSanitizerErrorSummaryCallback` is declared with `extern "C"` linkage in // `internal/sanitizer_interface.h` and defined in `internal/sanitizer_interface.cc`. -// - The signature matches `void FuzzTestSetSanitizerErrorSummaryCallback(void (*)(const char*, size_t))`: -// `*const u8` is layout- and ABI-compatible with `const char*`, and `usize` is ABI-compatible -// with `size_t`. +// - The signature matches `void FuzzTestSetSanitizerErrorSummaryCallback(void (*)(const char*, +// size_t))`: `*const u8` is layout- and ABI-compatible with `const char*`, and `usize` is +// ABI-compatible with `size_t`. unsafe extern "C" { fn FuzzTestSetSanitizerErrorSummaryCallback( callback: unsafe extern "C" fn(crash_type_data: *const u8, crash_type_size: usize), @@ -30,7 +33,8 @@ /// /// The caller must uphold the following preconditions: /// - If `crash_type_size > 0`, `crash_type_data` must be non-null and valid for reads of -/// `crash_type_size` consecutive, initialized `u8` bytes for the duration of the call. +/// `crash_type_size` consecutive, initialized `u8` bytes within a single allocated object for the +/// duration of the call. /// - The pointed-to memory must not be mutated concurrently for the duration of the call. /// - `crash_type_size` must not exceed `isize::MAX`. unsafe extern "C" fn sanitizer_error_summary_callback( @@ -44,14 +48,14 @@ // - Non-nullness: `crash_type_data` was verified non-null above. // - Alignment: `u8` has alignment 1, so any non-null pointer is properly aligned. // - Validity: The caller guarantees `crash_type_data` points to `crash_type_size` - // consecutive, initialized `u8` bytes valid for reads for the duration of this call. + // consecutive, initialized `u8` bytes within a single allocated object valid for reads + // for the duration of this call. // - Aliasing: The pointed-to memory is read-only and not mutated during the call. // - Size: The caller guarantees `crash_type_size <= isize::MAX`. - let crash_type_bytes = - unsafe { std::slice::from_raw_parts(crash_type_data, crash_type_size) }; - std::str::from_utf8(crash_type_bytes).unwrap_or("Sanitizer crash (invalid utf8)") + let crash_type_bytes = unsafe { slice::from_raw_parts(crash_type_data, crash_type_size) }; + str::from_utf8(crash_type_bytes).unwrap_or("Sanitizer crash (invalid utf8)") }; - crate::worker::try_emit_finding(crash_type, crash_type); + ::engine::try_emit_finding(crash_type, crash_type); } /// Registers the sanitizer error summary callback and ensures the sanitizer crash handler hook is @@ -64,6 +68,9 @@ // valid for the entire duration of program execution. // - `FuzzTestSetSanitizerErrorSummaryCallback` stores the function pointer in a `std::atomic` // using `memory_order_relaxed`, so concurrent registration is data-race free. + // - `internal/sanitizer_interface.cc` invokes the registered callback synchronously with a + // string literal / single-object buffer of length `<= isize::MAX` that is valid for reads and + // not mutated during the call. unsafe { FuzzTestSetSanitizerErrorSummaryCallback(sanitizer_error_summary_callback); }
diff --git a/rust/src/options.rs b/rust/src/options.rs index f827928..2c51c55 100644 --- a/rust/src/options.rs +++ b/rust/src/options.rs
@@ -13,7 +13,6 @@ // limitations under the License. use crate::internal::FuzzTestRegistration; -use ::engine::engine_ffi; use anyhow::Context; use std::env; use std::ffi::CString; @@ -21,8 +20,8 @@ use tempfile::{NamedTempFile, TempDir}; pub use fuzztest_options::{ - ExecutionMode, FuzzOptions, FuzzTestOptions, ReplayCorpusOptions, ReplayCrashOptions, - RunDuration, TimeBudgetType, get_fuzztest_options, set_fuzztest_options, + get_fuzztest_options, set_fuzztest_options, ExecutionMode, FuzzOptions, FuzzTestOptions, + ReplayCorpusOptions, ReplayCrashOptions, RunDuration, TimeBudgetType, }; trait ExecutionModeExt { @@ -94,28 +93,18 @@ /// Encapsulates command-line arguments and lifetime holders for Centipede execution. #[derive(Debug)] pub struct CentipedeArgs { - // Holds the owned C-compatible strings. We must keep these alive because the `views` - // field contains pointers into the memory owned by these `CString`s. + // Holds the arguments as owned C-compatible strings. _c_strings: Vec<CString>, // The (optional) TempDir instance which is to be used as a workdir by centipede. // We keep the ownership here so that it is not cleaned while the centipede execution is still // in progress. _temp_workdir: Option<TempDir>, - - // FFI-compatible views into the arguments in `_c_strings`. These are passed across - // the FFI boundary to Centipede. - views: Vec<engine_ffi::FuzzTestBytesView>, } impl CentipedeArgs { fn new(args: Vec<CString>, temp_workdir: Option<TempDir>) -> Self { - let views = args - .iter() - .map(|arg| engine_ffi::FuzzTestBytesView::from_bytes(arg.as_bytes())) - .collect(); - - Self { _c_strings: args, _temp_workdir: temp_workdir, views } + Self { _c_strings: args, _temp_workdir: temp_workdir } } /// Decides if Centipede needs to be invoked based on the execution mode, @@ -312,9 +301,11 @@ env_diff } - /// Exposes the FFI-compatible argument views vector for C++ Centipede binding. - pub fn as_bytes_views(&self) -> engine_ffi::FuzzTestBytesViews { - engine_ffi::FuzzTestBytesViews { views: self.views.as_ptr(), count: self.views.len() } + /// Returns the arguments as byte strings without their NUL terminators, which is how the + /// `engine` crate takes them. + #[must_use] + pub fn to_byte_slices(&self) -> Vec<&[u8]> { + self._c_strings.iter().map(|arg| arg.as_bytes()).collect() } } @@ -464,7 +455,7 @@ panic!("Expected Standalone action"); }; - expect_that!(args._c_strings.len(), eq(args.views.len())); + expect_that!(args.to_byte_slices().len(), eq(args._c_strings.len())); let args_str: Vec<&str> = args._c_strings.iter().map(|s| s.to_str().expect("invalid utf8")).collect();
diff --git a/rust/src/worker.rs b/rust/src/worker.rs index fcfbd6a..422e418 100644 --- a/rust/src/worker.rs +++ b/rust/src/worker.rs
@@ -12,744 +12,222 @@ // See the License for the specific language governing permissions and // limitations under the License. -use super::domains::GenericCorpusValue; +//! Runs a fuzz test: as a worker of the FuzzTest engine, as its controller, or as a smoke test. +//! +//! The FFI with the engine lives in the `engine` crate. This module implements the traits of +//! that crate for a fuzz test, and needs no `unsafe` code. + +#![forbid(unsafe_code)] + +use super::domains::{GenericCorpusValue, GenericDomain}; use super::internal::{BoxedFuzzTest, FuzzTest}; use super::options::{self, CentipedeArgs, ExecutionAction}; -use ::engine::engine_ffi; use ::engine::{ - BytesSink, CoverageDomainRegistry, DiagnosticSink, ExecuteContext, FeedbackSink, InputSink, + Adapter, AdapterManager, CoverageDomainRegistry, ExecuteContext, FeedbackSink, RunOutcome, }; -use spin::Mutex; use std::env; -use std::ffi::c_int; -use std::ffi::CString; +use std::ffi::OsString; 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; -/// The DiagnosticSink provided by the engine while creating the adapter. -/// -/// Storing the `DiagnosticSink` in this global is necessary because C callbacks (e.g., -/// sanitizer hooks in `crash_handler.rs`) do not have access to the adapter instance and must rely -/// on a global lookup to report crashes. -static DIAGNOSTIC_SINK: Mutex<Option<DiagnosticSink>> = Mutex::new(None); - -/// A global execution context token. -/// -/// This is set to `Some(ExecuteContext)` when the fuzz test is currently executing -/// (inside the `execute` method of `RustFuzzTestAdapter`) and `None` otherwise. -/// -/// The inner ExecuteContext is used as a witness token to prove to the fuzzing engine that findings -/// are being emitted during the execution of a test case. -/// A global is necessary because C callbacks (e.g. sanitizer hooks in `crash_handler.rs`) do -/// not have access to the adapter instance. -static EXECUTE_CONTEXT: Mutex<Option<ExecuteContext>> = Mutex::new(None); - -/// Sets the global DiagnosticSink. -pub(crate) fn set_diagnostic_sink(sink: DiagnosticSink) { - let mut guard = DIAGNOSTIC_SINK.lock(); - *guard = Some(sink); -} - -/// Clears the global DiagnosticSink, setting it to None. -pub(crate) fn clear_diagnostic_sink() { - let mut guard = DIAGNOSTIC_SINK.lock(); - *guard = None; -} - -/// Emits an error into the DiagnosticSink if the DiagnosticSink is set. -/// This function blocks till it can get the lock on the global DiagnosticSink and is not -/// signal-safe. -pub(crate) fn emit_error(message: &str) { - if let Some(sink) = DIAGNOSTIC_SINK.lock().as_ref() { - sink.emit_error(message) - } -} - -/// Emits a finding into the DiagnosticSink if the DiagnosticSink is set. -/// This function blocks till it can get the lock on the global DiagnosticSink and is not -/// signal-safe. Call `try_emit_finding` from a signal handler instead. -pub(crate) fn emit_finding(description: &str, signature: &str) { - let guard = EXECUTE_CONTEXT.lock(); - let token = - guard.as_ref().expect("emit_finding should only be called when a test is executing"); - DIAGNOSTIC_SINK - .lock() - .as_ref() - .expect("diagnostic sink should be present when a test is executing") - .emit_finding(token, description, signature); -} - -/// Emits a finding into the DiagnosticSink if the DiagnosticSink is set, and we are in the Execute -/// callback context. It only tries once to get the lock. The return value indicates if the finding -/// was successfully emitted. -/// -/// This function return false if: -/// - 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; - }; - let Some(sink) = diagnostic_guard.as_ref() else { - return false; - }; - let Some(execution_guard) = EXECUTE_CONTEXT.try_lock() else { - return false; - }; - let Some(token) = execution_guard.as_ref() else { - return false; - }; - sink.emit_finding(token, description, signature); - true -} - -// We double-box the input because `GenericCorpusValue` is a fat pointer (`Box<dyn Any>`), -// 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 -// 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. -fn pack_input(input: GenericCorpusValue) -> engine_ffi::FuzzTestInputHandle { - let ptr = Box::into_raw(Box::new(input)); - engine_ffi::FuzzTestInputHandle(ptr as usize) -} - -/// A guard that manages the global `EXECUTE_CONTEXT` state, setting it to `Some` on creation, -/// and resetting to `None` on drop. -#[must_use = "the execution guard must be held for the duration of the test execution to record findings and crashes"] -struct ExecutionGuard; - -impl ExecutionGuard { - /// Enters the execution context by setting `EXECUTE_CONTEXT`. - /// - /// # Safety - /// The caller must ensure we are in a valid state to create an `ExecuteContext`. - unsafe fn enter() -> Self { - *EXECUTE_CONTEXT.lock() = Some(unsafe { ExecuteContext::new() }); - Self - } -} - -impl Drop for ExecutionGuard { - fn drop(&mut self) { - *EXECUTE_CONTEXT.lock() = None; - } -} - +/// Drives one [`FuzzTest`] instance for the fuzzing engine. pub struct RustFuzzTestAdapter { fuzz_test: BoxedFuzzTest, } impl RustFuzzTestAdapter { - pub fn set_up_coverage_domains(&self, registry: &mut CoverageDomainRegistry) { + /// 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) + } +} + +impl Adapter for RustFuzzTestAdapter { + type Input = GenericCorpusValue; + // Reported to the engine in its `Debug` format, which for `anyhow::Error` is the message + // followed by the chain of causes. + type Error = anyhow::Error; + + fn set_up_coverage_domains(&self, registry: &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 + fn random_seed_input(&self) -> anyhow::Result<GenericCorpusValue> { + self.with_domains(|domains| domains.init(&mut rand::rng())) } - 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)); - } - } - } - - 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; - } - - sink.emit(pack_input(mutant)); - } - - pub fn cross_over( + fn mutate( &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); + shrink: bool, + ) -> anyhow::Result<GenericCorpusValue> { + let mut mutant = origin.clone(); + self.with_domains(|domains| domains.mutate(&mut mutant, &mut rand::rng(), shrink))?; + Ok(mutant) } - pub fn execute(&self, input: &GenericCorpusValue, sink: &mut FeedbackSink) { + fn execute( + &self, + cx: &ExecuteContext<'_>, + input: &GenericCorpusValue, + feedback: &FeedbackSink, + ) { // TODO(the-shank): modify this in order to support persistent mode and batch execution. static CLEAR_STARTUP_COVERAGE: AtomicBool = AtomicBool::new(true); // Called even in unguided mode: besides clearing coverage, this frees the SanCov state of // threads that exited during the previous execution, which would otherwise accumulate. coverage::prepare_coverage(CLEAR_STARTUP_COVERAGE.swap(false, Ordering::AcqRel)); - // SAFETY: We are currently in the `execute` callback of `RustFuzzTestAdapter`. - let _guard = unsafe { ExecutionGuard::enter() }; - let result = self.fuzz_test.execute(input); if !options::get_fuzztest_options().unguided { coverage::post_process_coverage(false); - sink.emit_sancov_features(); + feedback.emit_sancov_features(); } if !result { // TODO(the-shank): the signature should be different for different panics. Currently, // all test failures due to panics are reported with the same signature. - emit_finding("Property function ran but crashed.", "Unwinding panic"); + cx.emit_finding("Property function ran but crashed.", "Unwinding panic"); } } - 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)); - } - } + fn serialize_input(&self, input: &GenericCorpusValue) -> anyhow::Result<Vec<u8>> { + self.with_domains(|domains| domains.serialize_corpus(input)) } - 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)); - } - } - } - - 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 - // `deserialize_input_content_callback` (or `emit` in `InputSink`) and has - // not been freed yet. - unsafe { - let _ = Box::from_raw(input.0 as *mut GenericCorpusValue); - } - } + fn deserialize_input(&self, content: &[u8]) -> anyhow::Result<GenericCorpusValue> { + self.with_domains(|domains| domains.parse_corpus(content)) } } +/// 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()); - } - - // Replaces "::" with "." to avoid parsing issues in Centipede. Centipede uses ":" as a - // separator in CENTIPEDE_RUNNER_FLAGS and its parser replaces all ":" with "\0", which would - // truncate Rust paths. - pub fn get_test_name(&self, sink: &mut BytesSink) { - let name = self.test_name.replace("::", "."); - sink.emit(name.as_bytes()); - } - - pub fn construct_adapter(&self) -> RustFuzzTestAdapter { - let fuzz_test = (self.fuzz_test_factory)(); - RustFuzzTestAdapter { fuzz_test } - } - + /// Constructs a new [`BoxedFuzzTest`] instance for this test. pub fn construct_fuzz_test(&self) -> BoxedFuzzTest { (self.fuzz_test_factory)() } } -/// # Safety -/// -/// The caller must ensure that: -/// * `ctx` is a valid pointer to the `RustFuzzTestAdapterManager` passed during initialization. -/// * `sink` is a valid pointer to a `FuzzTestBytesSink` whose lifetime extends for the duration of -/// this call. -pub unsafe extern "C" fn get_binary_id_callback( - ctx: *mut engine_ffi::FuzzTestAdapterManagerCtx, - sink: *const engine_ffi::FuzzTestBytesSink, -) { - // SAFETY: The engine guarantees `ctx` is a valid pointer to the `RustFuzzTestAdapterManager` - // passed during initialization. - let manager = unsafe { &*(ctx as *const RustFuzzTestAdapterManager) }; - // SAFETY: The engine guarantees `sink` is a valid pointer to a `FuzzTestBytesSink` - // whose lifetime extends for the duration of this call. - let mut safe_sink = unsafe { BytesSink::from_raw(sink) }; - manager.get_binary_id(&mut safe_sink); +fn binary_id_from_arg(argv0: Option<OsString>) -> Vec<u8> { + let argv0 = argv0.unwrap_or_default(); + let file_name = Path::new(&argv0).file_name().unwrap_or_default(); + file_name.as_encoded_bytes().to_vec() } -/// # Safety -/// -/// The caller must ensure that: -/// * `ctx` is a valid pointer to the `RustFuzzTestAdapterManager` passed during initialization. -/// * `sink` is a valid pointer to a `FuzzTestBytesSink` whose lifetime extends for the duration of -/// this call. -pub unsafe extern "C" fn get_test_name_callback( - ctx: *mut engine_ffi::FuzzTestAdapterManagerCtx, - sink: *const engine_ffi::FuzzTestBytesSink, -) { - // SAFETY: The engine guarantees `ctx` is a valid pointer to the `RustFuzzTestAdapterManager` - // passed during initialization. - let manager = unsafe { &*(ctx as *const RustFuzzTestAdapterManager) }; - // SAFETY: The engine guarantees `sink` is a valid pointer to a `FuzzTestBytesSink` - // whose lifetime extends for the duration of this call. - let mut safe_sink = unsafe { BytesSink::from_raw(sink) }; - manager.get_test_name(&mut safe_sink); -} +impl AdapterManager for RustFuzzTestAdapterManager { + type Adapter = RustFuzzTestAdapter; -/// # Safety -/// -/// The caller must ensure that: -/// * `ctx` is a valid pointer to the `RustFuzzTestAdapterManager` passed during initialization. -/// * `diagnostic_sink` is a valid pointer to a `FuzzTestDiagnosticSink` whose lifetime extends -/// until `FreeCtx` is called on the adapter. -/// * `adapter_out` is a valid pointer to write the output `FuzzTestAdapter`. -pub unsafe extern "C" fn construct_adapter_callback( - ctx: *mut engine_ffi::FuzzTestAdapterManagerCtx, - diagnostic_sink: *const engine_ffi::FuzzTestDiagnosticSink, - adapter_out: *mut engine_ffi::FuzzTestAdapter, -) { - // SAFETY: The engine guarantees `ctx` is a valid pointer to the `RustFuzzTestAdapterManager` - // passed during initialization. - let manager = unsafe { &*(ctx as *const RustFuzzTestAdapterManager) }; + fn binary_id(&self) -> Vec<u8> { + // 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. + binary_id_from_arg(env::args_os().next()) + } - // SAFETY: The engine guarantees `diagnostic_sink` is a valid pointer to a - // `FuzzTestDiagnosticSink` whose lifetime extends until `FreeCtx` is called on the adapter. - let safe_sink = unsafe { DiagnosticSink::from_raw(diagnostic_sink) }; + // Replaces "::" with "." to avoid parsing issues in Centipede. Centipede uses ":" as a + // separator in CENTIPEDE_RUNNER_FLAGS and its parser replaces all ":" with "\0", which would + // truncate Rust paths. + fn test_name(&self) -> String { + self.test_name.replace("::", ".") + } - set_diagnostic_sink(safe_sink); - - // NOTE: `safe_sink` is not passed to `construct_adapter` or stored in `RustFuzzTestAdapter`. - // Instead, it is maintained in the global `DIAGNOSTIC_SINK` mutex via `set_diagnostic_sink`. - // This is necessary because C callbacks (e.g., sanitizer hooks in `crash_handler.rs`) do not - // have access to the adapter `self` pointer and must rely on a global lookup to report crashes. - let adapter = manager.construct_adapter(); - let boxed_adapter = Box::new(adapter); - // SAFETY: The engine guarantees `adapter_out` is a valid pointer to write the output adapter. - // The returned raw pointer `ctx` will be managed and eventually freed by `free_ctx_callback`. - unsafe { - *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), - get_random_seed_input: Some(get_random_seed_input_callback), - mutate: Some(mutate_callback), - cross_over: Some(cross_over_callback), - 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), - free_input: Some(free_input_callback), - free_ctx: Some(free_ctx_callback), - }; + fn construct_adapter(&self) -> RustFuzzTestAdapter { + RustFuzzTestAdapter { fuzz_test: self.construct_fuzz_test() } } } -/// # Safety +/// Runs `fuzztest` locally with random mutations for a short fixed duration. /// -/// The caller must ensure that: -/// * `ctx` is a valid pointer to the `RustFuzzTestAdapter` created by `construct_adapter_callback`. -/// * `registry` is a valid pointer to `FuzzTestCoverageDomainRegistry`. -pub unsafe extern "C" fn set_up_coverage_domains_callback( - ctx: *mut engine_ffi::FuzzTestAdapterCtx, - registry: *const engine_ffi::FuzzTestCoverageDomainRegistry, -) { - // 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 `registry` is a valid pointer to - // `FuzzTestCoverageDomainRegistry`. - let mut registry = unsafe { CoverageDomainRegistry::from_raw(registry) }; - adapter.set_up_coverage_domains(&mut registry); -} - -/// # Safety +/// # Panics /// -/// 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, -) { - // 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_random_seed_input(&mut safe_sink); -} - -/// # Safety -/// -/// 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. -/// * `sink` is a valid pointer to `FuzzTestInputSink`. -pub unsafe extern "C" fn mutate_callback( - ctx: *mut engine_ffi::FuzzTestAdapterCtx, - origin: engine_ffi::FuzzTestInputHandle, - shrink: c_int, - 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 `sink` is a valid pointer to `FuzzTestInputSink`. - let mut safe_sink = unsafe { InputSink::from_raw(sink) }; - adapter.mutate(origin_ref, shrink != 0, &mut safe_sink); -} - -/// # Safety -/// -/// 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`. -pub unsafe extern "C" fn execute_callback( - ctx: *mut engine_ffi::FuzzTestAdapterCtx, - input: engine_ffi::FuzzTestInputHandle, - sink: *const engine_ffi::FuzzTestFeedbackSink, -) { - // 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 `FuzzTestFeedbackSink`. - let mut safe_sink = unsafe { FeedbackSink::from_raw(sink) }; - - adapter.execute(input_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 `FuzzTestBytesSink`. -pub unsafe extern "C" fn serialize_input_content_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_content(input_ref, &mut safe_sink); -} - -/// # Safety -/// -/// The caller must ensure that: -/// * `ctx` is a valid pointer to the `RustFuzzTestAdapter` created by `construct_adapter_callback`. -/// * `content` is a valid pointer to `FuzzTestBytesView` containing serialized input content. -/// * `sink` is a valid pointer to `FuzzTestInputSink`. -pub unsafe extern "C" fn deserialize_input_content_callback( - ctx: *mut engine_ffi::FuzzTestAdapterCtx, - content: *const engine_ffi::FuzzTestBytesView, - 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 `content` is a valid pointer to `FuzzTestBytesView` - // containing serialized input content. - let bytes = unsafe { &*(*content).to_bytes() }; - // SAFETY: The engine guarantees `sink` is a valid pointer to `FuzzTestInputSink`. - let mut safe_sink = unsafe { InputSink::from_raw(sink) }; - adapter.deserialize_input_content(bytes, &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 `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, - 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) }; - adapter.free_input(input); -} - -/// # Safety -/// -/// The caller must ensure that: -/// * `ctx` is a valid pointer to the `RustFuzzTestAdapter` created by `construct_adapter_callback`. -pub unsafe extern "C" fn free_ctx_callback(ctx: *mut engine_ffi::FuzzTestAdapterCtx) { - if !ctx.is_null() { - // SAFETY: The engine guarantees `ctx` is a valid pointer to the `RustFuzzTestAdapter` - // created by `construct_adapter_callback`. - let ptr = ctx as *mut RustFuzzTestAdapter; - drop(unsafe { Box::from_raw(ptr) }); - - clear_diagnostic_sink(); - } -} - +/// 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); } } -pub enum WorkerStatus { - Success, - Failure, -} - /// 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 [`engine::run_worker_if_requested`]. /// - 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 [`RunOutcome::Success`], so that the harness continues with the next +/// test, and exits the process with status 1 on [`RunOutcome::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 ::engine::run_worker_if_requested(&manager) { + // The harness continues with the next test. + Some(RunOutcome::Success) => return, + Some(RunOutcome::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,52 +236,153 @@ } } -fn make_ffi_manager(manager: &RustFuzzTestAdapterManager) -> engine_ffi::FuzzTestAdapterManager { - let ctx = - manager as *const RustFuzzTestAdapterManager as *mut engine_ffi::FuzzTestAdapterManagerCtx; - - engine_ffi::FuzzTestAdapterManager { - ctx, - get_binary_id: Some(get_binary_id_callback), - get_test_name: Some(get_test_name_callback), - construct_adapter: Some(construct_adapter_callback), +/// Runs the controller and panics if it reports a failure, which fails the test in the harness. +fn run_controller(manager: &RustFuzzTestAdapterManager, args: CentipedeArgs) { + if ::engine::run_controller(manager, &args.to_byte_slices()) == RunOutcome::Failure { + panic!("FuzzTest controller reported failure"); } } -/// Attempts to run the fuzz test in Centipede worker mode using the FFI engine interface. +/// Replays every crash listed in `list_file`, with one controller run per crash ID. /// -/// This function constructs a C-compatible [`engine_ffi::FuzzTestAdapterManager`] wrapping -/// the given `manager` with required callback function pointers (`get_binary_id_callback`, -/// `get_test_name_callback`, `construct_adapter_callback`), and invokes -/// [`engine_ffi::FuzzTestWorkerMaybeRun`]. -/// -/// # 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. -fn maybe_run_as_worker(manager: &RustFuzzTestAdapterManager) -> Option<WorkerStatus> { - let ffi_manager = make_ffi_manager(manager); - - // SAFETY: `manager` is a valid heap-allocated `RustFuzzTestAdapterManager`, - // and `ffi_manager` contains valid C-compatible function pointer callbacks. - let status = unsafe { engine_ffi::FuzzTestWorkerMaybeRun(&ffi_manager) }; - - match status { - engine_ffi::FuzzTestWorkerStatus::Success => Some(WorkerStatus::Success), - engine_ffi::FuzzTestWorkerStatus::Failure => Some(WorkerStatus::Failure), - engine_ffi::FuzzTestWorkerStatus::NotRequired => None, +/// 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 outcome is ignored: replaying a crash is expected to report a failure, and + // the remaining crashes should still be replayed. + let _ = ::engine::run_controller(manager, &replay_args.to_byte_slices()); + } + 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 run_standalone_mode( - manager: &RustFuzzTestAdapterManager, - centipede_args: CentipedeArgs, -) -> engine_ffi::FuzzTestControllerStatus { - let ffi_manager = make_ffi_manager(manager); +#[cfg(test)] +mod tests { + use super::*; + use googletest::prelude::*; + use rand::Rng; + #[cfg(unix)] + use std::os::unix::ffi::OsStringExt; + use std::sync::{Arc, Mutex}; + use tempfile::TempDir; - // SAFETY: `ffi_manager` wraps `manager` which is guaranteed to be alive. `centipede_args` is - // alive until the end of this function, since we have the ownership, ensuring that the - // pointers passed to `FuzzTestControllerRun` remain valid. - unsafe { engine_ffi::FuzzTestControllerRun(&ffi_manager, ¢ipede_args.as_bytes_views()) } + struct FakeDomain; + + impl GenericDomain for FakeDomain { + fn init(&mut self, _rng: &mut dyn Rng) -> anyhow::Result<GenericCorpusValue> { + Ok(Box::new(())) + } + + fn mutate( + &mut self, + _corpus_value: &mut GenericCorpusValue, + _rng: &mut dyn Rng, + _only_shrink: bool, + ) -> anyhow::Result<()> { + Ok(()) + } + + fn parse_corpus(&self, _data: &[u8]) -> anyhow::Result<GenericCorpusValue> { + Ok(Box::new(())) + } + + fn serialize_corpus(&self, _val: &GenericCorpusValue) -> anyhow::Result<Vec<u8>> { + Ok(Vec::new()) + } + } + + struct FakeFuzzTest { + succeeds: bool, + } + + impl FuzzTest for FakeFuzzTest { + fn name(&self) -> &'static str { + "fake_test" + } + + fn activate(&mut self) {} + + fn mutate(&mut self) {} + + fn execute(&self, _args: &GenericCorpusValue) -> bool { + self.succeeds + } + + fn domains(&self) -> Arc<Mutex<dyn GenericDomain>> { + Arc::new(Mutex::new(FakeDomain)) + } + } + + fn make_succeeding_test() -> BoxedFuzzTest { + Box::new(FakeFuzzTest { succeeds: true }) + } + + #[gtest] + fn binary_id_from_arg_strips_directory_and_handles_missing_or_empty() { + expect_eq!(binary_id_from_arg(Some("/usr/local/bin/my_fuzzer".into())), b"my_fuzzer"); + expect_eq!(binary_id_from_arg(None), b""); + expect_eq!(binary_id_from_arg(Some("".into())), b""); + } + + #[cfg(unix)] + #[gtest] + fn binary_id_from_arg_preserves_non_utf8_bytes() { + let arg = OsString::from_vec(b"/tmp/fuzz_\xff_bin".to_vec()); + expect_eq!(binary_id_from_arg(Some(arg)), b"fuzz_\xff_bin"); + } + + #[gtest] + fn adapter_manager_replaces_double_colons_in_test_name() { + let manager = RustFuzzTestAdapterManager { + test_name: "crate::sub::prop", + fuzz_test_factory: make_succeeding_test, + }; + expect_eq!(manager.test_name(), "crate.sub.prop"); + } + + #[gtest] + fn replay_listed_crashes_ignores_missing_list_file() -> Result<()> { + let dir = TempDir::new()?; + let missing = dir.path().join("missing_crashes.txt"); + let manager = RustFuzzTestAdapterManager { + test_name: "crate::sub::prop", + fuzz_test_factory: make_succeeding_test, + }; + + replay_listed_crashes(&manager, &missing); + Ok(()) + } + + #[gtest] + fn run_smoke_test_succeeds_when_property_holds() { + run_smoke_test(&FakeFuzzTest { succeeds: true }); + } + + #[gtest] + #[should_panic(expected = "the property function failed")] + fn run_smoke_test_panics_when_property_fails() { + run_smoke_test(&FakeFuzzTest { succeeds: false }); + } }