No public description PiperOrigin-RevId: 1018756183
diff --git a/centipede/BUILD b/centipede/BUILD index 39a27ef..9370596 100644 --- a/centipede/BUILD +++ b/centipede/BUILD
@@ -635,6 +635,7 @@ ":byte_array_mutator", ":command", ":control_flow", + ":diff_baseline", ":environment", ":fuzztest_mutator", ":mutation_data", @@ -646,6 +647,7 @@ ":workdir", "@abseil-cpp//absl/base:no_destructor", "@abseil-cpp//absl/base:nullability", + "@abseil-cpp//absl/cleanup", "@abseil-cpp//absl/memory", "@abseil-cpp//absl/status:statusor", "@abseil-cpp//absl/strings", @@ -660,6 +662,29 @@ ) cc_library( + name = "diff_baseline", + srcs = ["diff_baseline.cc"], + hdrs = ["diff_baseline.h"], + deps = [ + ":environment", + ":execution_metadata", + ":runner_result", + ":stop", + "@abseil-cpp//absl/base:core_headers", + "@abseil-cpp//absl/base:no_destructor", + "@abseil-cpp//absl/container:flat_hash_map", + "@abseil-cpp//absl/status", + "@abseil-cpp//absl/strings", + "@abseil-cpp//absl/synchronization", + "@abseil-cpp//absl/types:span", + "@com_google_fuzztest//common:defs", + "@com_google_fuzztest//common:hash", + "@com_google_fuzztest//common:logging", + "@com_google_fuzztest//common:remote_file", + ], +) + +cc_library( name = "corpus_io", srcs = ["corpus_io.cc"], hdrs = ["corpus_io.h"], @@ -727,6 +752,7 @@ ":corpus", ":corpus_io", ":coverage", + ":diff_baseline", ":environment", ":feature", ":feature_set", @@ -771,6 +797,7 @@ ":coverage", ":crash_deduplication", ":crash_summary", + ":diff_baseline", ":distill", ":environment", ":minimize_crash", @@ -1600,11 +1627,30 @@ ) cc_test( + name = "diff_baseline_test", + srcs = ["diff_baseline_test.cc"], + deps = [ + ":diff_baseline", + ":environment", + ":execution_metadata", + ":runner_result", + ":stop", + ":util", + "@com_google_fuzztest//common:defs", + "@com_google_fuzztest//common:hash", + "@com_google_fuzztest//common:test_util", + "@googletest//:gtest_main", + ], +) + +cc_test( name = "execution_metadata_test", srcs = ["execution_metadata_test.cc"], deps = [ ":execution_metadata", + ":runner_request", ":shared_memory_blob_sequence", + "@abseil-cpp//absl/types:span", "@com_google_fuzztest//common:defs", "@googletest//:gtest_main", ], @@ -2049,6 +2095,7 @@ ":stop", ":util", ":workdir", + "@abseil-cpp//absl/container:flat_hash_map", "@abseil-cpp//absl/container:flat_hash_set", "@abseil-cpp//absl/strings", "@abseil-cpp//absl/time",
diff --git a/centipede/centipede.cc b/centipede/centipede.cc index 0057787..24eb388 100644 --- a/centipede/centipede.cc +++ b/centipede/centipede.cc
@@ -80,6 +80,7 @@ #include "./centipede/corpus.h" #include "./centipede/corpus_io.h" #include "./centipede/coverage.h" +#include "./centipede/diff_baseline.h" #include "./centipede/environment.h" #include "./centipede/feature.h" #include "./centipede/feature_set.h" @@ -496,6 +497,59 @@ bool success = ExecuteAndReportCrash(env_.binary, inputs, batch_result); FUZZTEST_CHECK_EQ(mutants.size(), batch_result.results().size()); + const size_t initial_read = + std::min(batch_result.num_outputs_read(), inputs.size()); + size_t total_outputs_read = initial_read; + uint64_t batch_peak_rss_mb = + initial_read > 0 + ? batch_result.results()[initial_read - 1].stats().peak_rss_mb + : 0; + + // Incremental differential fuzzing: when continuing after crashes, re-run the + // inputs after a single-input failure or shared-memory batch truncation so + // that every input in the batch is recorded or compared. + if (IsDiffActive(env_) && !env_.exit_on_crash) { + const auto next_tail_offset = [](bool sub_success, + const BatchResult& sub_result, + size_t sub_size) -> size_t { + const size_t read = sub_result.num_outputs_read(); + if (!sub_success) { + return IsSingleInputFailure(sub_result) && read + 1 < sub_size + ? read + 1 + : sub_size; + } + if (sub_result.exit_code() == EXIT_SUCCESS && read < sub_size) { + if (read == 0) { + DiffStats::Global().AddIncompleteBatch(); + return sub_size; + } + return read; + } + return sub_size; + }; + + for (size_t next = next_tail_offset(success, batch_result, inputs.size()); + next < inputs.size() && !stop_condition_.ShouldStop();) { + const auto sub_inputs = absl::MakeConstSpan(inputs).subspan(next); + BatchResult tail_result; + const bool tail_success = + ExecuteAndReportCrash(env_.binary, sub_inputs, tail_result); + success = success && tail_success; + const size_t tail_read = + std::min(tail_result.num_outputs_read(), sub_inputs.size()); + total_outputs_read += tail_read; + if (tail_read > 0) { + batch_peak_rss_mb = + std::max(batch_peak_rss_mb, + tail_result.results()[tail_read - 1].stats().peak_rss_mb); + } + for (size_t j = 0; j < tail_read; ++j) { + batch_result.results()[next + j] = std::move(tail_result.results()[j]); + } + next += next_tail_offset(tail_success, tail_result, sub_inputs.size()); + } + } + for (const auto &extra_binary : env_.extra_binaries) { if (stop_condition_.ShouldStop()) break; BatchResult extra_batch_result; @@ -570,16 +624,8 @@ } } } - num_runs_ += batch_result.num_outputs_read(); - if (batch_result.num_outputs_read() > 0) { - // The reported values increase monotonically within a batch. So it suffices - // to look at the last value. - execution_peak_rss_mb_ = - std::max(execution_peak_rss_mb_, - batch_result.results()[batch_result.num_outputs_read() - 1] - .stats() - .peak_rss_mb); - } + num_runs_ += total_outputs_read; + execution_peak_rss_mb_ = std::max(execution_peak_rss_mb_, batch_peak_rss_mb); corpus_.UpdateWeights(fs_, coverage_frontier_, env_.exec_time_weight_scaling); return batch_gained_new_coverage; }
diff --git a/centipede/centipede_callbacks.cc b/centipede/centipede_callbacks.cc index 1a79da2..d046f04 100644 --- a/centipede/centipede_callbacks.cc +++ b/centipede/centipede_callbacks.cc
@@ -37,6 +37,7 @@ #include <vector> #include "absl/base/no_destructor.h" +#include "absl/cleanup/cleanup.h" #include "absl/memory/memory.h" #include "absl/strings/ascii.h" #include "absl/strings/str_cat.h" @@ -49,6 +50,7 @@ #include "./centipede/binary_info.h" #include "./centipede/command.h" #include "./centipede/control_flow.h" +#include "./centipede/diff_baseline.h" #include "./centipede/mutation_data.h" #include "./centipede/runner_request.h" #include "./centipede/runner_result.h" @@ -550,15 +552,37 @@ outputs_blobseq_.Reset(); size_t num_inputs_written = 0; + // Incremental differential fuzzing (never active with input wildcards). + const bool diff_active = diff_store_.active(); + DiffBatch diff_batch; if (env_.has_input_wildcards) { FUZZTEST_CHECK_EQ(inputs.size(), 1); WriteToLocalFile(temp_input_file_path_, inputs[0]); num_inputs_written = 1; + } else if (diff_active) { + // In the validate mode, the baseline of each input (if any) is sent as + // metadata before the input. In the record mode, `diff_batch.metadata` is + // empty and no metadata blobs are written. + diff_batch = diff_store_.PrepareBatch(inputs); + if (diff_batch.metadata.empty()) { + num_inputs_written = RequestExecution(inputs, inputs_blobseq_); + } else { + const std::vector<ByteSpan> metadata(diff_batch.metadata.begin(), + diff_batch.metadata.end()); + num_inputs_written = RequestExecution(inputs, metadata, inputs_blobseq_); + } } else { // Feed the inputs to inputs_blobseq_. num_inputs_written = RequestExecution(inputs, inputs_blobseq_); } + // Post-processes the diff results on every return path below. + absl::Cleanup process_diff_results = [&] { + if (diff_active) { + diff_store_.ProcessBatchResult(diff_batch, batch_result, + num_inputs_written); + } + }; if (num_inputs_written != inputs.size()) { FUZZTEST_LOG(INFO) << "Wrote " << num_inputs_written << "/" << inputs.size()
diff --git a/centipede/centipede_callbacks.h b/centipede/centipede_callbacks.h index 38d6bc3..2a0fc87 100644 --- a/centipede/centipede_callbacks.h +++ b/centipede/centipede_callbacks.h
@@ -29,6 +29,7 @@ #include "./centipede/binary_info.h" #include "./centipede/byte_array_mutator.h" #include "./centipede/command.h" +#include "./centipede/diff_baseline.h" #include "./centipede/environment.h" #include "./centipede/fuzztest_mutator.h" #include "./centipede/mutation_data.h" @@ -209,6 +210,10 @@ // Need unique_ptr indirection because CommandContext is not movable/copyable // due to Command. std::vector<std::unique_ptr<CommandContext>> command_contexts_; + + // Baseline store for the incremental differential fuzzing (inactive unless + // the diff mode is set for corpus replay). + DiffBaselineStore diff_store_{env_}; }; // Abstract class for creating/destroying CentipedeCallbacks objects.
diff --git a/centipede/centipede_flags.inc b/centipede/centipede_flags.inc index a335b6e..8fab92b 100644 --- a/centipede/centipede_flags.inc +++ b/centipede/centipede_flags.inc
@@ -539,6 +539,12 @@ absl::Duration, fuzztest_time_limit_per_test, absl::InfiniteDuration(), "The time limit per fuzz test for working on the corpus database.") CENTIPEDE_FLAG( + std::string, fuzztest_diff_mode, "", + "Incremental differential fuzzing mode for corpus replay: \"record\", " + "\"validate\", or empty (disabled). Effective only together with " + "--fuzztest_only_replay. The baseline is stored under " + "<fuzztest_workdir_root>/baseline/<fuzztest_binary_identifier>/<test>/.") +CENTIPEDE_FLAG( size_t, replay_crash_attempts, 1, "Number of attempts to replay a crash input during batch failure triage " "or deduplication before considering it non-reproducible.")
diff --git a/centipede/centipede_interface.cc b/centipede/centipede_interface.cc index ffbb00f..4a63675 100644 --- a/centipede/centipede_interface.cc +++ b/centipede/centipede_interface.cc
@@ -50,6 +50,7 @@ #include "./centipede/coverage.h" #include "./centipede/crash_deduplication.h" #include "./centipede/crash_summary.h" +#include "./centipede/diff_baseline.h" #include "./centipede/distill.h" #include "./centipede/environment.h" #include "./centipede/minimize_crash.h" @@ -640,6 +641,15 @@ RemoteFileSetContents(execution_id_path, env.fuzztest_execution_id)); } + bool diff_prepared = false; + // Incremental differential fuzzing: print the summary and decide the result + // at the end of the test. Declared before `clean_up_workdir` so that it runs + // after the workdir cleanup (and after `RecordFuzzingResults`). + absl::Cleanup finish_diff = [&diff_prepared, &env, &stop_condition] { + if (diff_prepared) { + FinishDiffForTest(env, stop_condition); + } + }; absl::Cleanup clean_up_workdir = [is_workdir_specified, &env, &stop_condition] { if (!is_workdir_specified && !stop_condition.StopRequested()) { @@ -662,6 +672,13 @@ << "while generating the seed corpus"; } + // Incremental differential fuzzing: set up the baseline of the test (no-op + // unless the diff mode is active). May request a failing stop. + if (!stop_condition.StopRequested()) { + PrepareDiffBaselineForTest(env, stop_condition); + diff_prepared = !stop_condition.StopRequested(); + } + absl::Duration time_limit = env.fuzztest_time_limit_per_test; absl::Duration time_spent = absl::ZeroDuration(); const std::string fuzzing_time_file =
diff --git a/centipede/centipede_test.cc b/centipede/centipede_test.cc index d7fe79a..fdc58d9 100644 --- a/centipede/centipede_test.cc +++ b/centipede/centipede_test.cc
@@ -29,6 +29,7 @@ #include "gmock/gmock.h" #include "gtest/gtest.h" +#include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/str_cat.h" #include "absl/time/clock.h" @@ -63,7 +64,9 @@ using ::testing::IsSupersetOf; using ::testing::Le; using ::testing::Not; +using ::testing::Pair; using ::testing::SizeIs; +using ::testing::UnorderedElementsAre; inline std::vector<ByteSpan> AsByteSpans(const std::vector<ByteArray>& inputs) { std::vector<ByteSpan> results; @@ -1280,6 +1283,163 @@ EXPECT_EQ(batch_result.failure_description(), "stack-limit-exceeded"); } +// Fails the batch at every input whose only byte is in `crashing_values` (or +// truncates cleanly after `max_inputs_per_call` inputs when > 0), and counts +// the successful executions of every input value. +class FakeTailRerunCallbacks : public CentipedeCallbacks { + public: + FakeTailRerunCallbacks(const Environment& env, + absl::flat_hash_set<uint8_t> crashing, + size_t max_inputs_per_call = 0, + std::string failure_description = "crash") + : CentipedeCallbacks(env, internal_stop_condition_), + crashing_values_(std::move(crashing)), + max_inputs_per_call_(max_inputs_per_call), + failure_description_(std::move(failure_description)) {} + + bool Execute(std::string_view binary, absl::Span<const ByteSpan> inputs, + BatchResult& batch_result) override { + ++execute_calls_; + batch_result.ClearAndResize(inputs.size()); + const size_t limit = max_inputs_per_call_ > 0 + ? std::min(inputs.size(), max_inputs_per_call_) + : inputs.size(); + for (size_t i = 0; i < limit; ++i) { + FUZZTEST_CHECK_EQ(inputs[i].size(), 1); + if (crashing_values_.contains(inputs[i][0])) { + batch_result.num_outputs_read() = i; + batch_result.exit_code() = EXIT_FAILURE; + batch_result.failure_description() = failure_description_; + return false; + } + ++num_executions_[inputs[i][0]]; + } + batch_result.num_outputs_read() = limit; + return true; + } + + // Generates the 1-byte mutants 100, 101, ... (distinct from the seed {0}). + std::vector<Mutant> Mutate(absl::Span<const MutationInputRef> inputs, + size_t num_mutants) override { + std::vector<Mutant> mutants; + mutants.reserve(num_mutants); + for (size_t i = 0; i < num_mutants; ++i) { + mutants.push_back({/*data=*/{static_cast<uint8_t>(next_value_++)}, + Mutant::kOriginNone}); + } + return mutants; + } + + const absl::flat_hash_map<uint8_t, int>& num_executions() const { + return num_executions_; + } + int execute_calls() const { return execute_calls_; } + + private: + absl::flat_hash_set<uint8_t> crashing_values_; + size_t max_inputs_per_call_; + std::string failure_description_; + absl::flat_hash_map<uint8_t, int> num_executions_; + int execute_calls_ = 0; + size_t next_value_ = 100; + StopCondition internal_stop_condition_; +}; + +Environment TailRerunEnv(std::string_view workdir) { + Environment env; + env.log_level = 0; + env.workdir = workdir; + env.batch_size = 10; + // Seed {0} runs before `num_runs_` is reset, so `num_runs = 10` runs exactly + // one mutant batch of 10 inputs (100..109). + env.num_runs = 10; + env.require_pc_table = false; + env.exit_on_crash = false; + // Only re-execute the suspect when reporting a crash, so that the counts + // below reflect the batch executions. + env.batch_triage_suspect_only = true; + return env; +} + +TEST(Centipede, DiffModeReRunsTheTailOfAFailedBatch) { + TempDir temp_dir{test_info_->name()}; + Environment env = TailRerunEnv(temp_dir.path().string()); + env.fuzztest_diff_mode = "record"; + env.fuzztest_only_replay = true; + FakeTailRerunCallbacks fake(env, /*crashing=*/{103, 106}); + NonOwningCallbacksFactory factory(fake); + EXPECT_EQ(CentipedeMain(env, factory), EXIT_SUCCESS); + // Seed {0} plus all 8 non-crashing inputs of the mutant batch (100..109 \ + // {103, 106}). + EXPECT_THAT(fake.num_executions(), + UnorderedElementsAre(Pair(0, 1), Pair(100, 1), Pair(101, 1), + Pair(102, 1), Pair(104, 1), Pair(105, 1), + Pair(107, 1), Pair(108, 1), Pair(109, 1))); +} + +TEST(Centipede, DiffModeCrashOnFinalElementDoesNotIssueEmptyTailBatch) { + TempDir temp_dir{test_info_->name()}; + Environment env = TailRerunEnv(temp_dir.path().string()); + env.fuzztest_diff_mode = "record"; + env.fuzztest_only_replay = true; + FakeTailRerunCallbacks fake(env, /*crashing=*/{109}); + NonOwningCallbacksFactory factory(fake); + EXPECT_EQ(CentipedeMain(env, factory), EXIT_SUCCESS); + // 1 seed batch ({0}) + 1 mutant batch (100..109) + 1 suspect triage ({109}) = + // 3 Execute calls (no empty subspan tail call after 109). + EXPECT_EQ(fake.execute_calls(), 3); + EXPECT_THAT( + fake.num_executions(), + UnorderedElementsAre(Pair(0, 1), Pair(100, 1), Pair(101, 1), Pair(102, 1), + Pair(103, 1), Pair(104, 1), Pair(105, 1), + Pair(106, 1), Pair(107, 1), Pair(108, 1))); +} + +TEST(Centipede, DiffModeReRunsShmemTruncatedSubBatches) { + TempDir temp_dir{test_info_->name()}; + Environment env = TailRerunEnv(temp_dir.path().string()); + env.fuzztest_diff_mode = "validate"; + env.fuzztest_only_replay = true; + FakeTailRerunCallbacks fake(env, /*crashing=*/{}, + /*max_inputs_per_call=*/4); + NonOwningCallbacksFactory factory(fake); + EXPECT_EQ(CentipedeMain(env, factory), EXIT_SUCCESS); + // 1 seed batch ({0}) + 3 sub-batches (4 + 4 + 2) for 100..109 = 4 calls. + EXPECT_EQ(fake.execute_calls(), 4); + EXPECT_THAT(fake.num_executions(), + UnorderedElementsAre(Pair(0, 1), Pair(100, 1), Pair(101, 1), + Pair(102, 1), Pair(103, 1), Pair(104, 1), + Pair(105, 1), Pair(106, 1), Pair(107, 1), + Pair(108, 1), Pair(109, 1))); +} + +TEST(Centipede, DiffModeDoesNotReRunTailOnPerBatchTimeout) { + TempDir temp_dir{test_info_->name()}; + Environment env = TailRerunEnv(temp_dir.path().string()); + env.fuzztest_diff_mode = "validate"; + env.fuzztest_only_replay = true; + FakeTailRerunCallbacks fake(env, /*crashing=*/{102}, + /*max_inputs_per_call=*/0, + std::string(kExecutionFailurePerBatchTimeout)); + NonOwningCallbacksFactory factory(fake); + EXPECT_EQ(CentipedeMain(env, factory), EXIT_SUCCESS); + // Seed {0} + inputs 100, 101 ran; inputs 103..109 in the batch were NOT + // re-run because per-batch timeout is not a single-input failure. + EXPECT_THAT(fake.num_executions(), + UnorderedElementsAre(Pair(0, 1), Pair(100, 1), Pair(101, 1))); +} + +TEST(Centipede, WithoutDiffModeTheTailOfAFailedBatchIsNotReRun) { + TempDir temp_dir{test_info_->name()}; + Environment env = TailRerunEnv(temp_dir.path().string()); + FakeTailRerunCallbacks fake(env, /*crashing=*/{103, 106}); + NonOwningCallbacksFactory factory(fake); + EXPECT_EQ(CentipedeMain(env, factory), EXIT_SUCCESS); + EXPECT_THAT(fake.num_executions(), + UnorderedElementsAre(Pair(0, 1), Pair(100, 1), Pair(101, 1), + Pair(102, 1))); +} + class SetupFailureCallbacks : public CentipedeCallbacks { public: explicit SetupFailureCallbacks(const Environment& env)
diff --git a/centipede/diff_baseline.cc b/centipede/diff_baseline.cc new file mode 100644 index 0000000..8d3aba9 --- /dev/null +++ b/centipede/diff_baseline.cc
@@ -0,0 +1,459 @@ +// Copyright 2026 The Centipede Authors. +// +// 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. + +#include "./centipede/diff_baseline.h" + +#include <algorithm> +#include <cstddef> +#include <cstdint> +#include <cstdlib> +#include <filesystem> // NOLINT +#include <optional> +#include <string> +#include <string_view> +#include <utility> +#include <vector> + +#include "absl/base/no_destructor.h" +#include "absl/status/status.h" +#include "absl/strings/match.h" +#include "absl/synchronization/mutex.h" +#include "absl/types/span.h" +#include "./centipede/environment.h" +#include "./centipede/execution_metadata.h" +#include "./centipede/runner_result.h" +#include "./centipede/stop.h" +#include "./common/defs.h" +#include "./common/hash.h" +#include "./common/logging.h" +#include "./common/remote_file.h" + +namespace fuzztest::internal { + +namespace { + +// Maximum number of per-input log lines of each kind. +constexpr size_t kMaxPerInputLogLines = 20; + +bool IsValidAbsoluteOrRemoteDir(std::string_view dir) { + if (dir.empty()) return false; + if (absl::StrContains(dir, "://")) return true; + return std::filesystem::path(dir).is_absolute(); +} + +size_t DiffStats::Snapshot::* CounterForFlag(DiffStats::InputFlag flag) { + switch (flag) { + case DiffStats::InputFlag::kSent: + return &DiffStats::Snapshot::baselines_sent; + case DiffStats::InputFlag::kMissing: + return &DiffStats::Snapshot::baselines_missing; + case DiffStats::InputFlag::kAcknowledged: + return &DiffStats::Snapshot::baselines_acknowledged; + case DiffStats::InputFlag::kUnparsable: + return &DiffStats::Snapshot::inputs_unparsable; + case DiffStats::InputFlag::kUnparsableWithBaseline: + return &DiffStats::Snapshot::unparsable_with_baseline; + case DiffStats::InputFlag::kFailed: + return &DiffStats::Snapshot::inputs_failed; + case DiffStats::InputFlag::kMismatch: + return &DiffStats::Snapshot::mismatches; + } + FUZZTEST_LOG(FATAL) << "Unknown DiffStats::InputFlag: " + << static_cast<int>(flag); +} + +} // namespace + +bool IsDiffActive(const Environment& env) { + return (env.fuzztest_diff_mode == "record" || + env.fuzztest_diff_mode == "validate") && + env.fuzztest_only_replay && !env.replay_crash && + !env.has_input_wildcards; +} + +bool IsDiffRecord(const Environment& env) { + return IsDiffActive(env) && env.fuzztest_diff_mode == "record"; +} + +bool IsDiffValidate(const Environment& env) { + return IsDiffActive(env) && env.fuzztest_diff_mode == "validate"; +} + +bool IsSingleInputFailure(const BatchResult& result) { + return result.IsInputFailure() && + result.failure_description() != kExecutionFailurePerBatchTimeout; +} + +std::string DiffBaselineBinaryDir(const Environment& env) { + return (std::filesystem::path(env.fuzztest_workdir_root) / "baseline" / + env.fuzztest_binary_identifier) + .string(); +} + +std::string DiffBaselineTestDir(const Environment& env) { + return (std::filesystem::path(DiffBaselineBinaryDir(env)) / env.test_name) + .string(); +} + +DiffStats& DiffStats::Global() { + static absl::NoDestructor<DiffStats> stats; + return *stats; +} + +void DiffStats::Reset() { + absl::MutexLock lock(mu_); + snapshot_ = {}; + input_flags_.clear(); + warned_about_missing_diff_data_ = false; +} + +DiffStats::Snapshot DiffStats::Get() const { + absl::MutexLock lock(mu_); + return snapshot_; +} + +void DiffStats::AddExecution() { + absl::MutexLock lock(mu_); + ++snapshot_.executions; +} + +void DiffStats::AddBaselineWritten() { + absl::MutexLock lock(mu_); + ++snapshot_.baselines_written; +} + +void DiffStats::AddIoError() { + absl::MutexLock lock(mu_); + ++snapshot_.io_errors; +} + +void DiffStats::AddIncompleteBatch() { + absl::MutexLock lock(mu_); + ++snapshot_.incomplete_batches; +} + +size_t DiffStats::MarkInput(std::string_view hash, InputFlag flag) { + const uint8_t bit = static_cast<uint8_t>(flag); + absl::MutexLock lock(mu_); + auto [it, inserted] = input_flags_.try_emplace(hash, bit); + if (!inserted) { + if ((it->second & bit) != 0) return 0; + it->second |= bit; + } + return ++(snapshot_.*CounterForFlag(flag)); +} + +bool DiffStats::ShouldWarnAboutMissingDiffData() { + absl::MutexLock lock(mu_); + if (warned_about_missing_diff_data_) return false; + warned_about_missing_diff_data_ = true; + return true; +} + +DiffBaselineStore::DiffBaselineStore(const Environment& env) + : active_(IsDiffActive(env) && + IsValidAbsoluteOrRemoteDir(env.fuzztest_workdir_root)), + record_(IsDiffRecord(env)), + test_dir_(active_ ? DiffBaselineTestDir(env) : "") {} + +std::string DiffBaselineStore::BaselinePath(std::string_view hash) const { + return (std::filesystem::path(test_dir_) / hash).string(); +} + +std::optional<ByteArray> DiffBaselineStore::Lookup(std::string_view hash) { + { + absl::MutexLock lock(mu_); + if (auto it = cache_.find(hash); it != cache_.end()) return it->second; + } + const std::string path = BaselinePath(hash); + std::optional<ByteArray> result; + if (RemotePathExists(path)) { + if (RemotePathIsDirectory(path)) { + FUZZTEST_LOG(ERROR) << "[diff] ERROR: baseline path is a directory, " + "expected a file: " + << path; + DiffStats::Global().AddIoError(); + return std::nullopt; + } + ByteArray contents; + const absl::Status status = RemoteFileGetContents(path, contents); + if (!status.ok()) { + FUZZTEST_LOG(ERROR) << "[diff] ERROR: failed to read baseline file " + << path << ": " << status; + DiffStats::Global().AddIoError(); + return std::nullopt; + } + result = std::move(contents); + } + absl::MutexLock lock(mu_); + cache_.emplace(hash, result); + return result; +} + +absl::Status DiffBaselineStore::Save(std::string_view hash, + ByteSpan container) { + return RemoteFileSetContents(BaselinePath(hash), container); +} + +DiffBatch DiffBaselineStore::PrepareBatch(absl::Span<const ByteSpan> inputs) { + DiffBatch batch; + batch.hashes.reserve(inputs.size()); + if (!record_) { + batch.metadata.resize(inputs.size()); + } + for (size_t i = 0; i < inputs.size(); ++i) { + batch.hashes.push_back(Hash(inputs[i])); + if (record_) continue; + std::optional<ByteArray> baseline = Lookup(batch.hashes.back()); + if (baseline.has_value()) { + batch.metadata[i] = EncodeDiffEnvelope(DiffEnvelopeKind::kExpectations, + /*cmp_data=*/{}, *baseline); + } + } + return batch; +} + +void DiffBaselineStore::ProcessBatchResult( + const DiffBatch& batch, BatchResult& batch_result, + std::optional<size_t> num_inputs_written) { + DiffStats& stats = DiffStats::Global(); + const size_t n_written = std::min( + num_inputs_written.value_or(batch.hashes.size()), batch.hashes.size()); + const auto had_baseline = [&batch](size_t i) { + return i < batch.metadata.size() && !batch.metadata[i].empty(); + }; + if (!record_) { + for (size_t i = 0; i < n_written; ++i) { + stats.MarkInput(batch.hashes[i], had_baseline(i) + ? DiffStats::InputFlag::kSent + : DiffStats::InputFlag::kMissing); + } + } + const size_t num_results = + std::min({batch_result.num_outputs_read(), n_written, + batch_result.results().size()}); + for (size_t i = 0; i < num_results; ++i) { + ExecutionMetadata& metadata = batch_result.results()[i].metadata(); + DiffEnvelopeKind kind; + ByteSpan cmp_data; + ByteSpan payload; + if (!DecodeDiffEnvelope(metadata.cmp_data, kind, cmp_data, payload) || + kind == DiffEnvelopeKind::kExpectations) { + if (stats.ShouldWarnAboutMissingDiffData()) { + FUZZTEST_LOG(WARNING) + << "[diff] WARNING: worker returned no RecordOrDiff data for an " + "executed input; is RecordOrDiff supported by this binary?"; + } + continue; + } + const std::string& hash = batch.hashes[i]; + switch (kind) { + case DiffEnvelopeKind::kRecords: + stats.AddExecution(); + if (!record_) break; + if (const absl::Status status = Save(hash, payload); status.ok()) { + stats.AddBaselineWritten(); + } else { + FUZZTEST_LOG(ERROR) << "[diff] ERROR: failed to write baseline file " + << BaselinePath(hash) << ": " << status; + stats.AddIoError(); + } + break; + case DiffEnvelopeKind::kAck: + stats.AddExecution(); + if (had_baseline(i)) { + stats.MarkInput(hash, DiffStats::InputFlag::kAcknowledged); + } + break; + case DiffEnvelopeKind::kSkippedUnparsable: + stats.AddExecution(); + if (had_baseline(i)) { + stats.MarkInput(hash, DiffStats::InputFlag::kUnparsableWithBaseline); + } + if (const size_t count = + stats.MarkInput(hash, DiffStats::InputFlag::kUnparsable); + count > 0 && count <= kMaxPerInputLogLines) { + FUZZTEST_LOG(WARNING) + << "[diff] WARNING: input " << hash + << " could not be parsed by the current FUZZ_TEST domains; " + "RecordOrDiff skipped it"; + } + break; + case DiffEnvelopeKind::kExpectations: + break; + } + // Copy the plain CMP slice before replacing `metadata.cmp_data`, since + // `cmp_data` points into it. + metadata.cmp_data = ByteArray(cmp_data.begin(), cmp_data.end()); + } + if (batch_result.exit_code() != EXIT_SUCCESS) { + if (IsSingleInputFailure(batch_result) && + batch_result.num_outputs_read() < n_written) { + const std::string& hash = batch.hashes[batch_result.num_outputs_read()]; + stats.MarkInput(hash, DiffStats::InputFlag::kFailed); + if (absl::StartsWith(batch_result.failure_description(), + kDiffMismatchFailurePrefix)) { + if (const size_t count = + stats.MarkInput(hash, DiffStats::InputFlag::kMismatch); + count > 0 && count <= kMaxPerInputLogLines) { + FUZZTEST_LOG(INFO) << "[diff] Mismatch for input " << hash + << "; baseline file " << BaselinePath(hash); + } + } + } else if (!batch_result.IsIgnoredFailure() && + !batch_result.IsSkippedTest() && + batch_result.num_outputs_read() < batch.hashes.size()) { + stats.AddIncompleteBatch(); + } + } +} + +void PrepareDiffBaselineForTest(const Environment& env, + StopCondition& stop_condition) { + if (!env.fuzztest_diff_mode.empty() && env.fuzztest_diff_mode != "none" && + env.fuzztest_diff_mode != "record" && + env.fuzztest_diff_mode != "validate") { + FUZZTEST_LOG(ERROR) << "[diff] ERROR: invalid --fuzztest_diff_mode='" + << env.fuzztest_diff_mode + << "'; must be one of: none, record, validate"; + stop_condition.RequestStop(EXIT_FAILURE, "Invalid --fuzztest_diff_mode"); + return; + } + if (!IsDiffActive(env)) return; + DiffStats::Global().Reset(); + if (!IsValidAbsoluteOrRemoteDir(env.fuzztest_workdir_root)) { + FUZZTEST_LOG(ERROR) + << "[diff] ERROR: --fuzztest_workdir_root must be a non-empty " + "absolute path when --fuzztest_diff_mode is enabled (got '" + << env.fuzztest_workdir_root << "')"; + stop_condition.RequestStop( + EXIT_FAILURE, + "RecordOrDiff requires an absolute --fuzztest_workdir_root"); + return; + } + if (env.test_name.empty()) { + FUZZTEST_LOG(ERROR) << "[diff] ERROR: --test_name must not be empty when " + "--fuzztest_diff_mode is enabled"; + stop_condition.RequestStop(EXIT_FAILURE, + "RecordOrDiff requires a non-empty test_name"); + return; + } + const std::string test_dir = DiffBaselineTestDir(env); + if (IsDiffRecord(env)) { + FUZZTEST_LOG(INFO) << "[diff] Recording baseline for " << env.test_name + << " into " << test_dir; + // Start from scratch so that stale baselines cannot leak in. + if (RemotePathExists(test_dir)) { + FUZZTEST_CHECK_OK(RemotePathDelete(test_dir, /*recursively=*/true)); + } + FUZZTEST_CHECK_OK(RemoteMkdir(test_dir)); + return; + } + FUZZTEST_LOG(INFO) << "[diff] Validating " << env.test_name + << " against baseline " << test_dir; + const std::string binary_dir = DiffBaselineBinaryDir(env); + if (!RemotePathExists(binary_dir)) { + FUZZTEST_LOG(ERROR) << "[diff] ERROR: baseline directory " << binary_dir + << " does not exist; run --fuzztest_record with the " + "same --fuzztest_workdir_root first"; + stop_condition.RequestStop(EXIT_FAILURE, + "RecordOrDiff baseline directory is missing"); + return; + } + if (!RemotePathExists(test_dir)) { + FUZZTEST_LOG(WARNING) << "[diff] WARNING: baseline directory " << test_dir + << " does not exist; every input will count as " + "baselines_missing"; + } +} + +void FinishDiffForTest(const Environment& env, StopCondition& stop_condition) { + if (!IsDiffActive(env)) return; + const bool record = IsDiffRecord(env); + const DiffStats::Snapshot stats = DiffStats::Global().Get(); + FUZZTEST_LOG(INFO) << "[diff] Summary for " << env.test_name + << ": mode=" << (record ? "record" : "validate") + << " executions=" << stats.executions + << " baselines_written=" << stats.baselines_written + << " baselines_sent=" << stats.baselines_sent + << " baselines_acknowledged=" + << stats.baselines_acknowledged + << " baselines_missing=" << stats.baselines_missing + << " inputs_unparsable=" << stats.inputs_unparsable + << " inputs_failed=" << stats.inputs_failed + << " mismatches=" << stats.mismatches + << " io_errors=" << stats.io_errors + << " incomplete_batches=" << stats.incomplete_batches; + bool failed = false; + std::string failure_reason; + if (stats.io_errors > 0) { + FUZZTEST_LOG(ERROR) << "[diff] ERROR: " << stats.io_errors + << " baseline file I/O error(s) occurred for " + << env.test_name; + failed = true; + failure_reason = "RecordOrDiff baseline I/O error"; + } + if (stats.incomplete_batches > 0) { + FUZZTEST_LOG(ERROR) << "[diff] ERROR: " << stats.incomplete_batches + << " batch(es) of " << env.test_name + << " ended early leaving inputs unexecuted"; + failed = true; + if (failure_reason.empty()) { + failure_reason = "RecordOrDiff execution was incomplete"; + } + } + if (record) { + if (stats.inputs_failed > 0) { + // Fail the record run so that an incomplete baseline does not go + // unnoticed. + FUZZTEST_LOG(ERROR) << "[diff] ERROR: record of " << env.test_name + << " is incomplete because " << stats.inputs_failed + << " input(s) failed and have no baseline"; + failed = true; + if (failure_reason.empty()) { + failure_reason = "RecordOrDiff record had failing inputs"; + } + } + } else { + if (stats.mismatches > 0) { + FUZZTEST_LOG(ERROR) << "[diff] ERROR: " << stats.mismatches + << " input(s) of " << env.test_name + << " differ from the baseline"; + failed = true; + } + if (stats.unparsable_with_baseline > 0) { + FUZZTEST_LOG(ERROR) + << "[diff] ERROR: " << stats.unparsable_with_baseline + << " input(s) of " << env.test_name + << " have a baseline but could not be parsed by the current " + "FUZZ_TEST domains (did the signature or domains change since " + "record?)"; + failed = true; + } + if (stats.baselines_sent == 0 && stats.executions > 0) { + FUZZTEST_LOG(WARNING) + << "[diff] WARNING: no executed input of " << env.test_name + << " had a baseline; was the baseline recorded from the same corpus " + "database?"; + } + if (failed && failure_reason.empty()) { + failure_reason = "RecordOrDiff validation failed"; + } + } + if (failed && !stop_condition.StopRequested()) { + stop_condition.RequestStop(EXIT_FAILURE, failure_reason); + } +} + +} // namespace fuzztest::internal
diff --git a/centipede/diff_baseline.h b/centipede/diff_baseline.h new file mode 100644 index 0000000..7ab1145 --- /dev/null +++ b/centipede/diff_baseline.h
@@ -0,0 +1,190 @@ +// Copyright 2026 The Centipede Authors. +// +// 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. + +// Controller-side support for incremental differential fuzzing +// (`fuzztest::RecordOrDiff`). +// +// The baseline of a fuzz test is stored by the controller at +// +// <fuzztest_workdir_root>/baseline/<fuzztest_binary_identifier>/<test>/<hash> +// +// where <hash> is `Hash()` of the exact input bytes and the file content is the +// record container produced by the runner (opaque to Centipede). All file I/O +// of the feature happens here, in the controller; the runner never touches +// these paths. + +#ifndef FUZZTEST_CENTIPEDE_DIFF_BASELINE_H_ +#define FUZZTEST_CENTIPEDE_DIFF_BASELINE_H_ + +#include <cstddef> +#include <cstdint> +#include <optional> +#include <string> +#include <string_view> +#include <vector> + +#include "absl/base/thread_annotations.h" +#include "absl/container/flat_hash_map.h" +#include "absl/status/status.h" +#include "absl/synchronization/mutex.h" +#include "absl/types/span.h" +#include "./centipede/environment.h" +#include "./centipede/runner_result.h" +#include "./centipede/stop.h" +#include "./common/defs.h" + +namespace fuzztest::internal { + +// The failure description prefix of RecordOrDiff mismatch findings. +inline constexpr std::string_view kDiffMismatchFailurePrefix = + "RecordOrDiff mismatch"; + +// Returns true iff the incremental differential fuzzing is active for `env`. +bool IsDiffActive(const Environment& env); +bool IsDiffRecord(const Environment& env); +bool IsDiffValidate(const Environment& env); + +// Returns true iff `result` represents a failure attributable to a single +// executed input (as opposed to setup failures, skipped tests, or per-batch +// timeouts). +bool IsSingleInputFailure(const BatchResult& result); + +// Returns `<fuzztest_workdir_root>/baseline/<fuzztest_binary_identifier>`. +std::string DiffBaselineBinaryDir(const Environment& env); + +// Returns `<fuzztest_workdir_root>/baseline/<binary id>/<test_name>`. +std::string DiffBaselineTestDir(const Environment& env); + +// Counters of the incremental differential fuzzing of the current test, +// shared by all shards of the controller process. Reset by +// `PrepareDiffBaselineForTest`, so they are per-test as long as the tests of a +// controller run sequentially. +class DiffStats { + public: + struct Snapshot { + // Results with a well-formed envelope (counting re-executions). + size_t executions = 0; + // Baseline file writes (counting overwrites). + size_t baselines_written = 0; + // Baseline file read or write I/O errors. + size_t io_errors = 0; + // Batches that ended early without a single-input failure (e.g. per-batch + // timeout or setup failure) leaving inputs unexecuted. + size_t incomplete_batches = 0; + // The following count distinct inputs. + size_t baselines_sent = 0; + size_t baselines_acknowledged = 0; + size_t baselines_missing = 0; + size_t inputs_unparsable = 0; + size_t inputs_failed = 0; + size_t mismatches = 0; + // Inputs that were sent a baseline but were unparsable. + size_t unparsable_with_baseline = 0; + }; + + enum class InputFlag : uint8_t { + kSent = 1 << 0, + kMissing = 1 << 1, + kAcknowledged = 1 << 2, + kUnparsable = 1 << 3, + kUnparsableWithBaseline = 1 << 4, + kFailed = 1 << 5, + kMismatch = 1 << 6, + }; + + static DiffStats& Global(); + + void Reset(); + Snapshot Get() const; + + void AddExecution(); + void AddBaselineWritten(); + void AddIoError(); + void AddIncompleteBatch(); + // Records `flag` for `hash` if not already set. Returns the new count for + // `flag`, or 0 if `hash` was already recorded for `flag`. + size_t MarkInput(std::string_view hash, InputFlag flag); + // Returns true only for the first call after Reset(). + bool ShouldWarnAboutMissingDiffData(); + + private: + mutable absl::Mutex mu_; + Snapshot snapshot_ ABSL_GUARDED_BY(mu_); + absl::flat_hash_map<std::string, uint8_t> input_flags_ ABSL_GUARDED_BY(mu_); + bool warned_about_missing_diff_data_ ABSL_GUARDED_BY(mu_) = false; +}; + +// Per-batch bookkeeping between `PrepareBatch` and `ProcessBatchResult`. +struct DiffBatch { + // Per-input hashes of the input bytes. + std::vector<std::string> hashes; + // Validate mode: per-input metadata blobs to send (envelope with the + // baseline, or empty if the input has no baseline). Record mode: empty. + std::vector<ByteArray> metadata; +}; + +// Reads and writes the baseline files of the current test. Used by +// `CentipedeCallbacks` when executing inputs. +class DiffBaselineStore { + public: + explicit DiffBaselineStore(const Environment& env); + + bool active() const { return active_; } + + // Returns the baseline record container of the input with `hash`, or nullopt + // if there is none. Caches the result. + std::optional<ByteArray> Lookup(std::string_view hash); + + // Writes the baseline record container of the input with `hash`. + absl::Status Save(std::string_view hash, ByteSpan container); + + // Computes the hashes and (in validate mode) the metadata to send for + // `inputs`. + DiffBatch PrepareBatch(absl::Span<const ByteSpan> inputs); + + // Strips the diff envelopes from the results in `batch_result` (restoring + // the plain CMP metadata), persists records (record mode), and updates the + // counters for the `num_inputs_written` inputs actually written to shared + // memory (defaults to all `batch.hashes.size()` inputs). Must be called for + // every executed batch, on every return path. + void ProcessBatchResult( + const DiffBatch& batch, BatchResult& batch_result, + std::optional<size_t> num_inputs_written = std::nullopt); + + private: + std::string BaselinePath(std::string_view hash) const; + + const bool active_; + const bool record_; + const std::string test_dir_; + absl::Mutex mu_; + absl::flat_hash_map<std::string, std::optional<ByteArray>> cache_ + ABSL_GUARDED_BY(mu_); +}; + +// Called once per test before fuzzing (replaying) in the diff mode: resets +// `DiffStats`; record mode recreates the test's baseline directory; validate +// mode checks that the baseline directories exist and requests a failing stop +// if the binary's baseline directory is missing. +void PrepareDiffBaselineForTest(const Environment& env, + StopCondition& stop_condition); + +// Called once per test at the end of the diff mode: prints the summary and +// requests a failing stop if the validation failed (mismatches or unparsable +// inputs with a baseline) or if inputs failed during record. +void FinishDiffForTest(const Environment& env, StopCondition& stop_condition); + +} // namespace fuzztest::internal + +#endif // FUZZTEST_CENTIPEDE_DIFF_BASELINE_H_
diff --git a/centipede/diff_baseline_test.cc b/centipede/diff_baseline_test.cc new file mode 100644 index 0000000..f7671ce --- /dev/null +++ b/centipede/diff_baseline_test.cc
@@ -0,0 +1,578 @@ +// Copyright 2026 The Centipede Authors. +// +// 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. + +#include "./centipede/diff_baseline.h" + +#include <cstdlib> +#include <filesystem> // NOLINT +#include <optional> +#include <string> +#include <string_view> +#include <utility> +#include <vector> + +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "./centipede/environment.h" +#include "./centipede/execution_metadata.h" +#include "./centipede/runner_result.h" +#include "./centipede/stop.h" +#include "./centipede/util.h" +#include "./common/defs.h" +#include "./common/hash.h" +#include "./common/test_util.h" + +namespace fuzztest::internal { +namespace { + +using ::testing::IsEmpty; +using ::testing::Optional; + +class DiffBaselineTest : public ::testing::Test { + protected: + DiffBaselineTest() + : root_(::testing::UnitTest::GetInstance()->current_test_info()->name()), + env_([this] { + Environment env; + env.fuzztest_workdir_root = root_.path().string(); + env.fuzztest_binary_identifier = "pkg/bin"; + env.test_name = "Suite.Test"; + env.fuzztest_only_replay = true; + return env; + }()) {} + + void SetUp() override { DiffStats::Global().Reset(); } + void TearDown() override { DiffStats::Global().Reset(); } + + Environment EnvWithMode(std::string mode) const { + Environment env = env_; + env.fuzztest_diff_mode = std::move(mode); + return env; + } + + static ByteArray Bytes(std::string_view s) { + return ByteArray(s.begin(), s.end()); + } + + static void WriteBaseline(const Environment& env, ByteSpan input, + std::string_view container) { + const std::string test_dir = DiffBaselineTestDir(env); + std::filesystem::create_directories(test_dir); + WriteToLocalFile((std::filesystem::path(test_dir) / Hash(input)).string(), + Bytes(container)); + } + + static std::string ReadFileOrDie(const std::string& path) { + std::string contents; + ReadFromLocalFile(path, contents); + return contents; + } + + TempDir root_; + Environment env_; +}; + +TEST_F(DiffBaselineTest, LayoutIsUnderWorkdirRootBaseline) { + const Environment env = EnvWithMode("record"); + EXPECT_EQ(DiffBaselineBinaryDir(env), + (root_.path() / "baseline" / "pkg/bin").string()); + EXPECT_EQ(DiffBaselineTestDir(env), + (root_.path() / "baseline" / "pkg/bin" / "Suite.Test").string()); +} + +TEST_F(DiffBaselineTest, ActiveOnlyInReplayWithValidDiffModeAndNoWildcards) { + EXPECT_FALSE(IsDiffActive(EnvWithMode(""))); + EXPECT_FALSE(IsDiffActive(EnvWithMode("none"))); + EXPECT_FALSE(IsDiffActive(EnvWithMode("bogus"))); + EXPECT_TRUE(IsDiffRecord(EnvWithMode("record"))); + EXPECT_FALSE(IsDiffValidate(EnvWithMode("record"))); + EXPECT_TRUE(IsDiffValidate(EnvWithMode("validate"))); + Environment not_replay = EnvWithMode("record"); + not_replay.fuzztest_only_replay = false; + EXPECT_FALSE(IsDiffActive(not_replay)); + Environment replay_crash = EnvWithMode("validate"); + replay_crash.replay_crash = true; + EXPECT_FALSE(IsDiffActive(replay_crash)); + Environment wildcards = EnvWithMode("validate"); + wildcards.has_input_wildcards = true; + EXPECT_FALSE(IsDiffActive(wildcards)); + EXPECT_FALSE(DiffBaselineStore(not_replay).active()); +} + +TEST_F(DiffBaselineTest, PrepareRejectsInvalidDiffModeAndRelativeWorkdirRoot) { + { + const Environment invalid_mode = EnvWithMode("typo"); + StopCondition stop; + PrepareDiffBaselineForTest(invalid_mode, stop); + StopCondition::StopRequest request; + ASSERT_TRUE(stop.StopRequested(&request)); + EXPECT_EQ(request.exit_code, EXIT_FAILURE); + } + { + Environment relative_root = EnvWithMode("record"); + relative_root.fuzztest_workdir_root = "relative/workdir"; + StopCondition stop; + PrepareDiffBaselineForTest(relative_root, stop); + StopCondition::StopRequest request; + ASSERT_TRUE(stop.StopRequested(&request)); + EXPECT_EQ(request.exit_code, EXIT_FAILURE); + EXPECT_FALSE(DiffBaselineStore(relative_root).active()); + } +} + +TEST_F(DiffBaselineTest, RecordResetsTheTestDirectoryAndSaves) { + const Environment env = EnvWithMode("record"); + const std::string test_dir = DiffBaselineTestDir(env); + std::filesystem::create_directories(test_dir); + WriteToLocalFile((std::filesystem::path(test_dir) / "stale").string(), + Bytes("old")); + StopCondition stop; + PrepareDiffBaselineForTest(env, stop); + EXPECT_FALSE(stop.StopRequested()); + EXPECT_TRUE(std::filesystem::is_directory(test_dir)); + EXPECT_FALSE( + std::filesystem::exists(std::filesystem::path(test_dir) / "stale")); + + DiffBaselineStore store(env); + ASSERT_TRUE(store.active()); + const ByteArray input = Bytes("input"); + const std::string hash = Hash(input); + ASSERT_TRUE(store.Save(hash, Bytes("container")).ok()); + EXPECT_EQ(ReadFileOrDie((std::filesystem::path(test_dir) / hash).string()), + "container"); + EXPECT_EQ(hash.size(), 40); +} + +TEST_F(DiffBaselineTest, LookupReadsAndCaches) { + const Environment env = EnvWithMode("validate"); + const ByteArray input = Bytes("input"); + const std::string hash = Hash(input); + WriteBaseline(env, input, "baseline"); + const std::string path = + (std::filesystem::path(DiffBaselineTestDir(env)) / hash).string(); + + DiffBaselineStore store(env); + EXPECT_THAT(store.Lookup(hash), Optional(Bytes("baseline"))); + EXPECT_EQ(store.Lookup(Hash(Bytes("other"))), std::nullopt); + // Cached: removing the file does not change the result. + std::filesystem::remove(path); + EXPECT_THAT(store.Lookup(hash), Optional(Bytes("baseline"))); +} + +TEST_F(DiffBaselineTest, LookupAndSaveIoErrorsFailFinishDiffForTest) { + // Read failure in validate mode: create a directory where a baseline file is + // expected so reading it fails, and verify it is not cached as missing and + // fails FinishDiffForTest. + { + const Environment env = EnvWithMode("validate"); + const ByteArray input = Bytes("input"); + const std::string hash = Hash(input); + const std::string test_dir = DiffBaselineTestDir(env); + std::filesystem::create_directories(std::filesystem::path(test_dir) / hash); + StopCondition stop; + PrepareDiffBaselineForTest(env, stop); + ASSERT_FALSE(stop.StopRequested()); + + DiffBaselineStore store(env); + EXPECT_EQ(store.Lookup(hash), std::nullopt); + EXPECT_EQ(DiffStats::Global().Get().io_errors, 1); + FinishDiffForTest(env, stop); + StopCondition::StopRequest request; + ASSERT_TRUE(stop.StopRequested(&request)); + EXPECT_EQ(request.exit_code, EXIT_FAILURE); + } + // Write failure in record mode: occupy the baseline file path with a + // directory so Save() fails, and verify FinishDiffForTest fails. + { + const Environment env = EnvWithMode("record"); + StopCondition stop; + PrepareDiffBaselineForTest(env, stop); + ASSERT_FALSE(stop.StopRequested()); + + const ByteArray input = Bytes("input"); + const std::string hash = Hash(input); + std::filesystem::create_directories( + std::filesystem::path(DiffBaselineTestDir(env)) / hash); + + DiffBaselineStore store(env); + const std::vector<ByteSpan> inputs = {input}; + const DiffBatch batch = store.PrepareBatch(inputs); + BatchResult result; + result.ClearAndResize(1); + result.results()[0].metadata().cmp_data = + EncodeDiffEnvelope(DiffEnvelopeKind::kRecords, {}, Bytes("rec")); + result.num_outputs_read() = 1; + store.ProcessBatchResult(batch, result); + + EXPECT_EQ(DiffStats::Global().Get().io_errors, 1); + FinishDiffForTest(env, stop); + StopCondition::StopRequest request; + ASSERT_TRUE(stop.StopRequested(&request)); + EXPECT_EQ(request.exit_code, EXIT_FAILURE); + } +} + +TEST_F(DiffBaselineTest, ValidateWithoutBinaryDirectoryRequestsFailingStop) { + const Environment env = EnvWithMode("validate"); + StopCondition stop; + PrepareDiffBaselineForTest(env, stop); + StopCondition::StopRequest request; + ASSERT_TRUE(stop.StopRequested(&request)); + EXPECT_EQ(request.exit_code, EXIT_FAILURE); + // Validate never creates directories. + EXPECT_FALSE(std::filesystem::exists(DiffBaselineBinaryDir(env))); +} + +TEST_F(DiffBaselineTest, ValidateWithoutTestDirectoryOnlyWarns) { + const Environment env = EnvWithMode("validate"); + std::filesystem::create_directories(DiffBaselineBinaryDir(env)); + StopCondition stop; + PrepareDiffBaselineForTest(env, stop); + EXPECT_FALSE(stop.StopRequested()); + EXPECT_FALSE(std::filesystem::exists(DiffBaselineTestDir(env))); +} + +TEST_F(DiffBaselineTest, ValidateSendsExpectationsOnlyForInputsWithBaseline) { + const Environment env = EnvWithMode("validate"); + const ByteArray with = Bytes("with"); + const ByteArray without = Bytes("without"); + WriteBaseline(env, with, "expected"); + StopCondition stop; + PrepareDiffBaselineForTest(env, stop); // Resets the stats. + + DiffBaselineStore store(env); + const std::vector<ByteSpan> inputs = {with, without}; + const DiffBatch batch = store.PrepareBatch(inputs); + ASSERT_EQ(batch.metadata.size(), 2); + EXPECT_EQ(batch.hashes, + (std::vector<std::string>{Hash(with), Hash(without)})); + EXPECT_THAT(batch.metadata[1], IsEmpty()); + DiffEnvelopeKind kind; + ByteSpan cmp; + ByteSpan payload; + ASSERT_TRUE(DecodeDiffEnvelope(batch.metadata[0], kind, cmp, payload)); + EXPECT_EQ(kind, DiffEnvelopeKind::kExpectations); + EXPECT_THAT(cmp, IsEmpty()); + EXPECT_EQ(ByteArray(payload.begin(), payload.end()), Bytes("expected")); + + BatchResult result; + result.ClearAndResize(2); + result.results()[0].metadata().cmp_data = + EncodeDiffEnvelope(DiffEnvelopeKind::kAck, {}, {}); + result.results()[1].metadata().cmp_data = + EncodeDiffEnvelope(DiffEnvelopeKind::kAck, {}, {}); + result.num_outputs_read() = 2; + store.ProcessBatchResult(batch, result); + const DiffStats::Snapshot stats = DiffStats::Global().Get(); + EXPECT_EQ(stats.baselines_sent, 1); + EXPECT_EQ(stats.baselines_acknowledged, 1); + EXPECT_EQ(stats.baselines_missing, 1); +} + +TEST_F(DiffBaselineTest, + TruncatedBatchAndBatchTimeoutRecordIncompleteWithoutMisattributing) { + const Environment env = EnvWithMode("validate"); + const ByteArray a = Bytes("a"); + const ByteArray b = Bytes("b"); + const ByteArray unsent = Bytes("unsent"); + for (const ByteArray* input : {&a, &b, &unsent}) { + WriteBaseline(env, *input, "expected"); + } + StopCondition stop; + PrepareDiffBaselineForTest(env, stop); + DiffBaselineStore store(env); + const std::vector<ByteSpan> inputs = {a, b, unsent}; + const DiffBatch batch = store.PrepareBatch(inputs); + + // Only 2 of the 3 inputs fit into inputs_blobseq_, and the batch timed out + // after finishing input 0: neither `unsent` (not written) nor `b` (batch + // timeout, not single-input crash) should be marked failed/sent improperly, + // while `incomplete_batches` causes FinishDiffForTest to fail. + BatchResult result; + result.ClearAndResize(3); + result.results()[0].metadata().cmp_data = + EncodeDiffEnvelope(DiffEnvelopeKind::kAck, {}, {}); + result.num_outputs_read() = 1; + result.exit_code() = EXIT_FAILURE; + result.failure_description() = std::string(kExecutionFailurePerBatchTimeout); + store.ProcessBatchResult(batch, result, /*num_inputs_written=*/2); + + const DiffStats::Snapshot stats = DiffStats::Global().Get(); + EXPECT_EQ(stats.baselines_sent, 2); + EXPECT_EQ(stats.baselines_acknowledged, 1); + EXPECT_EQ(stats.inputs_failed, 0); + EXPECT_EQ(stats.incomplete_batches, 1); + + FinishDiffForTest(env, stop); + EXPECT_TRUE(stop.StopRequested()); +} + +TEST_F(DiffBaselineTest, SetupFailureMarksBatchIncompleteNotSingleInputFailed) { + const Environment env = EnvWithMode("validate"); + const ByteArray a = Bytes("a"); + WriteBaseline(env, a, "expected"); + StopCondition stop; + PrepareDiffBaselineForTest(env, stop); + DiffBaselineStore store(env); + const std::vector<ByteSpan> inputs = {a}; + const DiffBatch batch = store.PrepareBatch(inputs); + + BatchResult result; + result.ClearAndResize(1); + result.exit_code() = EXIT_FAILURE; + result.failure_description() = "SETUP FAILURE: fixture failed"; + store.ProcessBatchResult(batch, result); + + const DiffStats::Snapshot stats = DiffStats::Global().Get(); + EXPECT_EQ(stats.inputs_failed, 0); + EXPECT_EQ(stats.incomplete_batches, 1); + FinishDiffForTest(env, stop); + EXPECT_TRUE(stop.StopRequested()); +} + +TEST_F(DiffBaselineTest, SkippedTestDoesNotMarkBatchIncomplete) { + const Environment env = EnvWithMode("validate"); + const ByteArray a = Bytes("a"); + WriteBaseline(env, a, "expected"); + StopCondition stop; + PrepareDiffBaselineForTest(env, stop); + DiffBaselineStore store(env); + const std::vector<ByteSpan> inputs = {a}; + const DiffBatch batch = store.PrepareBatch(inputs); + + BatchResult result; + result.ClearAndResize(1); + result.exit_code() = EXIT_FAILURE; + result.failure_description() = "SKIPPED TEST: skipped"; + store.ProcessBatchResult(batch, result); + + const DiffStats::Snapshot stats = DiffStats::Global().Get(); + EXPECT_EQ(stats.inputs_failed, 0); + EXPECT_EQ(stats.incomplete_batches, 0); + FinishDiffForTest(env, stop); + EXPECT_FALSE(stop.StopRequested()); +} + +TEST_F(DiffBaselineTest, RecordPersistsRecordsAndRestoresCmpData) { + const Environment env = EnvWithMode("record"); + StopCondition stop; + PrepareDiffBaselineForTest(env, stop); + DiffBaselineStore store(env); + const ByteArray a = Bytes("a"); + const ByteArray b = Bytes("b"); + const ByteArray c = Bytes("c"); + const std::vector<ByteSpan> inputs = {a, b, c}; + const DiffBatch batch = store.PrepareBatch(inputs); + EXPECT_THAT(batch.metadata, IsEmpty()); // Record allocates no metadata. + + BatchResult result; + result.ClearAndResize(3); + result.results()[0].metadata().cmp_data = + EncodeDiffEnvelope(DiffEnvelopeKind::kRecords, {5}, Bytes("rec-a")); + result.results()[1].metadata().cmp_data = + EncodeDiffEnvelope(DiffEnvelopeKind::kSkippedUnparsable, {}, {}); + // Input c crashed: not read. + result.num_outputs_read() = 2; + result.exit_code() = EXIT_FAILURE; + result.failure_description() = "SIGSEGV"; + store.ProcessBatchResult(batch, result); + + EXPECT_EQ(result.results()[0].metadata().cmp_data, ByteArray{5}); + EXPECT_THAT(result.results()[1].metadata().cmp_data, IsEmpty()); + const std::string test_dir = DiffBaselineTestDir(env); + EXPECT_EQ(ReadFileOrDie((std::filesystem::path(test_dir) / Hash(a)).string()), + "rec-a"); + EXPECT_FALSE( + std::filesystem::exists(std::filesystem::path(test_dir) / Hash(b))); + EXPECT_FALSE( + std::filesystem::exists(std::filesystem::path(test_dir) / Hash(c))); + const DiffStats::Snapshot stats = DiffStats::Global().Get(); + EXPECT_EQ(stats.executions, 2); + EXPECT_EQ(stats.baselines_written, 1); + EXPECT_EQ(stats.inputs_unparsable, 1); + EXPECT_EQ(stats.inputs_failed, 1); + EXPECT_EQ(stats.mismatches, 0); + + // A record run with failed inputs fails at the end. + FinishDiffForTest(env, stop); + StopCondition::StopRequest request; + ASSERT_TRUE(stop.StopRequested(&request)); + EXPECT_EQ(request.exit_code, EXIT_FAILURE); +} + +TEST_F(DiffBaselineTest, CleanRecordDoesNotFail) { + const Environment env = EnvWithMode("record"); + StopCondition stop; + PrepareDiffBaselineForTest(env, stop); + DiffBaselineStore store(env); + const ByteArray a = Bytes("a"); + const std::vector<ByteSpan> inputs = {a}; + const DiffBatch batch = store.PrepareBatch(inputs); + BatchResult result; + result.ClearAndResize(1); + result.results()[0].metadata().cmp_data = + EncodeDiffEnvelope(DiffEnvelopeKind::kRecords, {}, Bytes("rec-a")); + result.num_outputs_read() = 1; + store.ProcessBatchResult(batch, result); + FinishDiffForTest(env, stop); + EXPECT_FALSE(stop.StopRequested()); +} + +TEST_F(DiffBaselineTest, ValidateCountsAcksMismatchesAndFailsAtTheEnd) { + const Environment env = EnvWithMode("validate"); + const ByteArray ok = Bytes("ok"); + const ByteArray bad = Bytes("bad"); + const ByteArray after = Bytes("after"); + for (const ByteArray* input : {&ok, &bad, &after}) { + WriteBaseline(env, *input, "expected"); + } + StopCondition stop; + PrepareDiffBaselineForTest(env, stop); + ASSERT_FALSE(stop.StopRequested()); + DiffBaselineStore store(env); + const std::vector<ByteSpan> inputs = {ok, bad, after}; + const DiffBatch batch = store.PrepareBatch(inputs); + BatchResult result; + result.ClearAndResize(3); + result.results()[0].metadata().cmp_data = + EncodeDiffEnvelope(DiffEnvelopeKind::kAck, {}, {}); + result.num_outputs_read() = 1; + result.exit_code() = EXIT_FAILURE; + result.failure_description() = "RecordOrDiff mismatch"; + store.ProcessBatchResult(batch, result); + + DiffStats::Snapshot stats = DiffStats::Global().Get(); + EXPECT_EQ(stats.baselines_sent, 3); + EXPECT_EQ(stats.baselines_acknowledged, 1); + EXPECT_EQ(stats.inputs_failed, 1); + EXPECT_EQ(stats.mismatches, 1); + + // The same mismatching input re-executed alone (e.g. by ReportCrash) is + // counted once. + const std::vector<ByteSpan> single = {bad}; + const DiffBatch single_batch = store.PrepareBatch(single); + BatchResult single_result; + single_result.ClearAndResize(1); + single_result.exit_code() = EXIT_FAILURE; + single_result.failure_description() = "RecordOrDiff mismatch"; + store.ProcessBatchResult(single_batch, single_result); + stats = DiffStats::Global().Get(); + EXPECT_EQ(stats.mismatches, 1); + EXPECT_EQ(stats.inputs_failed, 1); + + FinishDiffForTest(env, stop); + StopCondition::StopRequest request; + ASSERT_TRUE(stop.StopRequested(&request)); + EXPECT_EQ(request.exit_code, EXIT_FAILURE); +} + +TEST_F(DiffBaselineTest, ValidateFailsForUnparsableInputsWithBaseline) { + const Environment env = EnvWithMode("validate"); + const ByteArray input = Bytes("input"); + WriteBaseline(env, input, "expected"); + StopCondition stop; + PrepareDiffBaselineForTest(env, stop); + DiffBaselineStore store(env); + const std::vector<ByteSpan> inputs = {input}; + const DiffBatch batch = store.PrepareBatch(inputs); + BatchResult result; + result.ClearAndResize(1); + result.results()[0].metadata().cmp_data = + EncodeDiffEnvelope(DiffEnvelopeKind::kSkippedUnparsable, {}, {}); + result.num_outputs_read() = 1; + store.ProcessBatchResult(batch, result); + const DiffStats::Snapshot stats = DiffStats::Global().Get(); + EXPECT_EQ(stats.inputs_unparsable, 1); + EXPECT_EQ(stats.unparsable_with_baseline, 1); + FinishDiffForTest(env, stop); + EXPECT_TRUE(stop.StopRequested()); +} + +TEST_F(DiffBaselineTest, ValidateAllowsUnparsableInputsWithoutBaseline) { + const Environment env = EnvWithMode("validate"); + std::filesystem::create_directories(DiffBaselineTestDir(env)); + const ByteArray input = Bytes("unparsable_new_input"); + StopCondition stop; + PrepareDiffBaselineForTest(env, stop); + DiffBaselineStore store(env); + const std::vector<ByteSpan> inputs = {input}; + const DiffBatch batch = store.PrepareBatch(inputs); + BatchResult result; + result.ClearAndResize(1); + result.results()[0].metadata().cmp_data = + EncodeDiffEnvelope(DiffEnvelopeKind::kSkippedUnparsable, {}, {}); + result.num_outputs_read() = 1; + store.ProcessBatchResult(batch, result); + const DiffStats::Snapshot stats = DiffStats::Global().Get(); + EXPECT_EQ(stats.inputs_unparsable, 1); + EXPECT_EQ(stats.unparsable_with_baseline, 0); + FinishDiffForTest(env, stop); + EXPECT_FALSE(stop.StopRequested()); +} + +TEST_F(DiffBaselineTest, CleanValidatePasses) { + const Environment env = EnvWithMode("validate"); + const ByteArray a = Bytes("a"); + WriteBaseline(env, a, "expected"); + StopCondition stop; + PrepareDiffBaselineForTest(env, stop); + DiffBaselineStore store(env); + const std::vector<ByteSpan> inputs = {a}; + const DiffBatch batch = store.PrepareBatch(inputs); + BatchResult result; + result.ClearAndResize(1); + result.results()[0].metadata().cmp_data = + EncodeDiffEnvelope(DiffEnvelopeKind::kAck, {}, {}); + result.num_outputs_read() = 1; + store.ProcessBatchResult(batch, result); + FinishDiffForTest(env, stop); + EXPECT_FALSE(stop.StopRequested()); +} + +TEST_F(DiffBaselineTest, + ResultsWithoutEnvelopeOrWithExpectationsEnvelopeAreLeftUntouched) { + const Environment env = EnvWithMode("validate"); + std::filesystem::create_directories(DiffBaselineTestDir(env)); + StopCondition stop; + PrepareDiffBaselineForTest(env, stop); + DiffBaselineStore store(env); + const ByteArray a = Bytes("a"); + const ByteArray b = Bytes("b"); + const std::vector<ByteSpan> inputs = {a, b}; + const DiffBatch batch = store.PrepareBatch(inputs); + const ByteArray expectations_env = EncodeDiffEnvelope( + DiffEnvelopeKind::kExpectations, {9}, Bytes("unexpected")); + BatchResult result; + result.ClearAndResize(2); + result.results()[0].metadata().cmp_data = {2, 1, 2, 3, 4}; + result.results()[1].metadata().cmp_data = expectations_env; + result.num_outputs_read() = 2; + store.ProcessBatchResult(batch, result); + EXPECT_EQ(result.results()[0].metadata().cmp_data, + (ByteArray{2, 1, 2, 3, 4})); + EXPECT_EQ(result.results()[1].metadata().cmp_data, expectations_env); + EXPECT_EQ(DiffStats::Global().Get().executions, 0); +} + +TEST_F(DiffBaselineTest, InactiveDoesNothing) { + const Environment env = EnvWithMode(""); + StopCondition stop; + PrepareDiffBaselineForTest(env, stop); + FinishDiffForTest(env, stop); + EXPECT_FALSE(stop.StopRequested()); + EXPECT_FALSE(std::filesystem::exists(root_.path() / "baseline")); +} + +} // namespace +} // namespace fuzztest::internal
diff --git a/centipede/engine_abi.h b/centipede/engine_abi.h index cdb1f84..9bd6778 100644 --- a/centipede/engine_abi.h +++ b/centipede/engine_abi.h
@@ -200,6 +200,9 @@ const FuzzTestBytesSink* sink); // [Optional] Updates the test `input` metadata from serialized `metadata`. + // Called for mutation origins before `Mutate`/`CrossOver`, and for inputs of + // execution requests that carry metadata (e.g. the expected values of the + // incremental differential fuzzing validate mode) before `Execute`. void (*UpdateInputMetadata)(FuzzTestAdapterCtx* ctx, const FuzzTestBytesView* metadata, FuzzTestInputHandle input);
diff --git a/centipede/engine_worker.cc b/centipede/engine_worker.cc index a902fa1..f661f60 100644 --- a/centipede/engine_worker.cc +++ b/centipede/engine_worker.cc
@@ -645,6 +645,7 @@ // In-loop variables declared outside to save allocations. std::vector<uint64_t> features; std::vector<uint8_t> serialized_metadata; + ExecutionMetadata request_metadata; std::vector<FuzzTestInputHandle> emitted_inputs; const auto input_sink = GetInputSinkTo(emitted_inputs); @@ -659,8 +660,18 @@ // TODO(xinhaoyuan): Consider improving it. E.g. let user override stats. ExecutionResult::Stats stats = {}; (void)timer.UsecSinceLast(); - auto blob = inputs_blobseq->Read(); - if (!blob.IsValid()) return; // no more blobs to read. + const auto first_blob = inputs_blobseq->Read(); + if (!first_blob.IsValid()) return; // no more blobs to read. + // An execution request may carry an optional metadata blob before the data + // input (e.g. the expected values in the incremental differential fuzzing + // validate mode). It is delivered with `UpdateInputMetadata` before + // `Execute`. + const bool has_request_metadata = + IsExecutionMetadata(first_blob, request_metadata); + const auto blob = + has_request_metadata ? inputs_blobseq->Read() : first_blob; + // The inputs blob sequence may have overflown between the two blobs. + if (!blob.IsValid()) return; WorkerCheck(IsDataInput(blob), "Must read data input"); if (!BatchResult::WriteInputBegin(*outputs_blobseq)) { @@ -675,6 +686,12 @@ WorkerCheck(emitted_inputs.size() == 1, "Deserialize must emit exactly one input"); auto input = emitted_inputs[0]; + if (has_request_metadata && adapter.UpdateInputMetadata != nullptr) { + const auto input_metadata = FuzzTestBytesView{ + request_metadata.cmp_data.data(), request_metadata.cmp_data.size()}; + adapter.UpdateInputMetadata(adapter.ctx, &input_metadata, input); + WORKER_CHECK_FOR_ERROR(); + } features.clear(); FuzzTestFeedbackSink feedback_sink = {
diff --git a/centipede/environment.cc b/centipede/environment.cc index 8fb2a35..ec644d3 100644 --- a/centipede/environment.cc +++ b/centipede/environment.cc
@@ -251,6 +251,21 @@ fuzztest_execution_id = config.execution_id.value_or(""); fuzztest_replay_coverage_inputs = config.replay_coverage_inputs; fuzztest_time_limit_per_test = config.GetTimeLimitPerTest(); + if (config.diff_mode != fuzztest::internal::DiffMode::kNone) { + const std::string target_diff_mode = + fuzztest::internal::AbslUnparseFlag(config.diff_mode); + FUZZTEST_CHECK(fuzztest_diff_mode == Default().fuzztest_diff_mode || + fuzztest_diff_mode == target_diff_mode) + << "Value for --fuzztest_diff_mode is inconsistent with the value for " + "diff_mode in the target binary:" + << VV(fuzztest_diff_mode) << VV(target_diff_mode); + fuzztest_diff_mode = target_diff_mode; + } + if (fuzztest_only_replay && fuzztest_diff_mode == "record" && !replay_crash && + !config.crashing_input_to_reproduce.has_value()) { + // Record mode continues after crashes so that every input gets a baseline. + exit_on_crash = false; + } if (replay_crash_attempts == Default().replay_crash_attempts) { replay_crash_attempts = config.replay_crash_attempts; }
diff --git a/centipede/environment_test.cc b/centipede/environment_test.cc index 4b93216..fbb8748 100644 --- a/centipede/environment_test.cc +++ b/centipede/environment_test.cc
@@ -241,4 +241,49 @@ EXPECT_EQ(env.replay_crash_attempts, 10); } +TEST(Environment, UpdatesDiffModeAndRecordExitOnCrashFromTargetConfig) { + Environment env; + env.exit_on_crash = true; + fuzztest::internal::Configuration config; + config.only_replay = true; + config.diff_mode = DiffMode::kRecord; + env.UpdateWithTargetConfig(config); + EXPECT_EQ(env.fuzztest_diff_mode, "record"); + EXPECT_FALSE(env.exit_on_crash); +} + +TEST(Environment, PreservesExplicitFuzzTestDiffModeWhenTargetConfigIsNone) { + Environment env; + env.exit_on_crash = true; + env.fuzztest_diff_mode = "record"; + fuzztest::internal::Configuration config; + config.only_replay = true; + config.diff_mode = DiffMode::kNone; + env.UpdateWithTargetConfig(config); + EXPECT_EQ(env.fuzztest_diff_mode, "record"); + EXPECT_FALSE(env.exit_on_crash); +} + +TEST(Environment, PreservesExitOnCrashWhenOnlyReplayIsFalse) { + Environment env; + env.exit_on_crash = true; + fuzztest::internal::Configuration config; + config.only_replay = false; + config.diff_mode = DiffMode::kRecord; + env.UpdateWithTargetConfig(config); + EXPECT_EQ(env.fuzztest_diff_mode, "record"); + EXPECT_TRUE(env.exit_on_crash); +} + +TEST(Environment, DiesOnInconsistentFuzzTestDiffModeAndTargetConfigDiffMode) { + Environment env; + env.fuzztest_diff_mode = "validate"; + fuzztest::internal::Configuration config; + config.diff_mode = DiffMode::kRecord; + EXPECT_DEATH( + env.UpdateWithTargetConfig(config), + "Value for --fuzztest_diff_mode is inconsistent with the value for " + "diff_mode in the target binary"); +} + } // namespace fuzztest::internal
diff --git a/centipede/execution_metadata.cc b/centipede/execution_metadata.cc index 4b96116..c85f352 100644 --- a/centipede/execution_metadata.cc +++ b/centipede/execution_metadata.cc
@@ -15,6 +15,8 @@ #include "./centipede/execution_metadata.h" #include <cstddef> +#include <cstdint> +#include <cstring> #include <functional> #include "./centipede/shared_memory_blob_sequence.h" @@ -55,4 +57,79 @@ return true; } +namespace { + +constexpr size_t kDiffEnvelopeKindOffset = kDiffEnvelopeMagic.size(); +constexpr size_t kDiffEnvelopeCmpSizeOffset = kDiffEnvelopeKindOffset + 1; +constexpr size_t kDiffEnvelopeMinSize = + kDiffEnvelopeCmpSizeOffset + 2 * sizeof(uint64_t); + +void AppendUint64(ByteArray& out, uint64_t value) { + const auto* bytes = reinterpret_cast<const uint8_t*>(&value); + out.insert(out.end(), bytes, bytes + sizeof(value)); +} + +// Reads a uint64 at `offset` of `bytes`, advancing `offset`. Returns false if +// there are not enough bytes. +bool ReadUint64(ByteSpan bytes, size_t& offset, uint64_t& value) { + if (bytes.size() < offset || bytes.size() - offset < sizeof(value)) { + return false; + } + std::memcpy(&value, bytes.data() + offset, sizeof(value)); + offset += sizeof(value); + return true; +} + +} // namespace + +ByteArray EncodeDiffEnvelope(DiffEnvelopeKind kind, ByteSpan cmp_data, + ByteSpan payload) { + ByteArray result; + result.reserve(kDiffEnvelopeMinSize + cmp_data.size() + payload.size()); + result.insert(result.end(), kDiffEnvelopeMagic.begin(), + kDiffEnvelopeMagic.end()); + result.push_back(static_cast<uint8_t>(kind)); + AppendUint64(result, cmp_data.size()); + result.insert(result.end(), cmp_data.begin(), cmp_data.end()); + AppendUint64(result, payload.size()); + result.insert(result.end(), payload.begin(), payload.end()); + return result; +} + +bool DecodeDiffEnvelope(ByteSpan bytes, DiffEnvelopeKind& kind, + ByteSpan& cmp_data, ByteSpan& payload) { + if (bytes.size() < kDiffEnvelopeMinSize) return false; + if (std::memcmp(bytes.data(), kDiffEnvelopeMagic.data(), + kDiffEnvelopeMagic.size()) != 0) { + return false; + } + const uint8_t raw_kind = bytes[kDiffEnvelopeKindOffset]; + if (raw_kind > static_cast<uint8_t>(DiffEnvelopeKind::kSkippedUnparsable)) { + return false; + } + const auto decoded_kind = static_cast<DiffEnvelopeKind>(raw_kind); + size_t offset = kDiffEnvelopeCmpSizeOffset; + uint64_t cmp_size = 0; + if (!ReadUint64(bytes, offset, cmp_size)) return false; + if (bytes.size() - offset < cmp_size) return false; + const size_t cmp_offset = offset; + offset += static_cast<size_t>(cmp_size); + uint64_t diff_size = 0; + if (!ReadUint64(bytes, offset, diff_size)) return false; + // No trailing bytes are allowed. + if (bytes.size() - offset != diff_size) return false; + if ((decoded_kind == DiffEnvelopeKind::kAck || + decoded_kind == DiffEnvelopeKind::kSkippedUnparsable) && + diff_size != 0) { + return false; + } + kind = decoded_kind; + // Construct `ByteSpan` from `(data, size)` rather than `subspan()`, which + // pulls `absl::ThrowStdOutOfRange` / `RawLog` (and its sancov PCs) into + // runner binaries. + cmp_data = ByteSpan(bytes.data() + cmp_offset, static_cast<size_t>(cmp_size)); + payload = ByteSpan(bytes.data() + offset, static_cast<size_t>(diff_size)); + return true; +} + } // namespace fuzztest::internal
diff --git a/centipede/execution_metadata.h b/centipede/execution_metadata.h index 1e28e60..076e880 100644 --- a/centipede/execution_metadata.h +++ b/centipede/execution_metadata.h
@@ -20,7 +20,9 @@ #ifndef THIRD_PARTY_CENTIPEDE_EXECUTION_METADATA_H_ #define THIRD_PARTY_CENTIPEDE_EXECUTION_METADATA_H_ +#include <cstdint> #include <functional> +#include <string_view> #include "./centipede/shared_memory_blob_sequence.h" #include "./common/defs.h" @@ -55,6 +57,52 @@ ByteArray cmp_data; }; +// Incremental differential fuzzing (`fuzztest::RecordOrDiff`) envelope. +// +// When the diff mode is active, `ExecutionMetadata::cmp_data` carries this +// envelope in both directions instead of raw CMP entries: +// +// offset 0 : 8 bytes magic = kDiffEnvelopeMagic +// offset 8 : uint8 kind (DiffEnvelopeKind) +// offset 9 : uint64 cmp_size (host byte order, unaligned) +// offset 17: cmp_size bytes of CMP entries (the plain `cmp_data` format) +// next : uint64 diff_size +// next : diff_size bytes of payload +// (no trailing bytes) +// +// The payload of kExpectations/kRecords is a record container, which is opaque +// to Centipede and owned by the framework. kAck and kSkippedUnparsable have an +// empty payload. Outside the diff mode, the bytes on the wire are unchanged. +inline constexpr std::string_view kDiffEnvelopeMagic = "FTDIFF01"; + +enum class DiffEnvelopeKind : uint8_t { + // Controller -> worker (validate): the baseline record container. + kExpectations = 0, + // Worker -> controller (record): the record container of the execution. + kRecords = 1, + // Worker -> controller (validate): the input was compared (empty payload). + kAck = 2, + // Worker -> controller (both modes): the input could not be parsed by the + // current domains, so nothing was recorded or compared (empty payload). + kSkippedUnparsable = 3, +}; + +// The per-input diff result produced by the runner callbacks. +struct DiffResult { + DiffEnvelopeKind kind; + ByteArray payload; +}; + +// Returns the envelope of `kind` wrapping `cmp_data` and `payload`. +ByteArray EncodeDiffEnvelope(DiffEnvelopeKind kind, ByteSpan cmp_data, + ByteSpan payload); + +// Decodes `bytes` as a diff envelope. Returns false (and leaves the outputs +// untouched) if `bytes` is not a well-formed envelope. On success, `cmp_data` +// and `payload` point into `bytes`. +bool DecodeDiffEnvelope(ByteSpan bytes, DiffEnvelopeKind& kind, + ByteSpan& cmp_data, ByteSpan& payload); + } // namespace fuzztest::internal #endif // THIRD_PARTY_CENTIPEDE_EXECUTION_METADATA_H_
diff --git a/centipede/execution_metadata_test.cc b/centipede/execution_metadata_test.cc index 1bd0c42..412bc4b 100644 --- a/centipede/execution_metadata_test.cc +++ b/centipede/execution_metadata_test.cc
@@ -14,12 +14,15 @@ #include "./centipede/execution_metadata.h" +#include <cstddef> #include <cstdint> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" +#include "absl/types/span.h" +#include "./centipede/runner_request.h" #include "./centipede/shared_memory_blob_sequence.h" #include "./common/defs.h" @@ -118,5 +121,178 @@ })); } +TEST(DiffEnvelope, RoundTripsEveryKindAndEmptyCmp) { + const ByteArray payload = {'p', 0, 'q'}; + for (const ByteArray& cmp : std::vector<ByteArray>{{2, 1, 2, 3, 4}, {}}) { + for (const auto& [kind, kind_payload] : + std::vector<std::pair<DiffEnvelopeKind, ByteArray>>{ + {DiffEnvelopeKind::kExpectations, payload}, + {DiffEnvelopeKind::kRecords, payload}, + {DiffEnvelopeKind::kRecords, {}}, + {DiffEnvelopeKind::kAck, {}}, + {DiffEnvelopeKind::kSkippedUnparsable, {}}, + }) { + SCOPED_TRACE(static_cast<int>(kind)); + const ByteArray envelope = EncodeDiffEnvelope(kind, cmp, kind_payload); + DiffEnvelopeKind decoded_kind; + ByteSpan decoded_cmp; + ByteSpan decoded_payload; + ASSERT_TRUE(DecodeDiffEnvelope(envelope, decoded_kind, decoded_cmp, + decoded_payload)); + EXPECT_EQ(decoded_kind, kind); + EXPECT_EQ(ByteArray(decoded_cmp.begin(), decoded_cmp.end()), cmp); + EXPECT_EQ(ByteArray(decoded_payload.begin(), decoded_payload.end()), + kind_payload); + } + } +} + +TEST(DiffEnvelope, HasThePinnedLayout) { + const ByteArray envelope = + EncodeDiffEnvelope(DiffEnvelopeKind::kRecords, {9}, {7, 8}); + const ByteArray expected = { + 'F', 'T', 'D', 'I', 'F', 'F', '0', '1', // magic + 1, // kind + 1, 0, 0, 0, 0, 0, 0, 0, // cmp_size (LE) + 9, // cmp + 2, 0, 0, 0, 0, 0, 0, 0, // diff_size (LE) + 7, 8}; // payload + EXPECT_EQ(envelope, expected); +} + +TEST(DiffEnvelope, RejectsMalformedEnvelopesAndLeavesOutputsUntouched) { + const ByteArray good = + EncodeDiffEnvelope(DiffEnvelopeKind::kExpectations, {1, 2}, {3}); + std::vector<ByteArray> bad_envelopes; + // Wrong magic. + bad_envelopes.push_back(good); + bad_envelopes.back()[0] = 'X'; + // Unknown kind. + bad_envelopes.push_back(good); + bad_envelopes.back()[8] = 4; + // Non-empty payload for kAck and kSkippedUnparsable. + bad_envelopes.push_back(EncodeDiffEnvelope(DiffEnvelopeKind::kAck, {}, {1})); + bad_envelopes.push_back( + EncodeDiffEnvelope(DiffEnvelopeKind::kSkippedUnparsable, {}, {1})); + // Truncations at every length. + for (size_t size = 0; size < good.size(); ++size) { + bad_envelopes.push_back(ByteArray(good.begin(), good.begin() + size)); + } + // Trailing bytes. + bad_envelopes.push_back(good); + bad_envelopes.back().push_back(0); + // Huge cmp_size. + ByteArray huge_cmp = good; + for (size_t i = 9; i < 17; ++i) huge_cmp[i] = 0xff; + bad_envelopes.push_back(huge_cmp); + // 64-bit wrap-around on cmp_size: 17 + cmp_size wraps modulo 2^64. + ByteArray wrap_cmp = good; + const uint64_t wrap_cmp_val = ~uint64_t{0} - 16; + for (size_t i = 0; i < 8; ++i) { + wrap_cmp[9 + i] = static_cast<uint8_t>((wrap_cmp_val >> (8 * i)) & 0xff); + } + bad_envelopes.push_back(wrap_cmp); + // Huge diff_size (valid cmp_size = 2, diff_size = UINT64_MAX). + ByteArray huge_diff = good; + for (size_t i = 19; i < 27; ++i) huge_diff[i] = 0xff; + bad_envelopes.push_back(huge_diff); + // 64-bit wrap-around: cmp_size = 2, diff_size = UINT64_MAX - 26 so that + // header + cmp_size + diff_size wraps modulo 2^64. + ByteArray wrap_diff = good; + const uint64_t wrap_val = ~uint64_t{0} - 26; + for (size_t i = 0; i < 8; ++i) { + wrap_diff[19 + i] = static_cast<uint8_t>((wrap_val >> (8 * i)) & 0xff); + } + bad_envelopes.push_back(wrap_diff); + // Raw CMP data (no envelope). + bad_envelopes.push_back({2, 1, 2, 3, 4}); + + for (size_t idx = 0; idx < bad_envelopes.size(); ++idx) { + SCOPED_TRACE(idx); + const ByteArray& bad = bad_envelopes[idx]; + DiffEnvelopeKind kind = DiffEnvelopeKind::kAck; + const ByteArray sentinel = {42}; + ByteSpan cmp = sentinel; + ByteSpan payload = sentinel; + EXPECT_FALSE(DecodeDiffEnvelope(bad, kind, cmp, payload)); + EXPECT_EQ(kind, DiffEnvelopeKind::kAck); + EXPECT_EQ(cmp.data(), sentinel.data()); + EXPECT_EQ(payload.data(), sentinel.data()); + } +} + +TEST(RunnerRequest, RequestExecutionWithOptionalMetadataInterleavesCleanly) { + const ByteArray in0 = {10, 11}; + const ByteArray in1 = {20}; + const ByteArray in2 = {30, 31, 32}; + const ByteArray meta0 = + EncodeDiffEnvelope(DiffEnvelopeKind::kExpectations, {}, {1, 2}); + const ByteArray meta1 = {}; // Omitted metadata blob. + const ByteArray meta2 = + EncodeDiffEnvelope(DiffEnvelopeKind::kExpectations, {}, {3}); + + // All-empty metadata is byte-identical to the 2-argument RequestExecution. + std::vector<uint8_t> plain_buf(512, 0); + std::vector<uint8_t> empty_meta_buf(512, 0); + BlobSequence plain_seq(plain_buf.data(), plain_buf.size()); + BlobSequence empty_meta_seq(empty_meta_buf.data(), empty_meta_buf.size()); + const std::vector<ByteSpan> inputs = {in0, in1, in2}; + const std::vector<ByteSpan> all_empty = {{}, {}, {}}; + ASSERT_EQ(RequestExecution(inputs, plain_seq), 3); + ASSERT_EQ(RequestExecution(inputs, all_empty, empty_meta_seq), 3); + EXPECT_EQ(plain_seq.offset(), empty_meta_seq.offset()); + EXPECT_EQ(plain_buf, empty_meta_buf); + + // Mismatched metadata size returns 0. + std::vector<uint8_t> bad_buf(512, 0); + BlobSequence bad_seq(bad_buf.data(), bad_buf.size()); + EXPECT_EQ(RequestExecution(inputs, {meta0}, bad_seq), 0); + + // Mixed non-empty / empty metadata writes metadata only before in0 and in2. + std::vector<uint8_t> mixed_buf(1024, 0); + BlobSequence mixed_seq(mixed_buf.data(), mixed_buf.size()); + ASSERT_EQ(RequestExecution(inputs, {meta0, meta1, meta2}, mixed_seq), 3); + mixed_seq.Reset(); + + EXPECT_TRUE(IsExecutionRequest(mixed_seq.Read())); + size_t num_inputs = 0; + ASSERT_TRUE(IsNumInputs(mixed_seq.Read(), num_inputs)); + EXPECT_EQ(num_inputs, 3); + + ExecutionMetadata parsed_meta0; + const Blob meta0_blob = mixed_seq.Read(); + ASSERT_TRUE(IsExecutionMetadata(meta0_blob, parsed_meta0)); + EXPECT_EQ(parsed_meta0.cmp_data, meta0); + const Blob in0_blob = mixed_seq.Read(); + ASSERT_TRUE(IsDataInput(in0_blob)); + EXPECT_EQ(ByteArray(in0_blob.data, in0_blob.data + in0_blob.size), in0); + + // Input 1 has no preceding metadata blob. + const Blob in1_blob = mixed_seq.Read(); + ExecutionMetadata unused_meta; + EXPECT_FALSE(IsExecutionMetadata(in1_blob, unused_meta)); + ASSERT_TRUE(IsDataInput(in1_blob)); + EXPECT_EQ(ByteArray(in1_blob.data, in1_blob.data + in1_blob.size), in1); + + ExecutionMetadata parsed_meta2; + const Blob meta2_blob = mixed_seq.Read(); + ASSERT_TRUE(IsExecutionMetadata(meta2_blob, parsed_meta2)); + EXPECT_EQ(parsed_meta2.cmp_data, meta2); + const Blob in2_blob = mixed_seq.Read(); + ASSERT_TRUE(IsDataInput(in2_blob)); + EXPECT_EQ(ByteArray(in2_blob.data, in2_blob.data + in2_blob.size), in2); + + // If the buffer overflows mid-pair (fits meta0, fails on in0), returns 0. + const size_t exact_two_blobs = [&] { + std::vector<uint8_t> tmp(1024, 0); + BlobSequence seq(tmp.data(), tmp.size()); + RequestExecution({in0}, {meta0}, seq); + return seq.offset(); + }(); + std::vector<uint8_t> tight_buf(exact_two_blobs - 1, 0); + BlobSequence tight_seq(tight_buf.data(), tight_buf.size()); + EXPECT_EQ(RequestExecution({in0}, {meta0}, tight_seq), 0); +} + } // namespace } // namespace fuzztest::internal
diff --git a/centipede/runner.cc b/centipede/runner.cc index f8f38a9..4eafb71 100644 --- a/centipede/runner.cc +++ b/centipede/runner.cc
@@ -43,6 +43,7 @@ #include <ctime> #include <functional> #include <memory> +#include <optional> #include <string> #include <string_view> #include <utility> @@ -382,6 +383,13 @@ return Mutate(origin, origin_metadata); } +void RunnerCallbacks::SetDiffExpectations(void* input, + ByteSpan expected_container) {} + +std::optional<DiffResult> RunnerCallbacks::TakeDiffResult(void* input) { + return std::nullopt; +} + class LegacyRunnerCallbacks : public RunnerCallbacks { public: LegacyRunnerCallbacks(FuzzerTestOneInputCallback test_one_input_cb, @@ -792,12 +800,27 @@ if (runner_ctx->need_full_cleanup) { runner_ctx->need_full_cleanup = false; } + // Incremental differential fuzzing: the controller may have sent the + // expected values of this input as a diff envelope in the metadata (see + // `UpdateInputMetadata`). The metadata is overwritten below, so the callbacks + // must copy the expectations. + if (!input->metadata.cmp_data.empty()) { + DiffEnvelopeKind kind; + ByteSpan cmp_data; + ByteSpan payload; + if (DecodeDiffEnvelope(input->metadata.cmp_data, kind, cmp_data, payload) && + kind == DiffEnvelopeKind::kExpectations) { + runner_ctx->callbacks.SetDiffExpectations(input->content, payload); + } + } const int old_traced = CentipedeSetCurrentThreadTraced(/*traced=*/1); RunOneInput(input->content, runner_ctx->callbacks); CentipedeSetCurrentThreadTraced(old_traced); + const std::optional<DiffResult> diff_result = + runner_ctx->callbacks.TakeDiffResult(input->content); + bool has_overridden_execution_result = false; { LockGuard lock(state->execution_result_override_mu); - bool has_overridden_execution_result = false; if (state->execution_result_override != nullptr) { RunnerCheck(state->execution_result_override->results().size() <= 1, "unexpected number of overridden execution results"); @@ -814,11 +837,17 @@ }; sink->EmitCoverageFeatures(sink->ctx, &features); input->metadata = result.metadata(); - return; } } - SanCovRuntimeEmitFeatures(sink); - input->metadata = SanCovRuntimeGetExecutionMetadata(); + if (!has_overridden_execution_result) { + SanCovRuntimeEmitFeatures(sink); + input->metadata = SanCovRuntimeGetExecutionMetadata(); + } + // Merge the diff result (if any) with the CMP metadata into an envelope. + if (diff_result.has_value()) { + input->metadata.cmp_data = EncodeDiffEnvelope( + diff_result->kind, input->metadata.cmp_data, diff_result->payload); + } } void DeserializeInputContent(FuzzTestAdapterCtx* ctx, @@ -836,7 +865,7 @@ void UpdateInputMetadata(FuzzTestAdapterCtx* ctx, const FuzzTestBytesView* view, FuzzTestInputHandle handle) { auto* input = reinterpret_cast<Input*>(handle); - input->metadata.cmp_data = {view->data, view->data + view->size}; + input->metadata.cmp_data.assign(view->data, view->data + view->size); } void SerializeInputContent(FuzzTestAdapterCtx* ctx, FuzzTestInputHandle handle,
diff --git a/centipede/runner_interface.h b/centipede/runner_interface.h index 3163dd1..8719464 100644 --- a/centipede/runner_interface.h +++ b/centipede/runner_interface.h
@@ -22,6 +22,7 @@ #include <cstdint> #include <functional> #include <memory> +#include <optional> #include <string> #include <vector> @@ -188,6 +189,16 @@ virtual void* DeserializeInput(ByteSpan bytes) = 0; // Called when the runner is done with `input`. virtual void FreeInput(void* input) = 0; + // Incremental differential fuzzing: called before `Execute(input)` with the + // expected record container (the baseline) sent by the controller for + // `input`. `expected_container` does not outlive this call; implementations + // must copy it if needed during `Execute(input)`. The default implementation + // ignores it. + virtual void SetDiffExpectations(void* input, ByteSpan expected_container); + // Incremental differential fuzzing: called after `Execute(input)`. Returns + // the diff result of the execution to send back to the controller, or + // nullopt if there is none. The default implementation returns nullopt. + virtual std::optional<DiffResult> TakeDiffResult(void* input); virtual ~RunnerCallbacks() = default; };
diff --git a/centipede/runner_request.cc b/centipede/runner_request.cc index e6576a0..23f369e 100644 --- a/centipede/runner_request.cc +++ b/centipede/runner_request.cc
@@ -36,20 +36,6 @@ kTagDataInput, }; -// Writes `inputs` to `blobseq`, returns the number of inputs written. -static size_t WriteInputs(absl::Span<const ByteSpan> inputs, - BlobSequence& blobseq) { - size_t num_inputs = inputs.size(); - if (!blobseq.Write(kTagNumInputs, num_inputs)) return 0; - size_t result = 0; - for (const auto &input : inputs) { - if (!blobseq.Write({kTagDataInput, input.size(), input.data()})) - return result; - ++result; - } - return result; -} - static bool WriteMetadataFromRefOrDefault(const ExecutionMetadata *metadata, BlobSequence &blobseq) { if (metadata != nullptr) @@ -58,7 +44,7 @@ return default_metadata->Write(kTagExecutionMetadata, blobseq); } -// Similar to above, but for mutation inputs. +// Writes mutation `inputs` to `blobseq`, returns the number of inputs written. static size_t WriteInputs(absl::Span<const MutationInputRef> inputs, BlobSequence& blobseq) { size_t num_inputs = inputs.size(); @@ -73,12 +59,41 @@ return result; } +// Writes `inputs` (and optional per-input `metadata`, if non-empty) to +// `blobseq`, returns the number of inputs written. +static size_t WriteInputs(absl::Span<const ByteSpan> inputs, + absl::Span<const ByteSpan> metadata, + BlobSequence& blobseq) { + size_t num_inputs = inputs.size(); + if (!blobseq.Write(kTagNumInputs, num_inputs)) return 0; + size_t result = 0; + for (size_t i = 0; i < inputs.size(); ++i) { + if (i < metadata.size() && !metadata[i].empty() && + !blobseq.Write( + {kTagExecutionMetadata, metadata[i].size(), metadata[i].data()})) { + return result; + } + if (!blobseq.Write({kTagDataInput, inputs[i].size(), inputs[i].data()})) + return result; + ++result; + } + return result; +} + } // namespace size_t RequestExecution(absl::Span<const ByteSpan> inputs, BlobSequence& blobseq) { if (!blobseq.Write({kTagExecution, 0, nullptr})) return 0; - return WriteInputs(inputs, blobseq); + return WriteInputs(inputs, /*metadata=*/{}, blobseq); +} + +size_t RequestExecution(absl::Span<const ByteSpan> inputs, + absl::Span<const ByteSpan> metadata, + BlobSequence& blobseq) { + if (metadata.size() != inputs.size()) return 0; + if (!blobseq.Write({kTagExecution, 0, nullptr})) return 0; + return WriteInputs(inputs, metadata, blobseq); } size_t RequestMutation(size_t num_mutants,
diff --git a/centipede/runner_request.h b/centipede/runner_request.h index f1d7a5b..9816656 100644 --- a/centipede/runner_request.h +++ b/centipede/runner_request.h
@@ -39,6 +39,16 @@ size_t RequestExecution(absl::Span<const ByteSpan> inputs, BlobSequence& blobseq); +// Same as above, but `metadata[i]`, if non-empty, is sent as an execution +// metadata blob immediately before `inputs[i]` (used to deliver the baseline +// to the runner in the incremental differential fuzzing validate mode). +// `metadata` must have the same size as `inputs`. With all-empty `metadata`, +// the request is byte-identical to the overload above. Returns the number of +// inputs whose data blob was sent. +size_t RequestExecution(absl::Span<const ByteSpan> inputs, + absl::Span<const ByteSpan> metadata, + BlobSequence& blobseq); + // Sends a request (via `blobseq`) to compute `num_mutants` mutants of `inputs`. // Returns the number of sent inputs, which would normally be inputs.size(). size_t RequestMutation(size_t num_mutants,
diff --git a/e2e_tests/functional_test.cc b/e2e_tests/functional_test.cc index df5add5..3b22727 100644 --- a/e2e_tests/functional_test.cc +++ b/e2e_tests/functional_test.cc
@@ -856,6 +856,63 @@ EXPECT_THAT_LOG(std_err, HasSubstr("will not limit jobs")); } +TEST_F(GenericCommandLineInterfaceTest, RejectsInvalidForFlagUsage) { + { + auto [status, std_out, std_err] = + RunWith(/*flags=*/{{"for", "1s"}}, /*env=*/{}, + /*timeout=*/absl::Seconds(10), + /*binary=*/"testdata/unit_test_and_fuzz_tests"); + EXPECT_THAT(status, Ne(ExitCode(0))); + EXPECT_THAT_LOG(std_err, + AllOf(HasSubstr("for requires one of"), HasSubstr("fuzz"), + HasSubstr("replay_corpus"))); + } + for (const auto& flags : + std::vector<absl::flat_hash_map<std::string, std::string>>{ + {{"fuzz", "*"}, {"for", "0s"}}, + {{"replay_corpus", "*"}, {"for", "-1s"}}, + }) { + auto [status, std_out, std_err] = + RunWith(flags, /*env=*/{}, /*timeout=*/absl::Seconds(10), + /*binary=*/"testdata/unit_test_and_fuzz_tests"); + EXPECT_THAT(status, Ne(ExitCode(0))); + EXPECT_THAT_LOG(std_err, HasSubstr("for must be positive")); + } +} + +TEST_F(GenericCommandLineInterfaceTest, RejectsMutuallyExclusiveModeFlags) { + for (const auto& flags : + std::vector<absl::flat_hash_map<std::string, std::string>>{ + {{"fuzz", "*"}, {"replay_corpus", "*"}}, + {{"fuzz_for", "1s"}, {"replay_corpus", "*"}}, + {{"fuzz", "*"}, {"replay_corpus_for", "1s"}}, + {{"fuzz_for", "1s"}, {"replay_corpus_for", "1s"}}, + }) { + auto [status, std_out, std_err] = + RunWith(flags, /*env=*/{}, /*timeout=*/absl::Seconds(10), + /*binary=*/"testdata/unit_test_and_fuzz_tests"); + EXPECT_THAT(status, Ne(ExitCode(0))); + EXPECT_THAT_LOG(std_err, HasSubstr("At most one of")); + } +} + +TEST_F(GenericCommandLineInterfaceTest, + RejectsCombiningForFlagWithLegacyDurationFlags) { + for (const auto& flags : + std::vector<absl::flat_hash_map<std::string, std::string>>{ + {{"fuzz", "*"}, {"for", "1s"}, {"fuzz_for", "1s"}}, + {{"fuzz", "*"}, {"for", "1s"}, {"fuzz_for", "inf"}}, + {{"replay_corpus", "*"}, {"for", "1s"}, {"replay_corpus_for", "1s"}}, + {{"replay_corpus", "*"}, {"for", "1s"}, {"replay_corpus_for", "0s"}}, + }) { + auto [status, std_out, std_err] = + RunWith(flags, /*env=*/{}, /*timeout=*/absl::Seconds(10), + /*binary=*/"testdata/unit_test_and_fuzz_tests"); + EXPECT_THAT(status, Ne(ExitCode(0))); + EXPECT_THAT_LOG(std_err, HasSubstr("cannot be combined with")); + } +} + // Tests for the FuzzTest command line interface in fuzzing mode, which can only // run with coverage instrumentation enabled. class FuzzingModeCommandLineInterfaceTest @@ -1405,6 +1462,56 @@ EXPECT_THAT(status, Eq(ExitCode(0))); } +TEST_F(FuzzingModeCommandLineInterfaceTest, + FuzzWildcardWithForRunsOnlyFuzzTestsAndRespectsFilter) { + { + auto [status, std_out, std_err] = RunWith( + {{"fuzz", "*"}, {"for", "1s"}}, /*env=*/{}, + /*timeout=*/absl::Seconds(15), "testdata/unit_test_and_fuzz_tests"); + EXPECT_THAT_LOG(std_out, + Not(HasSubstr("[ RUN ] UnitTest.AlwaysPasses"))); + EXPECT_THAT_LOG(std_out, HasSubstr("[ RUN ] FuzzTest.AlwaysPasses")); + EXPECT_THAT_LOG(std_out, + HasSubstr("[ RUN ] FuzzTest.AlsoAlwaysPasses")); + EXPECT_THAT_LOG(std_out, HasSubstr("2 tests from 1 test suite ran.")); + EXPECT_THAT(status, Eq(ExitCode(0))); + } + { + auto [status, std_out, std_err] = RunWith( + {{"fuzz", "*"}, {"for", "1s"}}, /*env=*/{}, + /*timeout=*/absl::Seconds(15), "testdata/unit_test_and_fuzz_tests", + {{GTEST_FLAG_PREFIX_ "filter", + "UnitTest.AlwaysPasses:FuzzTest.AlsoAlwaysPasses"}}); + EXPECT_THAT_LOG(std_out, + Not(HasSubstr("[ RUN ] UnitTest.AlwaysPasses"))); + EXPECT_THAT_LOG(std_out, + Not(HasSubstr("[ RUN ] FuzzTest.AlwaysPasses"))); + EXPECT_THAT_LOG(std_out, + HasSubstr("[ RUN ] FuzzTest.AlsoAlwaysPasses")); + EXPECT_THAT_LOG(std_out, HasSubstr("1 test from 1 test suite ran.")); + EXPECT_THAT(status, Eq(ExitCode(0))); + } +} + +TEST_F(FuzzingModeCommandLineInterfaceTest, + ReplayCorpusWildcardWithForRunsOnlyFuzzTests) { + TempDir temp_dir; + const std::string corpus_database = temp_dir.path() / "corpus_database"; + auto [status, std_out, std_err] = RunWith( + {{"replay_corpus", "*"}, + {"for", "1s"}, + {"corpus_database", corpus_database}}, + // Needed for the legacy runtime to skip fuzzing. + /*env=*/{{"FUZZTEST_FUZZ_FOR", "0s"}}, + /*timeout=*/absl::Seconds(15), "testdata/unit_test_and_fuzz_tests"); + EXPECT_THAT_LOG(std_out, + Not(HasSubstr("[ RUN ] UnitTest.AlwaysPasses"))); + EXPECT_THAT_LOG(std_out, HasSubstr("[ RUN ] FuzzTest.AlwaysPasses")); + EXPECT_THAT_LOG(std_out, HasSubstr("[ RUN ] FuzzTest.AlsoAlwaysPasses")); + EXPECT_THAT_LOG(std_out, HasSubstr("2 tests from 1 test suite ran.")); + EXPECT_THAT(status, Eq(ExitCode(0))); +} + // This tests both the command line interface and the fuzzing logic. It is under // FuzzingModeCommandLineInterfaceTest so it can specify the command line. TEST_F(FuzzingModeCommandLineInterfaceTest, CorpusDoesNotContainSkippedInputs) {
diff --git a/fuzztest/BUILD b/fuzztest/BUILD index f2d0d11..e1b4121 100644 --- a/fuzztest/BUILD +++ b/fuzztest/BUILD
@@ -107,6 +107,39 @@ ) cc_library( + name = "record_or_diff", + srcs = ["record_or_diff.cc"], + hdrs = ["record_or_diff.h"], + deps = [ + ":domain", + "@abseil-cpp//absl/base:core_headers", + "@abseil-cpp//absl/functional:function_ref", + "@abseil-cpp//absl/strings", + "@abseil-cpp//absl/strings:string_view", + "@com_google_fuzztest//fuzztest/internal:meta", + "@com_google_fuzztest//fuzztest/internal:printer", + "@com_google_fuzztest//fuzztest/internal:runtime", + "@com_google_fuzztest//fuzztest/internal:serialization", + "@com_google_fuzztest//fuzztest/internal:type_support", + ], +) + +cc_test( + name = "record_or_diff_test", + srcs = ["record_or_diff_test.cc"], + deps = [ + ":record_or_diff", + "@abseil-cpp//absl/functional:function_ref", + "@abseil-cpp//absl/strings", + "@com_google_fuzztest//fuzztest/internal:configuration", + "@com_google_fuzztest//fuzztest/internal:meta", + "@com_google_fuzztest//fuzztest/internal:runtime", + "@com_google_fuzztest//fuzztest/internal:serialization", + "@googletest//:gtest_main", + ], +) + +cc_library( name = "fuzztest_gtest_main", testonly = 1, srcs = ["fuzztest_gtest_main.cc"],
diff --git a/fuzztest/CMakeLists.txt b/fuzztest/CMakeLists.txt index fc1dc64..7ac7c1e 100644 --- a/fuzztest/CMakeLists.txt +++ b/fuzztest/CMakeLists.txt
@@ -251,3 +251,39 @@ fuzztest::core_domains_impl fuzztest::lazy ) + +fuzztest_cc_library( + NAME + record_or_diff + HDRS + "record_or_diff.h" + SRCS + "record_or_diff.cc" + DEPS + fuzztest::domain + absl::core_headers + absl::function_ref + absl::strings + absl::string_view + fuzztest::meta + fuzztest::printer + fuzztest::runtime + fuzztest::serialization + fuzztest::type_support +) + +fuzztest_cc_test( + NAME + record_or_diff_test + SRCS + "record_or_diff_test.cc" + DEPS + fuzztest::record_or_diff + GTest::gmock_main + absl::function_ref + absl::strings + fuzztest::configuration + fuzztest::meta + fuzztest::runtime + fuzztest::serialization +)
diff --git a/fuzztest/init_fuzztest.cc b/fuzztest/init_fuzztest.cc index a1c9280..3c29cef 100644 --- a/fuzztest/init_fuzztest.cc +++ b/fuzztest/init_fuzztest.cc
@@ -55,20 +55,25 @@ FUZZTEST_DEFINE_FLAG( std::string, fuzz, std::string(kUnspecified), - "Runs a single FUZZ_TEST in continuous fuzzing mode. E.g., " - "`--" FUZZTEST_FLAG_PREFIX + "Runs a single FUZZ_TEST, or all FUZZ_TESTs when set to `*`, in continuous " + "fuzzing mode. E.g., `--" FUZZTEST_FLAG_PREFIX "fuzz=MySuite.MyFuzzTest` runs the given FUZZ_TEST in fuzzing mode. You " "can also provide just a part of the name, e.g., " "`--" FUZZTEST_FLAG_PREFIX "fuzz=MyFuzz`, if it matches only a single FUZZ_TEST. If you have only one " "fuzz test in your binary, you can also use `--" FUZZTEST_FLAG_PREFIX "fuzz=` to run it in fuzzing mode (i.e., by setting the flag to empty " - "string). In fuzzing mode the selected test runs until a bug is found or " - "until manually stopped. Fuzzing mode uses coverage feedback to " - "iteratively build up a corpus of inputs that maximize coverage and to " - "reach deep bugs. Note that the binary must be compiled with " - "`--config=fuzztest` for this to work, as it needs coverage " - "instrumentation."); + "string). Setting `--" FUZZTEST_FLAG_PREFIX + "fuzz=*` runs all FUZZ_TESTs in the binary (or those matching " + "`--" GTEST_FLAG_PREFIX_ + "filter`). Can be combined with " + "`--" FUZZTEST_FLAG_PREFIX + "for=<duration>` to bound the fuzzing time; otherwise the selected " + "FUZZ_TEST(s) run until a bug is found or until manually stopped. Fuzzing " + "mode uses coverage feedback to iteratively build up a corpus of inputs " + "that maximize coverage and to reach deep bugs. Note that the binary must " + "be compiled with `--config=fuzztest` for this to work, as it needs " + "coverage instrumentation."); FUZZTEST_DEFINE_FLAG( absl::Duration, fuzz_for, absl::InfiniteDuration(), @@ -105,8 +110,8 @@ FUZZTEST_DEFINE_FLAG( std::string, replay_corpus, std::string(kUnspecified), - "Runs a single FUZZ_TEST in corpus replay mode. E.g., " - "`--" FUZZTEST_FLAG_PREFIX + "Runs a single FUZZ_TEST, or all FUZZ_TESTs when set to `*`, in corpus " + "replay mode. E.g., `--" FUZZTEST_FLAG_PREFIX "replay_corpus=MySuite.MyFuzzTest` replays the corpus from the corpus " "database for the given FUZZ_TEST. You can also provide just a part of the " "name, e.g., `--" FUZZTEST_FLAG_PREFIX @@ -114,19 +119,24 @@ "only one fuzz test in your binary, you can also use " "`--" FUZZTEST_FLAG_PREFIX "replay_corpus=` to run it in the corpus replay mode (i.e., by setting the " - "flag to empty string). In corpus replay mode the selected test replays " - "the inputs that exercise unique coverage (corpus) from the corpus " - "database. Note that this does not include crashing inputs (counterexample " - "findings). Replaying coverage (non-crashing) inputs is useful for " - "measuring the coverage of the corpus built up during previously ran " - "fuzzing sessions, or to catch newly introduced regressions at presubmit " - "time in CI."); + "flag to empty string). Setting `--" FUZZTEST_FLAG_PREFIX + "replay_corpus=*` replays all FUZZ_TESTs in the binary (or those matching " + "`--" GTEST_FLAG_PREFIX_ + "filter`). Can be combined with " + "`--" FUZZTEST_FLAG_PREFIX + "for=<duration>` to bound the replay time; otherwise the entire corpus is " + "replayed. In corpus replay mode the selected test replays the inputs that " + "exercise unique coverage (corpus) from the corpus database. Note that " + "this does not include crashing inputs (counterexample findings). " + "Replaying coverage (non-crashing) inputs is useful for measuring the " + "coverage of the corpus built up during previously ran fuzzing sessions, " + "or to catch newly introduced regressions at presubmit time in CI."); FUZZTEST_DEFINE_FLAG( absl::Duration, replay_corpus_for, absl::ZeroDuration(), "Runs all fuzz tests in corpus replay mode up to the specified duration. " "Can be combined with --" FUZZTEST_FLAG_PREFIX - "fuzz to select a single fuzz test, or with --" GTEST_FLAG_PREFIX_ + "replay_corpus to select a single fuzz test, or with --" GTEST_FLAG_PREFIX_ "filter to select a subset of fuzz tests. To replay the entire corpus for " "each FUZZ_TEST in the binary, set this flag to `inf` (infinite time " "budget). It's recommended to run the tests in the binary in parallel " @@ -136,13 +146,22 @@ "value of --" FUZZTEST_FLAG_PREFIX "time_budget_type."); FUZZTEST_DEFINE_FLAG( + std::optional<absl::Duration>, for, std::nullopt, + "The maximum duration for `--" FUZZTEST_FLAG_PREFIX "fuzz` or `--" + FUZZTEST_FLAG_PREFIX + "replay_corpus`. Defaults to `inf` (infinite time budget) when omitted. " + "Whether the time budget applies per FUZZ_TEST or across all running " + "FUZZ_TESTs is controlled by `--" FUZZTEST_FLAG_PREFIX + "time_budget_type`."); + +FUZZTEST_DEFINE_FLAG( fuzztest::internal::TimeBudgetType, time_budget_type, fuzztest::internal::TimeBudgetType::kPerTest, "Determines whether the time budget specified by --" FUZZTEST_FLAG_PREFIX - "fuzz_for or --" FUZZTEST_FLAG_PREFIX - "replay_corpus_for is for each FUZZ_TEST or for all 'N' running FUZZ_TESTs " - ". In the latter case, each FUZZ_TEST will run for at most (1/N)th of the " - "time budget."); + "for, --" FUZZTEST_FLAG_PREFIX "fuzz_for, or --" FUZZTEST_FLAG_PREFIX + "replay_corpus_for is for each FUZZ_TEST or for all 'N' running " + "FUZZ_TESTs. In the latter case, each FUZZ_TEST will run for at most " + "(1/N)th of the time budget."); FUZZTEST_DEFINE_FLAG( std::optional<bool>, update_corpus_database, std::nullopt, @@ -241,7 +260,8 @@ absl::InfiniteDuration(), "Internal-only flag - do not use directly. If --" FUZZTEST_FLAG_PREFIX "internal_override_fuzz_test is set, override the time limit set by " - "--" FUZZTEST_FLAG_PREFIX "fuzz_for / --" FUZZTEST_FLAG_PREFIX + "--" FUZZTEST_FLAG_PREFIX "for / --" FUZZTEST_FLAG_PREFIX + "fuzz_for / --" FUZZTEST_FLAG_PREFIX "replay_corpus_for with --time_budget_type set to total.") .OnUpdate([] { FUZZTEST_PRECONDITION( @@ -316,36 +336,74 @@ namespace { std::optional<absl::Duration> GetFuzzingTime() { + const bool has_fuzz_target = + absl::GetFlag(FUZZTEST_FLAG(fuzz)) != kUnspecified; + if (const std::optional<absl::Duration> for_duration = + absl::GetFlag(FUZZTEST_FLAG(for)); + for_duration.has_value()) { + return has_fuzz_target ? for_duration : std::nullopt; + } absl::Duration fuzz_time_limit = absl::GetFlag(FUZZTEST_FLAG(fuzz_for)); if (fuzz_time_limit <= absl::ZeroDuration()) { fuzz_time_limit = absl::InfiniteDuration(); } - if (absl::GetFlag(FUZZTEST_FLAG(fuzz)) == kUnspecified && - fuzz_time_limit == absl::InfiniteDuration()) { + if (!has_fuzz_target && fuzz_time_limit == absl::InfiniteDuration()) { return std::nullopt; } return fuzz_time_limit; } std::optional<absl::Duration> GetReplayCorpusTime() { - absl::Duration replay_corpus_time_limit = - absl::GetFlag(FUZZTEST_FLAG(replay_corpus_for)); - if (absl::GetFlag(FUZZTEST_FLAG(replay_corpus)) == kUnspecified && - replay_corpus_time_limit <= absl::ZeroDuration()) { - return std::nullopt; + const bool has_replay_target = + absl::GetFlag(FUZZTEST_FLAG(replay_corpus)) != kUnspecified; + if (const std::optional<absl::Duration> for_duration = + absl::GetFlag(FUZZTEST_FLAG(for)); + for_duration.has_value()) { + return has_replay_target ? for_duration : std::nullopt; } - if (absl::GetFlag(FUZZTEST_FLAG(replay_corpus)) != kUnspecified && - replay_corpus_time_limit <= absl::ZeroDuration()) { - replay_corpus_time_limit = absl::InfiniteDuration(); + const absl::Duration replay_corpus_time_limit = + absl::GetFlag(FUZZTEST_FLAG(replay_corpus_for)); + if (replay_corpus_time_limit <= absl::ZeroDuration()) { + return has_replay_target + ? std::optional<absl::Duration>(absl::InfiniteDuration()) + : std::nullopt; } return replay_corpus_time_limit; } -bool GetDefaultUpdateCorpusDatabase() { - const std::string test_to_fuzz = absl::GetFlag(FUZZTEST_FLAG(fuzz)); - const bool is_fuzzing = - test_to_fuzz != kUnspecified || GetFuzzingTime().has_value(); - return is_fuzzing && !GetReplayCorpusTime().has_value(); +void ValidateModeAndDurationFlags() { + const bool has_fuzz_target = + absl::GetFlag(FUZZTEST_FLAG(fuzz)) != kUnspecified; + const bool has_replay_target = + absl::GetFlag(FUZZTEST_FLAG(replay_corpus)) != kUnspecified; + if (const std::optional<absl::Duration> for_duration = + absl::GetFlag(FUZZTEST_FLAG(for)); + for_duration.has_value()) { + FUZZTEST_CHECK(has_fuzz_target || has_replay_target) + << "--" FUZZTEST_FLAG_PREFIX "for requires one of --" + << FUZZTEST_FLAG_PREFIX "fuzz or --" FUZZTEST_FLAG_PREFIX + << "replay_corpus."; + FUZZTEST_CHECK(*for_duration > absl::ZeroDuration()) + << "--" FUZZTEST_FLAG_PREFIX "for must be positive (got " + << absl::FormatDuration(*for_duration) << ")."; + const bool legacy_fuzz_for_specified = + FUZZTEST_FLAG(fuzz_for).IsSpecifiedOnCommandLine() || + absl::GetFlag(FUZZTEST_FLAG(fuzz_for)) != absl::InfiniteDuration(); + const bool legacy_replay_for_specified = + FUZZTEST_FLAG(replay_corpus_for).IsSpecifiedOnCommandLine() || + absl::GetFlag(FUZZTEST_FLAG(replay_corpus_for)) != absl::ZeroDuration(); + FUZZTEST_CHECK(!legacy_fuzz_for_specified && !legacy_replay_for_specified) + << "--" FUZZTEST_FLAG_PREFIX "for cannot be combined with --" + << FUZZTEST_FLAG_PREFIX "fuzz_for or --" FUZZTEST_FLAG_PREFIX + << "replay_corpus_for."; + } + + FUZZTEST_CHECK(!GetFuzzingTime().has_value() || + !GetReplayCorpusTime().has_value()) + << "At most one of --" FUZZTEST_FLAG_PREFIX "fuzz / --" + << FUZZTEST_FLAG_PREFIX "fuzz_for and --" FUZZTEST_FLAG_PREFIX + << "replay_corpus / --" FUZZTEST_FLAG_PREFIX + << "replay_corpus_for may be specified at the same time."; } // Expands a leading `~/` to $HOME and, when running under a test, makes a @@ -365,6 +423,7 @@ internal::Configuration CreateConfigurationsFromFlags( absl::string_view binary_identifier) { + ValidateModeAndDurationFlags(); const bool reproduce_findings_as_separate_tests = absl::GetFlag(FUZZTEST_FLAG(reproduce_findings_as_separate_tests)); const std::optional<absl::Duration> fuzzing_time_limit = GetFuzzingTime(); @@ -376,7 +435,8 @@ fuzzing_time_limit.has_value() || replay_corpus_time_limit.has_value(); const bool update_corpus_database = absl::GetFlag(FUZZTEST_FLAG(update_corpus_database)) - .value_or(GetDefaultUpdateCorpusDatabase()); + .value_or(fuzzing_time_limit.has_value() && + !replay_corpus_time_limit.has_value()); const absl::Duration time_limit = override_fuzz_test.has_value() @@ -464,28 +524,21 @@ std::cout << std::flush; std::exit(0); } + ValidateModeAndDurationFlags(); std::optional<absl::Duration> fuzzing_time_limit = GetFuzzingTime(); std::optional<absl::Duration> replay_corpus_time_limit = GetReplayCorpusTime(); - FUZZTEST_CHECK(!fuzzing_time_limit || !replay_corpus_time_limit) - << "Cannot run in fuzzing and corpus replay mode at the same time."; - const auto specified_test = []() -> std::optional<std::string> { - if (auto internal_selected_test = - absl::GetFlag(FUZZTEST_FLAG(internal_override_fuzz_test)); - internal_selected_test.has_value()) { - return internal_selected_test; + std::optional<std::string> specified_test = + absl::GetFlag(FUZZTEST_FLAG(internal_override_fuzz_test)); + if (!specified_test.has_value()) { + std::string target = absl::GetFlag(FUZZTEST_FLAG(fuzz)); + if (target == kUnspecified) { + target = absl::GetFlag(FUZZTEST_FLAG(replay_corpus)); } - if (auto test_to_fuzz = absl::GetFlag(FUZZTEST_FLAG(fuzz)); - test_to_fuzz != kUnspecified) { - return test_to_fuzz; + if (target != kUnspecified && target != "*") { + specified_test = std::move(target); } - if (auto test_to_replay_corpus = - absl::GetFlag(FUZZTEST_FLAG(replay_corpus)); - test_to_replay_corpus != kUnspecified) { - return test_to_replay_corpus; - } - return std::nullopt; - }(); + } if (specified_test.has_value()) { const std::string matching_fuzz_test = GetMatchingFuzzTestOrExit(*specified_test);
diff --git a/fuzztest/internal/BUILD b/fuzztest/internal/BUILD index 0a055d1..e773105 100644 --- a/fuzztest/internal/BUILD +++ b/fuzztest/internal/BUILD
@@ -459,6 +459,7 @@ srcs = ["runtime_test.cc"], deps = [ ":configuration", + ":flag_name", ":runtime", ":test_protobuf_cc_proto", "@abseil-cpp//absl/base:core_headers",
diff --git a/fuzztest/internal/CMakeLists.txt b/fuzztest/internal/CMakeLists.txt index 27a86ab..5f1abaa 100644 --- a/fuzztest/internal/CMakeLists.txt +++ b/fuzztest/internal/CMakeLists.txt
@@ -425,6 +425,7 @@ "runtime_test.cc" DEPS fuzztest::configuration + fuzztest::flag_name fuzztest::runtime fuzztest::test_protobuf_cc_proto GTest::gmock_main
diff --git a/fuzztest/internal/configuration.cc b/fuzztest/internal/configuration.cc index 4ca302f..cb88cb3 100644 --- a/fuzztest/internal/configuration.cc +++ b/fuzztest/internal/configuration.cc
@@ -65,6 +65,45 @@ } } +bool AbslParseFlag(absl::string_view text, DiffMode* mode, std::string* error) { + if (text.empty() || text == "none") { + *mode = DiffMode::kNone; + return true; + } + if (text == "record") { + *mode = DiffMode::kRecord; + return true; + } + if (text == "validate") { + *mode = DiffMode::kValidate; + return true; + } + *error = "must be one of: none, record, validate"; + return false; +} + +absl::StatusOr<DiffMode> ParseDiffMode(absl::string_view text) { + DiffMode mode; + std::string error; + if (!AbslParseFlag(text, &mode, &error)) { + return absl::InvalidArgumentError(error); + } + return mode; +} + +std::string AbslUnparseFlag(DiffMode mode) { + switch (mode) { + case DiffMode::kNone: + return "none"; + case DiffMode::kRecord: + return "record"; + case DiffMode::kValidate: + return "validate"; + default: + return absl::StrCat(static_cast<int>(mode)); + } +} + namespace { template <typename T> @@ -203,6 +242,7 @@ absl::FormatDuration(time_limit_per_input); std::string time_limit_str = absl::FormatDuration(time_limit); std::string time_budget_type_str = AbslUnparseFlag(time_budget_type); + std::string diff_mode_str = AbslUnparseFlag(diff_mode); std::string out; out.resize( SpaceFor(corpus_database) + SpaceFor(stats_root) + @@ -218,7 +258,7 @@ SpaceFor(time_limit_str) + SpaceFor(time_budget_type_str) + SpaceFor(jobs) + SpaceFor(centipede_command) + SpaceFor(crashing_input_to_reproduce) + SpaceFor(replay_crash_attempts) + - SpaceFor(reproduction_command_template)); + SpaceFor(reproduction_command_template) + SpaceFor(diff_mode_str)); size_t offset = 0; offset = WriteString(out, offset, corpus_database); offset = WriteString(out, offset, stats_root); @@ -246,6 +286,7 @@ offset = WriteOptionalString(out, offset, crashing_input_to_reproduce); offset = WriteIntegral(out, offset, replay_crash_attempts); offset = WriteOptionalString(out, offset, reproduction_command_template); + offset = WriteString(out, offset, diff_mode_str); FUZZTEST_CHECK_EQ(offset, out.size()); return out; } @@ -283,6 +324,7 @@ ASSIGN_OR_RETURN(replay_crash_attempts, Consume<size_t>(serialized)); ASSIGN_OR_RETURN(reproduction_command_template, ConsumeOptionalString(serialized)); + ASSIGN_OR_RETURN(diff_mode_str, ConsumeString(serialized)); if (!serialized.empty()) { return absl::InvalidArgumentError( "Buffer is not empty after consuming a serialized configuration."); @@ -294,6 +336,7 @@ ASSIGN_OR_RETURN(time_limit, ParseDuration(*time_limit_str)); ASSIGN_OR_RETURN(time_budget_type, ParseTimeBudgetType(*time_budget_type_str)); + ASSIGN_OR_RETURN(diff_mode, ParseDiffMode(*diff_mode_str)); return Configuration{*std::move(corpus_database), *std::move(stats_root), *std::move(workdir_root), @@ -319,7 +362,8 @@ *std::move(centipede_command), *std::move(crashing_input_to_reproduce), *replay_crash_attempts, - *std::move(reproduction_command_template)}; + *std::move(reproduction_command_template), + *diff_mode}; }(); }
diff --git a/fuzztest/internal/configuration.h b/fuzztest/internal/configuration.h index 8f82196..3e5d6f3 100644 --- a/fuzztest/internal/configuration.h +++ b/fuzztest/internal/configuration.h
@@ -40,6 +40,20 @@ // string is not representing a valid TimeBudgetType. absl::StatusOr<TimeBudgetType> ParseTimeBudgetType(absl::string_view text); +// Incremental differential fuzzing mode (see `fuzztest::RecordOrDiff`). +enum class DiffMode { kNone, kRecord, kValidate }; + +// To be used by ABSL_FLAG for parsing DiffMode. Accepts "none", "record", +// "validate", and the empty string (= "none"). +bool AbslParseFlag(absl::string_view text, DiffMode* mode, std::string* error); + +// To be used by ABSL_FLAG for stringifying DiffMode. +std::string AbslUnparseFlag(DiffMode mode); + +// Returns the DiffMode from flag string values. Returns an error if the string +// does not represent a valid DiffMode. +absl::StatusOr<DiffMode> ParseDiffMode(absl::string_view text); + // The configuration of a fuzz test. struct Configuration { // The location of the database that contains coverage, regression, and @@ -122,6 +136,10 @@ // - $TEST_FILTER: for replaying only a subset of the tests in a binary. std::optional<std::string> reproduction_command_template; + // Incremental differential fuzzing mode for corpus replay. Only takes effect + // together with `only_replay` in the Centipede runner. + DiffMode diff_mode = DiffMode::kNone; + // Preprocessing step for reproducing crashing input. // Note: This field is not serialized and deserialized. // TODO(b/329709054): Consider eliminating the field.
diff --git a/fuzztest/internal/configuration_test.cc b/fuzztest/internal/configuration_test.cc index 70f9e3a..4c03900 100644 --- a/fuzztest/internal/configuration_test.cc +++ b/fuzztest/internal/configuration_test.cc
@@ -43,7 +43,8 @@ other->crashing_input_to_reproduce && config.replay_crash_attempts == other->replay_crash_attempts && config.reproduction_command_template == - other->reproduction_command_template; + other->reproduction_command_template && + config.diff_mode == other->diff_mode; } TEST(ConfigurationTest, @@ -73,7 +74,8 @@ /*centipede_command=*/std::nullopt, /*crashing_input_to_reproduce=*/std::nullopt, /*replay_crash_attempts=*/5, - /*reproduction_command_template=*/std::nullopt}; + /*reproduction_command_template=*/std::nullopt, + /*diff_mode=*/DiffMode::kNone}; EXPECT_THAT(Configuration::Deserialize(configuration.Serialize()), IsOkAndEquals(configuration)); @@ -106,12 +108,26 @@ "centipede_command", "crashing_input_to_reproduce", /*replay_crash_attempts=*/20, - "reproduction_command_template"}; + "reproduction_command_template", + /*diff_mode=*/DiffMode::kRecord}; EXPECT_THAT(Configuration::Deserialize(configuration.Serialize()), IsOkAndEquals(configuration)); } +TEST(ConfigurationTest, ParseAndUnparseDiffMode) { + EXPECT_EQ(ParseDiffMode(""), absl::StatusOr<DiffMode>(DiffMode::kNone)); + EXPECT_EQ(ParseDiffMode("none"), absl::StatusOr<DiffMode>(DiffMode::kNone)); + EXPECT_EQ(ParseDiffMode("record"), + absl::StatusOr<DiffMode>(DiffMode::kRecord)); + EXPECT_EQ(ParseDiffMode("validate"), + absl::StatusOr<DiffMode>(DiffMode::kValidate)); + EXPECT_FALSE(ParseDiffMode("invalid").ok()); + EXPECT_EQ(AbslUnparseFlag(DiffMode::kNone), "none"); + EXPECT_EQ(AbslUnparseFlag(DiffMode::kRecord), "record"); + EXPECT_EQ(AbslUnparseFlag(DiffMode::kValidate), "validate"); +} + TEST(ConfigurationTest, DeserializeFailsOnNonsenseInput) { EXPECT_FALSE( Configuration::Deserialize("Not a serialized configuration").ok());
diff --git a/fuzztest/internal/runtime.cc b/fuzztest/internal/runtime.cc index f2c7fe8..9af4552 100644 --- a/fuzztest/internal/runtime.cc +++ b/fuzztest/internal/runtime.cc
@@ -41,6 +41,7 @@ #include <deque> #include <filesystem> // NOLINT #include <functional> +#include <map> #include <memory> #include <optional> #include <string> @@ -395,6 +396,10 @@ // We don't want to try and print a fuzz report when we are not running a fuzz // test, even if we got a crash. if (!reporter_enabled_.exchange(false)) return; + if (diff_active()) { + re_enable_reporter_on_next_diff_input_.store(true, + std::memory_order_relaxed); + } if (auto* coverage = GetExecutionCoverage()) { // Turn off tracing to avoid having the report trigger more problems during @@ -450,6 +455,43 @@ trim ? kTrimIndicator : ""); }); + const DiffReportKind diff_report_kind = + diff_failure_report_.load(std::memory_order_relaxed); + if (diff_report_kind != DiffReportKind::kNone) { + const DiffMode active_diff_mode = diff_mode(); + const absl::string_view mode_flag = + active_diff_mode == DiffMode::kRecord ? "record" : "diff"; + // A RecordOrDiff finding reproduces only in corpus replay with + // --record/--diff, so the regression test draft and the reproducer would + // mislead. + absl::Format(out, "%s=== RecordOrDiff reproduction\n\n", GetSeparator()); + absl::Format( + out, + "This finding is a RecordOrDiff %s. It reproduces only with\n" + "--%s%s%s. A regression test or a\n" + "FUZZTEST_REPLAY reproducer does not reproduce it, because " + "RecordOrDiff is a no-op there.\n", + diff_report_kind == DiffReportKind::kMismatch ? "mismatch" : "error", + FUZZTEST_FLAG_PREFIX, mode_flag, + active_diff_mode == DiffMode::kValidate ? " against the same baseline" + : ""); + const absl::string_view corpus_database = + current_configuration_ != nullptr + ? absl::string_view(current_configuration_->corpus_database) + : ""; + const absl::string_view workdir_root = + current_configuration_ != nullptr + ? absl::string_view(current_configuration_->workdir_root) + : ""; + absl::Format(out, + "Re-run with: --%s%s=%s.%s --%scorpus_database=%s " + "--%sworkdir_root=%s\n", + FUZZTEST_FLAG_PREFIX, mode_flag, current_test_->suite_name(), + current_test_->test_name(), FUZZTEST_FLAG_PREFIX, + corpus_database, FUZZTEST_FLAG_PREFIX, workdir_root); + absl::Format(out, "%s", GetSeparator()); + return; + } // There doesn't seem to be a good way to generate a reproducer test when // the test uses a fixture (see b/241271658). if (!current_test_->uses_fixture()) { @@ -868,6 +910,309 @@ std::abort(); } +namespace { + +constexpr uint64_t kDiffRecordContainerVersion = 1; + +std::string TrimDiffValue(absl::string_view value) { + if (value.size() <= kValueMaxPrintLength) return std::string(value); + return absl::StrCat(value.substr(0, kValueMaxPrintLength), kTrimIndicator); +} + +} // namespace + +std::string EncodeDiffRecordContainer(std::vector<DiffRecord> records) { + std::sort(records.begin(), records.end(), + [](const DiffRecord& a, const DiffRecord& b) { + return a.label < b.label; + }); + IRObject container; + auto& subs = container.MutableSubs(); + subs.reserve(2); + subs.emplace_back(kDiffRecordContainerVersion); + IRObject list; + auto& list_subs = list.MutableSubs(); + list_subs.reserve(records.size()); + for (DiffRecord& record : records) { + IRObject entry; + auto& entry_subs = entry.MutableSubs(); + entry_subs.reserve(2); + entry_subs.emplace_back(IRObject::Value(std::move(record.label))); + entry_subs.emplace_back(IRObject::Value(std::move(record.payload))); + list_subs.push_back(std::move(entry)); + } + subs.push_back(std::move(list)); + return SerializeIRObject(container, /*binary_format=*/true); +} + +std::optional<std::vector<DiffRecord>> DecodeDiffRecordContainer( + absl::string_view container) { + const std::optional<IRObject> obj = ParseIRObject(container); + if (!obj.has_value()) return std::nullopt; + const auto subs = obj->Subs(); + if (!subs.has_value() || subs->size() != 2) return std::nullopt; + const auto version = (*subs)[0].GetScalar<uint64_t>(); + if (!version.has_value() || *version != kDiffRecordContainerVersion) { + return std::nullopt; + } + const auto entries = (*subs)[1].Subs(); + if (!entries.has_value()) return std::nullopt; + std::vector<DiffRecord> records; + records.reserve(entries->size()); + for (const IRObject& entry : *entries) { + const auto entry_subs = entry.Subs(); + if (!entry_subs.has_value() || entry_subs->size() != 2) { + return std::nullopt; + } + const std::optional<absl::string_view> label = + (*entry_subs)[0].GetScalar<std::string>(); + const std::optional<absl::string_view> payload = + (*entry_subs)[1].GetScalar<std::string>(); + if (!label.has_value() || !payload.has_value()) return std::nullopt; + records.push_back({std::string(*label), std::string(*payload)}); + } + std::sort(records.begin(), records.end(), + [](const DiffRecord& a, const DiffRecord& b) { + return a.label < b.label; + }); + for (size_t i = 1; i < records.size(); ++i) { + if (records[i - 1].label == records[i].label) return std::nullopt; + } + return records; +} + +void Runtime::ResetDiffInputState() { + diff_input_begun_ = false; + diff_input_unparsable_ = false; + diff_actual_records_.clear(); + diff_expected_records_.reset(); + diff_undecodable_container_size_.reset(); + diff_mismatches_.clear(); + diff_failure_reported_ = false; +} + +void Runtime::EnableDiffMode(DiffMode mode) { + FUZZTEST_CHECK(mode != DiffMode::kNone) << "Invalid diff mode to enable."; + diff_spinlock_.Lock(); + diff_mode_ = mode; + ResetDiffInputState(); + diff_spinlock_.Unlock(); + diff_active_.store(true, std::memory_order_relaxed); +} + +void Runtime::DisableDiffMode() { + diff_active_.store(false, std::memory_order_relaxed); + re_enable_reporter_on_next_diff_input_.store(false, + std::memory_order_relaxed); + diff_failure_report_.store(DiffReportKind::kNone, std::memory_order_relaxed); + diff_spinlock_.Lock(); + diff_mode_ = DiffMode::kNone; + ResetDiffInputState(); + diff_spinlock_.Unlock(); +} + +DiffMode Runtime::diff_mode() const { + diff_spinlock_.Lock(); + const DiffMode mode = diff_mode_; + diff_spinlock_.Unlock(); + return mode; +} + +void Runtime::BeginDiffInput(std::optional<std::string> expected_container, + bool unparsable) { + // Reset the per-process failure state so that a previous finding does not + // leak into this input (the runner process survives findings). + ResetCrashType(); + SetExternalFailureDetected(false); + if (re_enable_reporter_on_next_diff_input_.exchange( + false, std::memory_order_relaxed)) { + reporter_enabled_.store(true, std::memory_order_relaxed); + } + std::optional<std::map<std::string, std::string>> expected_records; + std::optional<size_t> undecodable_container_size; + if (expected_container.has_value()) { + std::optional<std::vector<DiffRecord>> records = + DecodeDiffRecordContainer(*expected_container); + if (records.has_value()) { + expected_records.emplace(); + for (DiffRecord& record : *records) { + expected_records->emplace(std::move(record.label), + std::move(record.payload)); + } + } else { + undecodable_container_size = expected_container->size(); + } + } + diff_spinlock_.Lock(); + ResetDiffInputState(); + diff_input_begun_ = true; + diff_input_unparsable_ = unparsable; + if (diff_mode_ == DiffMode::kValidate) { + diff_expected_records_ = std::move(expected_records); + diff_undecodable_container_size_ = undecodable_container_size; + } + diff_spinlock_.Unlock(); +} + +bool Runtime::ShouldSkipDiffCall() const { + diff_spinlock_.Lock(); + const bool skip = + !diff_input_begun_ || diff_input_unparsable_ || diff_failure_reported_; + diff_spinlock_.Unlock(); + return skip; +} + +Runtime::DiffCallDisposition Runtime::BeginDiffCall(const std::string& label) { + DiffCallDisposition disposition; + diff_spinlock_.Lock(); + if (!diff_input_begun_ || diff_input_unparsable_ || diff_failure_reported_) { + diff_spinlock_.Unlock(); + return disposition; + } + if (!diff_actual_records_.emplace(label, "").second) { + disposition.kind = DiffCallDisposition::Kind::kDuplicateLabel; + diff_spinlock_.Unlock(); + return disposition; + } + if (diff_mode_ == DiffMode::kRecord) { + disposition.kind = DiffCallDisposition::Kind::kRecord; + diff_spinlock_.Unlock(); + return disposition; + } + if (!diff_expected_records_.has_value()) { + disposition.kind = DiffCallDisposition::Kind::kValidateNoBaseline; + diff_spinlock_.Unlock(); + return disposition; + } + disposition.kind = DiffCallDisposition::Kind::kValidateWithBaseline; + if (auto it = diff_expected_records_->find(label); + it != diff_expected_records_->end()) { + disposition.expected_payload = it->second; + } + diff_spinlock_.Unlock(); + return disposition; +} + +void Runtime::AppendDiffRecord(std::string label, std::string payload) { + diff_spinlock_.Lock(); + if (diff_input_begun_ && !diff_failure_reported_) { + diff_actual_records_[std::move(label)] = std::move(payload); + } + diff_spinlock_.Unlock(); +} + +void Runtime::AddDiffMismatch(std::string label, std::string reason, + std::string expected_text, + std::string actual_text) { + diff_spinlock_.Lock(); + if (diff_input_begun_ && !diff_failure_reported_) { + diff_mismatches_.push_back({std::move(label), std::move(reason), + std::move(expected_text), + std::move(actual_text)}); + } + diff_spinlock_.Unlock(); +} + +void Runtime::ReportDiffUsageError(absl::string_view message, + std::string crash_type) { + absl::FPrintF(GetStderr(), "%s%s\n", GetSeparator(), message); + ReportDiffFailure(std::move(crash_type), /*is_mismatch=*/false); +} + +void Runtime::ReportDiffFailure(std::string crash_type, bool is_mismatch) { + diff_spinlock_.Lock(); + diff_failure_reported_ = true; + diff_spinlock_.Unlock(); + SetCrashTypeIfUnset(std::move(crash_type)); + diff_failure_report_.store( + is_mismatch ? DiffReportKind::kMismatch : DiffReportKind::kError, + std::memory_order_relaxed); + PrintReportOnDefaultSink(); + diff_failure_report_.store(DiffReportKind::kNone, std::memory_order_relaxed); +} + +void Runtime::CheckDiffRecordsAtInputEnd() { + if (!diff_active()) return; + std::vector<DiffMismatch> mismatches; + diff_spinlock_.Lock(); + if (!diff_input_begun_ || diff_input_unparsable_ || diff_failure_reported_ || + diff_mode_ != DiffMode::kValidate) { + diff_spinlock_.Unlock(); + return; + } + mismatches = std::move(diff_mismatches_); + diff_mismatches_.clear(); + if (diff_expected_records_.has_value()) { + for (const auto& [label, payload] : *diff_expected_records_) { + if (diff_actual_records_.find(label) != diff_actual_records_.end()) { + continue; + } + mismatches.push_back( + {label, + absl::StrCat("baseline output \"", label, "\" was not produced"), + absl::StrCat("<recorded value: ", payload.size(), " bytes>"), + "<no output>"}); + } + } + const std::optional<size_t> undecodable_size = + diff_undecodable_container_size_; + diff_spinlock_.Unlock(); + if (undecodable_size.has_value()) { + mismatches.push_back( + {"<baseline container>", "cannot decode baseline container", + absl::StrCat("<undecodable: ", *undecodable_size, " bytes>"), + "<not compared>"}); + } + if (mismatches.empty()) return; + std::stable_sort(mismatches.begin(), mismatches.end(), + [](const DiffMismatch& a, const DiffMismatch& b) { + return a.label < b.label; + }); + std::string block = absl::StrFormat( + "%s=== RecordOrDiff MISMATCH\nTest: %s\nMismatched outputs: %d\n", + GetSeparator(), + current_test_ != nullptr ? current_test_->full_name() : "<unknown>", + mismatches.size()); + for (const DiffMismatch& mismatch : mismatches) { + absl::StrAppendFormat( + &block, + "--- RecordOrDiff label: %s\n" + "Reason: %s\n" + "Expected (baseline): %s\n" + "Actual (current): %s\n", + mismatch.label.empty() ? "<unlabeled>" : mismatch.label, + mismatch.reason, TrimDiffValue(mismatch.expected_text), + TrimDiffValue(mismatch.actual_text)); + } + absl::FPrintF(GetStderr(), "%s", block); + ReportDiffFailure("RecordOrDiff mismatch", /*is_mismatch=*/true); +} + +std::optional<RuntimeDiffResult> Runtime::TakeDiffResult() { + if (!diff_active()) return std::nullopt; + std::optional<RuntimeDiffResult> result; + diff_spinlock_.Lock(); + if (diff_input_begun_) { + if (diff_input_unparsable_) { + result = + RuntimeDiffResult{RuntimeDiffResult::Kind::kSkippedUnparsable, ""}; + } else if (diff_mode_ == DiffMode::kRecord) { + std::vector<DiffRecord> records; + records.reserve(diff_actual_records_.size()); + for (auto& [label, payload] : diff_actual_records_) { + records.push_back({label, std::move(payload)}); + } + result = RuntimeDiffResult{RuntimeDiffResult::Kind::kRecords, + EncodeDiffRecordContainer(std::move(records))}; + } else if (diff_mode_ == DiffMode::kValidate) { + result = RuntimeDiffResult{RuntimeDiffResult::Kind::kAck, ""}; + } + } + ResetDiffInputState(); + diff_spinlock_.Unlock(); + return result; +} + using corpus_type = GenericDomainCorpusType; FuzzTestFuzzerImpl::FuzzTestFuzzerImpl( @@ -1346,6 +1691,9 @@ std::max(stats_.max_stack_used, execution_coverage_->MaxStackUsed()); } + // Detects "fewer RecordOrDiff calls than recorded" while the current args are + // still set, so that the counterexample can be printed. + runtime_.CheckDiffRecordsAtInputEnd(); runtime_.OnTestIterationEnd(); runtime_.UnsetCurrentArgs(); return {new_coverage, run_time};
diff --git a/fuzztest/internal/runtime.h b/fuzztest/internal/runtime.h index 4eb7ed6..9901dd2 100644 --- a/fuzztest/internal/runtime.h +++ b/fuzztest/internal/runtime.h
@@ -23,6 +23,7 @@ #include <cstring> #include <deque> #include <iostream> +#include <map> #include <memory> #include <optional> #include <random> @@ -134,6 +135,45 @@ // on other platforms. Async-signal-safe. uintptr_t GetCurrentThreadIdForCrashHandling(); +// A single value recorded by `fuzztest::RecordOrDiff()`: the label (the key, +// unique within an input) and the serialized value. +struct DiffRecord { + std::string label; + std::string payload; + + friend bool operator==(const DiffRecord& a, const DiffRecord& b) { + return a.label == b.label && a.payload == b.payload; + } +}; + +// Encodes `records` as a record container, which is the content of a baseline +// file and the payload exchanged with the controller: `SerializeIRObject` +// (binary) of `[uint64 1, [[label, payload], ...]]`, sorted by label so that +// the encoding is deterministic. REQUIRES: labels are unique. +std::string EncodeDiffRecordContainer(std::vector<DiffRecord> records); + +// Decodes a record container produced by `EncodeDiffRecordContainer`. Returns +// the records sorted by label, or nullopt if `container` is malformed, has an +// unsupported version, or has duplicate labels. +std::optional<std::vector<DiffRecord>> DecodeDiffRecordContainer( + absl::string_view container); + +// The per-input result of the incremental differential fuzzing. +struct RuntimeDiffResult { + enum class Kind { + // Record mode: `container` holds the records of the input. + kRecords, + // Validate mode: the input was executed and compared (if it had a + // baseline). `container` is empty. + kAck, + // The input could not be parsed by the current domains; nothing was + // recorded or compared. `container` is empty. + kSkippedUnparsable, + }; + Kind kind; + std::string container; +}; + // This class encapsulates the runtime state that is global by necessity. // The state is accessed by calling `Runtime::instance()`, which handles the // necessary initialization steps. @@ -204,6 +244,8 @@ // REQUIRES: `SetCurrentTest()` has been called with non-null arguments. void EnableReporter(const RuntimeStats* stats, absl::Time (*clock_fn)()) { reporter_enabled_ = true; + re_enable_reporter_on_next_diff_input_.store(false, + std::memory_order_relaxed); stats_ = stats; clock_fn_ = clock_fn; // In case we have not installed them yet, do so now. @@ -211,7 +253,11 @@ InstallUnexpectedExitHandler(); ResetCrashType(); } - void DisableReporter() { reporter_enabled_ = false; } + void DisableReporter() { + reporter_enabled_ = false; + re_enable_reporter_on_next_diff_input_.store(false, + std::memory_order_relaxed); + } bool reporter_enabled() const { return reporter_enabled_; } struct Args { @@ -300,6 +346,82 @@ // and aborts the process. Otherwise, does nothing. void HandleUnexpectedExit(); + // Incremental differential fuzzing (`fuzztest::RecordOrDiff`). + // + // All state is in memory; the runtime never reads or writes baseline files. + // The diff mode is enabled only by the Centipede runner callbacks during + // corpus replay. When it is not enabled, `RecordOrDiff` is a no-op. + + // Enables the diff mode `mode` (which must not be `kNone`). + void EnableDiffMode(DiffMode mode); + // Disables the diff mode and clears the per-input diff state. + void DisableDiffMode(); + bool diff_active() const { + return diff_active_.load(std::memory_order_relaxed); + } + DiffMode diff_mode() const; + + // Starts the diff state of a new input. Must be called before running every + // input while the diff mode is active. Resets the per-process failure state + // (crash type and external failure flag) so that each input is reported on + // its own. `expected_container` is the baseline record container sent by + // the controller (validate mode), or nullopt if there is no baseline. + // `unparsable` is true if the input could not be parsed by the current + // domains, in which case `RecordOrDiff` is a no-op for the input. + void BeginDiffInput(std::optional<std::string> expected_container, + bool unparsable); + + // The action `RecordOrDiff` should take for a single call site. + struct DiffCallDisposition { + enum class Kind { + // Nothing to do: input has not begun, is unparsable, or already reported + // a finding. + kSkip, + // `label` was already claimed during this input execution. + kDuplicateLabel, + // Record mode: serialize and pass to `AppendDiffRecord`. + kRecord, + // Validate mode without a decodable baseline for this input: no-op. + kValidateNoBaseline, + // Validate mode with a decodable baseline: compare against + // `expected_payload` (nullopt if `label` is not in the baseline). + kValidateWithBaseline, + }; + Kind kind = Kind::kSkip; + std::optional<std::string> expected_payload; + }; + + // Call-site helpers used by `fuzztest::RecordOrDiff`. + // True iff the current input has not begun, is unparsable, or already + // reported a RecordOrDiff finding. + bool ShouldSkipDiffCall() const; + // Atomically checks per-input preconditions, claims `label`, and returns the + // disposition (and expected baseline payload, if applicable) for a single + // `RecordOrDiff` call. + DiffCallDisposition BeginDiffCall(const std::string& label); + // Record mode: stores the payload of `label` for the current input. + void AppendDiffRecord(std::string label, std::string payload); + // Validate mode: collects a mismatch of `label`, reported at the end of the + // input together with all other mismatches of the input. + void AddDiffMismatch(std::string label, std::string reason, + std::string expected_text, std::string actual_text); + // Reports a RecordOrDiff usage error: prints `message` to stderr and reports + // the finding `crash_type`. + void ReportDiffUsageError(absl::string_view message, std::string crash_type); + // Reports a RecordOrDiff finding of `crash_type` through the crash report. + // `is_mismatch` selects the first line of the reproduction hint. + void ReportDiffFailure(std::string crash_type, bool is_mismatch); + + // Validate mode, at the end of an input: collects the baseline labels that + // were not produced (and an undecodable container), and reports all + // collected mismatches of the input as one finding `RecordOrDiff mismatch`. + void CheckDiffRecordsAtInputEnd(); + + // Returns the diff result of the current input and clears the per-input + // state. Returns nullopt if the diff mode is not active or `BeginDiffInput` + // was not called for the current input (e.g. the input was not executed). + std::optional<RuntimeDiffResult> TakeDiffResult(); + class Watchdog; // Returns a watchdog that periodically checks the time and memory limits in a // separate thread. The watchdog handles the logic of starting and joining the @@ -316,6 +438,8 @@ // Returns empty string if no reproducer file is dumped. std::string DumpReproducer() const; + void ResetDiffInputState() ABSL_EXCLUSIVE_LOCKS_REQUIRED(diff_spinlock_); + // Some failures are not necessarily detected by signal handlers or by // sanitizers. For example, we could have test framework failures like // `EXPECT_EQ` failures from GoogleTest. @@ -466,6 +590,39 @@ CrashMetadataBuffer<256> crash_type_; // In case of a crash, contains the crash signature. CrashMetadataBuffer<1024> crash_signature_; + + // Incremental differential fuzzing state. + enum class DiffReportKind { kNone, kMismatch, kError }; + struct DiffMismatch { + std::string label; + std::string reason; + std::string expected_text; + std::string actual_text; + }; + std::atomic<bool> diff_active_ = false; + // Set when `PrintReport` consumed `reporter_enabled_` while diff mode was + // active, so `BeginDiffInput` can re-arm it on the next input. + std::atomic<bool> re_enable_reporter_on_next_diff_input_ = false; + // Set while printing the report of a RecordOrDiff finding. + std::atomic<DiffReportKind> diff_failure_report_{DiffReportKind::kNone}; + mutable Spinlock diff_spinlock_; + DiffMode diff_mode_ ABSL_GUARDED_BY(diff_spinlock_) = DiffMode::kNone; + // True between `BeginDiffInput` and `TakeDiffResult`. + bool diff_input_begun_ ABSL_GUARDED_BY(diff_spinlock_) = false; + bool diff_input_unparsable_ ABSL_GUARDED_BY(diff_spinlock_) = false; + // Labels produced by the current input, with the recorded payloads (the + // payloads are only kept in record mode). + std::map<std::string, std::string> diff_actual_records_ + ABSL_GUARDED_BY(diff_spinlock_); + // Expected label -> payload of the current input, if a decodable baseline + // was received. + std::optional<std::map<std::string, std::string>> diff_expected_records_ + ABSL_GUARDED_BY(diff_spinlock_); + // Size of the received baseline container if it could not be decoded. + std::optional<size_t> diff_undecodable_container_size_ + ABSL_GUARDED_BY(diff_spinlock_); + std::vector<DiffMismatch> diff_mismatches_ ABSL_GUARDED_BY(diff_spinlock_); + bool diff_failure_reported_ ABSL_GUARDED_BY(diff_spinlock_) = false; }; struct ReproducerOutputLocation {
diff --git a/fuzztest/internal/runtime_test.cc b/fuzztest/internal/runtime_test.cc index 04e84ba..e23ce8b 100644 --- a/fuzztest/internal/runtime_test.cc +++ b/fuzztest/internal/runtime_test.cc
@@ -41,6 +41,7 @@ #include "absl/types/span.h" #include "./fuzztest/domain_core.h" #include "./fuzztest/internal/configuration.h" +#include "./fuzztest/internal/flag_name.h" #include "./fuzztest/internal/test_protobuf.pb.h" extern "C" void __sanitizer_report_error_summary(const char* error_summary); @@ -448,6 +449,130 @@ runtime.ResetCrashType(); } +TEST(OnFailureTest, RecordOrDiffReproductionOutput) { + auto& runtime = Runtime::instance(); + FuzzTest test({"SUITE_NAME", "TEST_NAME", "FILE", 123}, nullptr); + Configuration configuration; + configuration.corpus_database = "/path/to/corpus_db"; + configuration.workdir_root = "/path/to/workdir"; + std::tuple args(17, std::string("ABC")); + const RuntimeStats stats = {absl::FromUnixNanos(0), 1, 2, 3, 4, 5}; + UntypedDomain domain = TupleOf(Arbitrary<int>(), Arbitrary<std::string>()); + GenericDomainCorpusType generic_args( + std::in_place_type<std::tuple<int, std::string>>, args); + Runtime::Args debug_args{generic_args, domain}; + + runtime.EnableReporter(&stats, [] { return absl::FromUnixNanos(1979); }); + runtime.SetRunMode(RunMode::kFuzz); + runtime.SetCurrentTest(&test, &configuration); + runtime.SetCurrentArgs(&debug_args); + + // Validate-mode mismatch report. + runtime.EnableDiffMode(DiffMode::kValidate); + runtime.BeginDiffInput(/*expected_container=*/std::nullopt, + /*unparsable=*/false); + ::testing::internal::CaptureStderr(); + runtime.ReportDiffFailure("RecordOrDiff mismatch", /*is_mismatch=*/true); + const std::string validate_report = ::testing::internal::GetCapturedStderr(); + EXPECT_TRUE( + absl::StrContains(validate_report, "=== RecordOrDiff reproduction")) + << validate_report; + EXPECT_TRUE(absl::StrContains( + validate_report, + absl::StrCat("This finding is a RecordOrDiff mismatch. It reproduces " + "only with\n--", + FUZZTEST_FLAG_PREFIX, "diff against the same baseline."))) + << validate_report; + EXPECT_TRUE(absl::StrContains( + validate_report, + absl::StrCat("Re-run with: --", FUZZTEST_FLAG_PREFIX, + "diff=SUITE_NAME.TEST_NAME --", FUZZTEST_FLAG_PREFIX, + "corpus_database=/path/to/corpus_db --", + FUZZTEST_FLAG_PREFIX, "workdir_root=/path/to/workdir\n"))) + << validate_report; + EXPECT_FALSE(absl::StrContains(validate_report, "=== Regression test draft")) + << validate_report; + + // Record-mode usage error report (re-enable reporter since DisableDiffMode + // clears per-session diff state). + runtime.DisableDiffMode(); + runtime.EnableReporter(&stats, [] { return absl::FromUnixNanos(1979); }); + runtime.EnableDiffMode(DiffMode::kRecord); + runtime.BeginDiffInput(/*expected_container=*/std::nullopt, + /*unparsable=*/false); + ::testing::internal::CaptureStderr(); + runtime.ReportDiffFailure("RecordOrDiff usage error", /*is_mismatch=*/false); + const std::string record_report = ::testing::internal::GetCapturedStderr(); + EXPECT_TRUE(absl::StrContains( + record_report, + absl::StrCat("This finding is a RecordOrDiff error. It reproduces only " + "with\n--", + FUZZTEST_FLAG_PREFIX, "record."))) + << record_report; + EXPECT_TRUE(absl::StrContains( + record_report, + absl::StrCat("Re-run with: --", FUZZTEST_FLAG_PREFIX, + "record=SUITE_NAME.TEST_NAME --", FUZZTEST_FLAG_PREFIX, + "corpus_database=/path/to/corpus_db --", + FUZZTEST_FLAG_PREFIX, "workdir_root=/path/to/workdir\n"))) + << record_report; + + runtime.DisableDiffMode(); + runtime.DisableReporter(); + runtime.ResetCrashType(); + runtime.SetExternalFailureDetected(false); + runtime.UnsetCurrentArgs(); + runtime.SetCurrentTest(nullptr, nullptr); + runtime.SetRunMode(RunMode::kUnitTest); +} + +TEST(OnFailureTest, BeginDiffInputReEnablesReporterAcrossInputs) { + auto& runtime = Runtime::instance(); + FuzzTest test({"SUITE_NAME", "TEST_NAME", "FILE", 123}, nullptr); + Configuration configuration; + std::tuple args(17, std::string("ABC")); + const RuntimeStats stats = {absl::FromUnixNanos(0), 1, 2, 3, 4, 5}; + UntypedDomain domain = TupleOf(Arbitrary<int>(), Arbitrary<std::string>()); + GenericDomainCorpusType generic_args( + std::in_place_type<std::tuple<int, std::string>>, args); + Runtime::Args debug_args{generic_args, domain}; + + runtime.EnableReporter(&stats, [] { return absl::FromUnixNanos(1979); }); + runtime.SetCurrentTest(&test, &configuration); + runtime.SetCurrentArgs(&debug_args); + runtime.EnableDiffMode(DiffMode::kValidate); + + // Input 1 fails via a non-diff PrintReport (e.g., GTest assertion failure), + // which consumes reporter_enabled(). + runtime.BeginDiffInput(/*expected_container=*/std::nullopt, + /*unparsable=*/false); + ASSERT_TRUE(runtime.reporter_enabled()); + std::string report1; + runtime.PrintReport(&report1); + EXPECT_FALSE(report1.empty()); + EXPECT_FALSE(runtime.reporter_enabled()); + + // Input 2 re-arms the reporter so subsequent findings are still reported. + runtime.BeginDiffInput(/*expected_container=*/std::nullopt, + /*unparsable=*/false); + EXPECT_TRUE(runtime.reporter_enabled()); + std::string report2; + runtime.PrintReport(&report2); + EXPECT_FALSE(report2.empty()); + + // DisableDiffMode clears any pending re-arming. + runtime.DisableDiffMode(); + runtime.BeginDiffInput(/*expected_container=*/std::nullopt, + /*unparsable=*/false); + EXPECT_FALSE(runtime.reporter_enabled()); + + runtime.DisableReporter(); + runtime.ResetCrashType(); + runtime.SetExternalFailureDetected(false); + runtime.UnsetCurrentArgs(); + runtime.SetCurrentTest(nullptr, nullptr); +} + TEST(RegressionTestNameForCrashingInputTest, ReturnsRegressionTestNameForValidInputFilename) { const absl::StatusOr<std::string> regression_test_name =
diff --git a/fuzztest/record_or_diff.cc b/fuzztest/record_or_diff.cc new file mode 100644 index 0000000..905e16b --- /dev/null +++ b/fuzztest/record_or_diff.cc
@@ -0,0 +1,62 @@ +// 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. + +#include "./fuzztest/record_or_diff.h" + +#include <string> + +#include "absl/strings/escaping.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" +#include "./fuzztest/internal/runtime.h" + +namespace fuzztest::internal { + +void ReportRecordOrDiffDuplicateLabel(absl::string_view label) { + Runtime::instance().ReportDiffUsageError( + absl::StrCat("RecordOrDiff label \"", label, + "\" used twice in one input; give each call a distinct " + "label"), + "RecordOrDiff usage error: duplicate label"); +} + +void ReportRecordOrDiffMissingComparator(absl::string_view type_name, + bool is_proto) { + Runtime::instance().ReportDiffUsageError( + absl::StrCat( + "RecordOrDiff: ", type_name, + " has no operator==; pass RecordOrDiffOptions::comparator", + is_proto ? " (e.g. google::protobuf::util::MessageDifferencer::Equals)" : ""), + "RecordOrDiff usage error: missing comparator"); +} + +void ReportRecordOrDiffSerializationFailure(absl::string_view label) { + Runtime::instance().ReportDiffUsageError( + absl::StrCat("RecordOrDiff: cannot serialize the value for label \"", + label, "\"; provide a fuzztest::DiffCodec<T>."), + "RecordOrDiff serialization failure"); +} + +void ReportRecordOrDiffInvalidCodec(absl::string_view label) { + Runtime::instance().ReportDiffUsageError( + absl::StrCat("RecordOrDiff: the fuzztest::DiffCodec<T> for label \"", + label, "\" must have both a serializer and a deserializer"), + "RecordOrDiff usage error: invalid codec"); +} + +std::string EscapeRecordOrDiffBytes(absl::string_view bytes) { + return absl::StrCat("\"", absl::CEscape(bytes), "\""); +} + +} // namespace fuzztest::internal
diff --git a/fuzztest/record_or_diff.h b/fuzztest/record_or_diff.h new file mode 100644 index 0000000..d4901d2 --- /dev/null +++ b/fuzztest/record_or_diff.h
@@ -0,0 +1,305 @@ +// 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. + +// Incremental differential fuzzing: `fuzztest::RecordOrDiff()`. +// +// Call `RecordOrDiff(value, label)` in a FUZZ_TEST body to record observable +// outputs of the code under test. Replaying the corpus with +// +// --fuzztest_record=<test|*> --fuzztest_corpus_database=<db> +// --fuzztest_workdir_root=<abs dir> +// +// stores a baseline under <workdir_root>/baseline/. Replaying a changed version +// with `--fuzztest_diff=<test|*>` (and optional `--fuzztest_for=<duration>`) +// compares every recorded value with the baseline and fails with a diff and the +// input counterexample if any differs. +// +// Labels are the keys: they must be unique within one input execution (a +// duplicate label is a test failure), and calls are matched by label, so the +// call order does not matter. An unlabeled call uses the label "". +// +// Outside `--fuzztest_record` / `--fuzztest_diff` (normal fuzzing, unit-test +// runs, plain replay), `RecordOrDiff` is a no-op: it returns after one relaxed +// atomic load. + +#ifndef FUZZTEST_FUZZTEST_RECORD_OR_DIFF_H_ +#define FUZZTEST_FUZZTEST_RECORD_OR_DIFF_H_ + +#include <cmath> +#include <functional> +#include <optional> +#include <string> +#include <string_view> +#include <type_traits> +#include <utility> + +#include "absl/base/optimization.h" +#include "absl/functional/function_ref.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" +#include "./fuzztest/domain.h" +#include "./fuzztest/internal/meta.h" +#include "./fuzztest/internal/printer.h" +#include "./fuzztest/internal/runtime.h" +#include "./fuzztest/internal/serialization.h" +#include "./fuzztest/internal/type_support.h" + +namespace fuzztest { + +// Options common to all overloads. +template <typename T> +struct RecordOrDiffOptions { + // The key of the recorded value. Must be unique within one input execution + // (a duplicate label is reported as a test failure). Unlabeled calls use "". + // Build unique labels in loops, e.g. absl::StrCat("item/", i). + std::string label = ""; + // Optional equality. Returns true iff `expected` and `actual` are equivalent. + // If unset, operator== is used (NaN==NaN for top-level floating point). + // REQUIRED when T has no operator== (e.g. protos); otherwise the first call + // in diff mode reports an error. + std::function<bool(const T& expected, const T& actual)> comparator = nullptr; + // Optional printer used in mismatch reports. If unset, the Arbitrary<T>() + // domain printer (or, for the codec overload, an escaped byte dump) is used. + std::function<std::string(const T&)> printer = nullptr; +}; + +// Serialization adapter for types without Arbitrary<T>() support or for +// cross-language byte compatibility. Both closures are required. +template <typename T> +struct DiffCodec { + std::function<std::string(const T&)> serializer; + std::function<std::optional<T>(std::string_view)> deserializer; +}; + +namespace internal { + +// Non-template helpers, defined in record_or_diff.cc. None of them does any +// file I/O; the baseline is handled by the Centipede controller. + +// Reports the duplicate `label` usage error. +void ReportRecordOrDiffDuplicateLabel(absl::string_view label); +// Reports that `type_name` has no operator== and no comparator was given. +void ReportRecordOrDiffMissingComparator(absl::string_view type_name, + bool is_proto); +// Reports that the value of `label` could not be serialized. +void ReportRecordOrDiffSerializationFailure(absl::string_view label); +// Reports a DiffCodec without serializer or deserializer. +void ReportRecordOrDiffInvalidCodec(absl::string_view label); +// Returns `bytes` C-escaped, for printing serialized values. +std::string EscapeRecordOrDiffBytes(absl::string_view bytes); + +template <typename T, typename = void> +struct IsDiffEqualityComparable : std::false_type {}; +template <typename T> +struct IsDiffEqualityComparable< + T, std::void_t<decltype(static_cast<bool>(std::declval<const T&>() == + std::declval<const T&>()))>> + : std::true_type {}; + +template <typename T> +bool DefaultDiffEquals(const T& expected, const T& actual) { + if constexpr (std::is_floating_point_v<T>) { + return expected == actual || (std::isnan(expected) && std::isnan(actual)); + } else if constexpr (IsDiffEqualityComparable<T>::value) { + return expected == actual; + } else { + return false; // Unreachable: a comparator is required. + } +} + +// Default serialization: top-level enums by underlying value, everything else +// with the Arbitrary<T>() domain. +template <typename T> +std::optional<std::string> DefaultDiffSerialize(const T& value) { + if constexpr (std::is_enum_v<T>) { + return SerializeIRObject(IRObject(value)); + } else { + auto domain = Arbitrary<T>(); + auto corpus = domain.FromValue(value); + if (!corpus.has_value()) return std::nullopt; + return SerializeIRObject(domain.SerializeCorpus(*corpus)); + } +} + +// Decodes `bytes` and invokes `consume(expected)` while keeping the backing +// `corpus_type` alive on the stack. This avoids dangling views when `T` borrows +// from its domain corpus (e.g. `std::string_view` or `absl::string_view`). +template <typename T> +bool DefaultDiffWithDeserialized(absl::string_view bytes, + absl::FunctionRef<void(const T&)> consume) { + const std::optional<IRObject> obj = ParseIRObject(bytes); + if (!obj.has_value()) return false; + if constexpr (std::is_enum_v<T>) { + const std::optional<T> expected = obj->GetScalar<T>(); + if (!expected.has_value()) return false; + consume(*expected); + return true; + } else { + auto domain = Arbitrary<T>(); + const auto corpus = domain.ParseCorpus(*obj); + if (!corpus.has_value() || !domain.ValidateCorpusValue(*corpus).ok()) { + return false; + } + const T expected = domain.GetValue(*corpus); + consume(expected); + return true; + } +} + +template <typename T> +std::string DefaultDiffPrint(const T& value) { + if constexpr (std::is_enum_v<T>) { + return absl::StrCat(GetTypeName<T>(), "(", + +static_cast<std::underlying_type_t<T>>(value), ")"); + } else { + auto domain = Arbitrary<T>(); + auto corpus = domain.FromValue(value); + if (!corpus.has_value()) return "<unprintable value>"; + std::string out; + domain_implementor::PrintValue( + domain, *corpus, &out, domain_implementor::PrintMode::kHumanReadable); + return out; + } +} + +// The shared implementation of the overloads. REQUIRES: diff mode is active. +template <typename T> +void RecordOrDiffImpl( + const T& value, const RecordOrDiffOptions<T>& options, + absl::FunctionRef<std::optional<std::string>(const T&)> serialize, + absl::FunctionRef<bool(absl::string_view, + absl::FunctionRef<void(const T&)>)> + with_deserialized, + absl::FunctionRef<std::string(const T&)> default_print) { + Runtime& runtime = Runtime::instance(); + const std::string& label = options.label; + const Runtime::DiffCallDisposition disposition = runtime.BeginDiffCall(label); + if (disposition.kind == Runtime::DiffCallDisposition::Kind::kSkip) { + return; + } + if (disposition.kind == Runtime::DiffCallDisposition::Kind::kDuplicateLabel) { + ReportRecordOrDiffDuplicateLabel(label); + return; + } + if constexpr (!IsDiffEqualityComparable<T>::value) { + if (!options.comparator) { + ReportRecordOrDiffMissingComparator(GetTypeName<T>(), + is_protocol_buffer_v<T>); + return; + } + } + const auto print = [&](const T& v) { + return options.printer ? options.printer(v) : default_print(v); + }; + if (disposition.kind == Runtime::DiffCallDisposition::Kind::kRecord) { + std::optional<std::string> payload = serialize(value); + if (!payload.has_value()) { + ReportRecordOrDiffSerializationFailure(label); + return; + } + runtime.AppendDiffRecord(label, *std::move(payload)); + return; + } + if (disposition.kind == + Runtime::DiffCallDisposition::Kind::kValidateNoBaseline) { + return; + } + if (!disposition.expected_payload.has_value()) { + runtime.AddDiffMismatch( + label, absl::StrCat("new output \"", label, "\" not in baseline"), + "<no output>", print(value)); + return; + } + const bool decoded = + with_deserialized(*disposition.expected_payload, [&](const T& expected) { + const bool equal = options.comparator + ? options.comparator(expected, value) + : DefaultDiffEquals(expected, value); + if (!equal) { + runtime.AddDiffMismatch(label, "value differs", print(expected), + print(value)); + } + }); + if (!decoded) { + runtime.AddDiffMismatch( + label, "cannot decode baseline value", + absl::StrCat("<undecodable: ", disposition.expected_payload->size(), + " bytes>"), + print(value)); + } +} + +} // namespace internal + +// Records `value` (record mode) or compares it with the baseline (validate +// mode), keyed by `options.label`. Serializes with Arbitrary<T>() (top-level +// enums by underlying value). +// +// Note: omit the second argument instead of passing `{}`; `RecordOrDiff(v, {})` +// is ambiguous between the overloads. Pass `RecordOrDiff(v, "x")`, construct +// `RecordOrDiffOptions<T>`, or (in C++20+) use `RecordOrDiff(v, {.label = +// "x"})`. +template <typename T> +void RecordOrDiff(const T& value, const RecordOrDiffOptions<T>& options = {}) { + if (ABSL_PREDICT_TRUE(!internal::Runtime::instance().diff_active())) return; + internal::RecordOrDiffImpl<T>( + value, options, + [](const T& v) { return internal::DefaultDiffSerialize<T>(v); }, + [](absl::string_view bytes, absl::FunctionRef<void(const T&)> consume) { + return internal::DefaultDiffWithDeserialized<T>(bytes, consume); + }, + [](const T& v) { return internal::DefaultDiffPrint<T>(v); }); +} + +// Convenience: label only. +template <typename T> +void RecordOrDiff(const T& value, absl::string_view label) { + if (ABSL_PREDICT_TRUE(!internal::Runtime::instance().diff_active())) return; + RecordOrDiffOptions<T> options; + options.label = std::string(label); + RecordOrDiff(value, options); +} + +// Custom codec: never instantiates Arbitrary<T>(). +template <typename T> +void RecordOrDiff(const T& value, const DiffCodec<T>& codec, + const RecordOrDiffOptions<T>& options = {}) { + if (ABSL_PREDICT_TRUE(!internal::Runtime::instance().diff_active())) return; + if (!codec.serializer || !codec.deserializer) { + if (!internal::Runtime::instance().ShouldSkipDiffCall()) { + internal::ReportRecordOrDiffInvalidCodec(options.label); + } + return; + } + internal::RecordOrDiffImpl<T>( + value, options, + [&codec](const T& v) -> std::optional<std::string> { + return codec.serializer(v); + }, + [&codec](absl::string_view bytes, + absl::FunctionRef<void(const T&)> consume) { + const std::optional<T> expected = + codec.deserializer(std::string_view(bytes.data(), bytes.size())); + if (!expected.has_value()) return false; + consume(*expected); + return true; + }, + [&codec](const T& v) { + return internal::EscapeRecordOrDiffBytes(codec.serializer(v)); + }); +} + +} // namespace fuzztest + +#endif // FUZZTEST_FUZZTEST_RECORD_OR_DIFF_H_
diff --git a/fuzztest/record_or_diff_test.cc b/fuzztest/record_or_diff_test.cc new file mode 100644 index 0000000..0716dec --- /dev/null +++ b/fuzztest/record_or_diff_test.cc
@@ -0,0 +1,763 @@ +// 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. + +#include "./fuzztest/record_or_diff.h" + +#include <cstddef> +#include <cstdint> +#include <limits> +#include <optional> +#include <string> +#include <string_view> +#include <tuple> +#include <utility> + +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "absl/functional/function_ref.h" +#include "absl/strings/numbers.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" +#include "./fuzztest/internal/configuration.h" +#include "./fuzztest/internal/meta.h" +#include "./fuzztest/internal/runtime.h" +#include "./fuzztest/internal/serialization.h" + +namespace fuzztest { +namespace { + +using ::fuzztest::internal::DecodeDiffRecordContainer; +using ::fuzztest::internal::DiffMode; +using ::fuzztest::internal::DiffRecord; +using ::fuzztest::internal::EncodeDiffRecordContainer; +using ::fuzztest::internal::Runtime; +using ::fuzztest::internal::RuntimeDiffResult; +using ::testing::ElementsAre; +using ::testing::HasSubstr; +using ::testing::Not; +using ::testing::Optional; + +struct Quote { + int64_t total_cents; + int discount_pct; + friend bool operator==(const Quote& a, const Quote& b) { + return a.total_cents == b.total_cents && a.discount_pct == b.discount_pct; + } +}; + +// An aggregate without operator==. +struct NoEq { + int x; +}; + +// Minimal fake satisfying `internal::is_protocol_buffer_v<FakeProto>` without +// pulling in full protobuf runtime dependencies. +struct FakeProto { + struct Field {}; + struct Descriptor { + const Field* field(int) const { return nullptr; } + }; + struct Reflection { + bool HasField(const FakeProto&, const Field*) const { return false; } + }; + using Message = FakeProto; + const Descriptor* GetDescriptor() const { return nullptr; } + const Reflection* GetReflection() const { return nullptr; } +}; + +// A non-aggregate class that `Arbitrary<T>()` cannot handle. +class Opaque { + public: + explicit Opaque(int v) : v_(v) {} + int v() const { return v_; } + friend bool operator==(const Opaque& a, const Opaque& b) { + return a.v_ == b.v_; + } + + private: + int v_; +}; + +enum class Color : int16_t { kRed = 7, kBlue = -3 }; + +DiffCodec<Opaque> OpaqueCodec() { + DiffCodec<Opaque> codec; + codec.serializer = [](const Opaque& o) { return absl::StrCat("v=", o.v()); }; + codec.deserializer = [](std::string_view s) -> std::optional<Opaque> { + int v; + if (s.size() < 2 || s.substr(0, 2) != "v=" || + !absl::SimpleAtoi(s.substr(2), &v)) { + return std::nullopt; + } + return Opaque(v); + }; + return codec; +} + +template <typename T> +std::optional<T> RoundTripDefaultDeserialize(absl::string_view bytes) { + std::optional<T> decoded; + if (!internal::DefaultDiffWithDeserialized<T>( + bytes, [&](const T& v) { decoded = v; })) { + return std::nullopt; + } + return decoded; +} + +class RecordOrDiffTest : public ::testing::Test { + protected: + struct DiffRun { + RuntimeDiffResult::Kind kind = RuntimeDiffResult::Kind::kAck; + std::string container; + std::optional<std::string> crash_type; + std::string stderr_output; + }; + + void TearDown() override { + runtime().DisableDiffMode(); + runtime().ResetCrashType(); + runtime().SetExternalFailureDetected(false); + } + + static Runtime& runtime() { return Runtime::instance(); } + + DiffRun RunDiffInput(DiffMode mode, + std::optional<std::string> expected_container, + absl::FunctionRef<void()> body, bool unparsable) { + DiffRun run; + runtime().EnableDiffMode(mode); + runtime().BeginDiffInput(std::move(expected_container), unparsable); + ::testing::internal::CaptureStderr(); + body(); + runtime().CheckDiffRecordsAtInputEnd(); + run.stderr_output = ::testing::internal::GetCapturedStderr(); + run.crash_type = runtime().crash_type(); + std::optional<RuntimeDiffResult> result = runtime().TakeDiffResult(); + runtime().DisableDiffMode(); + runtime().ResetCrashType(); + runtime().SetExternalFailureDetected(false); + EXPECT_TRUE(result.has_value()); + if (result.has_value()) { + run.kind = result->kind; + run.container = std::move(result->container); + } + return run; + } + + // Runs `body` as one input in record mode and returns the run outcome. + DiffRun RecordOutcome(absl::FunctionRef<void()> body, + bool unparsable = false) { + return RunDiffInput(DiffMode::kRecord, std::nullopt, body, unparsable); + } + + std::string Record(absl::FunctionRef<void()> body, bool unparsable = false) { + DiffRun run = RecordOutcome(body, unparsable); + EXPECT_EQ(run.crash_type, std::nullopt); + return run.container; + } + + // Runs `body` as one input in validate mode against `container` and returns + // the run outcome. + DiffRun ValidateOutcome(std::optional<std::string> container, + absl::FunctionRef<void()> body, + bool unparsable = false) { + return RunDiffInput(DiffMode::kValidate, std::move(container), body, + unparsable); + } + + static int CountOccurrences(std::string_view haystack, + std::string_view needle) { + int count = 0; + for (size_t pos = haystack.find(needle); pos != haystack.npos; + pos = haystack.find(needle, pos + needle.size())) { + ++count; + } + return count; + } +}; + +TEST(DiffRecordContainerTest, RoundTripsSortedAndDeterministic) { + const std::string a = EncodeDiffRecordContainer( + {{"b", "2"}, {"a", std::string("\0x", 2)}, {"", ""}}); + const std::string b = EncodeDiffRecordContainer( + {{"", ""}, {"a", std::string("\0x", 2)}, {"b", "2"}}); + EXPECT_EQ(a, b); + EXPECT_THAT(DecodeDiffRecordContainer(a), + Optional(ElementsAre(DiffRecord{"", ""}, + DiffRecord{"a", std::string("\0x", 2)}, + DiffRecord{"b", "2"}))); +} + +TEST(DiffRecordContainerTest, EmptyContainerIsValid) { + EXPECT_THAT(DecodeDiffRecordContainer(EncodeDiffRecordContainer({})), + Optional(ElementsAre())); +} + +TEST(DiffRecordContainerTest, RejectsMalformedContainers) { + EXPECT_EQ(DecodeDiffRecordContainer("garbage"), std::nullopt); + EXPECT_EQ(DecodeDiffRecordContainer(""), std::nullopt); + // Duplicate labels. + internal::IRObject obj; + auto& subs = obj.MutableSubs(); + subs.emplace_back(uint64_t{1}); + internal::IRObject list; + for (int i = 0; i < 2; ++i) { + internal::IRObject entry; + entry.MutableSubs().emplace_back(internal::IRObject::Value("x")); + entry.MutableSubs().emplace_back(internal::IRObject::Value("p")); + list.MutableSubs().push_back(entry); + } + subs.push_back(list); + EXPECT_EQ(DecodeDiffRecordContainer(internal::SerializeIRObject(obj)), + std::nullopt); + // Unsupported version. + subs[0] = internal::IRObject(uint64_t{2}); + subs[1] = internal::IRObject(); + EXPECT_EQ(DecodeDiffRecordContainer(internal::SerializeIRObject(obj)), + std::nullopt); + // Non-string (monostate) label/payload. + subs[0] = internal::IRObject(uint64_t{1}); + internal::IRObject empty_entry_list; + internal::IRObject empty_entry; + empty_entry.MutableSubs().resize(2); + empty_entry_list.MutableSubs().push_back(std::move(empty_entry)); + subs[1] = std::move(empty_entry_list); + EXPECT_EQ(DecodeDiffRecordContainer(internal::SerializeIRObject(obj)), + std::nullopt); +} + +TEST_F(RecordOrDiffTest, InactiveIsNoOp) { + ASSERT_FALSE(runtime().diff_active()); + RecordOrDiff(42, "x"); + RecordOrDiff(42, "x"); // A duplicate label is not detected when inactive. + EXPECT_EQ(runtime().crash_type(), std::nullopt); + EXPECT_EQ(runtime().TakeDiffResult(), std::nullopt); +} + +TEST_F(RecordOrDiffTest, TakeDiffResultIsNulloptWithoutBeginDiffInput) { + runtime().EnableDiffMode(DiffMode::kRecord); + EXPECT_EQ(runtime().TakeDiffResult(), std::nullopt); + runtime().BeginDiffInput(std::nullopt, /*unparsable=*/false); + EXPECT_NE(runtime().TakeDiffResult(), std::nullopt); + // Consumed: a second take (e.g. for an input that was not executed) yields + // nothing. + EXPECT_EQ(runtime().TakeDiffResult(), std::nullopt); +} + +TEST_F(RecordOrDiffTest, CallsBeforeBeginDiffInputAreIgnoredWithoutPoisoning) { + runtime().EnableDiffMode(DiffMode::kRecord); + EXPECT_TRUE(runtime().ShouldSkipDiffCall()); + RecordOrDiff(10, "setup"); + RecordOrDiff(10, "setup"); // Duplicate before BeginDiffInput is ignored. + DiffCodec<Opaque> bad_codec; + RecordOrDiffOptions<Opaque> bad_options; + bad_options.label = "setup_codec"; + RecordOrDiff(Opaque(1), bad_codec, bad_options); + EXPECT_EQ(runtime().crash_type(), std::nullopt); + + // Subsequent input execution can still claim "setup" cleanly. + runtime().BeginDiffInput(std::nullopt, /*unparsable=*/false); + RecordOrDiff(99, "setup"); + runtime().CheckDiffRecordsAtInputEnd(); + EXPECT_EQ(runtime().crash_type(), std::nullopt); + std::optional<RuntimeDiffResult> result = runtime().TakeDiffResult(); + ASSERT_TRUE(result.has_value()); + auto records = DecodeDiffRecordContainer(result->container); + ASSERT_TRUE(records.has_value()); + ASSERT_EQ(records->size(), 1); + EXPECT_EQ((*records)[0].label, "setup"); + EXPECT_THAT(RoundTripDefaultDeserialize<int>((*records)[0].payload), + Optional(99)); +} + +TEST_F(RecordOrDiffTest, SingleUnlabeledCallIsRecordedUnderEmptyLabel) { + const DiffRun rec = RecordOutcome([] { RecordOrDiff(42); }); + EXPECT_EQ(rec.kind, RuntimeDiffResult::Kind::kRecords); + EXPECT_EQ(rec.crash_type, std::nullopt); + auto records = DecodeDiffRecordContainer(rec.container); + ASSERT_TRUE(records.has_value()); + ASSERT_EQ(records->size(), 1); + EXPECT_EQ((*records)[0].label, ""); + EXPECT_THAT(RoundTripDefaultDeserialize<int>((*records)[0].payload), + Optional(42)); + // And it validates. + const DiffRun val = ValidateOutcome(rec.container, [] { RecordOrDiff(42); }); + EXPECT_EQ(val.crash_type, std::nullopt); + EXPECT_THAT(val.stderr_output, Not(HasSubstr("RecordOrDiff MISMATCH"))); + EXPECT_EQ(val.kind, RuntimeDiffResult::Kind::kAck); +} + +TEST_F(RecordOrDiffTest, DuplicateLabelFailsInRecord) { + const DiffRun rec = RecordOutcome([] { + RecordOrDiff(1, "x"); + RecordOrDiff(2, "x"); + RecordOrDiff(3, "y"); + }); + EXPECT_THAT( + rec.crash_type, + Optional(std::string("RecordOrDiff usage error: duplicate label"))); + EXPECT_THAT(rec.stderr_output, + HasSubstr("RecordOrDiff label \"x\" used twice in one " + "input; give each call a distinct label")); +} + +TEST_F(RecordOrDiffTest, TwoUnlabeledCallsAreADuplicate) { + const DiffRun rec = RecordOutcome([] { + RecordOrDiff(1); + RecordOrDiff(2); + }); + EXPECT_THAT( + rec.crash_type, + Optional(std::string("RecordOrDiff usage error: duplicate label"))); + EXPECT_THAT(rec.stderr_output, + HasSubstr("RecordOrDiff label \"\" used twice")); +} + +TEST_F(RecordOrDiffTest, DuplicateLabelFailsInValidate) { + const std::string container = Record([] { RecordOrDiff(1, "x"); }); + const DiffRun val = ValidateOutcome(container, [] { + RecordOrDiff(1, "x"); + RecordOrDiff(1, "x"); + }); + EXPECT_THAT( + val.crash_type, + Optional(std::string("RecordOrDiff usage error: duplicate label"))); + EXPECT_THAT(val.stderr_output, + HasSubstr("RecordOrDiff label \"x\" used twice")); + // The usage error is the only finding of the input. + EXPECT_THAT(val.stderr_output, Not(HasSubstr("=== RecordOrDiff MISMATCH"))); +} + +TEST_F(RecordOrDiffTest, DuplicateLabelFailsInValidateWithoutBaseline) { + const DiffRun val = ValidateOutcome(std::nullopt, [] { + RecordOrDiff(1, "x"); + RecordOrDiff(2, "x"); + }); + EXPECT_THAT( + val.crash_type, + Optional(std::string("RecordOrDiff usage error: duplicate label"))); +} + +TEST_F(RecordOrDiffTest, LabelsInLoopsAreUnique) { + const std::string container = Record([] { + for (int i = 0; i < 3; ++i) RecordOrDiff(i * 10, absl::StrCat("item/", i)); + }); + auto records = DecodeDiffRecordContainer(container); + ASSERT_TRUE(records.has_value()); + EXPECT_EQ(records->size(), 3); +} + +TEST_F(RecordOrDiffTest, ReorderedCallsPass) { + const std::string container = Record([] { + RecordOrDiff(1, "a"); + RecordOrDiff(std::string("two"), "b"); + RecordOrDiff(Quote{300, 10}, "c"); + }); + const DiffRun val = ValidateOutcome(container, [] { + RecordOrDiff(Quote{300, 10}, "c"); + RecordOrDiff(1, "a"); + RecordOrDiff(std::string("two"), "b"); + }); + EXPECT_EQ(val.crash_type, std::nullopt); + EXPECT_THAT(val.stderr_output, Not(HasSubstr("RecordOrDiff MISMATCH"))); +} + +TEST_F(RecordOrDiffTest, ValueDiffersIsReportedWithLabelAndValues) { + const std::string container = Record([] { + RecordOrDiff(Quote{1000, 10}, "quote"); + RecordOrDiff(std::string("same"), "s"); + }); + const DiffRun val = ValidateOutcome(container, [] { + RecordOrDiff(Quote{1100, 11}, "quote"); + RecordOrDiff(std::string("same"), "s"); + }); + EXPECT_THAT(val.crash_type, Optional(std::string("RecordOrDiff mismatch"))); + EXPECT_THAT(val.stderr_output, HasSubstr("=== RecordOrDiff MISMATCH")); + EXPECT_THAT(val.stderr_output, HasSubstr("Mismatched outputs: 1\n")); + EXPECT_THAT(val.stderr_output, HasSubstr("--- RecordOrDiff label: quote\n" + "Reason: value differs\n" + "Expected (baseline): ")); + EXPECT_THAT(val.stderr_output, HasSubstr("1000")); + EXPECT_THAT(val.stderr_output, HasSubstr("1100")); + EXPECT_THAT(val.stderr_output, Not(HasSubstr("--- RecordOrDiff label: s\n"))); +} + +TEST_F(RecordOrDiffTest, NewLabelIsReported) { + const std::string container = Record([] { RecordOrDiff(1, "a"); }); + const DiffRun val = ValidateOutcome(container, [] { + RecordOrDiff(1, "a"); + RecordOrDiff(5, "extra"); + }); + EXPECT_THAT(val.crash_type, Optional(std::string("RecordOrDiff mismatch"))); + EXPECT_THAT(val.stderr_output, + HasSubstr("--- RecordOrDiff label: extra\n" + "Reason: new output \"extra\" not in baseline\n" + "Expected (baseline): <no output>\n" + "Actual (current): 5\n")); +} + +TEST_F(RecordOrDiffTest, MissingLabelIsReportedAtInputEnd) { + const std::string container = Record([] { + RecordOrDiff(1, "a"); + RecordOrDiff(2, "gone"); + }); + const DiffRun val = ValidateOutcome(container, [] { RecordOrDiff(1, "a"); }); + EXPECT_THAT(val.crash_type, Optional(std::string("RecordOrDiff mismatch"))); + EXPECT_THAT(val.stderr_output, + HasSubstr("--- RecordOrDiff label: gone\n" + "Reason: baseline output \"gone\" was not " + "produced\n")); + EXPECT_THAT(val.stderr_output, HasSubstr("Actual (current): <no output>\n")); +} + +TEST_F(RecordOrDiffTest, UnlabeledMismatchIsShownAsUnlabeled) { + const std::string container = Record([] { RecordOrDiff(1); }); + const DiffRun val = ValidateOutcome(container, [] { RecordOrDiff(2); }); + EXPECT_THAT(val.stderr_output, + HasSubstr("--- RecordOrDiff label: <unlabeled>\n" + "Reason: value differs\n" + "Expected (baseline): 1\n" + "Actual (current): 2\n")); +} + +TEST_F(RecordOrDiffTest, AllMismatchesAreReportedOnceSortedByLabel) { + const std::string container = Record([] { + RecordOrDiff(1, "b"); + RecordOrDiff(2, "a"); + RecordOrDiff(3, "c"); + }); + const DiffRun val = ValidateOutcome(container, [] { + RecordOrDiff(20, "a"); + RecordOrDiff(10, "b"); + RecordOrDiff(4, "d"); + }); + EXPECT_EQ(CountOccurrences(val.stderr_output, "=== RecordOrDiff MISMATCH"), + 1); + EXPECT_THAT(val.stderr_output, HasSubstr("Mismatched outputs: 4\n")); + const size_t a = val.stderr_output.find("--- RecordOrDiff label: a\n"); + const size_t b = val.stderr_output.find("--- RecordOrDiff label: b\n"); + const size_t c = val.stderr_output.find("--- RecordOrDiff label: c\n"); + const size_t d = val.stderr_output.find("--- RecordOrDiff label: d\n"); + ASSERT_NE(a, std::string::npos); + ASSERT_NE(b, std::string::npos); + ASSERT_NE(c, std::string::npos); + ASSERT_NE(d, std::string::npos); + EXPECT_LT(a, b); + EXPECT_LT(b, c); + EXPECT_LT(c, d); + EXPECT_THAT(val.crash_type, Optional(std::string("RecordOrDiff mismatch"))); +} + +TEST_F(RecordOrDiffTest, MissingBaselineComparesNothing) { + const DiffRun val = + ValidateOutcome(std::nullopt, [] { RecordOrDiff(1, "a"); }); + EXPECT_EQ(val.crash_type, std::nullopt); + EXPECT_THAT(val.stderr_output, Not(HasSubstr("RecordOrDiff MISMATCH"))); + EXPECT_EQ(val.kind, RuntimeDiffResult::Kind::kAck); +} + +TEST_F(RecordOrDiffTest, UndecodableContainerIsReported) { + const DiffRun val = ValidateOutcome(std::string("not a container"), + [] { RecordOrDiff(1, "a"); }); + EXPECT_THAT(val.crash_type, Optional(std::string("RecordOrDiff mismatch"))); + EXPECT_THAT(val.stderr_output, + HasSubstr("--- RecordOrDiff label: <baseline container>\n" + "Reason: cannot decode baseline container\n" + "Expected (baseline): <undecodable: 15 bytes>\n")); +} + +TEST_F(RecordOrDiffTest, UndecodableValueIsReported) { + const std::string container = EncodeDiffRecordContainer({{"a", "garbage"}}); + const DiffRun val = ValidateOutcome(container, [] { RecordOrDiff(1, "a"); }); + EXPECT_THAT(val.stderr_output, + HasSubstr("Reason: cannot decode baseline value\n" + "Expected (baseline): <undecodable: 7 bytes>\n" + "Actual (current): 1\n")); +} + +TEST_F(RecordOrDiffTest, UnparsableInputIsSkippedInBothModes) { + const DiffRun rec = RecordOutcome( + [] { + RecordOrDiff(1, "a"); + RecordOrDiff(1, "a"); // Not even a duplicate: the input is skipped. + }, + /*unparsable=*/true); + EXPECT_EQ(rec.kind, RuntimeDiffResult::Kind::kSkippedUnparsable); + EXPECT_EQ(rec.container, ""); + EXPECT_EQ(rec.crash_type, std::nullopt); + + const std::string baseline = EncodeDiffRecordContainer({{"a", "x"}}); + const DiffRun val = ValidateOutcome( + baseline, [] { RecordOrDiff(2, "b"); }, /*unparsable=*/true); + EXPECT_EQ(val.kind, RuntimeDiffResult::Kind::kSkippedUnparsable); + EXPECT_EQ(val.crash_type, std::nullopt); + EXPECT_THAT(val.stderr_output, Not(HasSubstr("RecordOrDiff MISMATCH"))); +} + +TEST_F(RecordOrDiffTest, TopLevelEnumIsEncodedByValue) { + const std::string container = + Record([] { RecordOrDiff(Color::kBlue, "color"); }); + auto records = DecodeDiffRecordContainer(container); + ASSERT_TRUE(records.has_value()); + ASSERT_EQ(records->size(), 1); + auto obj = internal::ParseIRObject((*records)[0].payload); + ASSERT_TRUE(obj.has_value()); + EXPECT_THAT(obj->GetScalar<Color>(), Optional(Color::kBlue)); + EXPECT_THAT(RoundTripDefaultDeserialize<Color>((*records)[0].payload), + Optional(Color::kBlue)); + const DiffRun val = + ValidateOutcome(container, [] { RecordOrDiff(Color::kRed, "color"); }); + EXPECT_THAT(val.stderr_output, HasSubstr("(-3)")); + EXPECT_THAT(val.stderr_output, HasSubstr("(7)")); +} + +TEST_F(RecordOrDiffTest, NanEqualsNanForFloatingPoint) { + const std::string container = Record( + [] { RecordOrDiff(std::numeric_limits<double>::quiet_NaN(), "nan"); }); + const DiffRun val = ValidateOutcome(container, [] { + RecordOrDiff(std::numeric_limits<double>::quiet_NaN(), "nan"); + }); + EXPECT_EQ(val.crash_type, std::nullopt); +} + +TEST_F(RecordOrDiffTest, NanVersusFiniteFloatingPointIsMismatch) { + const std::string container = Record( + [] { RecordOrDiff(std::numeric_limits<double>::quiet_NaN(), "nan"); }); + const DiffRun val = + ValidateOutcome(container, [] { RecordOrDiff(0.0, "nan"); }); + EXPECT_THAT(val.crash_type, Optional(std::string("RecordOrDiff mismatch"))); + EXPECT_THAT(val.stderr_output, HasSubstr("--- RecordOrDiff label: nan\n" + "Reason: value differs\n")); +} + +TEST_F(RecordOrDiffTest, MissingComparatorIsAUsageError) { + const DiffRun rec = RecordOutcome([] { RecordOrDiff(NoEq{1}, "noeq"); }); + EXPECT_THAT( + rec.crash_type, + Optional(std::string("RecordOrDiff usage error: missing comparator"))); + EXPECT_THAT(rec.stderr_output, HasSubstr("has no operator==; pass " + "RecordOrDiffOptions::comparator")); + EXPECT_THAT(rec.stderr_output, Not(HasSubstr("MessageDifferencer::Equals"))); +} + +TEST_F(RecordOrDiffTest, + MissingComparatorOnProtoTypeSuggestsMessageDifferencer) { + static_assert(internal::is_protocol_buffer_v<FakeProto>); + DiffCodec<FakeProto> codec; + codec.serializer = [](const FakeProto&) { return std::string(); }; + codec.deserializer = [](std::string_view) -> std::optional<FakeProto> { + return FakeProto{}; + }; + RecordOrDiffOptions<FakeProto> options; + options.label = "proto"; + const DiffRun rec = + RecordOutcome([&] { RecordOrDiff(FakeProto{}, codec, options); }); + EXPECT_THAT( + rec.crash_type, + Optional(std::string("RecordOrDiff usage error: missing comparator"))); + EXPECT_THAT(rec.stderr_output, HasSubstr("MessageDifferencer::Equals")); +} + +TEST_F(RecordOrDiffTest, CustomComparatorAcceptsEquivalentValues) { + RecordOrDiffOptions<NoEq> options; + options.label = "noeq"; + options.comparator = [](const NoEq& a, const NoEq& b) { + return a.x % 2 == b.x % 2; + }; + const std::string container = Record([&] { RecordOrDiff(NoEq{1}, options); }); + const DiffRun val = + ValidateOutcome(container, [&] { RecordOrDiff(NoEq{3}, options); }); + EXPECT_EQ(val.crash_type, std::nullopt); +} + +TEST_F(RecordOrDiffTest, CustomComparatorReportsNonEquivalentValues) { + RecordOrDiffOptions<NoEq> options; + options.label = "noeq"; + options.comparator = [](const NoEq& a, const NoEq& b) { + return a.x % 2 == b.x % 2; + }; + const std::string container = Record([&] { RecordOrDiff(NoEq{1}, options); }); + const DiffRun val = + ValidateOutcome(container, [&] { RecordOrDiff(NoEq{2}, options); }); + EXPECT_THAT(val.crash_type, Optional(std::string("RecordOrDiff mismatch"))); +} + +TEST_F(RecordOrDiffTest, CustomPrinterIsUsed) { + RecordOrDiffOptions<int> options; + options.label = "p"; + options.printer = [](const int& v) { return absl::StrCat("<<", v, ">>"); }; + const std::string container = Record([&] { RecordOrDiff(1, options); }); + const DiffRun val = + ValidateOutcome(container, [&] { RecordOrDiff(2, options); }); + EXPECT_THAT(val.stderr_output, HasSubstr("Expected (baseline): <<1>>\n" + "Actual (current): <<2>>\n")); +} + +TEST_F(RecordOrDiffTest, CodecPathRecordsAndValidatesMatchingBytes) { + RecordOrDiffOptions<Opaque> options; + options.label = "o"; + const std::string container = + Record([&] { RecordOrDiff(Opaque(5), OpaqueCodec(), options); }); + EXPECT_THAT(DecodeDiffRecordContainer(container), + Optional(ElementsAre(DiffRecord{"o", "v=5"}))); + const DiffRun val = ValidateOutcome( + container, [&] { RecordOrDiff(Opaque(5), OpaqueCodec(), options); }); + EXPECT_EQ(val.crash_type, std::nullopt); +} + +TEST_F(RecordOrDiffTest, CodecPathReportsEscapedBytesOnMismatch) { + RecordOrDiffOptions<Opaque> options; + options.label = "o"; + const std::string container = + Record([&] { RecordOrDiff(Opaque(5), OpaqueCodec(), options); }); + const DiffRun val = ValidateOutcome( + container, [&] { RecordOrDiff(Opaque(6), OpaqueCodec(), options); }); + EXPECT_THAT(val.crash_type, Optional(std::string("RecordOrDiff mismatch"))); + EXPECT_THAT(val.stderr_output, HasSubstr("Expected (baseline): \"v=5\"\n" + "Actual (current): \"v=6\"\n")); +} + +TEST_F(RecordOrDiffTest, CodecWithNullSerializerReportsInvalidCodec) { + DiffCodec<Opaque> codec = OpaqueCodec(); + codec.serializer = nullptr; + RecordOrDiffOptions<Opaque> options; + options.label = "bad_ser"; + const DiffRun rec = + RecordOutcome([&] { RecordOrDiff(Opaque(1), codec, options); }); + EXPECT_THAT(rec.crash_type, + Optional(std::string("RecordOrDiff usage error: invalid codec"))); + EXPECT_THAT(rec.stderr_output, + HasSubstr("for label \"bad_ser\" must have both a serializer and " + "a deserializer")); +} + +TEST_F(RecordOrDiffTest, CodecWithNullDeserializerReportsInvalidCodec) { + DiffCodec<Opaque> codec = OpaqueCodec(); + codec.deserializer = nullptr; + RecordOrDiffOptions<Opaque> options; + options.label = "bad_deser"; + const DiffRun rec = + RecordOutcome([&] { RecordOrDiff(Opaque(1), codec, options); }); + EXPECT_THAT(rec.crash_type, + Optional(std::string("RecordOrDiff usage error: invalid codec"))); + EXPECT_THAT(rec.stderr_output, + HasSubstr("for label \"bad_deser\" must have both a serializer " + "and a deserializer")); +} + +TEST_F(RecordOrDiffTest, CodecDeserializerNulloptReportsUndecodableValue) { + RecordOrDiffOptions<Opaque> options; + options.label = "o"; + const std::string container = + EncodeDiffRecordContainer({{"o", "corrupted_payload"}}); + const DiffRun val = ValidateOutcome( + container, [&] { RecordOrDiff(Opaque(5), OpaqueCodec(), options); }); + EXPECT_THAT(val.crash_type, Optional(std::string("RecordOrDiff mismatch"))); + EXPECT_THAT(val.stderr_output, + HasSubstr("Reason: cannot decode baseline value\n" + "Expected (baseline): <undecodable: 17 bytes>\n" + "Actual (current): \"v=5\"\n")); +} + +TEST_F(RecordOrDiffTest, StringViewAndBorrowingTupleValidateMatchingValues) { + const std::string baseline_str(64, 'a'); + const std::string container = Record([&] { + RecordOrDiff(std::string_view(baseline_str), "sv"); + RecordOrDiff(absl::string_view(baseline_str), "asv"); + RecordOrDiff(std::make_tuple(std::string_view(baseline_str), 7), "tup"); + }); + const DiffRun val = ValidateOutcome(container, [&] { + RecordOrDiff(std::string_view(baseline_str), "sv"); + RecordOrDiff(absl::string_view(baseline_str), "asv"); + RecordOrDiff(std::make_tuple(std::string_view(baseline_str), 7), "tup"); + }); + EXPECT_EQ(val.stderr_output, ""); + EXPECT_EQ(val.crash_type, std::nullopt); +} + +TEST_F(RecordOrDiffTest, StringViewAndBorrowingTupleReportMismatchesCleanly) { + const std::string baseline_str(64, 'a'); + const std::string changed_str(64, 'b'); + const std::string container = Record([&] { + RecordOrDiff(std::string_view(baseline_str), "sv"); + RecordOrDiff(absl::string_view(baseline_str), "asv"); + RecordOrDiff(std::make_tuple(std::string_view(baseline_str), 7), "tup"); + }); + const DiffRun val = ValidateOutcome(container, [&] { + RecordOrDiff(std::string_view(changed_str), "sv"); + RecordOrDiff(absl::string_view(baseline_str), "asv"); + RecordOrDiff(std::make_tuple(std::string_view(changed_str), 7), "tup"); + }); + EXPECT_THAT(val.crash_type, Optional(std::string("RecordOrDiff mismatch"))); + EXPECT_THAT(val.stderr_output, HasSubstr("Mismatched outputs: 2")); + EXPECT_THAT(val.stderr_output, HasSubstr("--- RecordOrDiff label: sv")); + EXPECT_THAT(val.stderr_output, HasSubstr("--- RecordOrDiff label: tup")); +} + +TEST_F(RecordOrDiffTest, StringViewLabelsWork) { + const std::string container = Record([] { + RecordOrDiff(11, std::string_view("std_sv")); + RecordOrDiff(22, absl::string_view("absl_sv")); + }); + const DiffRun val = ValidateOutcome(container, [] { + RecordOrDiff(11, std::string_view("std_sv")); + RecordOrDiff(22, absl::string_view("absl_sv")); + }); + EXPECT_EQ(val.crash_type, std::nullopt); + EXPECT_EQ(val.stderr_output, ""); +} + +TEST_F(RecordOrDiffTest, EmptyStringAndEmbeddedNulPayloadsRoundTrip) { + const std::string nul_str("\0\1\0x", 4); + const std::string container = Record([&] { + RecordOrDiff(std::string(""), "empty"); + RecordOrDiff(nul_str, "nul"); + }); + const DiffRun ok = ValidateOutcome(container, [&] { + RecordOrDiff(std::string(""), "empty"); + RecordOrDiff(nul_str, "nul"); + }); + EXPECT_EQ(ok.crash_type, std::nullopt); + + const DiffRun diff = ValidateOutcome(container, [&] { + RecordOrDiff(std::string(""), "empty"); + RecordOrDiff(std::string("\0\2\0x", 4), "nul"); + }); + EXPECT_THAT(diff.crash_type, Optional(std::string("RecordOrDiff mismatch"))); +} + +TEST_F(RecordOrDiffTest, BeginDiffInputResetsPerInputFailureState) { + const std::string container = Record([] { RecordOrDiff(1, "a"); }); + runtime().EnableDiffMode(DiffMode::kValidate); + runtime().BeginDiffInput(container, /*unparsable=*/false); + ::testing::internal::CaptureStderr(); + RecordOrDiff(2, "a"); + runtime().CheckDiffRecordsAtInputEnd(); + (void)::testing::internal::GetCapturedStderr(); + ASSERT_TRUE(runtime().crash_type().has_value()); + EXPECT_TRUE(runtime().ShouldSkipDiffCall()); + runtime().SetExternalFailureDetected(true); + + // The next input starts clean and is not reported. + runtime().BeginDiffInput(container, /*unparsable=*/false); + EXPECT_EQ(runtime().crash_type(), std::nullopt); + EXPECT_FALSE(runtime().external_failure_detected()); + EXPECT_FALSE(runtime().ShouldSkipDiffCall()); + RecordOrDiff(1, "a"); + runtime().CheckDiffRecordsAtInputEnd(); + EXPECT_EQ(runtime().crash_type(), std::nullopt); +} + +} // namespace +} // namespace fuzztest
diff --git a/rust/engine/src/engine_ffi.rs b/rust/engine/src/engine_ffi.rs index 276b3e1..7c625a8 100644 --- a/rust/engine/src/engine_ffi.rs +++ b/rust/engine/src/engine_ffi.rs
@@ -192,12 +192,10 @@ /// Constants for the layout of the coverage feature as a 64-bit unsigned /// integer: /// -/// - Bits 63..59: 5-bit domain ID of the feature. Each domain is a -/// logically independent feature namespace registered in -/// `FuzzTestAdapter::SetUpCoverageDomains`. +/// - Bits 63..59: 5-bit domain ID of the feature. Each domain is a logically independent feature +/// namespace registered in `FuzzTestAdapter::SetUpCoverageDomains`. /// - Bits 58..32: 27-bit feature ID within the domain. /// - Bits 31..0: 32-bit counter value of the feature. -/// pub struct FuzzTestCoverageFeatureLayout; impl FuzzTestCoverageFeatureLayout { @@ -368,6 +366,9 @@ >, /// [Optional] Updates the test `input` metadata from serialized `metadata`. + /// Called for mutation origins before `Mutate`/`CrossOver`, and for inputs + /// of execution requests that carry metadata (e.g. the expected values of + /// the incremental differential fuzzing validate mode) before `Execute`. pub update_input_metadata: Option< unsafe extern "C" fn( ctx: *mut FuzzTestAdapterCtx,