Cap and avoid zero-initializing write buffers in LocalRemoteFile. Callers of `RemoteFileSetWriteBufferSize` pass large flush thresholds (10 MiB to 100 MiB) tuned for remote I/O coalescing. `LocalRemoteFile::SetWriteBufSize` previously passed that size directly to `std::make_unique<char[]>(size)` and `std::setvbuf`, zero-filling 100 MiB buffers and bloating RSS under ASan for tiny local files. Cap the local `stdio` write buffer at 64 KiB and allocate it without value-initialization via `new char[...]`. PiperOrigin-RevId: 1024144073
diff --git a/common/remote_file_oss.cc b/common/remote_file_oss.cc index f6acde0..67ee4e6 100644 --- a/common/remote_file_oss.cc +++ b/common/remote_file_oss.cc
@@ -29,7 +29,9 @@ #include <windows.h> #endif // defined(_MSC_VER) +#include <algorithm> #include <cerrno> +#include <cstddef> #include <cstdint> #include <cstdio> #include <cstring> @@ -87,8 +89,13 @@ if (write_buf_ != nullptr) { return absl::FailedPreconditionError("SetWriteBufCapacity called twice"); } - write_buf_ = std::make_unique<char[]>(size); - if (std::setvbuf(file_, write_buf_.get(), _IOFBF, size) != 0) { + // Cap the stdio buffer size: callers pass large thresholds (e.g. 100 MiB) + // tuned for remote RPC coalescing, whereas local FILE* I/O does not benefit + // from huge buffers and eagerly allocating them bloats RSS. + static constexpr size_t kMaxWriteBufSize = 64UL * 1024; + const size_t capped_size = std::min(size, kMaxWriteBufSize); + write_buf_ = std::unique_ptr<char[]>(new char[capped_size]); + if (std::setvbuf(file_, write_buf_.get(), _IOFBF, capped_size) != 0) { return absl::UnknownError( absl::StrCat("std::setvbuf failed, path: ", path_, ", errno: ", std::strerror(errno)));
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..8d1bfdb 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 = @@ -415,7 +418,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 +460,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 +536,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 +631,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 +687,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 +728,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 +754,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 +774,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 +818,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 +957,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 +978,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 +1023,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 +1039,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 +1135,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};