Add --skip_triage to Centipede to skip re-execution for crash triaging. In the unit test mode with the default duration, crash handling (e.g. stack trace dumping) can take longer than the duration. The stop condition is then met before triage, and the crash is not reported. With `--skip_triage`, Centipede saves the suspected input of the crashing batch as the reproducer directly, without re-executing inputs. FuzzTest enables it in the unit test mode with the default duration. The trade-off in that mode is that the reproducer is not confirmed, and the crashing batch is not saved for crashes that need multiple inputs. PiperOrigin-RevId: 1024938352
diff --git a/centipede/BUILD b/centipede/BUILD index 30d5b85..12a87f8 100644 --- a/centipede/BUILD +++ b/centipede/BUILD
@@ -1202,6 +1202,7 @@ linkstatic = True, # Must be linked statically even when dynamic_mode=on. deps = [ ":centipede_runner_no_main", + ":engine_abi", ":execution_metadata", ":mutation_data", "@abseil-cpp//absl/base:nullability", @@ -1423,6 +1424,27 @@ ], ) +# Separated from :in_process_centipede_callbacks_test because linking the +# runner brings in its process-global state. +cc_test( + name = "runner_adapter_manager_test", + srcs = ["runner_adapter_manager_test.cc"], + deps = [ + ":centipede_runner_no_main", + ":engine_abi", + ":environment", + ":execution_metadata", + ":in_process_centipede_callbacks", + ":mutation_data", + ":runner_result", + ":stop", + "@abseil-cpp//absl/cleanup", + "@abseil-cpp//absl/strings", + "@com_google_fuzztest//common:defs", + "@googletest//:gtest_main", + ], +) + cc_test( name = "environment_test", srcs = ["environment_test.cc"],
diff --git a/centipede/centipede.cc b/centipede/centipede.cc index 0057787..9843860 100644 --- a/centipede/centipede.cc +++ b/centipede/centipede.cc
@@ -428,9 +428,10 @@ return true; } const bool can_report_without_reexecution = - input_vec.size() == 1 && !env_.persistent_mode && - batch_result.IsInputFailure() && !stop_condition_.StopRequested() && - batch_result.failure_description() != kExecutionFailurePerBatchTimeout; + env_.skip_triage || + (input_vec.size() == 1 && !env_.persistent_mode && + batch_result.IsInputFailure() && !stop_condition_.StopRequested() && + batch_result.failure_description() != kExecutionFailurePerBatchTimeout); if (stop_condition_.ShouldStop() && !can_report_without_reexecution) { FUZZTEST_LOG_FIRST_N(WARNING, 1) << "Crash found but the stop condition is met - not reporting further " @@ -1111,6 +1112,14 @@ SaveReproducer(wd_, log_prefix, /*input_idx=*/0, input_vec[0], batch_result); return; + } else if (env_.skip_triage) { + FUZZTEST_LOG(INFO) << log_prefix + << "Skipping triaging the crash per --skip_triage " + "and saving the suspect input as reproducer " + "directly."; + SaveReproducer(wd_, log_prefix, suspect_input_idx, + input_vec[suspect_input_idx], batch_result); + return; } // Determine the optimal order of the inputs to try to maximize the chances of
diff --git a/centipede/centipede_flags.inc b/centipede/centipede_flags.inc index a335b6e..4fca3e5 100644 --- a/centipede/centipede_flags.inc +++ b/centipede/centipede_flags.inc
@@ -407,7 +407,12 @@ CENTIPEDE_FLAG( bool, batch_triage_suspect_only, false, "If set, triage the crash on only the suspected input in a crashing " - "batch. Otherwise, triage on all the executed inputs") + "batch. Otherwise, triage on all the executed inputs.") +CENTIPEDE_FLAG( + bool, skip_triage, false, + "If set, do not re-execute inputs to triage a crash; save the suspected " + "input of the crashing batch as the reproducer directly. Takes precedence " + "over --batch_triage_suspect_only.") CENTIPEDE_FLAG( size_t, shmem_size_mb, 1024, "Size of the shared memory regions used to communicate between the "
diff --git a/centipede/centipede_test.cc b/centipede/centipede_test.cc index d7fe79a..c9eda62 100644 --- a/centipede/centipede_test.cc +++ b/centipede/centipede_test.cc
@@ -1080,6 +1080,47 @@ std::filesystem::exists(metadata_dir / (crashing_input_hash + ".sig"))); } +TEST(Centipede, SkipTriageSavesSuspectInputWithoutReexecution) { + constexpr size_t kNumBatches = 5; + constexpr size_t kBatchSize = 10; + // Not the first input of its batch, so that saving the suspect input can be + // told apart from saving the first input. + constexpr size_t kCrashingInputIdx = 15; + + TempDir temp_dir{test_info_->name()}; + Environment env; + env.workdir = temp_dir.path(); + env.num_runs = kBatchSize * kNumBatches; + env.batch_size = kBatchSize; + env.require_pc_table = false; + env.exit_on_crash = true; + env.skip_triage = true; + + // Would fail on the first triage attempt, if triage was not skipped. + FlakyCrashingInputMock mock(env, kCrashingInputIdx, + /*fail_on_triage_attempt=*/1); + NonOwningCallbacksFactory factory(mock); + CentipedeMain(env, factory); + + EXPECT_EQ(mock.triage_attempts(), 0); + const auto crash_dir = + std::filesystem::path{WorkDir{env}.CrashReproducerDirPaths().MyShard()}; + const auto crashing_input_hash = Hash(mock.crashing_input()); + // The suspect input must be the only thing saved: no other reproducer and no + // `crashing_batch-*` directory. + std::vector<std::string> saved_names; + for (const auto& dir_ent : std::filesystem::directory_iterator(crash_dir)) { + saved_names.push_back(dir_ent.path().filename()); + } + EXPECT_THAT(saved_names, ElementsAre(crashing_input_hash)); + const auto metadata_dir = + std::filesystem::path{WorkDir{env}.CrashMetadataDirPaths().MyShard()}; + EXPECT_TRUE( + std::filesystem::exists(metadata_dir / (crashing_input_hash + ".desc"))); + EXPECT_TRUE( + std::filesystem::exists(metadata_dir / (crashing_input_hash + ".sig"))); +} + TEST_F(CentipedeWithTemporaryLocalDir, GetsSeedInputs) { Environment env; env.binary =
diff --git a/centipede/runner.cc b/centipede/runner.cc index f8f38a9..1b69fb9 100644 --- a/centipede/runner.cc +++ b/centipede/runner.cc
@@ -916,6 +916,17 @@ } // namespace +FuzzTestAdapterManager CreateFuzzTestAdapterManager( + RunnerCallbacks* absl_nonnull callbacks) { + RunnerCheck(callbacks != nullptr, "callbacks must not be null"); + return { + /*ctx=*/reinterpret_cast<FuzzTestAdapterManagerCtx*>(callbacks), + /*GetBinaryId=*/nullptr, + /*GetTestName=*/GetTestName, + /*ConstructAdapter=*/ConstructAdapter, + }; +} + // Constructs a FuzzTestAdapterManager and try to run as an engine worker. // // If engine worker is not required, calls @@ -933,12 +944,7 @@ return EXIT_SUCCESS; } - FuzzTestAdapterManager manager = { - /*ctx=*/reinterpret_cast<FuzzTestAdapterManagerCtx*>(&callbacks), - /*GetBinaryId=*/nullptr, - /*GetTestName=*/GetTestName, - /*ConstructAdapter=*/ConstructAdapter, - }; + FuzzTestAdapterManager manager = CreateFuzzTestAdapterManager(&callbacks); const int old_traced = CentipedeSetCurrentThreadTraced(/*traced=*/0); const auto s = FuzzTestWorkerMaybeRun(&manager); CentipedeSetCurrentThreadTraced(old_traced);
diff --git a/centipede/runner_adapter_manager_test.cc b/centipede/runner_adapter_manager_test.cc new file mode 100644 index 0000000..23095c3 --- /dev/null +++ b/centipede/runner_adapter_manager_test.cc
@@ -0,0 +1,147 @@ +// 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 +// +// https://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. + +// Tests for `CreateFuzzTestAdapterManager()` in the runner interface. +// +// This is separated from other engine tests because linking the runner brings +// in its process-global state. + +#include <cstdint> +#include <functional> +#include <string> +#include <string_view> +#include <vector> + +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "absl/cleanup/cleanup.h" +#include "absl/strings/str_cat.h" +#include "./centipede/engine_abi.h" +#include "./centipede/environment.h" +#include "./centipede/execution_metadata.h" +#include "./centipede/in_process_centipede_callbacks.h" +#include "./centipede/mutation_data.h" +#include "./centipede/runner_interface.h" +#include "./centipede/runner_result.h" +#include "./centipede/stop.h" +#include "./common/defs.h" + +namespace fuzztest::internal { +namespace { + +using ::testing::SizeIs; + +ByteArray ToByteArray(std::string_view sv) { + return ByteArray(sv.begin(), sv.end()); +} + +std::string ToString(ByteSpan span) { + return std::string(reinterpret_cast<const char*>(span.data()), span.size()); +} + +class FakeRunnerCallbacks : public RunnerCallbacks { + public: + bool Execute(void* input) override { + const auto& str = *reinterpret_cast<const std::string*>(input); + if (str == "crash_me") { + CentipedeSetFailureDescription("runner_callbacks_crash"); + } + return true; + } + + void GetPresetSeedInputs( + const std::function<void(void*)>& seed_callback) override { + seed_callback(new std::string("runner_seed")); + } + + void* GetRandomSeedInput() override { + return new std::string(absl::StrCat("runner_random_", next_seed_++)); + } + + bool HasCustomMutator() const override { return true; } + + void* Mutate(void* origin, + const ExecutionMetadata& origin_metadata) override { + const auto& str = *reinterpret_cast<const std::string*>(origin); + return new std::string(absl::StrCat(str, "_mut")); + } + + void* CrossOver(void* origin, const ExecutionMetadata& origin_metadata, + void* other, + const ExecutionMetadata& other_metadata) override { + const auto& str1 = *reinterpret_cast<const std::string*>(origin); + const auto& str2 = *reinterpret_cast<const std::string*>(other); + return new std::string(absl::StrCat(str1, "+", str2)); + } + + void SerializeInput( + void* input, const std::function<void(ByteSpan)>& bytes_sink) override { + const auto& str = *reinterpret_cast<const std::string*>(input); + bytes_sink({reinterpret_cast<const uint8_t*>(str.data()), str.size()}); + } + + void* DeserializeInput(ByteSpan bytes) override { + return new std::string(reinterpret_cast<const char*>(bytes.data()), + bytes.size()); + } + + void FreeInput(void* input) override { + delete reinterpret_cast<std::string*>(input); + } + + private: + int next_seed_ = 0; +}; + +TEST(CreateFuzzTestAdapterManagerTest, WorksWithInProcessCentipedeCallbacks) { + // Disable tracing outside of the input executions, as required by + // `CreateFuzzTestAdapterManager()`. + const int old_traced = CentipedeSetCurrentThreadTraced(/*traced=*/0); + const absl::Cleanup tracing_restorer = [old_traced] { + CentipedeSetCurrentThreadTraced(old_traced); + }; + + FakeRunnerCallbacks runner_callbacks; + const FuzzTestAdapterManager manager = + CreateFuzzTestAdapterManager(&runner_callbacks); + + Environment env; + env.test_name = "some_test"; + env.crossover_level = 0; + StopCondition stop_condition; + InProcessCentipedeCallbacks callbacks(env, stop_condition, &manager); + + std::vector<ByteArray> seeds; + EXPECT_EQ(callbacks.GetSeeds(/*num_seeds=*/2, seeds), 32); + ASSERT_THAT(seeds, SizeIs(2)); + EXPECT_EQ(ToString(seeds[0]), "runner_seed"); + EXPECT_EQ(ToString(seeds[1]), "runner_random_0"); + + std::vector<MutationInputRef> mutation_inputs = {{seeds[0], nullptr}}; + std::vector<Mutant> mutants = + callbacks.Mutate(mutation_inputs, /*num_mutants=*/1); + ASSERT_THAT(mutants, SizeIs(1)); + EXPECT_EQ(ToString(mutants[0].data), "runner_seed_mut"); + + BatchResult batch_result; + EXPECT_TRUE(callbacks.Execute("binary", {seeds[0]}, batch_result)); + EXPECT_EQ(batch_result.num_outputs_read(), 1); + + EXPECT_FALSE( + callbacks.Execute("binary", {ToByteArray("crash_me")}, batch_result)); + EXPECT_EQ(batch_result.failure_description(), "runner_callbacks_crash"); +} + +} // namespace +} // namespace fuzztest::internal
diff --git a/centipede/runner_interface.h b/centipede/runner_interface.h index 3163dd1..b334087 100644 --- a/centipede/runner_interface.h +++ b/centipede/runner_interface.h
@@ -27,6 +27,7 @@ #include "absl/base/nullability.h" #include "absl/types/span.h" +#include "./centipede/engine_abi.h" #include "./centipede/execution_metadata.h" #include "./centipede/mutation_data.h" #include "./common/defs.h" @@ -197,6 +198,28 @@ FuzzerCustomMutatorCallback custom_mutator_cb, FuzzerCustomCrossOverCallback custom_crossover_cb); +// Creates a `FuzzTestAdapterManager` from `callbacks`, which must outlive the +// returned manager and any adapters constructed from it. +// +// NOTE: The returned manager and its adapters rely on process-global runner +// state that was designed for `RunnerMain()`. So a few limitations apply: +// +// - Execution feedback tracing: the adapter enables tracing on the current +// thread only while executing an input, and restores the previous value +// afterwards. Threads are traced by default, so the caller should call +// `CentipedeSetCurrentThreadTraced(0)` on the thread using the adapter before +// the first execution. Otherwise the code running between executions would be +// traced and pollute the feedback of later executions. +// - Single active adapter: at most one adapter constructed from any such +// manager may be alive in the process at a time, since the diagnostic sink of +// the adapter is stored in the global runner state. Constructing a second +// adapter overrides the sink of the first one, and freeing either adapter +// clears it. +// - Custom mutator: `Mutate` and `CrossOver` of the adapter terminate the +// process when `callbacks->HasCustomMutator()` returns false. +FuzzTestAdapterManager CreateFuzzTestAdapterManager( + RunnerCallbacks* absl_nonnull callbacks); + // The main Centipede Runner function. // It performs actions prescribed by argc/argv and environment variables // and returns EXIT_SUCCESS or EXIT_FAILURE.
diff --git a/e2e_tests/functional_test.cc b/e2e_tests/functional_test.cc index df5add5..3d74f4b 100644 --- a/e2e_tests/functional_test.cc +++ b/e2e_tests/functional_test.cc
@@ -92,19 +92,33 @@ // the code under test runs in a runner subprocess, so the controller reports // the runner's termination signal instead of being killed by it. void ExpectTargetKilledBySignal(TerminationStatus status, - absl::string_view std_err, int signum) { + absl::string_view std_err, int signum, + bool direct_termination = #ifdef FUZZTEST_USE_CENTIPEDE - EXPECT_THAT(status, Ne(ExitCode(0))); - EXPECT_TRUE( - RE2::PartialMatch(std_err, absl::StrCat("[Ee]xit code\\s*:\\s*", signum))) - << std_err; + false #else - EXPECT_THAT(status, Eq(Signal(signum))); + true #endif +) { + if (direct_termination) { + EXPECT_THAT(status, Eq(Signal(signum))); + } else { + EXPECT_THAT(status, Ne(ExitCode(0))); + EXPECT_TRUE(RE2::PartialMatch( + std_err, absl::StrCat("[Ee]xit code\\s*:\\s*", signum))) + << std_err; + } } -void ExpectTargetAbort(TerminationStatus status, absl::string_view std_err) { - ExpectTargetKilledBySignal(status, std_err, SIGABRT); +void ExpectTargetAbort(TerminationStatus status, absl::string_view std_err, + bool direct_termination = +#ifdef FUZZTEST_USE_CENTIPEDE + false +#else + true +#endif +) { + ExpectTargetKilledBySignal(status, std_err, SIGABRT, direct_termination); } int CountSubstrs(absl::string_view haystack, absl::string_view needle) { @@ -152,6 +166,16 @@ return RunWithExactFuzzerFlags(test_filter, target_binary, env, std::move(fuzzer_flags)); } + + void ExpectTargetAbort(TerminationStatus status, absl::string_view std_err) { + fuzztest::internal::ExpectTargetAbort(status, std_err, true); + } + + void ExpectTargetKilledBySignal(TerminationStatus status, + absl::string_view std_err, int signum) { + fuzztest::internal::ExpectTargetKilledBySignal(status, std_err, signum, + true); + } }; TEST_F(UnitTestModeTest, PassingTestPassesInUnitTestingMode) { @@ -728,6 +752,17 @@ EXPECT_THAT(status, Eq(ExitCode(0))); } +TEST_F(UnitTestModeTest, FirstTestIsSkippedByFixturePerTest) { + auto [status, std_out, std_err] = + Run("FixturePerTestSkippingFirstTest.*", kDefaultTargetBinary); +#ifdef FUZZTEST_USE_CENTIPEDE + EXPECT_THAT_LOG(std_err, HasSubstr("[.] Using in-process fuzzing execution")); +#endif + EXPECT_THAT_LOG(std_out, AllOf(HasSubstr("[ PASSED ] 1 test"), + HasSubstr("[ SKIPPED ] 1 test"))); + EXPECT_THAT(status, Eq(ExitCode(0))); +} + TEST_F(UnitTestModeTest, IterationIsSkippedWhenRequestedInFixturePerIteration) { auto [status, std_out, std_err] = Run("SkippedTestFixturePerIteration.SkippedTest", kDefaultTargetBinary, @@ -1623,6 +1658,7 @@ #else const int target_controller_runs = 0; #endif + SCOPED_TRACE(std_err); EXPECT_GT(CountTargetRuns(std_err) - target_controller_runs, 0); EXPECT_EQ(CountTargetRuns(std_err) - target_controller_runs, CountSubstrs(std_err, "<<FixtureTest::FixtureTest()>>"));
diff --git a/e2e_tests/testdata/fuzz_tests_using_googletest.cc b/e2e_tests/testdata/fuzz_tests_using_googletest.cc index 463ff24..79a4807 100644 --- a/e2e_tests/testdata/fuzz_tests_using_googletest.cc +++ b/e2e_tests/testdata/fuzz_tests_using_googletest.cc
@@ -197,6 +197,27 @@ }; FUZZ_TEST_F(SkippedTestFixturePerTest, SkippedTest); +class FixturePerTestSkippingFirstTest + : public ::fuzztest::PerFuzzTestFixtureAdapter<testing::Test> { + public: + FixturePerTestSkippingFirstTest() { + if (first_) { + first_ = false; + fuzztest::SkipTestsOrCurrentInput(); + } + } + + void TestA() { ASSERT_FALSE(first_); } + + void TestB() { ASSERT_FALSE(first_); } + + private: + static bool first_; +}; +bool FixturePerTestSkippingFirstTest::first_ = true; +FUZZ_TEST_F(FixturePerTestSkippingFirstTest, TestA); +FUZZ_TEST_F(FixturePerTestSkippingFirstTest, TestB); + class SkippedTestFixturePerIteration : public ::fuzztest::PerIterationFixtureAdapter<testing::Test> { public:
diff --git a/fuzztest/internal/BUILD b/fuzztest/internal/BUILD index 0a055d1..946a6b6 100644 --- a/fuzztest/internal/BUILD +++ b/fuzztest/internal/BUILD
@@ -97,9 +97,11 @@ "@com_google_fuzztest//centipede:centipede_default_callbacks", "@com_google_fuzztest//centipede:centipede_interface", "@com_google_fuzztest//centipede:centipede_runner_no_main", + "@com_google_fuzztest//centipede:engine_abi", "@com_google_fuzztest//centipede:environment", "@com_google_fuzztest//centipede:execution_metadata", "@com_google_fuzztest//centipede:fuzztest_mutator", + "@com_google_fuzztest//centipede:in_process_centipede_callbacks", "@com_google_fuzztest//centipede:mutation_data", "@com_google_fuzztest//centipede:runner_result", "@com_google_fuzztest//centipede:stop",
diff --git a/fuzztest/internal/centipede_adaptor.cc b/fuzztest/internal/centipede_adaptor.cc index a37fb32..3a01946 100644 --- a/fuzztest/internal/centipede_adaptor.cc +++ b/fuzztest/internal/centipede_adaptor.cc
@@ -25,6 +25,7 @@ #include <unistd.h> #include <algorithm> +#include <atomic> #include <cerrno> #include <cinttypes> #include <csignal> @@ -69,9 +70,11 @@ #include "./centipede/centipede_callbacks.h" #include "./centipede/centipede_default_callbacks.h" #include "./centipede/centipede_interface.h" +#include "./centipede/engine_abi.h" #include "./centipede/environment.h" #include "./centipede/execution_metadata.h" #include "./centipede/fuzztest_mutator.h" +#include "./centipede/in_process_centipede_callbacks.h" #include "./centipede/mutation_data.h" #include "./centipede/runner_interface.h" #include "./centipede/runner_result.h" @@ -222,7 +225,7 @@ const Configuration& configuration, absl::string_view workdir, absl::string_view test_name, RunMode run_mode) { fuzztest::internal::Environment env = CreateDefaultCentipedeEnvironment(); - constexpr absl::Duration kUnitTestDefaultDuration = absl::Seconds(3); + constexpr absl::Duration kUnitTestDefaultDuration = absl::Seconds(1); env.fuzztest_multi_test_mode_soon_to_be_removed = false; if (configuration.time_limit_per_input < absl::InfiniteDuration()) { const int64_t time_limit_seconds = @@ -265,6 +268,19 @@ if (total_time_limit == absl::ZeroDuration() && run_mode == RunMode::kUnitTest) { total_time_limit = kUnitTestDefaultDuration; + // When smoke testing (unguided fuzzing with the hardcoded unit-size + // duration), skip triaging to allow crash to be reported even when the + // crash handling (stack trace dumping) took longer than the set duration. + // This is an intended trade-off: reporting the crash within the short + // duration matters more than confirming the reproducer. + env.skip_triage = true; + FUZZTEST_LOG_FIRST_N(INFO, 1) + << "Crash triage is skipped when running with the default unit test " + "duration: the suspect input of a crashing batch is saved as the " + "reproducer without being re-executed for confirmation, and the " + "crashing batch is not saved for crashes that need multiple inputs " + "to reproduce. To enable triage, set the duration explicitly with " + "--" FUZZTEST_FLAG_PREFIX "fuzz_for."; } { Configuration single_test_configuration = configuration; @@ -415,7 +431,8 @@ } int RunCentipede(const Environment& env, - const std::optional<std::string>& centipede_command) { + const std::optional<std::string>& centipede_command, + RunnerCallbacks* runner_callbacks = nullptr) { FUZZTEST_CHECK(!IsCentipedeRunner()) << "Unexpected RunCentipede() in runner mode."; if (Runtime::instance().termination_requested()) { @@ -456,6 +473,17 @@ } global_stop_condition.ClearStopRequest(); global_stop_condition.SetStopTime(absl::InfiniteFuture()); + if (runner_callbacks != nullptr) { + FuzzTestAdapterManager adapter_manager = + CreateFuzzTestAdapterManager(runner_callbacks); + InProcessCentipedeCallbacksFactory factory(&adapter_manager); + // Disable tracing outside of the input executions, which enable tracing by + // themselves. + const int old_traced = CentipedeSetCurrentThreadTraced(/*traced=*/0); + const int result = CentipedeMain(env, factory, &global_stop_condition); + CentipedeSetCurrentThreadTraced(old_traced); + return result; + } static absl::NoDestructor<DefaultCallbacksFactory<CentipedeDefaultCallbacks>> factory; return CentipedeMain(env, *factory, &global_stop_condition); @@ -521,21 +549,6 @@ absl::Cleanup tracing_restorer = [old_traced] { CentipedeSetCurrentThreadTraced(old_traced); }; - static const bool skipped_on_setup = runtime_.skipping_requested(); - if (skipped_on_setup) { - absl::FPrintF(GetStderr(), - "[.] Skipping %s per request from the test setup.\n", - fuzzer_impl_.test_.full_name()); - if (const char* indicator = - std::getenv("FUZZTEST_SKIPPED_TEST_INDICATOR_FILE"); - indicator != nullptr) { - absl::FPrintF(GetStderr(), "[.] Touching the indicator file %s\n", - indicator); - WriteFile(indicator, ""); - } - CentipedeSetFailureDescription("SETUP FAILURE: Test is skipped"); - return false; - } if (runtime_.termination_requested()) { absl::FPrintF(GetStderr(), "[.] Termination requested - not executing input.\n"); @@ -631,6 +644,30 @@ namespace { +// Whether the crash metadata from the runtime should be forwarded to Centipede. +// It must be set only while Centipede is able to receive failures, since +// `CentipedeSetFailure()` terminates the process otherwise. +std::atomic<bool> forward_crash_metadata_to_centipede = false; + +// Registers the listener that forwards the crash metadata to Centipede. The +// registration happens at most once in the process, since the runtime is +// process-wide and its listeners cannot be unregistered. +void RegisterCrashMetadataForwarderOnce(Runtime& runtime) { + static const bool registered = [&runtime] { + runtime.RegisterCrashMetadataListener( + [](absl::string_view description, absl::string_view signature) { + if (!forward_crash_metadata_to_centipede.load( + std::memory_order_relaxed)) { + return; + } + CentipedeSetFailure(description.data(), description.size(), + signature.data(), signature.size()); + }); + return true; + }(); + (void)registered; +} + void PopulateTestLimitsToCentipedeRunner(const Configuration& configuration) { if (const size_t stack_limit = configuration.stack_limit; stack_limit > 0) { absl::FPrintF(GetStderr(), "[.] Stack limit set to: %zu\n", stack_limit); @@ -663,17 +700,36 @@ class CentipedeFixtureDriver : public UntypedFixtureDriver { public: CentipedeFixtureDriver( - Runtime& runtime, + Runtime& runtime, const FuzzTest& test, std::unique_ptr<UntypedFixtureDriver> orig_fixture_driver) : runtime_(runtime), + test_(test), orig_fixture_driver_(std::move(orig_fixture_driver)) {} void RunFuzzTest(absl::AnyInvocable<void() &&> run_fuzz_test_once) override { orig_fixture_driver_->RunFuzzTest([&, this] { + if (runtime_.skipping_requested()) { + absl::FPrintF(GetStderr(), + "[.] Skipping %s per request from the test setup.\n", + test_.full_name()); + if (!runner_mode) return; + if (const char* indicator = + std::getenv("FUZZTEST_SKIPPED_TEST_INDICATOR_FILE"); + indicator != nullptr) { + absl::FPrintF(GetStderr(), "[.] Touching the indicator file %s\n", + indicator); + WriteFile(indicator, ""); + } + CentipedeSetFailureDescription("SETUP FAILURE: Test is skipped"); + return; + } FUZZTEST_CHECK(configuration_ != nullptr) << "Setting up a fuzz test without configuration!"; PopulateTestLimitsToCentipedeRunner(*configuration_); std::move(run_fuzz_test_once)(); + // Skipping could be requested inside iterations, but it should not be + // exposed outside. + runtime_.SetSkippingRequested(false); }); } @@ -685,7 +741,7 @@ CentipedeSetCurrentThreadTraced(old_traced); }; orig_fixture_driver_->RunFuzzTestIteration([&, this] { - if (!runner_mode) CentipedePrepareProcessing(); + if (use_legacy_runtime_) CentipedePrepareProcessing(); std::move(run_iteration_once)(); }); if (runtime_.skipping_requested() || @@ -711,9 +767,19 @@ configuration_ = configuration; } + // Sets whether the iterations are driven by the legacy FuzzTest runtime + // (e.g. `ReplayInputsIfAvailable`) instead of the Centipede runner or + // adapter, in which case this driver needs to prepare the processing for + // each iteration by itself. + void set_use_legacy_runtime(bool use_legacy_runtime) { + use_legacy_runtime_ = use_legacy_runtime; + } + private: const Configuration* configuration_ = nullptr; + bool use_legacy_runtime_ = false; Runtime& runtime_; + const FuzzTest& test_; const bool runner_mode = IsCentipedeRunner(); std::unique_ptr<UntypedFixtureDriver> orig_fixture_driver_; }; @@ -721,8 +787,8 @@ CentipedeFuzzerAdaptor::CentipedeFuzzerAdaptor( const FuzzTest& test, std::unique_ptr<UntypedFixtureDriver> fixture_driver) : test_(test), - centipede_fixture_driver_( - new CentipedeFixtureDriver(runtime_, std::move(fixture_driver))), + centipede_fixture_driver_(new CentipedeFixtureDriver( + runtime_, test, std::move(fixture_driver))), fuzzer_impl_(test_, absl::WrapUnique(centipede_fixture_driver_)) { FUZZTEST_CHECK(centipede_fixture_driver_ != nullptr) << "Invalid fixture driver!"; @@ -765,7 +831,7 @@ char* replay_argv[] = {replay_argv0, crash_file.data()}; int result = 0; - fuzzer_impl_.fixture_driver_->RunFuzzTest([&] { + centipede_fixture_driver_->RunFuzzTest([&] { result = fuzztest::internal::RunnerMain(/*argc=*/2, replay_argv, runner_callbacks); }); @@ -904,6 +970,10 @@ const bool runner_mode = IsCentipedeRunner(); const bool is_running_property_function_in_this_process = runner_mode || + (mode == RunMode::kUnitTest && + !configuration.centipede_command.has_value() && + !configuration.continue_after_crash && + !configuration.crashing_input_to_reproduce.has_value()) || (configuration.crashing_input_to_reproduce.has_value() && configuration.replay_in_single_process) || std::getenv("FUZZTEST_REPLAY") || @@ -921,29 +991,33 @@ runtime_.SetRunMode(mode); runtime_.SetSkippingRequested(false); runtime_.SetCurrentTest(&test_, &configuration); - // We don't always enable reporter, but always disable it at the end for - // simplicity. - absl::Cleanup always_disable_reporter = [this]() { - runtime_.DisableReporter(); - }; + absl::Cleanup in_process_cleanup = + [this, is_running_property_function_in_this_process]() { + if (is_running_property_function_in_this_process) { + if (IsSilenceTargetEnabled()) RestoreTargetStdoutAndStderr(); + runtime_.DisableReporter(); + } + }; if (is_running_property_function_in_this_process) { if (IsSilenceTargetEnabled()) SilenceTargetStdoutAndStderr(); // TODO(b/393582695): Consider whether we need some kind of reporting // enabled in the controller mode to handle test setup failures. runtime_.EnableReporter(&fuzzer_impl_.stats_, [] { return absl::Now(); }); - } else { + } + if (!runner_mode) { + // When invoking the controller in-process these handlers may supercede with + // the what `EnableReporter` installs. But it's fine because the handlers + // here subsume the logic of the previous handles. InstallCentipedeTerminationHandler(); } + RegisterCrashMetadataForwarderOnce(runtime_); if (runner_mode) { - runtime_.RegisterCrashMetadataListener( - [](absl::string_view description, absl::string_view signature) { - CentipedeSetFailure(description.data(), description.size(), - signature.data(), signature.size()); - }); + // The runner reports all failures to the controller. + forward_crash_metadata_to_centipede.store(true, std::memory_order_relaxed); } if (runner_mode) { std::optional<int> result; - fuzzer_impl_.fixture_driver_->RunFuzzTest([&, this]() { + centipede_fixture_driver_->RunFuzzTest([&, this]() { CentipedeAdaptorRunnerCallbacks runner_callbacks(&runtime_, &fuzzer_impl_, &configuration); static char fake_argv0[] = "fake_argv"; @@ -962,17 +1036,13 @@ configuration.replay_in_single_process) { return ReplayCrashInSingleProcess(configuration); } - if (is_running_property_function_in_this_process) { - // If `is_running_property_function_in_this_process` holds at this point. We - // assume it is for `ReplayInputsIfAvailable` to handle `FUZZTEST_REPLAY` - // and `FUZZTEST_MINIMIZE_REPRODUCER`, which Centipede does not support. - // This is fine because it does not require coverage instrumentation. - FUZZTEST_CHECK(std::getenv("FUZZTEST_REPLAY") || - std::getenv("FUZZTEST_MINIMIZE_REPRODUCER")) - << "Both env vars `FUZZTEST_REPLAY` and `FUZZTEST_MINIMIZE_REPRODUCER` " - "are not set when calling the legacy input replaying - this is a " - "FuzzTest bug!"; - fuzzer_impl_.fixture_driver_->RunFuzzTest([&, this]() { + if (std::getenv("FUZZTEST_REPLAY") || + std::getenv("FUZZTEST_MINIMIZE_REPRODUCER")) { + // Handle `FUZZTEST_REPLAY` and `FUZZTEST_MINIMIZE_REPRODUCER`, which + // Centipede does not support. This is fine because it does not require + // coverage instrumentation. + centipede_fixture_driver_->set_use_legacy_runtime(true); + centipede_fixture_driver_->RunFuzzTest([&, this]() { FUZZTEST_PRECONDITION(fuzzer_impl_.ReplayInputsIfAvailable(configuration)) << "ReplayInputsIfAvailable failed to handle env vars " "`FUZZTEST_REPLAY` " @@ -982,6 +1052,13 @@ }); return true; } + FUZZTEST_CHECK(!is_running_property_function_in_this_process || + (mode == RunMode::kUnitTest && + !configuration.centipede_command.has_value() && + !configuration.continue_after_crash && + !configuration.crashing_input_to_reproduce.has_value())) + << "`is_running_property_function_in_this_process` is unexpectedly set " + " - this is a FuzzTest bug!"; // Run as the fuzzing engine. int result = EXIT_FAILURE; TempDir temp_dir("fuzztest_temp"); @@ -1071,7 +1148,25 @@ result = 0; return; } - result = RunCentipede(env, configuration.centipede_command); + if (is_running_property_function_in_this_process) { + absl::FPrintF(GetStderr(), "[.] Using in-process fuzzing execution.\n"); + centipede_fixture_driver_->RunFuzzTest([&, this] { + CentipedeAdaptorRunnerCallbacks runner_callbacks( + &runtime_, &fuzzer_impl_, &configuration); + // Forward the crash metadata only while Centipede is running in this + // process to receive it. + forward_crash_metadata_to_centipede.store(true, + std::memory_order_relaxed); + absl::Cleanup stop_forwarding = [] { + forward_crash_metadata_to_centipede.store(false, + std::memory_order_relaxed); + }; + result = RunCentipede(env, configuration.centipede_command, + &runner_callbacks); + }); + } else { + result = RunCentipede(env, configuration.centipede_command); + } if (std::filesystem::exists(skipped_test_indicator_file, ec)) { return; }
diff --git a/fuzztest/internal/googletest_adaptor.h b/fuzztest/internal/googletest_adaptor.h index 5580c6d..269c3a7 100644 --- a/fuzztest/internal/googletest_adaptor.h +++ b/fuzztest/internal/googletest_adaptor.h
@@ -100,6 +100,9 @@ Runtime::instance().skipping_requested()) << "Failure(s) found in the unit-test mode - please see the test " "log for more details."; + if (Runtime::instance().skipping_requested()) { + GTEST_SKIP() << "Requested by the fuzz test"; + } } } else { // TODO(b/245753736): Consider using `tolerate_failure` when FuzzTest can @@ -110,6 +113,9 @@ Runtime::instance().skipping_requested()) << "Failure(s) found in the fuzzing mode - please see the test log " "for more details."; + if (Runtime::instance().skipping_requested()) { + GTEST_SKIP() << "Requested by the fuzz test"; + } } }
diff --git a/fuzztest/internal/runtime.cc b/fuzztest/internal/runtime.cc index 2d4c296..941074b 100644 --- a/fuzztest/internal/runtime.cc +++ b/fuzztest/internal/runtime.cc
@@ -220,6 +220,8 @@ ReproducerOutputLocation GetReproducerOutputLocation() { #ifdef FUZZTEST_USE_CENTIPEDE + // TODO: b/587390979 - Fix the duplicated reproducer output when running with + // Centipede in-process execution. if (std::getenv("CENTIPEDE_RUNNER_FLAGS") != nullptr) { return ReproducerOutputLocation{ "", ReproducerOutputLocation::Type::kReportToController};