Print counterexample report on sanitizer crashes in Rust fuzz smoke tests. PiperOrigin-RevId: 1020487017
diff --git a/fuzztest/internal/runtime.cc b/fuzztest/internal/runtime.cc index 2d4c296..a8638e2 100644 --- a/fuzztest/internal/runtime.cc +++ b/fuzztest/internal/runtime.cc
@@ -88,12 +88,6 @@ #include "./fuzztest/internal/serialization.h" #include "./fuzztest/internal/status.h" -#if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \ - defined(THREAD_SANITIZER) -#define FUZZTEST_HAS_SANITIZER -#include <sanitizer/common_interface_defs.h> -#endif - #ifndef TRAP_PERF inline constexpr int TRAP_PERF = 6; #endif @@ -800,14 +794,12 @@ } signal_out = out; -#if defined(FUZZTEST_HAS_SANITIZER) // An ASan failure might come without a signal. // Eg a divide by zero is intercepted by ASan and it terminates the process // after printing its output. This handler helps us print our output - // afterwards. - __sanitizer_set_death_callback( - [](auto...) { Runtime::instance().PrintReport(&signal_out_sink); }); -#endif + // afterwards. Does nothing in builds without a sanitizer. + FuzzTestSetSanitizerDeathCallback( + [] { Runtime::instance().PrintReport(&signal_out_sink); }); if (const char* disabled = std::getenv("FUZZTEST_DISABLE_SIGNAL_HANDLERS"); disabled != nullptr) {
diff --git a/fuzztest/internal/sanitizer_interface.cc b/fuzztest/internal/sanitizer_interface.cc index 3b6a8d6..d0b2adc 100644 --- a/fuzztest/internal/sanitizer_interface.cc +++ b/fuzztest/internal/sanitizer_interface.cc
@@ -30,6 +30,7 @@ #include <cstddef> #include <cstdint> #include <cstring> +#include <mutex> // IWYU pragma: keep #include <optional> #include "absl/base/attributes.h" @@ -51,11 +52,19 @@ #include <sanitizer/tsan_interface.h> #endif +#if defined(ABSL_HAVE_ADDRESS_SANITIZER) || \ + defined(ABSL_HAVE_MEMORY_SANITIZER) || defined(ABSL_HAVE_THREAD_SANITIZER) +#define FUZZTEST_HAS_SANITIZER +#include <sanitizer/common_interface_defs.h> +#endif + namespace fuzztest::internal { std::atomic<FuzzTestSanitizerErrorSummaryCallback> sanitizer_error_summary_callback{nullptr}; +std::atomic<FuzzTestSanitizerDeathCallback> sanitizer_death_callback{nullptr}; + namespace { constexpr int kMaxStackFrames = 64; @@ -511,6 +520,11 @@ callback(crash_type.data(), crash_type.size()); } +ABSL_ATTRIBUTE_NO_SANITIZE_CFI void InvokeSanitizerDeathCallback( + FuzzTestSanitizerDeathCallback callback) { + callback(); +} + } // namespace fuzztest::internal // clang-format off @@ -542,6 +556,24 @@ callback, std::memory_order_relaxed); } +extern "C" void FuzzTestSetSanitizerDeathCallback( + [[maybe_unused]] FuzzTestSanitizerDeathCallback callback) { +#if defined(FUZZTEST_HAS_SANITIZER) + fuzztest::internal::sanitizer_death_callback.store(callback, + std::memory_order_release); + static std::once_flag register_once; // NOLINT(build/c++11) + std::call_once(register_once, [] { // NOLINT(build/c++11) + __sanitizer_set_death_callback([] { + if (const auto cb = fuzztest::internal::sanitizer_death_callback.load( + std::memory_order_acquire); + cb != nullptr) { + fuzztest::internal::InvokeSanitizerDeathCallback(cb); + } + }); + }); +#endif +} + extern "C" size_t FuzzTestFormatCrashDescription( const char* prefix, size_t prefix_size, const char* crash_type, size_t crash_type_size, const char* signature, size_t signature_size,
diff --git a/fuzztest/internal/sanitizer_interface.h b/fuzztest/internal/sanitizer_interface.h index 0295a63..6e40bab 100644 --- a/fuzztest/internal/sanitizer_interface.h +++ b/fuzztest/internal/sanitizer_interface.h
@@ -38,6 +38,21 @@ void FuzzTestSetSanitizerErrorSummaryCallback( FuzzTestSanitizerErrorSummaryCallback callback); +using FuzzTestSanitizerDeathCallback = void (*)(); + +// Registers `callback` to be invoked by the sanitizer runtime right before it +// terminates the process (see `__sanitizer_set_death_callback()`), replacing +// any previously registered death callback (or unregistering it if `callback` +// is null). +// +// Thread-safe: may be called concurrently from multiple threads and +// concurrently with a sanitizer crash on another thread (unlike +// `__sanitizer_set_death_callback()`, which is unsynchronized). +// +// Does nothing if the binary is not built with ASan, MSan, or TSan, so callers +// do not need to check for a sanitizer build themselves. +void FuzzTestSetSanitizerDeathCallback(FuzzTestSanitizerDeathCallback callback); + // Formats a crash description into `(out, out_size)`: writes // `<prefix><crash_type>` and, only if `signature_size > 0`, the metadata line // `\nCRASH_SIGNATURE=<signature>`. The output is truncated to `out_size` bytes
diff --git a/fuzztest/internal/sanitizer_interface_test.cc b/fuzztest/internal/sanitizer_interface_test.cc index bc69f66..714f9e8 100644 --- a/fuzztest/internal/sanitizer_interface_test.cc +++ b/fuzztest/internal/sanitizer_interface_test.cc
@@ -15,8 +15,11 @@ #include "./fuzztest/internal/sanitizer_interface.h" #include <cstddef> +#include <cstdio> +#include <cstdlib> // IWYU pragma: keep #include <functional> #include <string> +#include <thread> // NOLINT #include <vector> #include "gmock/gmock.h" @@ -26,17 +29,10 @@ #include "absl/base/optimization.h" #include "absl/status/status.h" #include "absl/status/statusor.h" +#include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" -#if defined(ABSL_HAVE_THREAD_SANITIZER) -#include <cstdio> -#include <cstdlib> -#include <thread> // NOLINT - -#include "absl/strings/str_format.h" -#endif - namespace fuzztest::internal { std::vector<std::string> CollectTopAppFunctions(int max_frames) { @@ -359,9 +355,11 @@ namespace fuzztest::internal { namespace { +using ::testing::AllOf; using ::testing::ElementsAre; using ::testing::HasSubstr; using ::testing::IsEmpty; +using ::testing::Not; TEST(ParseCrashTypeFromSanitizerSummaryTest, ExtractsCrashTypeWhenItIsTheOnlyToken) { @@ -632,6 +630,22 @@ FuzzTestSetSanitizerErrorSummaryCallback(nullptr); } +TEST(FuzzTestSanitizerDeathCallbackTest, ConcurrentRegistrationIsThreadSafe) { + std::thread t1([] { + for (int i = 0; i < 100; ++i) { + FuzzTestSetSanitizerDeathCallback([] {}); + } + }); + std::thread t2([] { + for (int i = 0; i < 100; ++i) { + FuzzTestSetSanitizerDeathCallback(nullptr); + } + }); + t1.join(); + t2.join(); + FuzzTestSetSanitizerDeathCallback(nullptr); +} + absl::string_view FormatCrashDescription(absl::string_view prefix, absl::string_view crash_type, absl::string_view signature, @@ -827,5 +841,50 @@ } #endif // defined(ABSL_HAVE_THREAD_SANITIZER) +ABSL_ATTRIBUTE_NOINLINE void TriggerSanitizerCrash() { +#if defined(ABSL_HAVE_ADDRESS_SANITIZER) + int* volatile p = new int(0); + delete p; + volatile int x = *p; + (void)x; +#elif defined(ABSL_HAVE_MEMORY_SANITIZER) + int* volatile p = new int; + if (*p != 0) { + std::_Exit(0); + } + delete p; +#elif defined(ABSL_HAVE_THREAD_SANITIZER) + volatile int shared = 0; + std::thread t1(test_app::RaceThreadA, &shared); + std::thread t2(test_app::RaceThreadB, &shared); + t1.join(); + t2.join(); + std::exit(0); +#endif +} + +TEST(FuzzTestSanitizerDeathCallbackDeathTest, + InvokesLatestRegisteredCallbackOnSanitizerCrash) { +#if !defined(ABSL_HAVE_ADDRESS_SANITIZER) && \ + !defined(ABSL_HAVE_MEMORY_SANITIZER) && \ + !defined(ABSL_HAVE_THREAD_SANITIZER) + GTEST_SKIP() << "Requires ASan, MSan, or TSan."; +#endif + EXPECT_DEATH( + { + FuzzTestSetSanitizerDeathCallback([] { + absl::FPrintF(stderr, "FIRST_DEATH_CALLBACK_INVOKED\n"); + std::fflush(stderr); + }); + FuzzTestSetSanitizerDeathCallback([] { + absl::FPrintF(stderr, "SECOND_DEATH_CALLBACK_INVOKED\n"); + std::fflush(stderr); + }); + TriggerSanitizerCrash(); + }, + AllOf(HasSubstr("SECOND_DEATH_CALLBACK_INVOKED"), + Not(HasSubstr("FIRST_DEATH_CALLBACK_INVOKED")))); +} + } // namespace } // namespace fuzztest::internal
diff --git a/rust/README.md b/rust/README.md index cd22591..2de76e7 100644 --- a/rust/README.md +++ b/rust/README.md
@@ -61,8 +61,9 @@ variable: ```bash -# Run all fuzztests in smoke-test mode. -FUZZTEST_LIB_PATH="$HOME/.local/lib" cargo test __fuzztest_mod__ +# Run all fuzztests in smoke-test mode, one at a time: FuzzTest keeps +# process-wide state about the fuzz test that is currently running. +FUZZTEST_LIB_PATH="$HOME/.local/lib" cargo test __fuzztest_mod__ -- --test-threads=1 ``` // TODO(the-shank): add example of more commands for fuzzing, along with sample
diff --git a/rust/e2e_tests/test_utils.rs b/rust/e2e_tests/test_utils.rs index 44caf04..7d8a0e9 100644 --- a/rust/e2e_tests/test_utils.rs +++ b/rust/e2e_tests/test_utils.rs
@@ -47,6 +47,24 @@ } } +const BAZEL_TEST_ENV_VARS: &[&str] = &[ + "TEST_DIAGNOSTICS_OUTPUT_DIR", + "TEST_INFRASTRUCTURE_FAILURE_FILE", + "TEST_LOGSPLITTER_OUTPUT_FILE", + "TEST_PREMATURE_EXIT_FILE", + "TEST_RANDOM_SEED", + "TEST_RUN_NUMBER", + "TEST_SHARD_INDEX", + "TEST_SHARD_STATUS_FILE", + "TEST_TOTAL_SHARDS", + "TEST_UNDECLARED_OUTPUTS_ANNOTATIONS_DIR", + "TEST_UNDECLARED_OUTPUTS_DIR", + "TEST_WARNINGS_OUTPUT_FILE", + "TESTBRIDGE_TEST_ONLY", + "GTEST_OUTPUT", + "XML_OUTPUT_FILE", +]; + /// Returns stderr of a Centipede process with `args` that is expected to terminate through some /// internal flag. e.g. `--exit_on_crash` or `--stop_after`. /// @@ -56,22 +74,7 @@ /// `--persistent_mode=0`, and `--env_diff_for_binaries`. pub fn run_centipede_with_args_expect_termination(fixture: &EnvVars, args: &[&str]) -> String { // Disable interference from Bazel environment variables. - let env_diff = [ - "-TEST_DIAGNOSTICS_OUTPUT_DIR", - "-TEST_INFRASTRUCTURE_FAILURE_FILE", - "-TEST_LOGSPLITTER_OUTPUT_FILE", - "-TEST_PREMATURE_EXIT_FILE", - "-TEST_RANDOM_SEED", - "-TEST_RUN_NUMBER", - "-TEST_SHARD_INDEX", - "-TEST_SHARD_STATUS_FILE", - "-TEST_TOTAL_SHARDS", - "-TEST_UNDECLARED_OUTPUTS_ANNOTATIONS_DIR", - "-TEST_UNDECLARED_OUTPUTS_DIR", - "-TEST_WARNINGS_OUTPUT_FILE", - "-GTEST_OUTPUT", - "-XML_OUTPUT_FILE", - ]; + let env_diff: Vec<String> = BAZEL_TEST_ENV_VARS.iter().map(|var| format!("-{var}")).collect(); let process = Command::new(&fixture.centipede_path) .arg("--populate_binary_info=0") .arg(format!("--env_diff_for_binaries={}", env_diff.join(","))) @@ -91,7 +94,11 @@ args: &[&str], envs: &[(&str, &str)], ) -> String { - let process = Command::new(fixture.binary_path("fuzztest_main")) + let mut cmd = Command::new(fixture.binary_path("fuzztest_main")); + for var in BAZEL_TEST_ENV_VARS { + cmd.env_remove(var); + } + let process = cmd .args(args) .env("FUZZTEST_PRINT_SUBPROCESS_LOG", "true") .env("FUZZTEST_CENTIPEDE_BINARY_PATH", &fixture.centipede_path)
diff --git a/rust/e2e_tests/testdata/fuzz_tests.rs b/rust/e2e_tests/testdata/fuzz_tests.rs index e725ff9..f8b30fd 100644 --- a/rust/e2e_tests/testdata/fuzz_tests.rs +++ b/rust/e2e_tests/testdata/fuzz_tests.rs
@@ -124,27 +124,46 @@ panic!("Bug found!"); } } +// Triggers a use-after-free on every input, so that tests using it do not depend on the fuzzer +// generating a particular input. Only run this under ASan. #[fuzztest(a = ByteVectorDomain::new())] fn use_after_free_asan_death_test(mut a: Vec<u8>) { - if !a.is_empty() && a[0] == 123 { + // Push a byte so that the vector always owns a heap allocation. + a.push(0); + let ptr = a.as_mut_ptr(); + drop(a); + // Intentionally trigger a use-after-free bug for ASAN to detect. + unsafe { + *(std::hint::black_box(ptr)) = 1; + } +} + +// Triggers a use-after-free on a spawned thread on every input, to verify that the sanitizer death +// callback still finds the active execution context from another thread. Only run this under ASan. +#[fuzztest(a = ByteVectorDomain::new())] +fn spawned_thread_use_after_free_asan_death_test(mut a: Vec<u8>) { + let _ = std::thread::spawn(move || { + // Push a byte so that the vector always owns a heap allocation. + a.push(0); let ptr = a.as_mut_ptr(); drop(a); // Intentionally trigger a use-after-free bug for ASAN to detect. unsafe { *(std::hint::black_box(ptr)) = 1; } - } + }) + .join(); } -#[fuzztest(a = ByteVectorDomain::new())] -fn msan_death_test(a: Vec<u8>) { - if !a.is_empty() && a[0] == 123 { - // Intentionally trigger an uninitialized memory bug for MSAN to detect. - unsafe { - let x: MaybeUninit<i32> = MaybeUninit::uninit(); - let y = std::hint::black_box(x).assume_init(); - println!("y: {}", y); - } +// Reads uninitialized memory on every input, so that tests using it do not depend on the fuzzer +// generating a particular input. Only run this under MSan. +#[fuzztest(_a = ByteVectorDomain::new())] +fn msan_death_test(_a: Vec<u8>) { + // Intentionally trigger an uninitialized memory bug for MSAN to detect. + unsafe { + let x: MaybeUninit<i32> = MaybeUninit::uninit(); + let y = std::hint::black_box(x).assume_init(); + println!("y: {}", y); } }
diff --git a/rust/e2e_tests/worker_with_centipede_sanitizer_test.rs b/rust/e2e_tests/worker_with_centipede_sanitizer_test.rs index 097c94b..fb0a6cb 100644 --- a/rust/e2e_tests/worker_with_centipede_sanitizer_test.rs +++ b/rust/e2e_tests/worker_with_centipede_sanitizer_test.rs
@@ -54,6 +54,46 @@ expect_that!(stderr, matchers::contains_regex("Failure[ \t]*: heap-use-after-free")); } +#[gtest] +#[cfg(sanitize = "address")] +fn smoke_test_mode_reports_use_after_free_with_asan(fixture: &EnvVars) { + let args = ["__fuzztest_mod__use_after_free_asan_death_test::use_after_free_asan_death_test"]; + + let stderr = + test_utils::run_target_binary_with_args_and_env_expect_termination(fixture, &args, &[]); + + expect_that!(stderr, matchers::contains_substring("heap-use-after-free")); + expect_that!(stderr, matchers::contains_substring("=== BUG FOUND!")); + expect_that!( + stderr, + matchers::contains_substring( + "Counterexample found for fuzztest_main::__fuzztest_mod__use_after_free_asan_death_test::use_after_free_asan_death_test." + ) + ); + expect_that!(stderr, matchers::contains_substring("The test fails with input:\nargument 0: [")); +} + +#[gtest] +#[cfg(sanitize = "address")] +fn smoke_test_mode_reports_use_after_free_on_spawned_thread_with_asan(fixture: &EnvVars) { + let args = [ + "__fuzztest_mod__spawned_thread_use_after_free_asan_death_test::spawned_thread_use_after_free_asan_death_test", + ]; + + let stderr = + test_utils::run_target_binary_with_args_and_env_expect_termination(fixture, &args, &[]); + + expect_that!(stderr, matchers::contains_substring("heap-use-after-free")); + expect_that!(stderr, matchers::contains_substring("=== BUG FOUND!")); + expect_that!( + stderr, + matchers::contains_substring( + "Counterexample found for fuzztest_main::__fuzztest_mod__spawned_thread_use_after_free_asan_death_test::spawned_thread_use_after_free_asan_death_test." + ) + ); + expect_that!(stderr, matchers::contains_substring("The test fails with input:\nargument 0: [")); +} + // TODO(yamilmorales): Enable this test on presubmit with --config=msan. #[gtest] #[cfg(sanitize = "memory")] @@ -85,3 +125,22 @@ expect_that!(stderr, matchers::contains_regex("Failure[ \t]*: use-of-uninitialized-value")); } + +#[gtest] +#[cfg(sanitize = "memory")] +fn smoke_test_mode_reports_uninitialized_value_with_msan(fixture: &EnvVars) { + let args = ["__fuzztest_mod__msan_death_test::msan_death_test"]; + + let stderr = + test_utils::run_target_binary_with_args_and_env_expect_termination(fixture, &args, &[]); + + expect_that!(stderr, matchers::contains_substring("use-of-uninitialized-value")); + expect_that!(stderr, matchers::contains_substring("=== BUG FOUND!")); + expect_that!( + stderr, + matchers::contains_substring( + "Counterexample found for fuzztest_main::__fuzztest_mod__msan_death_test::msan_death_test." + ) + ); + expect_that!(stderr, matchers::contains_substring("The test fails with input:\nargument 0: [")); +}
diff --git a/rust/fuzztest_macro/src/helpers/fuzztest_domain.rs b/rust/fuzztest_macro/src/helpers/fuzztest_domain.rs index f74a152..ef99be0 100644 --- a/rust/fuzztest_macro/src/helpers/fuzztest_domain.rs +++ b/rust/fuzztest_macro/src/helpers/fuzztest_domain.rs
@@ -58,7 +58,7 @@ parse_quote! { for <#user_value_lifetime_generic> #domain_gen: #crate_name::domains::Domain<UserValue<#user_value_lifetime_generic> = #ty > }); - where_clauses.predicates.push(parse_quote! { #domain_gen::CorpusValue: #crate_name::serde::Serialize + #crate_name::serde::de::DeserializeOwned + ::std::clone::Clone }); + where_clauses.predicates.push(parse_quote! { #domain_gen::CorpusValue: #crate_name::serde::Serialize + #crate_name::serde::de::DeserializeOwned + ::std::clone::Clone + ::std::marker::Send + ::std::marker::Sync }); field_names.push((*name).clone()); domain_field_types.push(domain_gen); } @@ -143,9 +143,9 @@ impl<T0, T1> ::fuzztest::domains::Domain for __FuzzTestTestFuzzStateWrapper<T0, T1> where for < 'user > T0: ::fuzztest::domains::Domain<UserValue< 'user > = &'user Vec<&'user i32> >, - T0::CorpusValue: ::fuzztest::serde::Serialize + ::fuzztest::serde::de::DeserializeOwned + ::std::clone::Clone, + T0::CorpusValue: ::fuzztest::serde::Serialize + ::fuzztest::serde::de::DeserializeOwned + ::std::clone::Clone + ::std::marker::Send + ::std::marker::Sync, for < 'user > T1: ::fuzztest::domains::Domain<UserValue< 'user > = std::string::String>, - T1::CorpusValue: ::fuzztest::serde::Serialize + ::fuzztest::serde::de::DeserializeOwned + ::std::clone::Clone { + T1::CorpusValue: ::fuzztest::serde::Serialize + ::fuzztest::serde::de::DeserializeOwned + ::std::clone::Clone + ::std::marker::Send + ::std::marker::Sync { type UserValue<'user> = __FuzzTestTestFuzzStateWrapper<T0::UserValue<'user>, T1::UserValue<'user> >; type CorpusValue = __FuzzTestTestFuzzStateWrapper<T0::CorpusValue, T1::CorpusValue>;
diff --git a/rust/fuzztest_macro/src/helpers/test_registration.rs b/rust/fuzztest_macro/src/helpers/test_registration.rs index adc9c20..fe29e19 100644 --- a/rust/fuzztest_macro/src/helpers/test_registration.rs +++ b/rust/fuzztest_macro/src/helpers/test_registration.rs
@@ -227,6 +227,19 @@ test_fn: #test_fn_type } + impl #impl_generics #fuzz_test_struct_name #ty_generics #where_clause { + fn try_get_user_value<'a>( + &self, + args: &'a #crate_name::domains::GenericCorpusValue, + ) -> ::std::option::Option< <#domain_struct_name #ty_generics as #crate_name::domains::Domain>::UserValue<'a> > { + use #crate_name::domains::Domain; + + let wrapper = args.downcast_ref::<#domain_struct_name<#(#corpus_generics),*>>()?; + let domain = self.domain.try_lock().ok()?; + domain.corpus_to_user_value(wrapper).ok() + } + } + impl #impl_generics #crate_name::internal::FuzzTest for #fuzz_test_struct_name #ty_generics #where_clause { fn name(&self) -> &'static str { #test_fn_name @@ -241,24 +254,18 @@ use #crate_name::domains::Domain; let wrapper = args - .downcast_ref::<#domain_struct_name<#(#corpus_generics),*>>() - .expect("Attempt to recover user value before testing failed."); + .downcast_ref::<#domain_struct_name<#(#corpus_generics),*>>() + .expect("Attempt to recover user value before testing failed."); - let get_user_value = || { - self.domain.lock() + let user_value = self.domain + .lock() .expect("Failed to acquire domain lock") .corpus_to_user_value(wrapper) - .expect("Failed to get user value from corpus value") - }; + .expect("Failed to get user value from corpus value"); - let user_value = get_user_value(); let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (self.test_fn)(#(user_value.#fuzz_test_domain_field_names),* ) )); if result.is_err() { - let user_value = get_user_value(); - self.print_finding_report( - &FUZZTEST_INFO, - &[#(::std::format!("{:?}", user_value.#fuzz_test_domain_field_names)),*], - ); + self.print_finding_report(args); } result.is_ok() @@ -266,10 +273,21 @@ fn domains(&self) -> std::sync::Arc<std::sync::Mutex<dyn #crate_name::domains::GenericDomain>> { std::sync::Arc::clone(&self.domain) as std::sync::Arc<std::sync::Mutex<dyn #crate_name::domains::GenericDomain>> } + fn print_finding_report(&self, args: &#crate_name::domains::GenericCorpusValue) { + // The report may be printed from a sanitizer death callback, so recovering the + // user value must neither block nor panic. + let ::std::option::Option::Some(user_value) = self.try_get_user_value(args) else { + return; + }; + #crate_name::internal::print_finding_report( + &FUZZTEST_INFO, + &[#(::std::format!("{:?}", user_value.#fuzz_test_domain_field_names)),*], + ); + } } - fn #fuzz_test_struct_factory_fn_name() -> #crate_name::internal::BoxedFuzzTest { - ::std::boxed::Box::new(#fuzztest_instance) + fn #fuzz_test_struct_factory_fn_name() -> ::std::sync::Arc<dyn #crate_name::internal::FuzzTest + ::std::marker::Send + ::std::marker::Sync> { + ::std::sync::Arc::new(#fuzztest_instance) } }; @@ -302,6 +320,23 @@ test_fn: fn(i32, std::string::String) } + impl<T0, T1> __FuzzTestTestFuzz<T0, T1> + where for <'user> T0: ::fuzztest::domains::Domain<UserValue<'user> = i32> + 'static, + T0::CorpusValue: 'static, + for <'user> T1: ::fuzztest::domains::Domain<UserValue<'user> = std::string::String> + 'static, + T1::CorpusValue: 'static { + fn try_get_user_value<'a>( + &self, + args: &'a ::fuzztest::domains::GenericCorpusValue, + ) -> ::std::option::Option< <__FuzzTestTestFuzzStateWrapper<T0, T1> as ::fuzztest::domains::Domain>::UserValue<'a> > { + use ::fuzztest::domains::Domain; + + let wrapper = args.downcast_ref::<__FuzzTestTestFuzzStateWrapper<T0::CorpusValue, T1::CorpusValue>>()?; + let domain = self.domain.try_lock().ok()?; + domain.corpus_to_user_value(wrapper).ok() + } + } + impl<T0, T1> ::fuzztest::internal::FuzzTest for __FuzzTestTestFuzz<T0, T1> where for <'user> T0: ::fuzztest::domains::Domain<UserValue<'user> = i32> + 'static, T0::CorpusValue: 'static, @@ -320,25 +355,19 @@ use ::fuzztest::domains::Domain; let wrapper = args - .downcast_ref::<__FuzzTestTestFuzzStateWrapper<T0::CorpusValue, T1::CorpusValue>>() - .expect("Attempt to recover user value before testing failed."); + .downcast_ref::<__FuzzTestTestFuzzStateWrapper<T0::CorpusValue, T1::CorpusValue>>() + .expect("Attempt to recover user value before testing failed."); - let get_user_value = || { - self.domain.lock() + let user_value = self.domain + .lock() .expect("Failed to acquire domain lock") .corpus_to_user_value(wrapper) - .expect("Failed to get user value from corpus value") - }; + .expect("Failed to get user value from corpus value"); // Safety: Data is not reused after the test. - let user_value = get_user_value(); let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (self.test_fn)(user_value.a, user_value.b) )); if result.is_err() { - let user_value = get_user_value(); - self.print_finding_report( - &FUZZTEST_INFO, - &[::std::format!("{:?}", user_value.a), ::std::format!("{:?}", user_value.b)], - ); + self.print_finding_report(args); } result.is_ok() @@ -346,10 +375,19 @@ fn domains(&self) -> std::sync::Arc<std::sync::Mutex<dyn ::fuzztest::domains::GenericDomain>> { std::sync::Arc::clone(&self.domain) as std::sync::Arc<std::sync::Mutex<dyn ::fuzztest::domains::GenericDomain>> } + fn print_finding_report(&self, args: &::fuzztest::domains::GenericCorpusValue) { + let ::std::option::Option::Some(user_value) = self.try_get_user_value(args) else { + return; + }; + ::fuzztest::internal::print_finding_report( + &FUZZTEST_INFO, + &[::std::format!("{:?}", user_value.a), ::std::format!("{:?}", user_value.b)], + ); + } } - fn __FuzzTestTestFuzz_factory() -> ::fuzztest::internal::BoxedFuzzTest { - ::std::boxed::Box::new(__FuzzTestTestFuzz { + fn __FuzzTestTestFuzz_factory() -> ::std::sync::Arc<dyn ::fuzztest::internal::FuzzTest + ::std::marker::Send + ::std::marker::Sync> { + ::std::sync::Arc::new(__FuzzTestTestFuzz { domain: std::sync::Arc::new(std::sync::Mutex::new( __FuzzTestTestFuzzStateWrapper { a: ::fuzztest::domains::arbitrary::Arbitrary::<i32>::default(),
diff --git a/rust/src/crash_handler.rs b/rust/src/crash_handler.rs index 335f82a..c401c50 100644 --- a/rust/src/crash_handler.rs +++ b/rust/src/crash_handler.rs
@@ -12,18 +12,37 @@ // See the License for the specific language governing permissions and // limitations under the License. +use crate::worker; +use std::{panic, slice, 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), ); } +// SAFETY: +// - `FuzzTestSetSanitizerDeathCallback` is declared with `extern "C"` linkage in +// `internal/sanitizer_interface.h` and defined in `internal/sanitizer_interface.cc`. +// - The signature matches `void FuzzTestSetSanitizerDeathCallback(void (*)())`. +unsafe extern "C" { + fn FuzzTestSetSanitizerDeathCallback(callback: extern "C" fn()); +} + +/// Sanitizer death callback, invoked by the sanitizer runtime right before it terminates the +/// process. Prints the counterexample for the input being executed, if any. +extern "C" fn sanitizer_death_callback() { + // Catch any panic from user `corpus_to_user_value` or `Debug::fmt` implementations so that + // unwinding cannot cross the `extern "C"` boundary and abort inside `__sanitizer::Die()`. + let _ = panic::catch_unwind(worker::try_print_finding_report); +} + /// Sanitizer error summary callback invoked by the C++ sanitizer interface. /// /// # Safety @@ -47,15 +66,14 @@ // consecutive, initialized `u8` bytes 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); + worker::try_emit_finding(crash_type, crash_type); } -/// Registers the sanitizer error summary callback and ensures the sanitizer crash handler hook is -/// linked into the binary. +/// Registers the sanitizer error summary and death callbacks and ensures the sanitizer crash +/// handler hook is linked into the binary. pub fn register_crash_handler() { // SAFETY: // - `sanitizer_error_summary_callback` is an `unsafe extern "C" fn` matching the C callback @@ -67,4 +85,68 @@ unsafe { FuzzTestSetSanitizerErrorSummaryCallback(sanitizer_error_summary_callback); } + // SAFETY: + // - `sanitizer_death_callback` is an `extern "C" fn` matching the C callback signature + // `FuzzTestSanitizerDeathCallback` (`void (*)()`), and catches panics internally so it cannot + // unwind across the FFI boundary. + // - As a function item, `sanitizer_death_callback` has `'static` lifetime and remains valid for + // the entire duration of program execution. + // - `FuzzTestSetSanitizerDeathCallback` stores the function pointer in a `std::atomic` and + // registers the underlying sanitizer hook via `std::call_once` (and is a no-op in builds + // without a sanitizer), so concurrent registration is data-race free. + unsafe { + FuzzTestSetSanitizerDeathCallback(sanitizer_death_callback); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domains::{GenericCorpusValue, GenericDomain}; + use crate::internal::FuzzTest; + use googletest::prelude::*; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Arc, Mutex}; + + struct PanickingReportFuzzTest { + report_called: Arc<AtomicBool>, + } + + impl FuzzTest for PanickingReportFuzzTest { + fn name(&self) -> &'static str { + "panicking_report_fuzz_test" + } + fn activate(&mut self) { + unimplemented!() + } + fn mutate(&mut self) { + unimplemented!() + } + fn execute(&self, _args: &GenericCorpusValue) -> bool { + unimplemented!() + } + fn domains(&self) -> Arc<Mutex<dyn GenericDomain>> { + unimplemented!() + } + fn print_finding_report(&self, _args: &GenericCorpusValue) { + self.report_called.store(true, Ordering::Relaxed); + panic!("simulated panic in Debug::fmt or corpus_to_user_value"); + } + } + + #[googletest::test] + fn test_sanitizer_death_callback_catches_panic_from_finding_report() { + let report_called = Arc::new(AtomicBool::new(false)); + let fuzz_test = Arc::new(PanickingReportFuzzTest { + report_called: Arc::clone(&report_called), + }); + let input: GenericCorpusValue = Box::new(()); + + worker::with_active_smoke_test(fuzz_test, Arc::new(input), || { + // Unwinding out of `extern "C" fn sanitizer_death_callback` would abort the process. + sanitizer_death_callback(); + }); + + expect_true!(report_called.load(Ordering::Relaxed)); + } }
diff --git a/rust/src/domains.rs b/rust/src/domains.rs index 15eed8e..1e53cad 100644 --- a/rust/src/domains.rs +++ b/rust/src/domains.rs
@@ -37,7 +37,7 @@ pub use seeds::SeedableDomainExt; pub use seeds::Seeded; -pub trait CloneAny: Any { +pub trait CloneAny: Any + Send + Sync { fn clone_box(&self) -> Box<dyn CloneAny>; fn as_any(&self) -> &dyn Any; fn as_mut_any(&mut self) -> &mut dyn Any; @@ -60,7 +60,7 @@ } } -impl<T: Any + Clone> CloneAny for T { +impl<T: Any + Clone + Send + Sync> CloneAny for T { fn clone_box(&self) -> Box<dyn CloneAny> { // Prevent infinite recursion if T is a nested Box type. if let Some(boxed) = self.as_any().downcast_ref::<Box<dyn CloneAny>>() { @@ -132,9 +132,7 @@ /// The type of the corpus from which the values of type UserValue are drawn. /// For example, if the domain should output an `&str` then the UserValue should be `&str` and /// the CorpusValue could the owned data structured that the `&str` points to (eg: String). - /// The CorpusValue type should implement `serde::Serialize`, `serde::de::DeserializeOwned` and - /// `Clone`. - type CorpusValue: Serialize + DeserializeOwned + Clone; + type CorpusValue: Serialize + DeserializeOwned + Clone + Send + Sync; /// Initializes a new value drawn from the domain. fn init(&mut self, rng: &mut dyn rand::Rng) -> anyhow::Result<Self::CorpusValue>;
diff --git a/rust/src/internal.rs b/rust/src/internal.rs index 4308734..5b3afee 100644 --- a/rust/src/internal.rs +++ b/rust/src/internal.rs
@@ -17,6 +17,7 @@ pub use fuzztest_registry::FuzzTestInfo; pub use fuzztest_registry::FuzzTestRegistration; use std::fmt::Write; +use std::io::{self, Write as _}; use std::sync::Arc; use std::sync::Mutex; @@ -42,10 +43,8 @@ fn execute(&self, args: &GenericCorpusValue) -> bool; fn domains(&self) -> Arc<Mutex<dyn GenericDomain>>; - /// Formats and prints the counterexample finding report for `formatted_args` to `stderr`. - fn print_finding_report(&self, info: &FuzzTestInfo, formatted_args: &[String]) { - print_finding_report(info, formatted_args); - } + /// Formats and prints the counterexample finding report for `args` to `stderr`. + fn print_finding_report(&self, args: &GenericCorpusValue); } /// Formats the `=== BUG FOUND!` finding report block for the given fuzz test and formatted @@ -78,12 +77,11 @@ } /// Prints the `=== BUG FOUND!` finding report block to `stderr`. -fn print_finding_report(info: &FuzzTestInfo, formatted_args: &[String]) { - eprint!("{}", format_finding_report(info, formatted_args)); +pub fn print_finding_report(info: &FuzzTestInfo, formatted_args: &[String]) { + let report = format_finding_report(info, formatted_args); + let _ = io::stderr().write_all(report.as_bytes()); } -pub type BoxedFuzzTest = Box<dyn FuzzTest + Send + Sync>; - pub struct InputStateAndDomain<I, D> { pub input_state: Option<I>, pub domain: D,
diff --git a/rust/src/worker.rs b/rust/src/worker.rs index fcfbd6a..4d78e37 100644 --- a/rust/src/worker.rs +++ b/rust/src/worker.rs
@@ -13,7 +13,7 @@ // limitations under the License. use super::domains::GenericCorpusValue; -use super::internal::{BoxedFuzzTest, FuzzTest}; +use super::internal::FuzzTest; use super::options::{self, CentipedeArgs, ExecutionAction}; use ::engine::engine_ffi; use ::engine::{ @@ -27,6 +27,7 @@ use std::path::Path; use std::process; use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; use std::sync::LazyLock; use std::time::Duration; use std::time::Instant; @@ -49,6 +50,21 @@ /// not have access to the adapter instance. static EXECUTE_CONTEXT: Mutex<Option<ExecuteContext>> = Mutex::new(None); +/// The fuzz test and corpus input of a property function execution that is in progress. +struct ActiveExecution { + fuzz_test: Arc<dyn FuzzTest + Send + Sync>, + input: Arc<GenericCorpusValue>, +} + +/// Global execution context for the currently running fuzz test case in smoke-test mode. +/// +/// A global (rather than a thread-local) lets the sanitizer death callback find the context +/// when the sanitizer fires on a thread spawned by the property function. It assumes that at most +/// one smoke test executes at a time: when tests run in parallel (the `libtest` default), +/// concurrent smoke tests overwrite each other's context and the report may show another test's +/// input. Fuzz tests should therefore be run with `--test-threads=1`. +static ACTIVE_EXECUTION: Mutex<Option<ActiveExecution>> = Mutex::new(None); + /// Sets the global DiagnosticSink. pub(crate) fn set_diagnostic_sink(sink: DiagnosticSink) { let mut guard = DIAGNOSTIC_SINK.lock(); @@ -110,6 +126,22 @@ true } +/// Prints the counterexample finding report for the test input currently executing in smoke-test +/// mode, if any (see `ACTIVE_EXECUTION`). +/// +/// Uses non-blocking `try_lock` to access the execution context without deadlocking if called from +/// a sanitizer death callback while `ACTIVE_EXECUTION` is locked; if the lock is contended or no +/// smoke test is active, this is a no-op. +pub(crate) fn try_print_finding_report() { + let Some(guard) = ACTIVE_EXECUTION.try_lock() else { + return; + }; + let Some(active) = guard.as_ref() else { + return; + }; + active.fuzz_test.print_finding_report(&active.input); +} + // 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 @@ -121,30 +153,62 @@ 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. +/// A guard that manages the global `EXECUTE_CONTEXT` (in worker mode) or the global +/// `ACTIVE_EXECUTION` (in smoke-test mode), 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; +enum ExecutionGuard { + Worker, + SmokeTest, +} impl ExecutionGuard { - /// Enters the execution context by setting `EXECUTE_CONTEXT`. + /// Enters the adapter 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 + Self::Worker + } + + /// Enters the smoke-test execution context by setting `ACTIVE_EXECUTION`. + fn enter_smoke_test( + fuzz_test: Arc<dyn FuzzTest + Send + Sync>, + input: Arc<GenericCorpusValue>, + ) -> Self { + let prev = ACTIVE_EXECUTION.lock().replace(ActiveExecution { fuzz_test, input }); + drop(prev); + Self::SmokeTest } } impl Drop for ExecutionGuard { fn drop(&mut self) { - *EXECUTE_CONTEXT.lock() = None; + match self { + Self::Worker => { + *EXECUTE_CONTEXT.lock() = None; + } + Self::SmokeTest => { + let prev = ACTIVE_EXECUTION.lock().take(); + drop(prev); + } + } } } +#[cfg(test)] +pub(crate) fn with_active_smoke_test( + fuzz_test: Arc<dyn FuzzTest + Send + Sync>, + input: Arc<GenericCorpusValue>, + f: impl FnOnce(), +) { + let _guard = ExecutionGuard::enter_smoke_test(fuzz_test, input); + f(); +} + pub struct RustFuzzTestAdapter { - fuzz_test: BoxedFuzzTest, + fuzz_test: Arc<dyn FuzzTest + Send + Sync>, } impl RustFuzzTestAdapter { @@ -265,7 +329,7 @@ pub struct RustFuzzTestAdapterManager { pub test_name: &'static str, - pub fuzz_test_factory: fn() -> BoxedFuzzTest, + pub fuzz_test_factory: fn() -> Arc<dyn FuzzTest + Send + Sync>, } impl RustFuzzTestAdapterManager { @@ -295,7 +359,7 @@ RustFuzzTestAdapter { fuzz_test } } - pub fn construct_fuzz_test(&self) -> BoxedFuzzTest { + pub fn construct_fuzz_test(&self) -> Arc<dyn FuzzTest + Send + Sync> { (self.fuzz_test_factory)() } } @@ -641,7 +705,7 @@ } } -pub fn run_smoke_test(fuzztest: &dyn FuzzTest) { +pub fn run_smoke_test(fuzztest: Arc<dyn FuzzTest + Send + Sync>) { let start_time = Instant::now(); // TODO(the-shank): these should be configurable externally. @@ -651,14 +715,22 @@ // TODO(the-shank): the rng seed should be configurable let mut rng = rand::rng(); - let mut generic_corpus_value = fuzztest - .domains() - .lock() - .expect("Failed to lock domains") - .init(&mut rng) - .expect("domain initialization should succeed to provide an initial corpus value"); + let mut generic_corpus_value = Arc::new( + fuzztest + .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); + let result = { + let _guard = ExecutionGuard::enter_smoke_test( + Arc::clone(&fuzztest), + Arc::clone(&generic_corpus_value), + ); + fuzztest.execute(&generic_corpus_value) + }; // DISCUSS: probably need a more "googletest" approach to handling the result here? assert!(result); @@ -667,9 +739,20 @@ .domains() .lock() .expect("Failed to lock domains") - .mutate(&mut generic_corpus_value, &mut rng, only_shrink) + .mutate( + Arc::get_mut(&mut generic_corpus_value) + .expect("execution guard should be dropped before mutating corpus value"), + &mut rng, + only_shrink, + ) .expect("domain mutation should succeed"); - let result = fuzztest.execute(&generic_corpus_value); + let result = { + let _guard = ExecutionGuard::enter_smoke_test( + Arc::clone(&fuzztest), + Arc::clone(&generic_corpus_value), + ); + fuzztest.execute(&generic_corpus_value) + }; // DISCUSS: probably need a more "googletest" approach to handling the result here? assert!(result); } @@ -753,7 +836,7 @@ } ExecutionAction::SmokeTest => { let fuzz_test = manager.construct_fuzz_test(); - run_smoke_test(fuzz_test.as_ref()); + run_smoke_test(fuzz_test); } } } @@ -807,3 +890,144 @@ // pointers passed to `FuzzTestControllerRun` remain valid. unsafe { engine_ffi::FuzzTestControllerRun(&ffi_manager, ¢ipede_args.as_bytes_views()) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::domains::GenericDomain; + use googletest::prelude::*; + use std::panic::{AssertUnwindSafe, catch_unwind}; + use std::sync::Mutex as StdMutex; + use std::thread; + + struct RecordingFuzzTest { + reported_inputs: StdMutex<Vec<i32>>, + } + + impl RecordingFuzzTest { + fn new() -> Self { + Self { reported_inputs: StdMutex::new(Vec::new()) } + } + + fn reported_inputs(&self) -> Vec<i32> { + self.reported_inputs.lock().unwrap().clone() + } + } + + impl FuzzTest for RecordingFuzzTest { + fn name(&self) -> &'static str { + "recording_fuzz_test" + } + fn activate(&mut self) { + unimplemented!() + } + fn mutate(&mut self) { + unimplemented!() + } + fn execute(&self, _args: &GenericCorpusValue) -> bool { + unimplemented!() + } + fn domains(&self) -> Arc<StdMutex<dyn GenericDomain>> { + unimplemented!() + } + fn print_finding_report(&self, args: &GenericCorpusValue) { + let value = *args.downcast_ref::<i32>().expect("expected i32 corpus value"); + self.reported_inputs.lock().unwrap().push(value); + } + } + + #[gtest] + fn try_print_finding_report_when_empty_is_noop() { + expect_true!(ACTIVE_EXECUTION.lock().is_none()); + + try_print_finding_report(); + + expect_true!(ACTIVE_EXECUTION.lock().is_none()); + } + + #[gtest] + fn try_print_finding_report_when_active_prints_report_and_clears_on_drop() { + let fuzz_test = Arc::new(RecordingFuzzTest::new()); + let input: Arc<GenericCorpusValue> = Arc::new(Box::new(42_i32)); + + { + let _guard = ExecutionGuard::enter_smoke_test(Arc::clone(&fuzz_test) as _, input); + try_print_finding_report(); + } + expect_that!(fuzz_test.reported_inputs(), elements_are![eq(&42)]); + + // Dropping the guard clears `ACTIVE_EXECUTION`, so subsequent calls do not print again. + try_print_finding_report(); + expect_that!(fuzz_test.reported_inputs(), elements_are![eq(&42)]); + } + + #[gtest] + fn enter_smoke_test_clears_active_execution_on_unwind() { + let fuzz_test = Arc::new(RecordingFuzzTest::new()); + let input: Arc<GenericCorpusValue> = Arc::new(Box::new(7_i32)); + + let unwind_result = catch_unwind(AssertUnwindSafe(|| { + let _guard = ExecutionGuard::enter_smoke_test(Arc::clone(&fuzz_test) as _, input); + panic!("simulated property panic"); + })); + expect_true!(unwind_result.is_err()); + + try_print_finding_report(); + expect_that!(fuzz_test.reported_inputs(), is_empty()); + } + + #[gtest] + fn try_print_finding_report_when_lock_held_is_noop() { + let fuzz_test = Arc::new(RecordingFuzzTest::new()); + let input: Arc<GenericCorpusValue> = Arc::new(Box::new(99_i32)); + + let _guard = ExecutionGuard::enter_smoke_test(Arc::clone(&fuzz_test) as _, input); + { + let _held_lock = ACTIVE_EXECUTION.lock(); + try_print_finding_report(); + } + + expect_that!(fuzz_test.reported_inputs(), is_empty()); + } + + #[gtest] + fn try_print_finding_report_from_spawned_thread_prints_active_input() { + let fuzz_test = Arc::new(RecordingFuzzTest::new()); + let input: Arc<GenericCorpusValue> = Arc::new(Box::new(123_i32)); + + let _guard = ExecutionGuard::enter_smoke_test(Arc::clone(&fuzz_test) as _, input); + thread::spawn(try_print_finding_report).join().unwrap(); + + expect_that!(fuzz_test.reported_inputs(), elements_are![eq(&123)]); + } + + #[gtest] + fn smoke_test_guard_drops_active_execution_outside_lock() { + #[derive(Clone)] + struct CheckUnlockedOnDrop(Arc<AtomicBool>); + + impl Drop for CheckUnlockedOnDrop { + fn drop(&mut self) { + self.0.store(ACTIVE_EXECUTION.try_lock().is_some(), Ordering::Relaxed); + } + } + + let fuzz_test: Arc<dyn FuzzTest + Send + Sync> = Arc::new(RecordingFuzzTest::new()); + let unlocked_on_replace = Arc::new(AtomicBool::new(false)); + let unlocked_on_guard_drop = Arc::new(AtomicBool::new(false)); + + let guard1 = ExecutionGuard::enter_smoke_test( + Arc::clone(&fuzz_test), + Arc::new(Box::new(CheckUnlockedOnDrop(Arc::clone(&unlocked_on_replace)))), + ); + let guard2 = ExecutionGuard::enter_smoke_test( + fuzz_test, + Arc::new(Box::new(CheckUnlockedOnDrop(Arc::clone(&unlocked_on_guard_drop)))), + ); + expect_true!(unlocked_on_replace.load(Ordering::Relaxed)); + + drop(guard2); + expect_true!(unlocked_on_guard_drop.load(Ordering::Relaxed)); + drop(guard1); + } +}