No public description PiperOrigin-RevId: 1018756180
diff --git a/centipede/BUILD b/centipede/BUILD index e7c3faf..69e0501 100644 --- a/centipede/BUILD +++ b/centipede/BUILD
@@ -583,6 +583,36 @@ ) cc_library( + name = "input_metadata_store", + srcs = ["input_metadata_store.cc"], + hdrs = ["input_metadata_store.h"], + deps = [ + ":environment", + ":runner_result", + "@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_test( + name = "input_metadata_store_test", + srcs = ["input_metadata_store_test.cc"], + deps = [ + ":environment", + ":input_metadata_store", + ":runner_result", + "@com_google_fuzztest//common:defs", + "@com_google_fuzztest//common:hash", + "@com_google_fuzztest//common:remote_file", + "@com_google_fuzztest//common:test_util", + "@googletest//:gtest_main", + ], +) + +cc_library( name = "centipede_callbacks", srcs = ["centipede_callbacks.cc"], hdrs = ["centipede_callbacks.h"], @@ -593,6 +623,7 @@ ":control_flow", ":environment", ":fuzztest_mutator", + ":input_metadata_store", ":mutation_data", ":runner_request", ":runner_result", @@ -1567,6 +1598,17 @@ ) cc_test( + name = "runner_request_test", + srcs = ["runner_request_test.cc"], + deps = [ + ":runner_request", + ":shared_memory_blob_sequence", + "@com_google_fuzztest//common:defs", + "@googletest//:gtest_main", + ], +) + +cc_test( name = "runner_result_test", srcs = ["runner_result_test.cc"], deps = [ @@ -1958,6 +2000,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..5509a52 100644 --- a/centipede/centipede.cc +++ b/centipede/centipede.cc
@@ -496,6 +496,69 @@ 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; + + // When replaying and continuing after crashes, re-run the inputs after a + // single-input failure or a truncated batch, so that one failing input does + // not prevent the rest of the batch from being executed. + if (env_.fuzztest_only_replay && !env_.exit_on_crash) { + // Returns the offset, within a (sub-)batch of `sub_size` inputs, of the + // first input that still needs to be executed, or `sub_size` if there is + // none. + 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) { + // Skip the failing input. Failures that are not attributable to a + // single input (e.g. per-batch timeouts) end the batch. + const bool is_single_input_failure = + sub_result.IsInputFailure() && sub_result.failure_description() != + kExecutionFailurePerBatchTimeout; + return is_single_input_failure && read + 1 < sub_size ? read + 1 + : sub_size; + } + if (sub_result.exit_code() == EXIT_SUCCESS && read < sub_size) { + if (read == 0) { + // No progress: give up instead of looping forever. + FUZZTEST_LOG(WARNING) + << "Batch execution produced no outputs; skipping the remaining " + << sub_size << " inputs of the batch"; + 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 +633,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..9ceeb28 100644 --- a/centipede/centipede_callbacks.cc +++ b/centipede/centipede_callbacks.cc
@@ -550,11 +550,25 @@ outputs_blobseq_.Reset(); size_t num_inputs_written = 0; + // The persistent input metadata is exchanged with the primary binary only, + // and needs the inputs to be passed via shared memory. + const bool use_input_metadata_store = input_metadata_store_.enabled() && + binary == env_.binary && + !env_.has_input_wildcards; if (env_.has_input_wildcards) { FUZZTEST_CHECK_EQ(inputs.size(), 1); WriteToLocalFile(temp_input_file_path_, inputs[0]); num_inputs_written = 1; + } else if (use_input_metadata_store) { + // Feed the inputs, each preceded by its stored persistent metadata (if + // any), to inputs_blobseq_. + const std::vector<ByteArray> stored_metadata = + input_metadata_store_.Load(inputs); + const std::vector<ByteSpan> persistent_metadata(stored_metadata.begin(), + stored_metadata.end()); + num_inputs_written = + RequestExecution(inputs, persistent_metadata, inputs_blobseq_); } else { // Feed the inputs to inputs_blobseq_. num_inputs_written = RequestExecution(inputs, inputs_blobseq_); @@ -579,6 +593,11 @@ const bool read_success = batch_result.Read(outputs_blobseq_); FUZZTEST_LOG_IF(ERROR, !read_success) << "Failed to read batch result!"; outputs_blobseq_.ReleaseSharedMemory(); // Outputs are already consumed. + if (use_input_metadata_store) { + // Store the persistent metadata of the executed inputs, including those + // executed before a failure. + input_metadata_store_.Save(inputs.first(num_inputs_written), batch_result); + } // We may have fewer feature blobs than inputs if // * some inputs were not written (i.e. num_inputs_written < inputs.size).
diff --git a/centipede/centipede_callbacks.h b/centipede/centipede_callbacks.h index 38d6bc3..3fc908c 100644 --- a/centipede/centipede_callbacks.h +++ b/centipede/centipede_callbacks.h
@@ -31,6 +31,7 @@ #include "./centipede/command.h" #include "./centipede/environment.h" #include "./centipede/fuzztest_mutator.h" +#include "./centipede/input_metadata_store.h" #include "./centipede/mutation_data.h" #include "./centipede/runner_result.h" #include "./centipede/shared_memory_blob_sequence.h" @@ -168,6 +169,9 @@ StopCondition& stop_condition_; ByteArrayMutator byte_array_mutator_; FuzzTestMutator fuzztest_mutator_; + // Storage of the persistent input metadata of the test. Disabled unless + // `env_.fuzztest_persistent_metadata_root` is set. + InputMetadataStore input_metadata_store_{env_}; private: class PersistentModeServer;
diff --git a/centipede/centipede_flags.inc b/centipede/centipede_flags.inc index a335b6e..af85197 100644 --- a/centipede/centipede_flags.inc +++ b/centipede/centipede_flags.inc
@@ -515,6 +515,12 @@ "The root directory for Centipede workdirs for working on the " "corpus database.") CENTIPEDE_FLAG( + std::string, fuzztest_persistent_metadata_root, "", + "If set to non-empty, the root directory for storing the persistent input " + "metadata that tests attach to their inputs. The metadata of an input is " + "stored under <root>/<fuzztest_binary_identifier>/<test_name>/ and is " + "passed back to the test before the next execution of the same input.") +CENTIPEDE_FLAG( std::vector<std::string>, fuzztest_seed_corpus_databases, {}, "A comma-separated list of read-only corpus databases. When fuzzing with " "the corpus database, the coverage inputs of the test in these databases "
diff --git a/centipede/centipede_test.cc b/centipede/centipede_test.cc index d7fe79a..530ba81 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,169 @@ 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; + env.fuzztest_only_replay = true; + // 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, ReplayReRunsTheTailOfAFailedBatch) { + 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); + // 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, ReplayCrashOnFinalElementDoesNotIssueEmptyTailBatch) { + TempDir temp_dir{test_info_->name()}; + Environment env = TailRerunEnv(temp_dir.path().string()); + 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, ReplayReRunsTruncatedSubBatches) { + TempDir temp_dir{test_info_->name()}; + Environment env = TailRerunEnv(temp_dir.path().string()); + 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, ReplayDoesNotReRunTailOnPerBatchTimeout) { + TempDir temp_dir{test_info_->name()}; + Environment env = TailRerunEnv(temp_dir.path().string()); + 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, ReplayDoesNotReRunTailWithExitOnCrash) { + TempDir temp_dir{test_info_->name()}; + Environment env = TailRerunEnv(temp_dir.path().string()); + env.exit_on_crash = true; + FakeTailRerunCallbacks fake(env, /*crashing=*/{103, 106}); + NonOwningCallbacksFactory factory(fake); + EXPECT_EQ(CentipedeMain(env, factory), EXIT_FAILURE); + EXPECT_THAT(fake.num_executions(), + UnorderedElementsAre(Pair(0, 1), Pair(100, 1), Pair(101, 1), + Pair(102, 1))); +} + +TEST(Centipede, FuzzingDoesNotReRunTheTailOfAFailedBatch) { + TempDir temp_dir{test_info_->name()}; + Environment env = TailRerunEnv(temp_dir.path().string()); + env.fuzztest_only_replay = false; + 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/engine_abi.h b/centipede/engine_abi.h index a139500..4cce087 100644 --- a/centipede/engine_abi.h +++ b/centipede/engine_abi.h
@@ -75,6 +75,35 @@ void (*Emit)(FuzzTestBytesSinkCtx* ctx, const FuzzTestBytesView* view); } FuzzTestBytesSink; +// Types of input metadata. The engine handles each type differently, and the +// content of every type is opaque to the engine. +typedef enum { + // Hints for mutating the input (e.g. the operands of comparisons seen when + // executing it). Kept in memory only, and passed back to the adapter for the + // origin inputs of mutations. + kFuzzTestInputMetadataMutationHints = 0, + // Metadata that the engine may store for the input and pass back to the + // adapter before a later execution of the same input. + kFuzzTestInputMetadataPersistent = 1, +} FuzzTestInputMetadataType; + +// A piece of input metadata of a given type. +typedef struct { + FuzzTestInputMetadataType type; + FuzzTestBytesView bytes; +} FuzzTestInputMetadataView; + +// Sink for input metadata. +typedef struct FuzzTestInputMetadataSinkCtx FuzzTestInputMetadataSinkCtx; +typedef struct { + FuzzTestInputMetadataSinkCtx* ctx; + + // Emits a piece of input metadata. Multiple emissions of the same type are + // concatenated. A type that is never emitted is treated as absent. + void (*Emit)(FuzzTestInputMetadataSinkCtx* ctx, + const FuzzTestInputMetadataView* metadata); +} FuzzTestInputMetadataSink; + // Sink for seed inputs. typedef struct FuzzTestInputSinkCtx FuzzTestInputSinkCtx; typedef struct { @@ -215,14 +244,18 @@ const FuzzTestBytesView* content, const FuzzTestInputSink* sink); - // [Optional] Serializes the test `input` metadata into bytes using `sink`. + // [Optional] Serializes the test `input` metadata, of any type, using + // `sink`. void (*SerializeInputMetadata)(FuzzTestAdapterCtx* ctx, FuzzTestInputHandle input, - const FuzzTestBytesSink* sink); + const FuzzTestInputMetadataSink* sink); - // [Optional] Updates the test `input` metadata from serialized `metadata`. + // [Optional] Updates the test `input` metadata of type `metadata->type` from + // the serialized `metadata->bytes`. Called with the mutation hints of + // mutation origins before `Mutate`/`CrossOver`, and with the persistent + // metadata stored for `input` (if any) before `Execute`. void (*UpdateInputMetadata)(FuzzTestAdapterCtx* ctx, - const FuzzTestBytesView* metadata, + const FuzzTestInputMetadataView* metadata, FuzzTestInputHandle input); // Callback to run when the engine is done with `input`.
diff --git a/centipede/engine_worker.cc b/centipede/engine_worker.cc index 464931e..6a0356d 100644 --- a/centipede/engine_worker.cc +++ b/centipede/engine_worker.cc
@@ -398,6 +398,39 @@ }}; } +// The serialized input metadata collected from an adapter, by type. +struct SerializedInputMetadata { + std::vector<uint8_t> mutation_hints; + std::vector<uint8_t> persistent; + + void clear() { + mutation_hints.clear(); + persistent.clear(); + } +}; + +FuzzTestInputMetadataSink GetInputMetadataSinkTo( + SerializedInputMetadata& metadata) { + return {/*ctx=*/reinterpret_cast<FuzzTestInputMetadataSinkCtx*>(&metadata), + /*Emit=*/[](FuzzTestInputMetadataSinkCtx* ctx, + const FuzzTestInputMetadataView* view) { + auto* output = reinterpret_cast<SerializedInputMetadata*>(ctx); + std::vector<uint8_t>* bytes = nullptr; + switch (view->type) { + case kFuzzTestInputMetadataMutationHints: + bytes = &output->mutation_hints; + break; + case kFuzzTestInputMetadataPersistent: + bytes = &output->persistent; + break; + } + // Ignore metadata of unknown types. + if (bytes == nullptr) return; + bytes->insert(bytes->end(), view->bytes.data, + view->bytes.data + view->bytes.size); + }}; +} + FuzzTestInputSink GetInputSinkTo(std::vector<FuzzTestInputHandle>& inputs) { return {/*ctx=*/reinterpret_cast<FuzzTestInputSinkCtx*>(&inputs), /*Emit=*/[](FuzzTestInputSinkCtx* ctx, FuzzTestInputHandle input) { @@ -512,8 +545,9 @@ if (!IsDataInput(blob)) break; emitted_inputs.clear(); auto input_content = FuzzTestBytesView{blob.data, blob.size}; - auto input_metadata = - FuzzTestBytesView{metadata.cmp_data.data(), metadata.cmp_data.size()}; + const auto input_metadata = FuzzTestInputMetadataView{ + kFuzzTestInputMetadataMutationHints, + {metadata.cmp_data.data(), metadata.cmp_data.size()}}; adapter.DeserializeInputContent(adapter.ctx, &input_content, &input_sink); WORKER_CHECK_FOR_ERROR(); WorkerCheck(emitted_inputs.size() == 1, @@ -655,7 +689,8 @@ // In-loop variables declared outside to save allocations. std::vector<uint64_t> features; - std::vector<uint8_t> serialized_metadata; + SerializedInputMetadata serialized_metadata; + const auto metadata_sink = GetInputMetadataSinkTo(serialized_metadata); std::vector<FuzzTestInputHandle> emitted_inputs; const auto input_sink = GetInputSinkTo(emitted_inputs); @@ -670,8 +705,19 @@ // 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. + // The data input may be preceded by its persistent metadata, which is + // passed to the adapter before `Execute`. + const bool has_persistent_metadata = IsPersistentMetadata(first_blob); + const auto persistent_metadata = FuzzTestInputMetadataView{ + kFuzzTestInputMetadataPersistent, + {has_persistent_metadata ? first_blob.data : nullptr, + has_persistent_metadata ? first_blob.size : 0}}; + const auto blob = + has_persistent_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)) { @@ -686,6 +732,10 @@ WorkerCheck(emitted_inputs.size() == 1, "Deserialize must emit exactly one input"); auto input = emitted_inputs[0]; + if (has_persistent_metadata && adapter.UpdateInputMetadata != nullptr) { + adapter.UpdateInputMetadata(adapter.ctx, &persistent_metadata, input); + WORKER_CHECK_FOR_ERROR(); + } features.clear(); FuzzTestFeedbackSink feedback_sink = { @@ -706,7 +756,6 @@ serialized_metadata.clear(); if (adapter.SerializeInputMetadata != nullptr) { - const auto metadata_sink = GetBytesSinkTo(serialized_metadata); adapter.SerializeInputMetadata(adapter.ctx, input, &metadata_sink); } adapter.FreeInput(adapter.ctx, input); @@ -746,7 +795,10 @@ WorkerLog("failed to write feedback"); break; } - if (!BatchResult::WriteMetadata(serialized_metadata, *outputs_blobseq)) { + if (!BatchResult::WriteMetadata(serialized_metadata.mutation_hints, + *outputs_blobseq) || + !BatchResult::WritePersistentMetadata(serialized_metadata.persistent, + *outputs_blobseq)) { WorkerLog("failed to write input metadata"); break; }
diff --git a/centipede/environment.cc b/centipede/environment.cc index 8fb2a35..6ff21de 100644 --- a/centipede/environment.cc +++ b/centipede/environment.cc
@@ -245,6 +245,7 @@ fuzztest_binary_identifier = config.binary_identifier; fuzztest_stats_root = config.stats_root; fuzztest_workdir_root = config.workdir_root; + fuzztest_persistent_metadata_root = config.persistent_metadata_root; fuzztest_seed_corpus_databases = config.seed_corpus_databases; fuzztest_only_replay = config.only_replay; fuzztest_update_corpus_database = config.update_corpus_database;
diff --git a/centipede/environment_test.cc b/centipede/environment_test.cc index 4b93216..3900dab 100644 --- a/centipede/environment_test.cc +++ b/centipede/environment_test.cc
@@ -194,6 +194,7 @@ config.binary_identifier = "bin"; config.stats_root = "stats"; config.workdir_root = "workdir"; + config.persistent_metadata_root = "metadata"; config.seed_corpus_databases = {"seed_db1", "seed_db2"}; config.only_replay = true; config.execution_id = "exec"; @@ -207,6 +208,7 @@ EXPECT_EQ(env.fuzztest_binary_identifier, "bin"); EXPECT_EQ(env.fuzztest_stats_root, "stats"); EXPECT_EQ(env.fuzztest_workdir_root, "workdir"); + EXPECT_EQ(env.fuzztest_persistent_metadata_root, "metadata"); EXPECT_EQ(env.fuzztest_seed_corpus_databases, (std::vector<std::string>{"seed_db1", "seed_db2"})); EXPECT_TRUE(env.fuzztest_only_replay);
diff --git a/centipede/in_process_centipede_callbacks.cc b/centipede/in_process_centipede_callbacks.cc index 59539d9..0bb931d 100644 --- a/centipede/in_process_centipede_callbacks.cc +++ b/centipede/in_process_centipede_callbacks.cc
@@ -81,6 +81,32 @@ }; } +// Returns a sink that appends the emitted input metadata to the field of +// `metadata` that corresponds to its type. +FuzzTestInputMetadataSink GetInputMetadataSinkTo(ExecutionMetadata& metadata) { + return { + /*ctx=*/reinterpret_cast<FuzzTestInputMetadataSinkCtx*>(&metadata), + /*Emit=*/ + [](FuzzTestInputMetadataSinkCtx* ctx, + const FuzzTestInputMetadataView* view) { + auto* output = reinterpret_cast<ExecutionMetadata*>(ctx); + ByteArray* bytes = nullptr; + switch (view->type) { + case kFuzzTestInputMetadataMutationHints: + bytes = &output->cmp_data; + break; + case kFuzzTestInputMetadataPersistent: + bytes = &output->persistent_data; + break; + } + // Ignore metadata of unknown types. + if (bytes == nullptr) return; + bytes->insert(bytes->end(), view->bytes.data, + view->bytes.data + view->bytes.size); + }, + }; +} + FuzzTestInputSink GetInputSinkTo(std::vector<FuzzTestInputHandle>& inputs) { return { /*ctx=*/reinterpret_cast<FuzzTestInputSinkCtx*>(&inputs), @@ -476,8 +502,9 @@ FUZZTEST_CHECK_EQ(emitted_inputs.size(), 1) << "DeserializeInputContent must emit exactly one input"; if (adapter_.UpdateInputMetadata != nullptr && input.metadata != nullptr) { - const FuzzTestBytesView input_metadata{input.metadata->cmp_data.data(), - input.metadata->cmp_data.size()}; + const FuzzTestInputMetadataView input_metadata{ + kFuzzTestInputMetadataMutationHints, + {input.metadata->cmp_data.data(), input.metadata->cmp_data.size()}}; adapter_.UpdateInputMetadata(adapter_.ctx, &input_metadata, emitted_inputs[0]); if (CheckError()) { @@ -561,6 +588,21 @@ }; const auto input_sink = GetInputSinkTo(emitted_inputs); + // The persistent input metadata is exchanged with the primary binary only. + const bool use_input_metadata_store = + input_metadata_store_.enabled() && binary == env_.binary; + // Empty if the store is not used. + const std::vector<ByteArray> stored_metadata = + use_input_metadata_store ? input_metadata_store_.Load(inputs) + : std::vector<ByteArray>(); + // Stores the persistent metadata of the executed inputs on all return paths, + // including those executed before a failure. + absl::Cleanup save_persistent_metadata = [&] { + if (use_input_metadata_store) { + input_metadata_store_.Save(inputs, batch_result); + } + }; + for (size_t i = 0; i < inputs.size(); ++i) { if (stop_condition_.ShouldStop()) { return true; @@ -578,6 +620,17 @@ FUZZTEST_CHECK_EQ(emitted_inputs.size(), 1) << "DeserializeInputContent must emit exactly one input"; const FuzzTestInputHandle input = emitted_inputs[0]; + if (i < stored_metadata.size() && !stored_metadata[i].empty() && + adapter_.UpdateInputMetadata != nullptr) { + const FuzzTestInputMetadataView persistent_metadata{ + kFuzzTestInputMetadataPersistent, + {stored_metadata[i].data(), stored_metadata[i].size()}}; + adapter_.UpdateInputMetadata(adapter_.ctx, &persistent_metadata, input); + if (CheckError()) { + CopyErrorOrMoveFindingToBatchResult(batch_result); + return false; + } + } features.clear(); FuzzTestFeedbackSink feedback_sink = { @@ -609,8 +662,7 @@ ExecutionResult& exec_result = batch_result.results()[i]; if (adapter_.SerializeInputMetadata != nullptr) { - const auto metadata_sink = - GetBytesSinkTo(exec_result.metadata().cmp_data); + const auto metadata_sink = GetInputMetadataSinkTo(exec_result.metadata()); adapter_.SerializeInputMetadata(adapter_.ctx, input, &metadata_sink); } // Frees `input`, the only emitted input.
diff --git a/centipede/in_process_centipede_callbacks_test.cc b/centipede/in_process_centipede_callbacks_test.cc index 1b40572..108ed30 100644 --- a/centipede/in_process_centipede_callbacks_test.cc +++ b/centipede/in_process_centipede_callbacks_test.cc
@@ -80,7 +80,11 @@ struct FakeInput { std::string content; + // Mutation hints. std::string metadata; + // Persistent metadata: what the engine passed before `Execute` (if any), + // and what the adapter emits afterwards. + std::string persistent_metadata; }; struct FakeAdapterState { @@ -304,6 +308,12 @@ // = 44. features.push_back(MakeEngineFeature(1, 10, 0xB0)); input_obj->metadata = "recorded_cmp_meta"; + } else if (input_obj->content == "with_persistent_meta") { + features.push_back(MakeEngineFeature(0, 8, 0)); + // Echo what the engine passed (if anything), so that tests can observe + // both directions. + input_obj->persistent_metadata = + absl::StrCat("persisted(", input_obj->persistent_metadata, ")"); } const FuzzTestUint64sView features_view{features.data(), features.size()}; @@ -334,18 +344,31 @@ void FakeSerializeInputMetadata(FuzzTestAdapterCtx* ctx, FuzzTestInputHandle input, - const FuzzTestBytesSink* sink) { + const FuzzTestInputMetadataSink* sink) { const auto* input_obj = reinterpret_cast<FakeInput*>(input); - const FuzzTestBytesView bytes = ToBytesView(input_obj->metadata); - sink->Emit(sink->ctx, &bytes); + const FuzzTestInputMetadataView metadata = { + kFuzzTestInputMetadataMutationHints, ToBytesView(input_obj->metadata)}; + sink->Emit(sink->ctx, &metadata); + if (input_obj->persistent_metadata.empty()) return; + const FuzzTestInputMetadataView persistent_metadata = { + kFuzzTestInputMetadataPersistent, + ToBytesView(input_obj->persistent_metadata)}; + sink->Emit(sink->ctx, &persistent_metadata); } void FakeUpdateInputMetadata(FuzzTestAdapterCtx* ctx, - const FuzzTestBytesView* metadata, + const FuzzTestInputMetadataView* metadata, FuzzTestInputHandle input) { auto* input_obj = reinterpret_cast<FakeInput*>(input); - input_obj->metadata.assign(reinterpret_cast<const char*>(metadata->data), - metadata->size); + if (metadata->type == kFuzzTestInputMetadataMutationHints) { + input_obj->metadata.assign( + reinterpret_cast<const char*>(metadata->bytes.data), + metadata->bytes.size); + } else if (metadata->type == kFuzzTestInputMetadataPersistent) { + input_obj->persistent_metadata.assign( + reinterpret_cast<const char*>(metadata->bytes.data), + metadata->bytes.size); + } MaybeEmitDiagnostic(reinterpret_cast<FakeAdapterState*>(ctx), "UpdateInputMetadata"); } @@ -726,10 +749,89 @@ expected_counter_feature_id))); EXPECT_EQ(ToString(batch_result.results()[1].metadata().cmp_data), "recorded_cmp_meta"); + EXPECT_THAT(batch_result.results()[1].metadata().persistent_data, IsEmpty()); EXPECT_EQ(state.active_inputs, 0); } TEST(InProcessCentipedeCallbacksTest, + ExecuteSeparatesPersistentMetadataFromMutationHints) { + FakeAdapterState state; + const FuzzTestAdapterManager manager = MakeFakeAdapterManager(&state); + + Environment env; + StopCondition stop_condition; + InProcessCentipedeCallbacks callbacks(env, stop_condition, &manager); + + const ByteArray input = ToByteArray("with_persistent_meta"); + BatchResult batch_result; + EXPECT_TRUE(callbacks.Execute("binary", {input}, batch_result)); + ASSERT_EQ(batch_result.num_outputs_read(), 1); + + const ExecutionMetadata& metadata = batch_result.results()[0].metadata(); + EXPECT_THAT(metadata.cmp_data, IsEmpty()); + EXPECT_EQ(ToString(metadata.persistent_data), "persisted()"); + EXPECT_EQ(state.active_inputs, 0); +} + +TEST(InProcessCentipedeCallbacksTest, + ExecutePassesBackTheStoredPersistentMetadata) { + TempDir temp_dir{test_info_->name()}; + FakeAdapterState state; + const FuzzTestAdapterManager manager = MakeFakeAdapterManager(&state); + + Environment env; + env.binary = "binary"; + env.fuzztest_persistent_metadata_root = temp_dir.path().string(); + env.fuzztest_binary_identifier = "binary_id"; + StopCondition stop_condition; + InProcessCentipedeCallbacks callbacks(env, stop_condition, &manager); + + const ByteArray input = ToByteArray("with_persistent_meta"); + // An input that emits no persistent metadata. + const ByteArray other_input = ToByteArray("random_seed"); + BatchResult batch_result; + + // Nothing is stored for the first execution. + EXPECT_TRUE(callbacks.Execute("binary", {other_input, input}, batch_result)); + ASSERT_EQ(batch_result.num_outputs_read(), 2); + EXPECT_THAT(batch_result.results()[0].metadata().persistent_data, IsEmpty()); + EXPECT_EQ(ToString(batch_result.results()[1].metadata().persistent_data), + "persisted()"); + + // The second execution gets what the first one emitted, for the same input + // only. + EXPECT_TRUE(callbacks.Execute("binary", {input, other_input}, batch_result)); + ASSERT_EQ(batch_result.num_outputs_read(), 2); + EXPECT_EQ(ToString(batch_result.results()[0].metadata().persistent_data), + "persisted(persisted())"); + EXPECT_THAT(batch_result.results()[1].metadata().persistent_data, IsEmpty()); + EXPECT_EQ(state.active_inputs, 0); +} + +TEST(InProcessCentipedeCallbacksTest, + ExecuteDoesNotExchangePersistentMetadataWithOtherBinaries) { + TempDir temp_dir{test_info_->name()}; + FakeAdapterState state; + const FuzzTestAdapterManager manager = MakeFakeAdapterManager(&state); + + Environment env; + env.binary = "binary"; + env.fuzztest_persistent_metadata_root = temp_dir.path().string(); + StopCondition stop_condition; + InProcessCentipedeCallbacks callbacks(env, stop_condition, &manager); + + const ByteArray input = ToByteArray("with_persistent_meta"); + BatchResult batch_result; + EXPECT_TRUE(callbacks.Execute("extra_binary", {input}, batch_result)); + EXPECT_TRUE(callbacks.Execute("extra_binary", {input}, batch_result)); + + // Nothing was stored by the first execution. + ASSERT_EQ(batch_result.num_outputs_read(), 1); + EXPECT_EQ(ToString(batch_result.results()[0].metadata().persistent_data), + "persisted()"); +} + +TEST(InProcessCentipedeCallbacksTest, ExecuteReportsFindingAndResetsOnNextBatch) { FakeAdapterState state; const FuzzTestAdapterManager manager = MakeFakeAdapterManager(&state);
diff --git a/centipede/input_metadata_store.cc b/centipede/input_metadata_store.cc new file mode 100644 index 0000000..ae949b5 --- /dev/null +++ b/centipede/input_metadata_store.cc
@@ -0,0 +1,86 @@ +// 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/input_metadata_store.h" + +#include <algorithm> +#include <cstddef> +#include <filesystem> // NOLINT +#include <string> +#include <string_view> +#include <vector> + +#include "absl/types/span.h" +#include "./centipede/environment.h" +#include "./centipede/runner_result.h" +#include "./common/defs.h" +#include "./common/hash.h" +#include "./common/logging.h" +#include "./common/remote_file.h" + +namespace fuzztest::internal { +namespace { + +std::string MetadataDir(const Environment& env) { + if (env.fuzztest_persistent_metadata_root.empty()) return ""; + return (std::filesystem::path(env.fuzztest_persistent_metadata_root) / + env.fuzztest_binary_identifier / env.test_name) + .string(); +} + +std::string MetadataPath(std::string_view dir, ByteSpan input) { + return (std::filesystem::path(dir) / Hash(input)).string(); +} + +} // namespace + +InputMetadataStore::InputMetadataStore(const Environment& env) + : dir_(MetadataDir(env)) {} + +std::vector<ByteArray> InputMetadataStore::Load( + absl::Span<const ByteSpan> inputs) const { + if (!enabled()) return {}; + std::vector<ByteArray> metadata(inputs.size()); + for (size_t i = 0; i < inputs.size(); ++i) { + const std::string path = MetadataPath(dir_, inputs[i]); + if (!RemotePathExists(path)) continue; + FUZZTEST_CHECK_OK(RemoteFileGetContents(path, metadata[i])) + << "Failed to read the persistent input metadata from " << path; + } + return metadata; +} + +void InputMetadataStore::Save(absl::Span<const ByteSpan> inputs, + const BatchResult& batch_result) { + if (!enabled()) return; + const size_t num_results = + std::min({inputs.size(), batch_result.num_outputs_read(), + batch_result.results().size()}); + for (size_t i = 0; i < num_results; ++i) { + const ByteArray& metadata = + batch_result.results()[i].metadata().persistent_data; + if (metadata.empty()) continue; + if (!dir_created_) { + FUZZTEST_CHECK_OK(RemoteMkdir(dir_)) + << "Failed to create the persistent input metadata directory " + << dir_; + dir_created_ = true; + } + const std::string path = MetadataPath(dir_, inputs[i]); + FUZZTEST_CHECK_OK(RemoteFileSetContents(path, metadata)) + << "Failed to write the persistent input metadata to " << path; + } +} + +} // namespace fuzztest::internal
diff --git a/centipede/input_metadata_store.h b/centipede/input_metadata_store.h new file mode 100644 index 0000000..2ac53e6 --- /dev/null +++ b/centipede/input_metadata_store.h
@@ -0,0 +1,72 @@ +// 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 storage of persistent input metadata. +// +// Persistent input metadata is opaque data that the test attaches to an input +// when executing it (see `ExecutionMetadata::persistent_data`). The engine +// stores it per input and passes it back to the test before the next execution +// of the same input. The engine never interprets it. +// +// The metadata of an input is stored in the file +// +// <fuzztest_persistent_metadata_root>/<fuzztest_binary_identifier>/ +// <test_name>/<hash> +// +// where <hash> is `Hash()` of the input bytes. + +#ifndef FUZZTEST_CENTIPEDE_INPUT_METADATA_STORE_H_ +#define FUZZTEST_CENTIPEDE_INPUT_METADATA_STORE_H_ + +#include <string> +#include <vector> + +#include "absl/types/span.h" +#include "./centipede/environment.h" +#include "./centipede/runner_result.h" +#include "./common/defs.h" + +namespace fuzztest::internal { + +class InputMetadataStore { + public: + // The store is enabled iff `env.fuzztest_persistent_metadata_root` is + // non-empty. + explicit InputMetadataStore(const Environment& env); + + bool enabled() const { return !dir_.empty(); } + + // Returns the directory with the metadata files, or empty if disabled. + const std::string& dir() const { return dir_; } + + // Returns the stored metadata of each of `inputs`, in the same order. The + // metadata of an input without stored metadata is empty. Returns an empty + // vector if the store is disabled. Crashes on I/O errors. + std::vector<ByteArray> Load(absl::Span<const ByteSpan> inputs) const; + + // Stores the persistent metadata in the results of `batch_result` that were + // read after executing `inputs`. Results without persistent metadata leave + // the stored metadata of their inputs unchanged. No-op if the store is + // disabled. Crashes on I/O errors. + void Save(absl::Span<const ByteSpan> inputs, const BatchResult& batch_result); + + private: + // Empty if the store is disabled. + const std::string dir_; + bool dir_created_ = false; +}; + +} // namespace fuzztest::internal + +#endif // FUZZTEST_CENTIPEDE_INPUT_METADATA_STORE_H_
diff --git a/centipede/input_metadata_store_test.cc b/centipede/input_metadata_store_test.cc new file mode 100644 index 0000000..a605f4f --- /dev/null +++ b/centipede/input_metadata_store_test.cc
@@ -0,0 +1,155 @@ +// 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/input_metadata_store.h" + +#include <cstddef> +#include <filesystem> // NOLINT +#include <string> +#include <vector> + +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "./centipede/environment.h" +#include "./centipede/runner_result.h" +#include "./common/defs.h" +#include "./common/hash.h" +#include "./common/remote_file.h" +#include "./common/test_util.h" + +namespace fuzztest::internal { +namespace { + +using ::testing::ElementsAre; +using ::testing::IsEmpty; + +Environment EnvWithRoot(const std::string& root) { + Environment env; + env.fuzztest_persistent_metadata_root = root; + env.fuzztest_binary_identifier = "some/binary"; + env.test_name = "Suite.Test"; + return env; +} + +// Saves to `store` the results of executing `inputs`, with `metadata[i]` as the +// persistent metadata of the result of `inputs[i]`. Only the first +// `num_outputs_read` results count as read. +void SaveResults(InputMetadataStore& store, const std::vector<ByteSpan>& inputs, + const std::vector<ByteArray>& metadata, + size_t num_outputs_read) { + BatchResult batch_result; + batch_result.ClearAndResize(metadata.size()); + for (size_t i = 0; i < metadata.size(); ++i) { + batch_result.results()[i].metadata().persistent_data = metadata[i]; + } + batch_result.num_outputs_read() = num_outputs_read; + store.Save(inputs, batch_result); +} + +void SaveResults(InputMetadataStore& store, const std::vector<ByteSpan>& inputs, + const std::vector<ByteArray>& metadata) { + SaveResults(store, inputs, metadata, metadata.size()); +} + +TEST(InputMetadataStore, IsDisabledWithoutARoot) { + const Environment env = EnvWithRoot(""); + InputMetadataStore store(env); + const ByteArray input = {1}; + + EXPECT_FALSE(store.enabled()); + EXPECT_THAT(store.Load({input}), IsEmpty()); + // Must not crash or write anything. + SaveResults(store, {input}, {{7}}); +} + +TEST(InputMetadataStore, UsesAPerBinaryAndPerTestDirectory) { + const Environment env = EnvWithRoot("/root"); + InputMetadataStore store(env); + + EXPECT_TRUE(store.enabled()); + EXPECT_EQ(store.dir(), "/root/some/binary/Suite.Test"); +} + +TEST(InputMetadataStore, LoadsWhatWasSavedForTheSameInputBytes) { + TempDir temp_dir{test_info_->name()}; + const Environment env = EnvWithRoot(temp_dir.path().string()); + const ByteArray in0 = {1, 2}; + const ByteArray in1 = {3}; + const ByteArray in2 = {4, 5, 6}; + const ByteArray metadata0 = {'a', 0, 'b'}; + const ByteArray metadata2 = {'c'}; + + { + InputMetadataStore store(env); + // Nothing is stored yet. + EXPECT_THAT(store.Load({in0, in1, in2}), + ElementsAre(IsEmpty(), IsEmpty(), IsEmpty())); + // Input 1 returns no persistent metadata. + SaveResults(store, {in0, in1, in2}, {metadata0, {}, metadata2}); + } + + // A new store (e.g. of a later run) sees the stored metadata, keyed by the + // input bytes and regardless of the order. + InputMetadataStore store(env); + EXPECT_THAT(store.Load({in2, in1, in0}), + ElementsAre(metadata2, IsEmpty(), metadata0)); + EXPECT_TRUE(RemotePathExists( + (std::filesystem::path(store.dir()) / Hash(in0)).string())); + EXPECT_FALSE(RemotePathExists( + (std::filesystem::path(store.dir()) / Hash(in1)).string())); +} + +TEST(InputMetadataStore, KeepsStoredMetadataWhenAResultHasNone) { + TempDir temp_dir{test_info_->name()}; + const Environment env = EnvWithRoot(temp_dir.path().string()); + InputMetadataStore store(env); + const ByteArray input = {1, 2}; + const ByteArray metadata = {'a'}; + + SaveResults(store, {input}, {metadata}); + SaveResults(store, {input}, {{}}); + + EXPECT_THAT(store.Load({input}), ElementsAre(metadata)); +} + +TEST(InputMetadataStore, OverwritesStoredMetadataWithNewMetadata) { + TempDir temp_dir{test_info_->name()}; + const Environment env = EnvWithRoot(temp_dir.path().string()); + InputMetadataStore store(env); + const ByteArray input = {1, 2}; + const ByteArray new_metadata = {'n', 'e', 'w'}; + + SaveResults(store, {input}, {{'o', 'l', 'd'}}); + SaveResults(store, {input}, {new_metadata}); + + EXPECT_THAT(store.Load({input}), ElementsAre(new_metadata)); +} + +TEST(InputMetadataStore, SavesOnlyTheResultsThatWereRead) { + TempDir temp_dir{test_info_->name()}; + const Environment env = EnvWithRoot(temp_dir.path().string()); + InputMetadataStore store(env); + const ByteArray in0 = {1}; + const ByteArray in1 = {2}; + const ByteArray metadata0 = {'a'}; + + // The second input was not executed (e.g. the first one crashed after its + // result was written), so its result slot must be ignored. + SaveResults(store, {in0, in1}, {metadata0, {'x'}}, /*num_outputs_read=*/1); + + EXPECT_THAT(store.Load({in0, in1}), ElementsAre(metadata0, IsEmpty())); +} + +} // namespace +} // namespace fuzztest::internal
diff --git a/centipede/runner.cc b/centipede/runner.cc index 57147d7..e588dc5 100644 --- a/centipede/runner.cc +++ b/centipede/runner.cc
@@ -374,6 +374,10 @@ return DeserializeInput({0}); } +void RunnerCallbacks::SetPersistentMetadata(void* input, ByteSpan metadata) {} + +ByteArray RunnerCallbacks::TakePersistentMetadata(void* input) { return {}; } + void* RunnerCallbacks::CrossOver(void* origin, const ExecutionMetadata& origin_metadata, void* other, @@ -805,6 +809,8 @@ const int old_traced = CentipedeSetCurrentThreadTraced(/*traced=*/1); RunOneInput(input->content, runner_ctx->callbacks); CentipedeSetCurrentThreadTraced(old_traced); + ByteArray persistent_metadata = + runner_ctx->callbacks.TakePersistentMetadata(input->content); { LockGuard lock(state->execution_result_override_mu); bool has_overridden_execution_result = false; @@ -824,11 +830,13 @@ }; sink->EmitCoverageFeatures(sink->ctx, &features); input->metadata = result.metadata(); + input->metadata.persistent_data = std::move(persistent_metadata); return; } } SanCovRuntimeEmitFeatures(sink); input->metadata = SanCovRuntimeGetExecutionMetadata(); + input->metadata.persistent_data = std::move(persistent_metadata); } void DeserializeInputContent(FuzzTestAdapterCtx* ctx, @@ -843,10 +851,22 @@ sink->Emit(sink->ctx, reinterpret_cast<FuzzTestInputHandle>(input)); } -void UpdateInputMetadata(FuzzTestAdapterCtx* ctx, const FuzzTestBytesView* view, +void UpdateInputMetadata(FuzzTestAdapterCtx* ctx, + const FuzzTestInputMetadataView* view, FuzzTestInputHandle handle) { auto* input = reinterpret_cast<Input*>(handle); - input->metadata.cmp_data = {view->data, view->data + view->size}; + switch (view->type) { + case kFuzzTestInputMetadataMutationHints: + input->metadata.cmp_data.assign(view->bytes.data, + view->bytes.data + view->bytes.size); + break; + case kFuzzTestInputMetadataPersistent: { + auto* runner_ctx = reinterpret_cast<RunnerAdapterCtx*>(ctx); + runner_ctx->callbacks.SetPersistentMetadata( + input->content, ByteSpan{view->bytes.data, view->bytes.size}); + break; + } + } } void SerializeInputContent(FuzzTestAdapterCtx* ctx, FuzzTestInputHandle handle, @@ -863,13 +883,20 @@ } void SerializeInputMetadata(FuzzTestAdapterCtx* ctx, FuzzTestInputHandle handle, - const FuzzTestBytesSink* sink) { + const FuzzTestInputMetadataSink* sink) { auto* input = reinterpret_cast<Input*>(handle); - const auto input_bytes = FuzzTestBytesView{ - reinterpret_cast<const uint8_t*>(input->metadata.cmp_data.data()), - input->metadata.cmp_data.size(), + const auto mutation_hints = FuzzTestInputMetadataView{ + kFuzzTestInputMetadataMutationHints, + {input->metadata.cmp_data.data(), input->metadata.cmp_data.size()}, }; - sink->Emit(sink->ctx, &input_bytes); + sink->Emit(sink->ctx, &mutation_hints); + if (input->metadata.persistent_data.empty()) return; + const auto persistent = FuzzTestInputMetadataView{ + kFuzzTestInputMetadataPersistent, + {input->metadata.persistent_data.data(), + input->metadata.persistent_data.size()}, + }; + sink->Emit(sink->ctx, &persistent); } void FreeInput(FuzzTestAdapterCtx* ctx, FuzzTestInputHandle handle) {
diff --git a/centipede/runner_interface.h b/centipede/runner_interface.h index 4a22b2d..bdfd954 100644 --- a/centipede/runner_interface.h +++ b/centipede/runner_interface.h
@@ -189,6 +189,14 @@ virtual void* DeserializeInput(ByteSpan bytes) = 0; // Called when the runner is done with `input`. virtual void FreeInput(void* input) = 0; + // Called before `Execute(input)` with the persistent metadata that the + // engine has stored for `input`, if any. `metadata` does not outlive the + // call. The default implementation ignores it. + virtual void SetPersistentMetadata(void* input, ByteSpan metadata); + // Called after `Execute(input)`. Returns the persistent metadata for the + // engine to store for `input`, or empty to store nothing. The default + // implementation returns empty. + virtual ByteArray TakePersistentMetadata(void* input); virtual ~RunnerCallbacks() = default; };
diff --git a/centipede/runner_request.cc b/centipede/runner_request.cc index 9ce49ce..48a0779 100644 --- a/centipede/runner_request.cc +++ b/centipede/runner_request.cc
@@ -34,16 +34,25 @@ kTagNumMutants, kTagExecutionMetadata, kTagDataInput, + kTagPersistentMetadata, }; // Writes `inputs` to `blobseq`, returns the number of inputs written. +// `persistent_metadata` is either empty or has the same size as `inputs`; a +// non-empty `persistent_metadata[i]` is written before `inputs[i]`. static size_t WriteInputs(absl::Span<const ByteSpan> inputs, + absl::Span<const ByteSpan> persistent_metadata, 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()})) + for (size_t i = 0; i < inputs.size(); ++i) { + if (i < persistent_metadata.size() && !persistent_metadata[i].empty() && + !blobseq.Write({kTagPersistentMetadata, persistent_metadata[i].size(), + persistent_metadata[i].data()})) { + return result; + } + if (!blobseq.Write({kTagDataInput, inputs[i].size(), inputs[i].data()})) return result; ++result; } @@ -78,8 +87,18 @@ size_t RequestExecution(absl::Span<const ByteSpan> inputs, BlobSequence& blobseq) { + return RequestExecution(inputs, /*persistent_metadata=*/{}, blobseq); +} + +size_t RequestExecution(absl::Span<const ByteSpan> inputs, + absl::Span<const ByteSpan> persistent_metadata, + BlobSequence& blobseq) { + if (!persistent_metadata.empty() && + persistent_metadata.size() != inputs.size()) { + return 0; + } if (!blobseq.Write({kTagExecution, 0, nullptr})) return 0; - return WriteInputs(inputs, blobseq); + return WriteInputs(inputs, persistent_metadata, blobseq); } size_t RequestMutation(size_t num_mutants, @@ -114,6 +133,10 @@ return true; } +bool IsPersistentMetadata(Blob blob) { + return blob.tag == kTagPersistentMetadata; +} + bool IsDataInput(Blob blob) { return blob.tag == kTagDataInput; } } // namespace fuzztest::internal
diff --git a/centipede/runner_request.h b/centipede/runner_request.h index 01132c4..590d29b 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 also sends the persistent input metadata of the inputs: +// a non-empty `persistent_metadata[i]` is sent as a separate blob immediately +// before `inputs[i]`. `persistent_metadata` must be empty or have the same +// size as `inputs`. Without any non-empty persistent metadata, the request is +// byte-identical to the one sent by the overload above. +// Returns the number of sent inputs. +size_t RequestExecution(absl::Span<const ByteSpan> inputs, + absl::Span<const ByteSpan> persistent_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, @@ -63,6 +73,10 @@ // execution metadata. bool IsExecutionMetadata(Blob blob, ExecutionMetadata &metadata); +// Returns true iff `blob` indicates the persistent metadata of the data input +// that follows it in an execution request. +bool IsPersistentMetadata(Blob blob); + // Returns true iff `blob` indicates a data input. bool IsDataInput(Blob blob);
diff --git a/centipede/runner_request_test.cc b/centipede/runner_request_test.cc new file mode 100644 index 0000000..19a83d0 --- /dev/null +++ b/centipede/runner_request_test.cc
@@ -0,0 +1,127 @@ +// 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/runner_request.h" + +#include <cstddef> +#include <cstdint> +#include <vector> + +#include "gtest/gtest.h" +#include "./centipede/shared_memory_blob_sequence.h" +#include "./common/defs.h" + +namespace fuzztest::internal { +namespace { + +ByteArray ToByteArray(Blob blob) { + return ByteArray(blob.data, blob.data + blob.size); +} + +TEST(RequestExecution, WithoutPersistentMetadataIsByteIdentical) { + const ByteArray in0 = {10, 11}; + const ByteArray in1 = {20}; + const std::vector<ByteSpan> inputs = {in0, in1}; + + std::vector<uint8_t> plain(512, 0); + std::vector<uint8_t> no_metadata(512, 0); + std::vector<uint8_t> all_empty_metadata(512, 0); + BlobSequence plain_seq(plain.data(), plain.size()); + BlobSequence no_metadata_seq(no_metadata.data(), no_metadata.size()); + BlobSequence all_empty_metadata_seq(all_empty_metadata.data(), + all_empty_metadata.size()); + + ASSERT_EQ(RequestExecution(inputs, plain_seq), 2); + ASSERT_EQ( + RequestExecution(inputs, /*persistent_metadata=*/{}, no_metadata_seq), 2); + ASSERT_EQ(RequestExecution(inputs, std::vector<ByteSpan>{{}, {}}, + all_empty_metadata_seq), + 2); + + EXPECT_EQ(plain, no_metadata); + EXPECT_EQ(plain, all_empty_metadata); +} + +TEST(RequestExecution, WritesPersistentMetadataBeforeItsInput) { + const ByteArray in0 = {10, 11}; + const ByteArray in1 = {20}; + const ByteArray in2 = {30, 31, 32}; + const ByteArray metadata0 = {1, 2}; + const ByteArray metadata2 = {3}; + const std::vector<ByteSpan> inputs = {in0, in1, in2}; + // Input 1 has no persistent metadata. + const std::vector<ByteSpan> persistent_metadata = {metadata0, {}, metadata2}; + + std::vector<uint8_t> buffer(1024, 0); + BlobSequence blobseq(buffer.data(), buffer.size()); + ASSERT_EQ(RequestExecution(inputs, persistent_metadata, blobseq), 3); + blobseq.Reset(); + + EXPECT_TRUE(IsExecutionRequest(blobseq.Read())); + size_t num_inputs = 0; + ASSERT_TRUE(IsNumInputs(blobseq.Read(), num_inputs)); + EXPECT_EQ(num_inputs, 3); + + const Blob metadata0_blob = blobseq.Read(); + ASSERT_TRUE(IsPersistentMetadata(metadata0_blob)); + EXPECT_FALSE(IsDataInput(metadata0_blob)); + EXPECT_EQ(ToByteArray(metadata0_blob), metadata0); + const Blob in0_blob = blobseq.Read(); + ASSERT_TRUE(IsDataInput(in0_blob)); + EXPECT_EQ(ToByteArray(in0_blob), in0); + + const Blob in1_blob = blobseq.Read(); + EXPECT_FALSE(IsPersistentMetadata(in1_blob)); + ASSERT_TRUE(IsDataInput(in1_blob)); + EXPECT_EQ(ToByteArray(in1_blob), in1); + + const Blob metadata2_blob = blobseq.Read(); + ASSERT_TRUE(IsPersistentMetadata(metadata2_blob)); + EXPECT_EQ(ToByteArray(metadata2_blob), metadata2); + const Blob in2_blob = blobseq.Read(); + ASSERT_TRUE(IsDataInput(in2_blob)); + EXPECT_EQ(ToByteArray(in2_blob), in2); + + EXPECT_FALSE(blobseq.Read().IsValid()); +} + +TEST(RequestExecution, RejectsPersistentMetadataOfMismatchedSize) { + const ByteArray in0 = {10, 11}; + const ByteArray in1 = {20}; + const ByteArray metadata0 = {1, 2}; + std::vector<uint8_t> buffer(512, 0); + BlobSequence blobseq(buffer.data(), buffer.size()); + + EXPECT_EQ(RequestExecution({in0, in1}, {metadata0}, blobseq), 0); +} + +TEST(RequestExecution, DoesNotCountAnInputWhoseDataDoesNotFit) { + const ByteArray in0 = {10, 11}; + const ByteArray metadata0 = {1, 2}; + // The size of a request with just the metadata and the input. + const size_t request_size = [&] { + std::vector<uint8_t> buffer(1024, 0); + BlobSequence blobseq(buffer.data(), buffer.size()); + RequestExecution({in0}, {metadata0}, blobseq); + return blobseq.offset(); + }(); + + // One byte short: the metadata fits, but the input does not. + std::vector<uint8_t> buffer(request_size - 1, 0); + BlobSequence blobseq(buffer.data(), buffer.size()); + EXPECT_EQ(RequestExecution({in0}, {metadata0}, blobseq), 0); +} + +} // namespace +} // namespace fuzztest::internal
diff --git a/centipede/runner_result.cc b/centipede/runner_result.cc index 0220d52..637c726 100644 --- a/centipede/runner_result.cc +++ b/centipede/runner_result.cc
@@ -46,6 +46,9 @@ kTagHasCustomMutator, kTagMutantOrigin, kTagMutant, + + // Appended after the mutation result tags to keep the existing tag values. + kTagPersistentMetadata, }; } // namespace @@ -72,13 +75,20 @@ bool BatchResult::WriteMetadata(const ExecutionMetadata &metadata, BlobSequence &blobseq) { - return WriteMetadata(metadata.cmp_data, blobseq); + return WriteMetadata(metadata.cmp_data, blobseq) && + WritePersistentMetadata(metadata.persistent_data, blobseq); } bool BatchResult::WriteMetadata(ByteSpan bytes, BlobSequence &blobseq) { return blobseq.Write({kTagMetadata, bytes.size(), bytes.data()}); } +bool BatchResult::WritePersistentMetadata(ByteSpan bytes, + BlobSequence& blobseq) { + if (bytes.empty()) return true; + return blobseq.Write({kTagPersistentMetadata, bytes.size(), bytes.data()}); +} + // The sequence we expect to receive is // InputBegin, Features, Stats, InputEnd, InputBegin, ... // with a total of results().size() tuples (InputBegin ... InputEnd). @@ -113,6 +123,12 @@ blob.data, blob.data + blob.size); continue; } + if (blob.tag == kTagPersistentMetadata) { + if (current_execution_result == nullptr) return false; + current_execution_result->metadata().persistent_data.assign( + blob.data, blob.data + blob.size); + continue; + } if (blob.tag == kTagStats) { if (current_execution_result == nullptr) return false; if (blob.size != sizeof(ExecutionResult::Stats)) return false;
diff --git a/centipede/runner_result.h b/centipede/runner_result.h index e113c12..5ff1be9 100644 --- a/centipede/runner_result.h +++ b/centipede/runner_result.h
@@ -129,15 +129,22 @@ // Writes unit execution stats. static bool WriteStats(const ExecutionResult::Stats& stats, BlobSequence& blobseq); - // Writes the execution `metadata` to `blobseq`. + // Writes the execution `metadata` (the mutation hints and, if non-empty, the + // persistent metadata) to `blobseq`. // Returns true iff successful. static bool WriteMetadata(const ExecutionMetadata& metadata, BlobSequence& blobseq); - // Writes the execution `metadata` to `blobseq` as raw bytes. + // Writes the mutation hints of the execution metadata to `blobseq` as raw + // bytes. // Returns true iff successful. static bool WriteMetadata(ByteSpan bytes, BlobSequence& blobseq); + // Writes the persistent input metadata to `blobseq` as raw bytes. Writes + // nothing if `bytes` is empty. + // Returns true iff successful. + static bool WritePersistentMetadata(ByteSpan bytes, BlobSequence& blobseq); + // Reads everything written by the runner to `blobseq` into `this`. // Returns true iff successful. // When running N inputs, ClearAndResize(N) must be called before Read().
diff --git a/centipede/runner_result_test.cc b/centipede/runner_result_test.cc index 38d6aa3..1857599 100644 --- a/centipede/runner_result_test.cc +++ b/centipede/runner_result_test.cc
@@ -38,6 +38,7 @@ namespace { using ::testing::ElementsAre; +using ::testing::IsEmpty; TEST(ExecutionResult, WriteThenRead) { auto buffer = std::make_unique<uint8_t[]>(1000); @@ -270,5 +271,50 @@ [](ByteSpan, ByteSpan) {})); } +TEST(ExecutionResult, ReadsPersistentMetadataSeparatelyFromMutationHints) { + auto buffer = std::make_unique<uint8_t[]>(1000); + BlobSequence blobseq(buffer.get(), 1000); + + ExecutionMetadata metadata; + metadata.cmp_data = {2, 1, 2, 3, 4}; + metadata.persistent_data = {'p', 0, 'q'}; + const ByteArray hints_only = {5, 6}; + + // Input 0 has both types, input 1 has only mutation hints. + EXPECT_TRUE(BatchResult::WriteInputBegin(blobseq)); + EXPECT_TRUE(BatchResult::WriteMetadata(metadata, blobseq)); + EXPECT_TRUE(BatchResult::WriteInputEnd(blobseq)); + EXPECT_TRUE(BatchResult::WriteInputBegin(blobseq)); + EXPECT_TRUE(BatchResult::WriteMetadata(hints_only, blobseq)); + EXPECT_TRUE(BatchResult::WritePersistentMetadata({}, blobseq)); + EXPECT_TRUE(BatchResult::WriteInputEnd(blobseq)); + blobseq.Reset(); + + BatchResult batch_result; + batch_result.ClearAndResize(2); + EXPECT_TRUE(batch_result.Read(blobseq)); + ASSERT_EQ(batch_result.num_outputs_read(), 2); + EXPECT_EQ(batch_result.results()[0].metadata().cmp_data, metadata.cmp_data); + EXPECT_EQ(batch_result.results()[0].metadata().persistent_data, + metadata.persistent_data); + EXPECT_EQ(batch_result.results()[1].metadata().cmp_data, hints_only); + EXPECT_THAT(batch_result.results()[1].metadata().persistent_data, IsEmpty()); +} + +TEST(ExecutionResult, EmptyPersistentMetadataDoesNotChangeTheWrittenBytes) { + std::vector<uint8_t> without(256, 0); + std::vector<uint8_t> with_empty(256, 0); + BlobSequence without_seq(without.data(), without.size()); + BlobSequence with_empty_seq(with_empty.data(), with_empty.size()); + const ByteArray hints = {13, 14}; + + EXPECT_TRUE(BatchResult::WriteMetadata(hints, without_seq)); + EXPECT_TRUE(BatchResult::WriteMetadata(hints, with_empty_seq)); + EXPECT_TRUE(BatchResult::WritePersistentMetadata({}, with_empty_seq)); + + EXPECT_EQ(without_seq.offset(), with_empty_seq.offset()); + EXPECT_EQ(without, with_empty); +} + } // namespace } // namespace fuzztest::internal
diff --git a/e2e_tests/functional_test.cc b/e2e_tests/functional_test.cc index 13a2bfb..e59aad0 100644 --- a/e2e_tests/functional_test.cc +++ b/e2e_tests/functional_test.cc
@@ -916,6 +916,75 @@ EXPECT_THAT_LOG(std_err, HasSubstr("will not limit jobs")); } +TEST_F(GenericCommandLineInterfaceTest, RejectsInvalidDurationFlagUsage) { + { + auto [status, std_out, std_err] = + RunWith(/*flags=*/{{"duration", "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("duration requires one of"), HasSubstr("fuzz"), + HasSubstr("replay_corpus"), HasSubstr("record"), + HasSubstr("diff"))); + } + for (const auto& flags : + std::vector<absl::flat_hash_map<std::string, std::string>>{ + {{"fuzz", "*"}, {"duration", "0s"}}, + {{"record", "*"}, {"duration", "-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("duration must be positive")); + } +} + +TEST_F(GenericCommandLineInterfaceTest, RejectsMutuallyExclusiveModeFlags) { + for (const auto& flags : + std::vector<absl::flat_hash_map<std::string, std::string>>{ + {{"record", "*"}, {"diff", "*"}}, + {{"fuzz", "*"}, {"record", "*"}}, + {{"replay_corpus", "*"}, {"diff", "*"}}, + {{"fuzz", "*"}, {"replay_corpus", "*"}}, + {{"fuzz_for", "1s"}, {"replay_corpus", "*"}}, + {{"fuzz", "*"}, {"replay_corpus_for", "1s"}}, + {{"fuzz_for", "1s"}, {"replay_corpus_for", "1s"}}, + {{"fuzz_for", "1s"}, {"record", "*"}}, + {{"replay_corpus_for", "1s"}, {"diff", "*"}}, + }) { + 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, + RejectsCombiningDurationOrDiffFlagsWithLegacyDurationFlags) { + for (const auto& flags : + std::vector<absl::flat_hash_map<std::string, std::string>>{ + {{"fuzz", "*"}, {"duration", "1s"}, {"fuzz_for", "1s"}}, + {{"fuzz", "*"}, {"duration", "1s"}, {"fuzz_for", "inf"}}, + {{"replay_corpus", "*"}, + {"duration", "1s"}, + {"replay_corpus_for", "1s"}}, + {{"replay_corpus", "*"}, + {"duration", "1s"}, + {"replay_corpus_for", "0s"}}, + {{"record", "*"}, {"fuzz_for", "0s"}}, + {{"diff", "*"}, {"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 @@ -1465,6 +1534,56 @@ EXPECT_THAT(status, Eq(ExitCode(0))); } +TEST_F(FuzzingModeCommandLineInterfaceTest, + FuzzWildcardWithDurationRunsOnlyFuzzTestsAndRespectsFilter) { + { + auto [status, std_out, std_err] = RunWith( + {{"fuzz", "*"}, {"duration", "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", "*"}, {"duration", "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, + ReplayCorpusWildcardWithDurationRunsOnlyFuzzTests) { + TempDir temp_dir; + const std::string corpus_database = temp_dir.path() / "corpus_database"; + auto [status, std_out, std_err] = RunWith( + {{"replay_corpus", "*"}, + {"duration", "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/e2e_tests/testdata/BUILD b/e2e_tests/testdata/BUILD index 439f0fc..72078a9 100644 --- a/e2e_tests/testdata/BUILD +++ b/e2e_tests/testdata/BUILD
@@ -138,6 +138,7 @@ deps = [ "@com_google_fuzztest//fuzztest", "@com_google_fuzztest//fuzztest:fuzztest_gtest_main", + "@com_google_fuzztest//fuzztest:record_or_diff", ], )
diff --git a/e2e_tests/testdata/CMakeLists.txt b/e2e_tests/testdata/CMakeLists.txt index dc21568..c0daae5 100644 --- a/e2e_tests/testdata/CMakeLists.txt +++ b/e2e_tests/testdata/CMakeLists.txt
@@ -87,6 +87,11 @@ unit_test_and_fuzz_tests.stripped unit_test_and_fuzz_tests.cc ) +target_link_libraries( + unit_test_and_fuzz_tests.stripped + PUBLIC + fuzztest::record_or_diff +) link_fuzztest(unit_test_and_fuzz_tests.stripped) set_target_properties( unit_test_and_fuzz_tests.stripped
diff --git a/e2e_tests/testdata/unit_test_and_fuzz_tests.cc b/e2e_tests/testdata/unit_test_and_fuzz_tests.cc index 4ae15eb..070642c 100644 --- a/e2e_tests/testdata/unit_test_and_fuzz_tests.cc +++ b/e2e_tests/testdata/unit_test_and_fuzz_tests.cc
@@ -12,17 +12,28 @@ // See the License for the specific language governing permissions and // limitations under the License. +#include <cstdlib> + #include "gtest/gtest.h" #include "./fuzztest/fuzztest.h" +#include "./fuzztest/record_or_diff.h" namespace { TEST(UnitTest, AlwaysPasses) {} -void AlwaysPasses(int) {} +void AlwaysPasses(int x) { + const int mask = + std::getenv("FUZZTEST_TEST_DIFF_PERTURB_FIRST") != nullptr ? 1 : 0; + fuzztest::RecordOrDiff(x ^ mask, "first_value"); +} FUZZ_TEST(FuzzTest, AlwaysPasses); -void AlsoAlwaysPasses(int) {} +void AlsoAlwaysPasses(int x) { + const int mask = + std::getenv("FUZZTEST_TEST_DIFF_PERTURB_SECOND") != nullptr ? 1 : 0; + fuzztest::RecordOrDiff(x ^ mask, "second_value"); +} FUZZ_TEST(FuzzTest, AlsoAlwaysPasses); } // namespace
diff --git a/framework_shared/internal/execution_metadata.h b/framework_shared/internal/execution_metadata.h index e7d860f..7fa7e09 100644 --- a/framework_shared/internal/execution_metadata.h +++ b/framework_shared/internal/execution_metadata.h
@@ -13,7 +13,8 @@ // limitations under the License. // Abstraction of metadata collected from executions that does not -// contribute to coverage but can be useful in mutation. +// contribute to coverage: hints that can be useful in mutation, and opaque +// data that the engine persists per input for the test framework. // // This library is for both engine and runner. @@ -42,6 +43,11 @@ // * `value0` (`size` bytes) // * `value1` (`size` bytes) ByteArray cmp_data; + + // Persistent input metadata: opaque bytes that the test framework attaches + // to an input, for the engine to store and pass back before a later + // execution of the same input. Empty if there is none. + ByteArray persistent_data; }; } // namespace fuzztest::internal
diff --git a/fuzztest/BUILD b/fuzztest/BUILD index 78abaea..5c0a20b 100644 --- a/fuzztest/BUILD +++ b/fuzztest/BUILD
@@ -109,6 +109,40 @@ ) 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", + "@abseil-cpp//absl/time", + "@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"], @@ -136,6 +170,7 @@ "@abseil-cpp//absl/strings:str_format", "@abseil-cpp//absl/time", "@com_google_fuzztest//common:logging", + "@com_google_fuzztest//common:remote_file", "@com_google_fuzztest//fuzztest/internal:configuration", "@com_google_fuzztest//fuzztest/internal:flag_name", "@com_google_fuzztest//fuzztest/internal:googletest_adaptor",
diff --git a/fuzztest/CMakeLists.txt b/fuzztest/CMakeLists.txt index 75738a3..af566f9 100644 --- a/fuzztest/CMakeLists.txt +++ b/fuzztest/CMakeLists.txt
@@ -213,6 +213,7 @@ absl::str_format absl::time fuzztest::common_logging + fuzztest::remote_file fuzztest::configuration fuzztest::flag_name fuzztest::googletest_adaptor @@ -253,3 +254,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..bc0e3f9 100644 --- a/fuzztest/init_fuzztest.cc +++ b/fuzztest/init_fuzztest.cc
@@ -31,6 +31,7 @@ #include "absl/strings/strip.h" #include "absl/time/time.h" #include "./common/logging.h" +#include "./common/remote_file.h" #include "./fuzztest/internal/configuration.h" #include "./fuzztest/internal/flag_name.h" #include "./fuzztest/internal/googletest_adaptor.h" @@ -55,20 +56,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 + "duration=<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 +111,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 +120,25 @@ "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 + "duration=<duration>` to bound the replay time; otherwise the entire " + "corpus " + "is replayed. In corpus replay mode the selected test replays the inputs " + "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 +148,22 @@ "value of --" FUZZTEST_FLAG_PREFIX "time_budget_type."); FUZZTEST_DEFINE_FLAG( + std::optional<absl::Duration>, duration, std::nullopt, + "The maximum duration for `--" FUZZTEST_FLAG_PREFIX + "fuzz`, `--" FUZZTEST_FLAG_PREFIX "replay_corpus`, `--" FUZZTEST_FLAG_PREFIX + "record`, or `--" FUZZTEST_FLAG_PREFIX + "diff`. 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."); + "duration, --" 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, @@ -211,6 +232,37 @@ "When used with --" FUZZTEST_FLAG_PREFIX "fuzz_for, regular tests also run by default."); +FUZZTEST_DEFINE_FLAG( + std::string, record, std::string(kUnspecified), + "Runs a single FUZZ_TEST, or all FUZZ_TESTs when set to `*`, in " + "corpus-replay baseline recording mode for `fuzztest::RecordOrDiff()`. " + "Target selection follows `--" FUZZTEST_FLAG_PREFIX + "replay_corpus` (full `Suite.Test`, unique substring, empty string when " + "there is a single FUZZ_TEST, or `*` for all FUZZ_TESTs matching " + "`--" GTEST_FLAG_PREFIX_ + "filter`). Can be combined with " + "`--" FUZZTEST_FLAG_PREFIX + "duration` to bound the duration. Requires " + "`--" FUZZTEST_FLAG_PREFIX + "corpus_database`" + "."); + +FUZZTEST_DEFINE_FLAG( + std::string, diff, std::string(kUnspecified), + "Runs a single FUZZ_TEST, or all FUZZ_TESTs when set to `*`, in " + "corpus-replay differential validation mode: compares the values passed to " + "`fuzztest::RecordOrDiff()` against the recorded baseline and fails on any " + "difference. Target selection follows `--" FUZZTEST_FLAG_PREFIX + "replay_corpus` (full `Suite.Test`, unique substring, empty string when " + "there is a single FUZZ_TEST, or `*` for all FUZZ_TESTs matching " + "`--" GTEST_FLAG_PREFIX_ + "filter`). Can be combined with " + "`--" FUZZTEST_FLAG_PREFIX + "duration` to bound the duration. Requires " + "`--" FUZZTEST_FLAG_PREFIX + "corpus_database`" + "."); + // Internal flags - not part of the user interface. // // These flags are meant to be set only by the parent controller process for its @@ -241,7 +293,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 "duration / --" FUZZTEST_FLAG_PREFIX + "fuzz_for / --" FUZZTEST_FLAG_PREFIX "replay_corpus_for with --time_budget_type set to total.") .OnUpdate([] { FUZZTEST_PRECONDITION( @@ -316,36 +369,92 @@ namespace { std::optional<absl::Duration> GetFuzzingTime() { + const bool has_fuzz_target = + absl::GetFlag(FUZZTEST_FLAG(fuzz)) != kUnspecified; + if (const std::optional<absl::Duration> duration = + absl::GetFlag(FUZZTEST_FLAG(duration)); + duration.has_value()) { + return has_fuzz_target ? 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> duration = + absl::GetFlag(FUZZTEST_FLAG(duration)); + duration.has_value()) { + return has_replay_target ? 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; + const bool has_record_target = + absl::GetFlag(FUZZTEST_FLAG(record)) != kUnspecified; + const bool has_diff_target = + absl::GetFlag(FUZZTEST_FLAG(diff)) != kUnspecified; + 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(); + + if (const std::optional<absl::Duration> duration = + absl::GetFlag(FUZZTEST_FLAG(duration)); + duration.has_value()) { + FUZZTEST_CHECK(has_fuzz_target || has_replay_target || has_record_target || + has_diff_target) + << "--" FUZZTEST_FLAG_PREFIX "duration requires one of --" + << FUZZTEST_FLAG_PREFIX "fuzz, --" FUZZTEST_FLAG_PREFIX + << "replay_corpus, --" FUZZTEST_FLAG_PREFIX "record, or --" + << FUZZTEST_FLAG_PREFIX "diff."; + FUZZTEST_CHECK(*duration > absl::ZeroDuration()) + << "--" FUZZTEST_FLAG_PREFIX "duration must be positive (got " + << absl::FormatDuration(*duration) << ")."; + FUZZTEST_CHECK(!legacy_fuzz_for_specified && !legacy_replay_for_specified) + << "--" FUZZTEST_FLAG_PREFIX "duration cannot be combined with --" + << FUZZTEST_FLAG_PREFIX "fuzz_for or --" FUZZTEST_FLAG_PREFIX + << "replay_corpus_for."; + } + + const int active_mode_families = + static_cast<int>(GetFuzzingTime().has_value()) + + static_cast<int>(GetReplayCorpusTime().has_value()) + + static_cast<int>(has_record_target) + static_cast<int>(has_diff_target); + FUZZTEST_CHECK(active_mode_families <= 1) + << "At most one of --" FUZZTEST_FLAG_PREFIX "fuzz / --" + << FUZZTEST_FLAG_PREFIX "fuzz_for, --" FUZZTEST_FLAG_PREFIX + << "replay_corpus / --" FUZZTEST_FLAG_PREFIX "replay_corpus_for, --" + << FUZZTEST_FLAG_PREFIX "record, and --" FUZZTEST_FLAG_PREFIX + << "diff may be specified at the same time."; + + FUZZTEST_CHECK(!(has_record_target || has_diff_target) || + (!legacy_fuzz_for_specified && !legacy_replay_for_specified)) + << "--" FUZZTEST_FLAG_PREFIX "record and --" FUZZTEST_FLAG_PREFIX + << "diff cannot be combined with --" FUZZTEST_FLAG_PREFIX + << "fuzz_for or --" FUZZTEST_FLAG_PREFIX "replay_corpus_for; use --" + << FUZZTEST_FLAG_PREFIX "duration instead."; } // Expands a leading `~/` to $HOME and, when running under a test, makes a @@ -363,27 +472,46 @@ return path; } +// Returns the directory where the baseline of `fuzztest::RecordOrDiff()` is +// stored for the given `workdir_root`. +std::string GetDiffBaselineRoot(absl::string_view workdir_root) { + return (std::filesystem::path(std::string(workdir_root)) / "baseline") + .string(); +} + 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(); const std::optional<absl::Duration> replay_corpus_time_limit = GetReplayCorpusTime(); + const bool is_record = absl::GetFlag(FUZZTEST_FLAG(record)) != kUnspecified; + const bool is_diff = absl::GetFlag(FUZZTEST_FLAG(diff)) != kUnspecified; + std::optional<absl::Duration> diff_or_record_time_limit; + if (is_record || is_diff) { + diff_or_record_time_limit = absl::GetFlag(FUZZTEST_FLAG(duration)) + .value_or(absl::InfiniteDuration()); + } + const std::optional<absl::Duration> replay_like_time_limit = + replay_corpus_time_limit.has_value() ? replay_corpus_time_limit + : diff_or_record_time_limit; const std::optional<std::string> override_fuzz_test = absl::GetFlag(FUZZTEST_FLAG(internal_override_fuzz_test)); const bool replay_coverage_inputs = - fuzzing_time_limit.has_value() || replay_corpus_time_limit.has_value(); + fuzzing_time_limit.has_value() || replay_like_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() ? absl::GetFlag(FUZZTEST_FLAG(internal_override_total_time_limit)) - : fuzzing_time_limit.has_value() ? *fuzzing_time_limit - : replay_corpus_time_limit.has_value() ? *replay_corpus_time_limit - : absl::ZeroDuration(); + : fuzzing_time_limit.has_value() ? *fuzzing_time_limit + : replay_like_time_limit.has_value() ? *replay_like_time_limit + : absl::ZeroDuration(); const internal::TimeBudgetType time_budget_type = override_fuzz_test.has_value() ? internal::TimeBudgetType::kTotal @@ -407,7 +535,7 @@ } std::string corpus_database = absl::GetFlag(FUZZTEST_FLAG(corpus_database)); corpus_database = NormalizeCorpusDatabasePath(std::move(corpus_database)); - return internal::Configuration{ + internal::Configuration configuration{ corpus_database, /*stats_root=*/"", /*workdir_root=*/"", @@ -420,7 +548,7 @@ reproduce_findings_as_separate_tests, replay_coverage_inputs, /*only_replay=*/ - replay_corpus_time_limit.has_value(), + replay_like_time_limit.has_value(), update_corpus_database, /*replay_in_single_process=*/false, absl::GetFlag(FUZZTEST_FLAG(execution_id)), @@ -436,6 +564,65 @@ absl::GetFlag(FUZZTEST_FLAG(internal_crashing_input_to_reproduce)), absl::GetFlag(FUZZTEST_FLAG(replay_crash_attempts)), }; + configuration.diff_mode = is_record ? internal::DiffMode::kRecord + : is_diff ? internal::DiffMode::kValidate + : internal::DiffMode::kNone; + if (is_record || is_diff) { + // The baseline is stored by the engine as the persistent metadata of the + // inputs. The engine is not aware of the record and diff modes: it stores + // whatever the test returns for an input, and passes it back before the + // next execution of the same input. + if (!configuration.workdir_root.empty()) { + configuration.persistent_metadata_root = + GetDiffBaselineRoot(configuration.workdir_root); + } + } + if (is_record && !configuration.continue_after_crash) { + // Keep recording after a crashing input so that every other input gets a + // baseline. The run still fails because of the crash. + absl::FPrintF(stderr, + "[.] --" FUZZTEST_FLAG_PREFIX + "record: continuing after crashes so that every input gets " + "a baseline.\n"); + configuration.continue_after_crash = true; + } + return configuration; +} + +// Validates the flags and the configuration for incremental differential +// fuzzing (`--[fuzztest_]record` / `--[fuzztest_]diff`). Must be called after +// the configuration is created from the flags, since some checks need the +// resolved corpus database and the binary identifier. No-op when the diff mode +// is not set. +void ValidateDiffModeConfiguration( + const internal::Configuration& configuration) { + if (configuration.diff_mode == internal::DiffMode::kNone) return; + const absl::string_view mode_flag = + configuration.diff_mode == internal::DiffMode::kRecord ? "record" + : "diff"; + FUZZTEST_CHECK(configuration.only_replay) + << "--" FUZZTEST_FLAG_PREFIX << mode_flag + << " requires corpus replay mode."; + FUZZTEST_CHECK(!configuration.corpus_database.empty()) + << "--" FUZZTEST_FLAG_PREFIX << mode_flag << " requires --" + << FUZZTEST_FLAG_PREFIX "corpus_database."; + FUZZTEST_CHECK(false) << "--" FUZZTEST_FLAG_PREFIX << mode_flag + << " is not supported in this build."; + FUZZTEST_CHECK(!configuration.execution_id.has_value()) + << "--" FUZZTEST_FLAG_PREFIX << mode_flag << " cannot be combined with --" + << FUZZTEST_FLAG_PREFIX "execution_id."; + FUZZTEST_CHECK(!configuration.reproduce_findings_as_separate_tests) + << "--" FUZZTEST_FLAG_PREFIX << mode_flag << " cannot be combined with --" + << FUZZTEST_FLAG_PREFIX "reproduce_findings_as_separate_tests."; + FUZZTEST_CHECK(absl::GetFlag(FUZZTEST_FLAG(update_corpus_database)) != true) + << "--" FUZZTEST_FLAG_PREFIX << mode_flag << " cannot be combined with --" + << FUZZTEST_FLAG_PREFIX "update_corpus_database=true."; +#ifndef FUZZTEST_USE_CENTIPEDE + FUZZTEST_CHECK(false) << "--" FUZZTEST_FLAG_PREFIX << mode_flag + << " requires the Centipede engine " + "(build with --config=fuzztest)."; +#else +#endif // FUZZTEST_USE_CENTIPEDE } } // namespace @@ -443,6 +630,7 @@ const std::string matching_fuzz_test = GetMatchingFuzzTestOrExit(name); internal::Configuration configuration = CreateConfigurationsFromFlags({binary_id.data(), binary_id.size()}); + ValidateDiffModeConfiguration(configuration); internal::ForEachTest([&](auto& test) { // TODO(b/301965259): Properly initialize the configuration. if (test.full_name() == matching_fuzz_test) { @@ -464,28 +652,29 @@ 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; + const bool is_record = absl::GetFlag(FUZZTEST_FLAG(record)) != kUnspecified; + const bool is_diff = absl::GetFlag(FUZZTEST_FLAG(diff)) != kUnspecified; + std::optional<std::string> specified_test = + absl::GetFlag(FUZZTEST_FLAG(internal_override_fuzz_test)); + if (!specified_test.has_value()) { + for (const std::string& target : { + absl::GetFlag(FUZZTEST_FLAG(fuzz)), + absl::GetFlag(FUZZTEST_FLAG(replay_corpus)), + absl::GetFlag(FUZZTEST_FLAG(record)), + absl::GetFlag(FUZZTEST_FLAG(diff)), + }) { + if (target != kUnspecified) { + if (target != "*") { + specified_test = target; + } + break; + } } - if (auto test_to_fuzz = absl::GetFlag(FUZZTEST_FLAG(fuzz)); - test_to_fuzz != kUnspecified) { - return test_to_fuzz; - } - 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); @@ -499,13 +688,14 @@ std::optional<std::string> reproduction_command_template; internal::Configuration configuration = CreateConfigurationsFromFlags(derived_binary_id); + ValidateDiffModeConfiguration(configuration); configuration.reproduction_command_template = reproduction_command_template; runtime.SetInitConfiguration(configuration); internal::RegisterSeparateRegressionTestsForEachCrashingInput(configuration); internal::RegisterGoogleTestEventListener(); const bool is_fuzzing_or_replaying = - (fuzzing_time_limit || replay_corpus_time_limit); + (fuzzing_time_limit || replay_corpus_time_limit || is_record || is_diff); if (is_fuzzing_or_replaying && !specified_test.has_value()) { absl::flat_hash_set<std::string> fuzz_tests = { configuration.fuzz_tests.begin(), configuration.fuzz_tests.end()};
diff --git a/fuzztest/internal/BUILD b/fuzztest/internal/BUILD index 23fb8d4..09998ef 100644 --- a/fuzztest/internal/BUILD +++ b/fuzztest/internal/BUILD
@@ -81,6 +81,7 @@ "@abseil-cpp//absl/base:no_destructor", "@abseil-cpp//absl/cleanup", "@abseil-cpp//absl/container:flat_hash_map", + "@abseil-cpp//absl/container:flat_hash_set", "@abseil-cpp//absl/functional:any_invocable", "@abseil-cpp//absl/memory", "@abseil-cpp//absl/random", @@ -455,6 +456,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 dff8020..4243fdf 100644 --- a/fuzztest/internal/CMakeLists.txt +++ b/fuzztest/internal/CMakeLists.txt
@@ -415,6 +415,7 @@ "runtime_test.cc" DEPS fuzztest::configuration + fuzztest::flag_name fuzztest::runtime fuzztest::crash_reporting fuzztest::test_protobuf_cc_proto
diff --git a/fuzztest/internal/centipede_adaptor.cc b/fuzztest/internal/centipede_adaptor.cc index 5b9e200..15f8ec3 100644 --- a/fuzztest/internal/centipede_adaptor.cc +++ b/fuzztest/internal/centipede_adaptor.cc
@@ -51,6 +51,7 @@ #include "absl/base/no_destructor.h" #include "absl/cleanup/cleanup.h" #include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" #include "absl/functional/any_invocable.h" #include "absl/memory/memory.h" #include "absl/random/distributions.h" @@ -524,11 +525,25 @@ : runtime_(*runtime), fuzzer_impl_(*fuzzer_impl), configuration_(*configuration), - prng_(GetRandomSeed()) {} + prng_(GetRandomSeed()) { + if (configuration_.diff_mode != DiffMode::kNone && + configuration_.only_replay && + !configuration_.crashing_input_to_reproduce.has_value()) { + runtime_.EnableDiffMode(configuration_.diff_mode); + } + } bool Execute(void* input) override { const auto* input_object = reinterpret_cast<const FuzzTestFuzzerImpl::Input*>(input); + // Always consume the pending diff expectations, even if the input is not + // executed below, so that they never leak into another input. + std::optional<std::string> expectations; + if (pending_expectations_input_ == input) { + expectations = std::move(pending_expectations_); + } + pending_expectations_.reset(); + pending_expectations_input_ = nullptr; // Disable tracing until running the property function in // `CentipedeFxitureDriver::RunFuzzTestIteration()` @@ -541,6 +556,23 @@ "[.] Termination requested - not executing input.\n"); return false; } + if (runtime_.diff_active()) { + const bool unparsable = unparsable_inputs_.contains(input); + const bool has_baseline = expectations.has_value(); + runtime_.BeginDiffInput(std::move(expectations), unparsable); + if (unparsable && has_baseline && + runtime_.diff_mode() == DiffMode::kValidate) { + // The input was replaced by a random substitute, which cannot be + // compared against the baseline of the original input. Report it + // instead of silently skipping the comparison. + runtime_.ReportDiffUsageError( + "RecordOrDiff: the input has a baseline but could not be parsed " + "by the current FUZZ_TEST domains. Did the signature or the " + "domains of the test change since the baseline was recorded?", + "RecordOrDiff unparsable input with baseline"); + return true; + } + } // We should avoid doing anything other than executing the input here so // that we don't affect the execution time. fuzzer_impl_.RunOneInput(*input_object); @@ -590,11 +622,46 @@ return reinterpret_cast<void*>( new FuzzTestFuzzerImpl::Input{*std::move(parse_result)}); } - return reinterpret_cast<void*>( + void* substitute = reinterpret_cast<void*>( new FuzzTestFuzzerImpl::Input{fuzzer_impl_.params_domain_.Init(prng_)}); + // In the diff mode, the random substitute must not be recorded or + // compared, so remember that the input was unparsable. + if (runtime_.diff_active()) unparsable_inputs_.insert(substitute); + return substitute; + } + + // Incremental differential fuzzing: the baseline of an input is exchanged + // with the engine as the persistent metadata of the input. The engine + // stores what `TakePersistentMetadata` returns and passes it back via + // `SetPersistentMetadata` before a later execution of the same input. + void SetPersistentMetadata(void* input, ByteSpan metadata) override { + if (!runtime_.diff_active()) return; + pending_expectations_input_ = input; + pending_expectations_ = std::string( + reinterpret_cast<const char*>(metadata.data()), metadata.size()); + } + + ByteArray TakePersistentMetadata(void* input) override { + pending_expectations_.reset(); + pending_expectations_input_ = nullptr; + if (!runtime_.diff_active()) return {}; + const std::optional<RuntimeDiffResult> result = runtime_.TakeDiffResult(); + // Only the records of the record mode become the new baseline. In the + // validate mode, and for inputs that were not recorded, nothing is + // returned so that the stored baseline (if any) is left unchanged. + if (!result.has_value() || + result->kind != RuntimeDiffResult::Kind::kRecords) { + return {}; + } + return ByteArray(result->container.begin(), result->container.end()); } void FreeInput(void* input) override { + unparsable_inputs_.erase(input); + if (pending_expectations_input_ == input) { + pending_expectations_.reset(); + pending_expectations_input_ = nullptr; + } auto it = cmp_tables_.find(input); if (it != cmp_tables_.end()) { delete it->second; @@ -618,7 +685,10 @@ return mutant; } - ~CentipedeAdaptorRunnerCallbacks() override { runtime_.UnsetCurrentArgs(); } + ~CentipedeAdaptorRunnerCallbacks() override { + runtime_.UnsetCurrentArgs(); + runtime_.DisableDiffMode(); + } private: Runtime& runtime_; @@ -627,6 +697,11 @@ absl::BitGen prng_; absl::flat_hash_map<void*, fuzztest::internal::TablesOfRecentCompares*> cmp_tables_; + // Incremental differential fuzzing: inputs that could not be parsed by the + // current domains, and the expectations set for the next input to execute. + absl::flat_hash_set<void*> unparsable_inputs_; + void* pending_expectations_input_ = nullptr; + std::optional<std::string> pending_expectations_; }; namespace {
diff --git a/fuzztest/internal/configuration.cc b/fuzztest/internal/configuration.cc index 4ca302f..2710a0e 100644 --- a/fuzztest/internal/configuration.cc +++ b/fuzztest/internal/configuration.cc
@@ -65,6 +65,44 @@ } } +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"; + } + return absl::StrCat(static_cast<int>(mode)); +} + namespace { template <typename T> @@ -203,6 +241,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 +257,8 @@ 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(persistent_metadata_root) + SpaceFor(diff_mode_str)); size_t offset = 0; offset = WriteString(out, offset, corpus_database); offset = WriteString(out, offset, stats_root); @@ -246,6 +286,8 @@ 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, persistent_metadata_root); + offset = WriteString(out, offset, diff_mode_str); FUZZTEST_CHECK_EQ(offset, out.size()); return out; } @@ -283,6 +325,8 @@ ASSIGN_OR_RETURN(replay_crash_attempts, Consume<size_t>(serialized)); ASSIGN_OR_RETURN(reproduction_command_template, ConsumeOptionalString(serialized)); + ASSIGN_OR_RETURN(persistent_metadata_root, ConsumeString(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 +338,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 +364,9 @@ *std::move(centipede_command), *std::move(crashing_input_to_reproduce), *replay_crash_attempts, - *std::move(reproduction_command_template)}; + *std::move(reproduction_command_template), + *std::move(persistent_metadata_root), + *diff_mode}; }(); }
diff --git a/fuzztest/internal/configuration.h b/fuzztest/internal/configuration.h index 8f82196..d82e110 100644 --- a/fuzztest/internal/configuration.h +++ b/fuzztest/internal/configuration.h
@@ -40,6 +40,27 @@ // 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 { + // `RecordOrDiff` is a no-op. + kNone, + // `RecordOrDiff` records the values passed to it as the baseline. + kRecord, + // `RecordOrDiff` compares the values passed to it against the baseline. + 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 +143,16 @@ // - $TEST_FILTER: for replaying only a subset of the tests in a binary. std::optional<std::string> reproduction_command_template; + // If non-empty, the root directory where the engine stores the persistent + // input metadata that the test attaches to its inputs, and from where it + // passes the stored metadata back before executing the same inputs again. + std::string persistent_metadata_root; + + // Incremental differential fuzzing mode for corpus replay. Only read by the + // test framework in the process that executes the inputs; the engine is not + // aware of it. Only takes effect together with `only_replay`. + 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..e6069af 100644 --- a/fuzztest/internal/configuration_test.cc +++ b/fuzztest/internal/configuration_test.cc
@@ -43,7 +43,9 @@ 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.persistent_metadata_root == other->persistent_metadata_root && + config.diff_mode == other->diff_mode; } TEST(ConfigurationTest, @@ -106,7 +108,9 @@ "centipede_command", "crashing_input_to_reproduce", /*replay_crash_attempts=*/20, - "reproduction_command_template"}; + "reproduction_command_template", + "persistent_metadata_root", + DiffMode::kValidate}; EXPECT_THAT(Configuration::Deserialize(configuration.Serialize()), IsOkAndEquals(configuration)); @@ -117,5 +121,18 @@ Configuration::Deserialize("Not a serialized configuration").ok()); } +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"); +} + } // namespace } // namespace fuzztest::internal
diff --git a/fuzztest/internal/domains/container_of_impl.h b/fuzztest/internal/domains/container_of_impl.h index 312f1f4..1d6b9ae 100644 --- a/fuzztest/internal/domains/container_of_impl.h +++ b/fuzztest/internal/domains/container_of_impl.h
@@ -51,6 +51,13 @@ // Default maximum size for FuzzTest containers/lists. inline constexpr size_t kDefaultContainerMaxSize = 5000; +// Thread-local override allowing `RecordOrDiff` baseline deserialization to +// validate element constraints without enforcing `kDefaultContainerMaxSize`. +inline bool& SkipContainerMaxSizeValidationForCurrentThread() { + thread_local bool skip = false; + return skip; +} + // For cases where the type is a container, choose one of the elements in the // container. template <typename Container> @@ -345,7 +352,9 @@ return absl::InvalidArgumentError(absl::StrCat( "Invalid size: ", corpus_value.size(), ". Min size: ", min_size())); } - if (validate_max_size() && corpus_value.size() > max_size()) { + if (validate_max_size() && + !SkipContainerMaxSizeValidationForCurrentThread() && + corpus_value.size() > max_size()) { return absl::InvalidArgumentError(absl::StrCat( "Invalid size: ", corpus_value.size(), ". Max size: ", max_size())); }
diff --git a/fuzztest/internal/runtime.cc b/fuzztest/internal/runtime.cc index bdc81b3..1f10974 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> @@ -432,6 +433,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 @@ -491,6 +496,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()) { @@ -913,6 +955,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( @@ -1392,6 +1737,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(); // Reporting a failure disables the reporter for the rest of the input, so
diff --git a/fuzztest/internal/runtime.h b/fuzztest/internal/runtime.h index a128943..9b212ff 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,47 @@ // 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 baseline of an input. +// It is exchanged with the engine as the persistent metadata of the input, +// and is opaque to the engine: `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, to be stored + // as its baseline. + kRecords, + // Validate mode: the input was executed and compared (if it had a + // baseline). `container` is empty, so the baseline is left unchanged. + 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 +246,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 +255,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 { @@ -303,6 +351,85 @@ // 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 baseline of an input is given to `BeginDiffInput` and returned by + // `TakeDiffResult`; the caller exchanges it with the engine, which stores it + // as the persistent metadata of the input. + // 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 of the + // input (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 @@ -319,6 +446,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. @@ -472,6 +601,39 @@ // In case of an assertion failure with a custom `FailureKey`, contains the // sanitized assertion failure key. CrashMetadataBuffer<256> assertion_failure_key_; + + // 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 fc9f40f..7500703 100644 --- a/fuzztest/internal/runtime_test.cc +++ b/fuzztest/internal/runtime_test.cc
@@ -43,6 +43,7 @@ #include "./fuzztest/domain_core.h" #include "./framework_shared/crash_reporting.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); @@ -577,6 +578,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..42b841f --- /dev/null +++ b/fuzztest/record_or_diff.h
@@ -0,0 +1,317 @@ +// 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_duration=<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 stored by the engine as opaque input metadata. + +// 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()) { + return false; + } + // Validate domain constraints (e.g., `ElementOfImpl`, `InRangeImpl`, + // `absl::Duration` tick bounds) while bypassing `kDefaultContainerMaxSize` + // so recorded containers/strings > 5000 elements still round-trip. + bool& skip_max_size = + internal::SkipContainerMaxSizeValidationForCurrentThread(); + const bool prev_skip_max_size = skip_max_size; + skip_max_size = true; + const bool valid = domain.ValidateCorpusValue(*corpus).ok(); + skip_max_size = prev_skip_max_size; + if (!valid) { + 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..48564b0 --- /dev/null +++ b/fuzztest/record_or_diff_test.cc
@@ -0,0 +1,806 @@ +// 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 <vector> + +#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 "absl/time/time.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, LargeContainersAndStringsRoundTrip) { + const std::string large_str(6000, 'a'); + const std::vector<int> large_vec(6000, 42); + const std::string container = Record([&] { + RecordOrDiff(large_str, "large_str"); + RecordOrDiff(large_vec, "large_vec"); + }); + const DiffRun ok = ValidateOutcome(container, [&] { + RecordOrDiff(large_str, "large_str"); + RecordOrDiff(large_vec, "large_vec"); + }); + EXPECT_EQ(ok.crash_type, std::nullopt); + EXPECT_EQ(ok.stderr_output, ""); + + std::string modified_str = large_str; + modified_str[5500] = 'b'; + std::vector<int> modified_vec = large_vec; + modified_vec[5500] = 99; + const DiffRun diff = ValidateOutcome(container, [&] { + RecordOrDiff(modified_str, "large_str"); + RecordOrDiff(modified_vec, "large_vec"); + }); + EXPECT_THAT(diff.crash_type, Optional(std::string("RecordOrDiff mismatch"))); + EXPECT_THAT(diff.stderr_output, HasSubstr("Mismatched outputs: 2")); +} + +TEST_F(RecordOrDiffTest, CorruptedDurationBaselineReportsDecodeError) { + // Valid `absl::Duration` corpus is `(seconds, ticks)` with `ticks <= + // 3999999999`. A corrupted tick count must fail validation cleanly instead of + // aborting inside `MakeDuration`. + const internal::IRObject invalid_duration_ir = internal::IRObject::FromCorpus( + std::make_tuple(int64_t{0}, uint32_t{4000000000u})); + const std::string container = + internal::EncodeDiffRecordContainer({internal::DiffRecord{ + "dur", internal::SerializeIRObject(invalid_duration_ir)}}); + const DiffRun val = ValidateOutcome( + container, [&] { RecordOrDiff(absl::Seconds(1), "dur"); }); + EXPECT_THAT(val.crash_type, Optional(std::string("RecordOrDiff mismatch"))); + EXPECT_THAT(val.stderr_output, HasSubstr("cannot decode baseline value")); +} + +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 e1c0f07..004e378 100644 --- a/rust/engine/src/engine_ffi.rs +++ b/rust/engine/src/engine_ffi.rs
@@ -146,6 +146,56 @@ >, } +/// Types of input metadata. The engine handles each type differently, and the +/// content of every type is opaque to the engine. +/// +/// Represented as an integer rather than a Rust enum, since values received +/// from the engine are not guaranteed to be one of the known constants. +#[repr(transparent)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct FuzzTestInputMetadataType(pub u32); + +impl FuzzTestInputMetadataType { + /// Hints for mutating the input (e.g. the operands of comparisons seen when + /// executing it). Kept in memory only, and passed back to the adapter for + /// the origin inputs of mutations. + pub const MUTATION_HINTS: Self = Self(0); + /// Metadata that the engine may store for the input and pass back to the + /// adapter before a later execution of the same input. + pub const PERSISTENT: Self = Self(1); +} + +/// A piece of input metadata of a given type. +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct FuzzTestInputMetadataView { + pub metadata_type: FuzzTestInputMetadataType, + pub bytes: FuzzTestBytesView, +} + +#[repr(C)] +pub struct FuzzTestInputMetadataSinkCtx { + _opaque: (), + _not_send_nor_sync: PhantomData<*mut ()>, + _not_unpin: PhantomPinned, +} + +/// Sink for input metadata. +#[repr(C)] +#[derive(Copy, Clone)] +pub struct FuzzTestInputMetadataSink { + pub ctx: *mut FuzzTestInputMetadataSinkCtx, + + /// Emits a piece of input metadata. Multiple emissions of the same type are + /// concatenated. A type that is never emitted is treated as absent. + pub emit: Option< + unsafe extern "C" fn( + ctx: *mut FuzzTestInputMetadataSinkCtx, + metadata: *const FuzzTestInputMetadataView, + ), + >, +} + #[repr(C)] pub struct FuzzTestInputSinkCtx { _opaque: (), @@ -376,20 +426,25 @@ ), >, - /// [Optional] Serializes the test `input` metadata into bytes using `sink`. + /// [Optional] Serializes the test `input` metadata, of any type, using + /// `sink`. pub serialize_input_metadata: Option< unsafe extern "C" fn( ctx: *mut FuzzTestAdapterCtx, input: FuzzTestInputHandle, - sink: *const FuzzTestBytesSink, + sink: *const FuzzTestInputMetadataSink, ), >, - /// [Optional] Updates the test `input` metadata from serialized `metadata`. + /// [Optional] Updates the test `input` metadata of type + /// `metadata.metadata_type` from the serialized `metadata.bytes`. Called + /// with the mutation hints of mutation origins before + /// `Mutate`/`CrossOver`, and with the persistent metadata stored for + /// `input` (if any) before `Execute`. pub update_input_metadata: Option< unsafe extern "C" fn( ctx: *mut FuzzTestAdapterCtx, - metadata: *const FuzzTestBytesView, + metadata: *const FuzzTestInputMetadataView, input: FuzzTestInputHandle, ), >,