Windows support 1/x: Use path::string() explicitly and replace ::c_str() with it. Needed because C++ compiler on Windows does not implicitly convert std::filesystem::path to std::string, because on Windows path is natively in wchar_t. PiperOrigin-RevId: 981955484
diff --git a/.github/workflows/bazel_test_centipede.yml b/.github/workflows/bazel_test_centipede.yml index 9a16bf6..822b16b 100644 --- a/.github/workflows/bazel_test_centipede.yml +++ b/.github/workflows/bazel_test_centipede.yml
@@ -196,8 +196,32 @@ <# Only supported libraries are tested here. #> ` bazelisk test --local_test_jobs=1 --test_output=errors --no//fuzztest:use_riegeli ` --extra_toolchains=@local_config_cc//:cc-toolchain-x64_windows-clang-cl ` - --extra_execution_platforms=//:x64_windows-clang-cl --enable_runfiles ` - -- centipede:util_test centipede:command_test + --extra_execution_platforms=//:x64_windows-clang-cl --enable_runfiles -- ` + centipede:call_graph_test ` + centipede:callstack_test ` + centipede:command_test ` + centipede:concurrent_bitset_test ` + centipede:concurrent_byteset_test ` + centipede:config_file_test ` + centipede:crash_summary_test ` + centipede:execution_metadata_test ` + centipede:feature_set_test ` + centipede:feature_test ` + centipede:foreach_nonzero_test ` + centipede:hashed_ring_buffer_test ` + centipede:int_utils_test ` + centipede:knobs_test ` + centipede:mutation_data_test ` + centipede:pc_info_test ` + centipede:periodic_action_test ` + centipede:reverse_pc_table_test ` + centipede:rolling_hash_test ` + centipede:runner_flags_test ` + centipede:runner_result_test ` + centipede:rusage_stats_test ` + centipede:shared_memory_blob_sequence_test ` + centipede:stop_test ` + centipede:util_test - name: Save new cache based on main # Save a new cache on nightly scheduled runs (or manual dispatch on # main), or on a push to main when no previous cache exists for this
diff --git a/centipede/BUILD b/centipede/BUILD index 6238cc0..5c466fc 100644 --- a/centipede/BUILD +++ b/centipede/BUILD
@@ -298,6 +298,7 @@ "@abseil-cpp//absl/strings:str_format", "@abseil-cpp//absl/time", "@com_google_fuzztest//common:logging", + "@com_google_fuzztest//common:windows_includes", ], ) @@ -418,12 +419,16 @@ copts = DISABLE_SANCOV_COPTS, linkopts = select({ "@platforms//os:macos": [], + "@platforms//os:windows": [], "//conditions:default": [ "-lrt", # for shm_open ], }), - deps = ["@abseil-cpp//absl/base:nullability"], - # don't add any dependencies. + deps = [ + "@abseil-cpp//absl/base:nullability", + "@com_google_fuzztest//common:windows_includes", + ], + # Don't add any dependencies. ) cc_library( @@ -1601,6 +1606,7 @@ srcs = ["shared_memory_blob_sequence_test.cc"], deps = [ ":shared_memory_blob_sequence", + "@com_google_fuzztest//common:windows_includes", "@googletest//:gtest_main", ], )
diff --git a/centipede/analyze_corpora_test.cc b/centipede/analyze_corpora_test.cc index c349ec3..f0baad1 100644 --- a/centipede/analyze_corpora_test.cc +++ b/centipede/analyze_corpora_test.cc
@@ -42,7 +42,8 @@ // Returns path to test_fuzz_target. static std::string GetTargetPath() { - return GetDataDependencyFilepath("centipede/testing/test_fuzz_target"); + return GetDataDependencyFilepath("centipede/testing/test_fuzz_target") + .string(); } // TODO(ussuri): Implement. @@ -91,7 +92,7 @@ auto corpus_records = RunInputsAndCollectCorpusRecords(env, {"func1"}); ASSERT_EQ(corpus_records.size(), 1); - const std::string test_tmpdir = GetTestTempDir(test_info_->name()); + const std::string test_tmpdir = GetTestTempDir(test_info_->name()).string(); BinaryInfo binary_info; binary_info.InitializeFromSanCovBinary(GetTargetPath(), /*env_diff=*/{}, GetObjDumpPath(), @@ -100,7 +101,7 @@ GetCoverage(corpus_records, std::move(binary_info)); const std::string coverage_report_path = - std::filesystem::path{test_tmpdir} / "covered_symbol_table"; + (std::filesystem::path{test_tmpdir} / "covered_symbol_table").string(); DumpCoverageReport(coverage_results, coverage_report_path); std::string symbol_table_contents; ASSERT_OK(RemoteFileGetContents(coverage_report_path, symbol_table_contents));
diff --git a/centipede/binary_info.cc b/centipede/binary_info.cc index 1ef77b6..a8222fb 100644 --- a/centipede/binary_info.cc +++ b/centipede/binary_info.cc
@@ -66,7 +66,7 @@ ":arg3=", EscapeEngineFlag(dso_table_path.path()), ":")); Command::Options cmd_options; cmd_options.env_diff = std::move(env_diff); - cmd_options.stdout_file_prefix = log_prefix; + cmd_options.stdout_file_prefix = log_prefix.string(); Command cmd{binary_path_with_args, std::move(cmd_options)}; int exit_code = cmd.Execute(); if (exit_code != EXIT_SUCCESS) { @@ -131,20 +131,20 @@ std::string symbol_table_contents; // TODO(b/295978603): move calculation of paths into WorkDir class. FUZZTEST_CHECK_OK(RemoteFileGetContents( - (std::filesystem::path(dir) / kSymbolTableFileName).c_str(), + (std::filesystem::path(dir) / kSymbolTableFileName).string(), symbol_table_contents)); std::istringstream symbol_table_stream(symbol_table_contents); symbols.ReadFromLLVMSymbolizer(symbol_table_stream); std::string pc_table_contents; FUZZTEST_CHECK_OK(RemoteFileGetContents( - (std::filesystem::path(dir) / kPCTableFileName).c_str(), + (std::filesystem::path(dir) / kPCTableFileName).string(), pc_table_contents)); std::istringstream pc_table_stream(pc_table_contents); pc_table = ReadPcTable(pc_table_stream); cf_table = - ReadCfTable((std::filesystem::path(dir) / kCfTableFileName).c_str()); + ReadCfTable((std::filesystem::path(dir) / kCfTableFileName).string()); } void BinaryInfo::Write(std::string_view dir) { @@ -152,19 +152,19 @@ symbols.WriteToLLVMSymbolizer(symbol_table_stream); // TODO(b/295978603): move calculation of paths into WorkDir class. FUZZTEST_CHECK_OK(RemoteFileSetContents( - (std::filesystem::path(dir) / kSymbolTableFileName).c_str(), + (std::filesystem::path(dir) / kSymbolTableFileName).string(), symbol_table_stream.str())); std::ostringstream pc_table_stream; WritePcTable(pc_table, pc_table_stream); FUZZTEST_CHECK_OK(RemoteFileSetContents( - (std::filesystem::path(dir) / kPCTableFileName).c_str(), + (std::filesystem::path(dir) / kPCTableFileName).string(), pc_table_stream.str())); std::ostringstream cf_table_stream; WriteCfTable(cf_table, cf_table_stream); FUZZTEST_CHECK_OK(RemoteFileSetContents( - (std::filesystem::path(dir) / kCfTableFileName).c_str(), + (std::filesystem::path(dir) / kCfTableFileName).string(), cf_table_stream.str())); }
diff --git a/centipede/binary_info_test.cc b/centipede/binary_info_test.cc index 2b730f9..02fe110 100644 --- a/centipede/binary_info_test.cc +++ b/centipede/binary_info_test.cc
@@ -28,7 +28,7 @@ namespace { TEST(BinaryInfoTest, SerializesAndDeserializesBinaryInfoSuccessfully) { - const std::string temp_dir = GetTestTempDir(test_info_->name()); + const std::string temp_dir = GetTestTempDir(test_info_->name()).string(); const PCTable input_pcs = {{/*pc=*/0, /*flags=*/1}, {/*pc=*/2, /*flags=*/3}}; std::string input_symbols = @@ -57,7 +57,7 @@ } TEST(BinaryInfoTest, SerializesAndDeserializesEmptyBinaryInfoSuccessfully) { - const std::string temp_dir = GetTestTempDir(test_info_->name()); + const std::string temp_dir = GetTestTempDir(test_info_->name()).string(); const PCTable input_pcs = {}; std::string input_symbols = "";
diff --git a/centipede/blob_file_converter.cc b/centipede/blob_file_converter.cc index 7b88889..5d0bd6a 100644 --- a/centipede/blob_file_converter.cc +++ b/centipede/blob_file_converter.cc
@@ -100,7 +100,7 @@ FUZZTEST_CHECK(RemotePathExists(in)) << VV(in); FUZZTEST_CHECK_OK( - RemoteMkdir(std::filesystem::path{out}.parent_path().c_str())); + RemoteMkdir(std::filesystem::path{out}.parent_path().string())); // Open blob file reader and writer.
diff --git a/centipede/centipede.cc b/centipede/centipede.cc index 0057787..8ea81e7 100644 --- a/centipede/centipede.cc +++ b/centipede/centipede.cc
@@ -114,14 +114,15 @@ void SaveReproducer(const WorkDir& wd, std::string_view log_prefix, size_t input_idx, ByteSpan reproducer, const BatchResult& result) { - auto hash = Hash(reproducer); - auto crash_dir = wd.CrashReproducerDirPaths().MyShard(); + const auto hash = Hash(reproducer); + const auto crash_dir = wd.CrashReproducerDirPaths().MyShard(); FUZZTEST_CHECK_OK(RemoteMkdir(crash_dir)); - std::string input_file_path = std::filesystem::path(crash_dir) / hash; - auto crash_metadata_dir = wd.CrashMetadataDirPaths().MyShard(); + const auto input_file_path = + (std::filesystem::path(crash_dir) / hash).string(); + const auto crash_metadata_dir = wd.CrashMetadataDirPaths().MyShard(); FUZZTEST_CHECK_OK(RemoteMkdir(crash_metadata_dir)); - std::string crash_metadata_path_prefix = - std::filesystem::path(crash_metadata_dir) / hash; + const auto crash_metadata_path_prefix = + (std::filesystem::path(crash_metadata_dir) / hash).string(); FUZZTEST_LOG(INFO) << log_prefix << "Detected crash-reproducing input:" << "\nInput index : " << input_idx @@ -169,13 +170,15 @@ coverage_logger_(coverage_logger), stats_(stats), input_filter_path_(std::filesystem::path(TemporaryLocalDirPath()) - .append("filter-input")), + .append("filter-input") + .string()), input_filter_cmd_{[&] { Command::Options cmd_options; cmd_options.args = {input_filter_path_}; cmd_options.stdout_file_prefix = std::filesystem::path(TemporaryLocalDirPath()) - .append("filter-input.log"); + .append("filter-input.log") + .string(); cmd_options.stderr_file_prefix = cmd_options.stdout_file_prefix; return Command{env_.input_filter, std::move(cmd_options)}; }()}, @@ -274,7 +277,8 @@ std::vector<std::string> reproducer_paths, RemoteListFiles(reproducer_dir, /*recursively=*/false)); for (const auto &reproducer_path : reproducer_paths) { - std::string id = std::filesystem::path{reproducer_path}.filename(); + std::string id = + std::filesystem::path{reproducer_path}.filename().string(); if (auto [_it, inserted] = crash_ids.insert(id); !inserted) { continue; } @@ -1180,21 +1184,25 @@ FUZZTEST_CHECK_OK(RemoteMkdir(crash_dir)); std::string crashing_batch_name = absl::StrCat("crashing_batch-", suspect_hash); - std::string save_dir = std::filesystem::path(crash_dir) / crashing_batch_name; + std::string save_dir = + (std::filesystem::path(crash_dir) / crashing_batch_name).string(); FUZZTEST_CHECK_OK(RemoteMkdir(save_dir)); FUZZTEST_LOG(INFO) << log_prefix << "Saving used inputs from batch to: " << save_dir; for (int i = 0; i <= suspect_input_idx; ++i) { const auto &one_input = input_vec[i]; auto hash = Hash(one_input); - std::string file_path = std::filesystem::path(save_dir).append( - absl::StrFormat("input-%010d-%s", i, hash)); + std::string file_path = + std::filesystem::path(save_dir) + .append(absl::StrFormat("input-%010d-%s", i, hash)) + .string(); FUZZTEST_CHECK_OK(RemoteFileSetContents(file_path, one_input)); } auto crash_metadata_dir = wd_.CrashMetadataDirPaths().MyShard(); FUZZTEST_CHECK_OK(RemoteMkdir(crash_metadata_dir)); std::string crash_metadata_file_path = - std::filesystem::path(crash_metadata_dir) / crashing_batch_name; + (std::filesystem::path(crash_metadata_dir) / crashing_batch_name) + .string(); FUZZTEST_LOG(INFO) << log_prefix << "Saving crash metadata to: " << crash_metadata_file_path; FUZZTEST_CHECK_OK(RemoteFileSetContents(crash_metadata_file_path,
diff --git a/centipede/centipede_callbacks.cc b/centipede/centipede_callbacks.cc index 1a79da2..c89d77f 100644 --- a/centipede/centipede_callbacks.cc +++ b/centipede/centipede_callbacks.cc
@@ -402,8 +402,8 @@ absl::StrCat( ":shmem_size_mb=", env_.shmem_size_mb, ":test=", EscapeEngineFlag(env_.test_name), - ":arg1=", EscapeEngineFlag(inputs_blobseq_.path()), - ":arg2=", EscapeEngineFlag(outputs_blobseq_.path()), + ":arg1=", EscapeEngineFlag(inputs_blobseq_->path()), + ":arg2=", EscapeEngineFlag(outputs_blobseq_->path()), ":failure_description_path=", EscapeEngineFlag(failure_description_path_), ":failure_signature_path=", EscapeEngineFlag(failure_signature_path_), @@ -546,8 +546,8 @@ batch_result.ClearAndResize(inputs.size()); // Reset the blobseqs. - inputs_blobseq_.Reset(); - outputs_blobseq_.Reset(); + inputs_blobseq_->Reset(); + outputs_blobseq_->Reset(); size_t num_inputs_written = 0; @@ -557,7 +557,7 @@ num_inputs_written = 1; } else { // Feed the inputs to inputs_blobseq_. - num_inputs_written = RequestExecution(inputs, inputs_blobseq_); + num_inputs_written = RequestExecution(inputs, *inputs_blobseq_); } if (num_inputs_written != inputs.size()) { @@ -569,16 +569,16 @@ // Run. const auto batch_start_time = absl::Now(); const int exit_code = RunBatchForBinary(binary); - inputs_blobseq_.ReleaseSharedMemory(); // Inputs are already consumed. + inputs_blobseq_->ReleaseSharedMemory(); // Inputs are already consumed. const bool batch_timed_out = env_.timeout_per_batch > 0 && absl::Now() - batch_start_time > absl::Seconds(env_.timeout_per_batch); // Get results. batch_result.exit_code() = exit_code; - const bool read_success = batch_result.Read(outputs_blobseq_); + 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. + outputs_blobseq_->ReleaseSharedMemory(); // Outputs are already consumed. // We may have fewer feature blobs than inputs if // * some inputs were not written (i.e. num_inputs_written < inputs.size). @@ -696,7 +696,7 @@ std::vector<std::string> seed_input_filenames; for (const auto& dir_ent : std::filesystem::directory_iterator(output_dir)) { - seed_input_filenames.push_back(dir_ent.path().filename()); + seed_input_filenames.push_back(dir_ent.path().filename().string()); } std::sort(seed_input_filenames.begin(), seed_input_filenames.end()); num_avail_seeds = seed_input_filenames.size(); @@ -720,11 +720,11 @@ // See also: `DumpSerializedTargetConfigToFile()`. bool CentipedeCallbacks::GetSerializedTargetConfigViaExternalBinary( std::string_view binary, std::string& serialized_config) { - const auto config_file_path = - std::filesystem::path{temp_dir_} / "configuration"; + const std::string config_file_path = + (std::filesystem::path{temp_dir_} / "configuration").string(); std::string centipede_runner_flags = absl::StrCat("CENTIPEDE_RUNNER_FLAGS=:dump_configuration:arg1=", - EscapeEngineFlag(config_file_path.string()), ":"); + EscapeEngineFlag(config_file_path), ":"); if (!env_.runner_dl_path_suffix.empty()) { absl::StrAppend(¢ipede_runner_flags, "dl_path_suffix=", EscapeEngineFlag(env_.runner_dl_path_suffix), ":"); @@ -741,7 +741,7 @@ if (is_success) { if (std::filesystem::exists(config_file_path)) { - ReadFromLocalFile(config_file_path.string(), serialized_config); + ReadFromLocalFile(config_file_path, serialized_config); } else { serialized_config = ""; } @@ -764,17 +764,17 @@ << "Standalone binary does not support custom mutator"; auto start_time = absl::Now(); - inputs_blobseq_.Reset(); - outputs_blobseq_.Reset(); + inputs_blobseq_->Reset(); + outputs_blobseq_->Reset(); size_t num_inputs_written = - RequestMutation(num_mutants, inputs, inputs_blobseq_); + RequestMutation(num_mutants, inputs, *inputs_blobseq_); FUZZTEST_LOG_IF(INFO, num_inputs_written != inputs.size()) << VV(num_inputs_written) << VV(inputs.size()); // Execute. const int exit_code = RunBatchForBinary(binary); - inputs_blobseq_.ReleaseSharedMemory(); // Inputs are already consumed. + inputs_blobseq_->ReleaseSharedMemory(); // Inputs are already consumed. if (exit_code != EXIT_SUCCESS) { FUZZTEST_LOG(WARNING) << "Custom mutator failed with exit code: " @@ -786,8 +786,8 @@ MutationResult result; result.exit_code() = exit_code; - result.Read(num_mutants, outputs_blobseq_); - outputs_blobseq_.ReleaseSharedMemory(); // Outputs are already consumed. + result.Read(num_mutants, *outputs_blobseq_); + outputs_blobseq_->ReleaseSharedMemory(); // Outputs are already consumed. FUZZTEST_VLOG(1) << __FUNCTION__ << " took " << (absl::Now() - start_time); return result;
diff --git a/centipede/centipede_callbacks.h b/centipede/centipede_callbacks.h index 38d6bc3..de2652a 100644 --- a/centipede/centipede_callbacks.h +++ b/centipede/centipede_callbacks.h
@@ -53,10 +53,12 @@ stop_condition_(stop_condition), byte_array_mutator_(env.knobs, GetRandomSeed(env.seed)), fuzztest_mutator_(env.knobs, GetRandomSeed(env.seed)), - inputs_blobseq_(shmem_name1_.c_str(), env.shmem_size_mb << 20, - env.use_posix_shmem), - outputs_blobseq_(shmem_name2_.c_str(), env.shmem_size_mb << 20, - env.use_posix_shmem) { + inputs_blobseq_(CreateSharedMemoryBlobSequence(shmem_name1_.c_str(), + env.shmem_size_mb << 20, + env.use_posix_shmem)), + outputs_blobseq_(CreateSharedMemoryBlobSequence(shmem_name2_.c_str(), + env.shmem_size_mb << 20, + env.use_posix_shmem)) { if (env.use_legacy_default_mutator) FUZZTEST_CHECK(byte_array_mutator_.set_max_len(env.max_len)); else @@ -188,23 +190,23 @@ // They are computed in CTOR, to avoid extra computation in the hot loop. std::string temp_dir_ = TemporaryLocalDirPath(); std::string temp_input_file_path_ = - std::filesystem::path(temp_dir_).append("temp_input_file"); + std::filesystem::path(temp_dir_).append("temp_input_file").string(); const std::string execute_log_prefix_ = - std::filesystem::path(temp_dir_).append("log"); + std::filesystem::path(temp_dir_).append("log").string(); // An owned file path to save the last execution log before it goes out of // scope. const std::string saved_execute_log_path_ = - std::filesystem::path(temp_dir_).append("saved_log"); + std::filesystem::path(temp_dir_).append("saved_log").string(); std::string last_execute_log_path_; std::string failure_description_path_ = - std::filesystem::path(temp_dir_).append("failure_description"); + std::filesystem::path(temp_dir_).append("failure_description").string(); std::string failure_signature_path_ = - std::filesystem::path(temp_dir_).append("failure_signature"); + std::filesystem::path(temp_dir_).append("failure_signature").string(); const std::string shmem_name1_ = ProcessAndThreadUniqueID("/ctpd-shm1-"); const std::string shmem_name2_ = ProcessAndThreadUniqueID("/ctpd-shm2-"); - SharedMemoryBlobSequence inputs_blobseq_; - SharedMemoryBlobSequence outputs_blobseq_; + std::unique_ptr<SharedMemoryBlobSequence> absl_nonnull inputs_blobseq_; + std::unique_ptr<SharedMemoryBlobSequence> absl_nonnull outputs_blobseq_; // Need unique_ptr indirection because CommandContext is not movable/copyable // due to Command.
diff --git a/centipede/centipede_interface.cc b/centipede/centipede_interface.cc index ffbb00f..4beadfc 100644 --- a/centipede/centipede_interface.cc +++ b/centipede/centipede_interface.cc
@@ -84,7 +84,7 @@ void ForEachBlob(const Environment& env, StopCondition& stop_condition) { auto tmpdir = TemporaryLocalDirPath(); CreateLocalDirRemovedAtExit(tmpdir); - std::string tmpfile = std::filesystem::path(tmpdir).append("t"); + std::string tmpfile = (std::filesystem::path(tmpdir) / "t").string(); for (const auto& arg : env.args) { FUZZTEST_LOG(INFO) << "Running '" << env.for_each_blob << "' on " << arg; @@ -213,7 +213,8 @@ binary_info.Write(binary_info_dir); } if (binary_info.uses_legacy_trace_pc_instrumentation) { - pcs_file_path = std::filesystem::path(TemporaryLocalDirPath()) / "pcs"; + pcs_file_path = + (std::filesystem::path(TemporaryLocalDirPath()) / "pcs").string(); SavePCTableToFile(binary_info.pc_table, pcs_file_path); } if (env.use_pcpair_features) { @@ -339,21 +340,21 @@ const std::vector<std::string>& seed_coverage_dirs) { const WorkDir workdir{env}; SeedCorpusSource regression; - regression.dir_glob = std::string(regression_dir); + regression.src_dirs = {std::string(regression_dir)}; regression.num_recent_dirs = 1; - regression.individual_input_rel_glob = "*"; + regression.individual_input_rel_prefix = ""; regression.sampled_fraction_or_count = 1.0f; std::vector<SeedCorpusSource> sources = {std::move(regression)}; const auto make_coverage_source = [&workdir](std::string_view dir) { SeedCorpusSource coverage; - coverage.dir_glob = std::string(dir); + coverage.src_dirs = {std::string(dir)}; coverage.num_recent_dirs = 1; // We're using the previously distilled corpus files as seeds. - coverage.shard_rel_glob = - std::filesystem::path{ - workdir.DistilledCorpusFilePaths().AllShardsGlob()} - .filename(); - coverage.individual_input_rel_glob = "*"; + coverage.shard_rel_prefix = + std::filesystem::path{workdir.DistilledCorpusFilePaths().prefix()} + .filename() + .string(); + coverage.individual_input_rel_prefix = ""; coverage.sampled_fraction_or_count = 1.0f; return coverage; }; @@ -369,9 +370,10 @@ SeedCorpusDestination destination; destination.dir_path = env.workdir; // We're seeding the current corpus files. - destination.shard_rel_glob = - std::filesystem::path{workdir.CorpusFilePaths().AllShardsGlob()} - .filename(); + destination.shard_rel_prefix = + std::filesystem::path{workdir.CorpusFilePaths().prefix()} + .filename() + .string(); destination.shard_index_digits = WorkDir::kDigitsInShardIndex; destination.num_shards = static_cast<uint32_t>(env.num_threads); return { @@ -498,22 +500,22 @@ if (update_coverage_db) { // Distill and store the coverage corpus. Distill(env); - if (RemotePathExists(db_paths.coverage_dir.c_str())) { + if (RemotePathExists(db_paths.coverage_dir.string())) { // In the future, we will store k latest coverage corpora for some k, but // for now we only keep the latest one. - FUZZTEST_CHECK_OK(RemotePathDelete(db_paths.coverage_dir.c_str(), + FUZZTEST_CHECK_OK(RemotePathDelete(db_paths.coverage_dir.string(), /*recursively=*/true)); } - FUZZTEST_CHECK_OK(RemoteMkdir(db_paths.coverage_dir.c_str())); + FUZZTEST_CHECK_OK(RemoteMkdir(db_paths.coverage_dir.string())); std::vector<std::string> distilled_corpus_files; FUZZTEST_CHECK_OK( RemoteGlobMatch(workdir.DistilledCorpusFilePaths().AllShardsGlob(), distilled_corpus_files)); for (const std::string& corpus_file : distilled_corpus_files) { const std::string file_name = - std::filesystem::path(corpus_file).filename(); + std::filesystem::path(corpus_file).filename().string(); FUZZTEST_CHECK_OK(RemoteFileRename( - corpus_file, (db_paths.coverage_dir / file_name).c_str())); + corpus_file, (db_paths.coverage_dir / file_name).string())); } } } @@ -583,7 +585,7 @@ stop_condition.SetStopTime(absl::InfiniteFuture()); if (!is_workdir_specified) { - env.workdir = base_workdir_path / env.test_name; + env.workdir = (base_workdir_path / env.test_name).string(); } const auto execution_id_path = (base_workdir_path / absl::StrCat(env.test_name, ".execution_id")) @@ -653,9 +655,9 @@ // inputs from the previous fuzzing session. if (!is_resuming) { FUZZTEST_CHECK_OK(GenerateSeedCorpusFromConfig( - GetSeedCorpusConfig(env, db_paths.regression_dir.c_str(), + GetSeedCorpusConfig(env, db_paths.regression_dir.string(), env.fuzztest_replay_coverage_inputs - ? db_paths.coverage_dir.c_str() + ? db_paths.coverage_dir.string() : "", GetSeedCoverageDirs(env)), env.binary_name, env.binary_hash)) @@ -665,7 +667,7 @@ absl::Duration time_limit = env.fuzztest_time_limit_per_test; absl::Duration time_spent = absl::ZeroDuration(); const std::string fuzzing_time_file = - std::filesystem::path(env.workdir) / "fuzzing_time"; + (std::filesystem::path(env.workdir) / "fuzzing_time").string(); if (is_resuming && RemotePathExists(fuzzing_time_file)) { time_spent = ReadFuzzingTime(fuzzing_time_file); time_limit = std::max(time_limit - time_spent, absl::ZeroDuration()); @@ -698,10 +700,11 @@ if (!stats_root_path.empty()) { const auto stats_dir = stats_root_path / env.test_name; - FUZZTEST_CHECK_OK(RemoteMkdir(stats_dir.c_str())); + FUZZTEST_CHECK_OK(RemoteMkdir(stats_dir.string())); FUZZTEST_CHECK_OK(RemoteFileRename( workdir.FuzzingStatsPath(), - (stats_dir / absl::StrCat("fuzzing_stats_", execution_stamp)).c_str())); + (stats_dir / absl::StrCat("fuzzing_stats_", execution_stamp)) + .string())); } if (stop_condition.StopRequested(&stop_request)) { @@ -741,7 +744,8 @@ std::vector<std::string> results; results.reserve(crash_paths.size()); for (const auto& crash_path : crash_paths) { - std::string crash_id = std::filesystem::path{crash_path}.filename(); + std::string crash_id = + std::filesystem::path{crash_path}.filename().string(); results.push_back(std::move(crash_id)); } FUZZTEST_CHECK_OK(RemoteFileSetContents(env.list_crash_ids_file, @@ -762,21 +766,24 @@ "crashing"; const WorkDir workdir{env}; SeedCorpusSource crash_corpus_source; - crash_corpus_source.dir_glob = crash_dir; + crash_corpus_source.src_dirs = {crash_dir.string()}; crash_corpus_source.num_recent_dirs = 1; - crash_corpus_source.individual_input_rel_glob = env.crash_id; + crash_corpus_source.individual_input_rel_prefix = env.crash_id; crash_corpus_source.sampled_fraction_or_count = 1.0f; - const SeedCorpusConfig crash_corpus_config = { - /*sources=*/{crash_corpus_source}, - /*destination=*/{ - /*dir_path=*/env.workdir, - /*shard_rel_glob=*/ - std::filesystem::path{workdir.CorpusFilePaths().AllShardsGlob()} - .filename(), - /*shard_index_digits=*/WorkDir::kDigitsInShardIndex, - /*num_shards=*/1}}; - FUZZTEST_CHECK_OK(GenerateSeedCorpusFromConfig( - crash_corpus_config, env.binary_name, env.binary_hash)); + { + SeedCorpusDestination crash_corpus_destination; + crash_corpus_destination.dir_path = env.workdir; + crash_corpus_destination.shard_rel_prefix = + std::filesystem::path{workdir.CorpusFilePaths().prefix()} + .filename() + .string(); + crash_corpus_destination.shard_index_digits = WorkDir::kDigitsInShardIndex; + crash_corpus_destination.num_shards = 1; + FUZZTEST_CHECK_OK( + GenerateSeedCorpusFromConfig({/*sources=*/{crash_corpus_source}, + /*destination=*/crash_corpus_destination}, + env.binary_name, env.binary_hash)); + } Environment run_crash_env = env; run_crash_env.load_shards_only = true; run_crash_env.persistent_mode = false; @@ -809,11 +816,12 @@ env.fuzztest_binary_identifier / env.test_name / "crashing"; std::string crash_contents; - const auto read_status = - RemoteFileGetContents((crash_dir / env.crash_id).c_str(), crash_contents); + const auto read_status = RemoteFileGetContents( + (crash_dir / env.crash_id).string(), crash_contents); if (!read_status.ok()) { FUZZTEST_LOG(ERROR) << "Failed reading the crash " << env.crash_id - << " from " << crash_dir.c_str() << ": " << read_status; + << " from " << crash_dir.string() << ": " + << read_status; return EXIT_FAILURE; } const auto write_status =
diff --git a/centipede/centipede_test.cc b/centipede/centipede_test.cc index d7fe79a..2b8feaf 100644 --- a/centipede/centipede_test.cc +++ b/centipede/centipede_test.cc
@@ -153,7 +153,7 @@ TempCorpusDir tmp_dir{test_info_->name()}; Environment env; env.log_level = 0; // Disable most of the logging in the test. - env.workdir = tmp_dir.path(); + env.workdir = tmp_dir.path().string(); env.num_runs = 100000; // Enough to run through all 1- and 2-byte inputs. env.batch_size = 7; // Just some small number. env.require_pc_table = false; // No PC table here. @@ -181,11 +181,11 @@ TempDir corpus_dir{test_info_->name(), "corpus"}; Environment env; env.log_level = 0; // Disable most of the logging in the test. - env.workdir = workdir_1.path(); + env.workdir = workdir_1.path().string(); env.num_runs = 100000; // Enough to run through all 1- and 2-byte inputs. env.batch_size = 7; // Just some small number. env.require_pc_table = false; // No PC table here. - env.corpus_dir.push_back(corpus_dir.path()); + env.corpus_dir.push_back(corpus_dir.path().string()); // Need to wrap each CentipedeMain in a scope to make sure the shmem is // released before the next call. Otherwise it may fail in MacOS. @@ -202,7 +202,7 @@ { // Second, run without fuzzing using the same corpus_dir. - env.workdir = workdir_2.path(); + env.workdir = workdir_2.path().string(); env.num_runs = 0; CentipedeMock mock_2(env); NonOwningCallbacksFactory factory_2(mock_2); @@ -218,11 +218,11 @@ TempDir corpus_dir{test_info_->name(), "corpus"}; Environment env; env.log_level = 0; // Disable most of the logging in the test. - env.workdir = workdir_1.path(); + env.workdir = workdir_1.path().string(); env.num_runs = 100000; // Enough to run through all 1- and 2-byte inputs. env.batch_size = 7; // Just some small number. env.require_pc_table = false; // No PC table here. - env.corpus_dir.push_back(corpus_dir.path()); + env.corpus_dir.push_back(corpus_dir.path().string()); { // First, generate corpus files in corpus_dir. @@ -238,7 +238,7 @@ { // Second, run without fuzzing using the same corpus_dir, but as // output-only. - env.workdir = workdir_2.path(); + env.workdir = workdir_2.path().string(); env.num_runs = 0; env.first_corpus_dir_output_only = true; CentipedeMock mock_2(env); @@ -253,7 +253,7 @@ TempCorpusDir tmp_dir{test_info_->name()}; Environment env; env.log_level = 0; // Disable most of the logging in the test. - env.workdir = tmp_dir.path(); + env.workdir = tmp_dir.path().string(); env.num_runs = 100000; // Enough to run through all 1- and 2-byte inputs. env.batch_size = 7; // Just some small number. env.require_pc_table = false; // No PC table here. @@ -274,7 +274,7 @@ TEST(Centipede, ShardsAndDistillTest) { TempCorpusDir tmp_dir{test_info_->name()}; Environment env; - env.workdir = tmp_dir.path(); + env.workdir = tmp_dir.path().string(); env.log_level = 0; // Disable most of the logging in the test. size_t combined_num_runs = 100000; // Enough to run through all inputs. env.total_shards = 20; @@ -337,13 +337,14 @@ TEST(Centipede, InputFilter) { TempCorpusDir tmp_dir{test_info_->name()}; Environment env; - env.workdir = tmp_dir.path(); + env.workdir = tmp_dir.path().string(); env.num_runs = 256; // Enough to run through all 1- byte inputs. env.log_level = 0; // Disable most of the logging in the test. env.require_pc_table = false; // No PC table here. // Add %f so that test_input_filter doesn't need to be linked with forkserver. - env.input_filter = "%f" + std::string{GetDataDependencyFilepath( - "centipede/testing/test_input_filter")}; + env.input_filter = + "%f" + + GetDataDependencyFilepath("centipede/testing/test_input_filter").string(); CentipedeMock mock(env); NonOwningCallbacksFactory factory(mock); CentipedeMain(env, factory); // Run fuzzing. @@ -405,10 +406,10 @@ TEST_F(CentipedeWithTemporaryLocalDir, MutateViaExternalBinary) { // This binary contains a test-friendly custom mutator. const std::string binary_with_custom_mutator = - GetDataDependencyFilepath("centipede/testing/test_fuzz_target"); + GetDataDependencyFilepath("centipede/testing/test_fuzz_target").string(); // This binary does not contain a custom mutator. const std::string binary_without_custom_mutator = - GetDataDependencyFilepath("centipede/testing/abort_fuzz_target"); + GetDataDependencyFilepath("centipede/testing/abort_fuzz_target").string(); // Mutate a couple of different inputs. std::vector<ByteArray> inputs = {{0, 1, 2}, {3, 4}}; // The custom mutator in the test binary will revert the order of bytes @@ -548,7 +549,7 @@ // each. TempCorpusDir work_tmp_dir{test_info_->name(), "workdir"}; Environment env; - env.workdir = work_tmp_dir.path(); + env.workdir = work_tmp_dir.path().string(); env.num_runs = 3; // Just a few runs. env.require_pc_table = false; // No PC table here. MergeMock mock(env); @@ -564,7 +565,7 @@ // the seed {0} each. TempCorpusDir merge_tmp_dir(test_info_->name(), "merge_from"); Environment merge_env; - merge_env.workdir = merge_tmp_dir.path(); + merge_env.workdir = merge_tmp_dir.path().string(); merge_env.num_runs = 4; merge_env.require_pc_table = false; // No PC table here. mock.Reset(); @@ -579,7 +580,7 @@ // Merge shards of `merge_env` into shards of `env`. // Shard 0 will receive one extra input: {4} // Shard 1 will receive two extra inputs: {7}, {8} - env.merge_from = merge_tmp_dir.path(); + env.merge_from = merge_tmp_dir.path().string(); env.num_runs = 0; for (env.my_shard_index = 0; env.my_shard_index < 2; ++env.my_shard_index) { CentipedeMain(env, factory); @@ -649,12 +650,13 @@ static std::vector<ByteArray> RunWithFunctionFilter( std::string_view function_filter, const TempDir& tmp_dir) { Environment env; - env.workdir = tmp_dir.path(); + env.workdir = tmp_dir.path().string(); env.seed = 1; // make the runs predictable. env.exec_time_weight_scaling = false; env.num_runs = 100; env.batch_size = 10; - env.binary = GetDataDependencyFilepath("centipede/testing/test_fuzz_target"); + env.binary = + GetDataDependencyFilepath("centipede/testing/test_fuzz_target").string(); env.coverage_binary = env.binary; // Must symbolize in order for the filter to work. env.symbolizer_path = GetLLVMSymbolizerPath(); @@ -769,8 +771,9 @@ const std::string& dir_path = arg; std::vector<FileAndContents> files_and_contents; for (const auto& dir_ent : std::filesystem::directory_iterator(dir_path)) { - auto file_and_contents = FileAndContents{dir_ent.path().filename()}; - ReadFromLocalFile(dir_ent.path().c_str(), file_and_contents.contents); + auto file_and_contents = + FileAndContents{dir_ent.path().filename().string()}; + ReadFromLocalFile(dir_ent.path().string(), file_and_contents.contents); files_and_contents.push_back(std::move(file_and_contents)); } return ExplainMatchResult(expected_files_and_contents, files_and_contents, @@ -783,7 +786,7 @@ TEST(Centipede, ExtraBinaries) { TempDir tmp_dir{test_info_->name()}; Environment env; - env.workdir = tmp_dir.path(); + env.workdir = tmp_dir.path().string(); env.num_runs = 100; env.batch_size = 10; env.log_level = 1; @@ -911,7 +914,7 @@ TempDir temp_dir{test_info_->name()}; Environment env; - env.workdir = temp_dir.path(); + env.workdir = temp_dir.path().string(); env.num_runs = kBatchSize * kNumBatches; env.batch_size = kBatchSize; // No real binary: prevent attempts by Centipede to read a PCtable from it. @@ -936,7 +939,7 @@ std::vector<std::string> found_crash_file_names; for (auto const& dir_ent : std::filesystem::directory_iterator(crashes_dir_path)) { - found_crash_file_names.push_back(dir_ent.path().filename()); + found_crash_file_names.push_back(dir_ent.path().filename().string()); } // TODO(ussuri): Verify exact names/contents of the files, not just count. EXPECT_EQ(found_crash_file_names.size(), kCrashingInputIdxInBatch + 1); @@ -948,7 +951,7 @@ // Verify that when `env.batch_triage_suspect_only` is set, only triage the // suspect. TempDir suspect_only_temp_dir{test_info_->name()}; - env.workdir = suspect_only_temp_dir.path(); + env.workdir = suspect_only_temp_dir.path().string(); env.batch_triage_suspect_only = true; UndetectedCrashingInputMock suspect_only_mock(env, kCrashingInputIdx); NonOwningCallbacksFactory suspect_only_factory(suspect_only_mock); @@ -1082,8 +1085,8 @@ TEST_F(CentipedeWithTemporaryLocalDir, GetsSeedInputs) { Environment env; - env.binary = - GetDataDependencyFilepath("centipede/testing/seeded_fuzz_target"); + env.binary = GetDataDependencyFilepath("centipede/testing/seeded_fuzz_target") + .string(); CentipedeDefaultCallbacks callbacks(env, stop_condition); std::vector<ByteArray> seeds; @@ -1181,7 +1184,8 @@ TEST_F(CentipedeWithTemporaryLocalDir, GetsSerializedTargetConfig) { Environment env; env.binary = - GetDataDependencyFilepath("centipede/testing/fuzz_target_with_config"); + GetDataDependencyFilepath("centipede/testing/fuzz_target_with_config") + .string(); CentipedeDefaultCallbacks callbacks(env, stop_condition); const auto serialized_config = callbacks.GetSerializedTargetConfig(); @@ -1194,7 +1198,7 @@ Environment env; env.binary = absl::StrCat( GetDataDependencyFilepath("centipede/testing/fuzz_target_with_config") - .c_str(), + .string(), " --simulate_failure"); CentipedeDefaultCallbacks callbacks(env, stop_condition); @@ -1205,7 +1209,8 @@ TEST_F(CentipedeWithTemporaryLocalDir, CleansUpMetadataAfterStartup) { Environment env; env.binary = GetDataDependencyFilepath( - "centipede/testing/expensive_startup_fuzz_target"); + "centipede/testing/expensive_startup_fuzz_target") + .string(); CentipedeDefaultCallbacks callbacks(env, stop_condition); BatchResult batch_result; @@ -1252,7 +1257,7 @@ TEST(Centipede, RunsExecuteCallbackInTheCurrentThreadWhenFuzzingWithOneThread) { TempDir temp_dir{test_info_->name()}; Environment env; - env.workdir = temp_dir.path(); + env.workdir = temp_dir.path().string(); env.require_pc_table = false; ASSERT_EQ(env.num_threads, 1); FakeCentipedeCallbacksForThreadChecking callbacks(env, @@ -1267,7 +1272,8 @@ TEST_F(CentipedeWithTemporaryLocalDir, DetectsStackOverflow) { Environment env; - env.binary = GetDataDependencyFilepath("centipede/testing/test_fuzz_target"); + env.binary = + GetDataDependencyFilepath("centipede/testing/test_fuzz_target").string(); env.stack_limit_kb = 64; CentipedeDefaultCallbacks callbacks(env, stop_condition); @@ -1310,7 +1316,7 @@ TempDir temp_dir{test_info_->name()}; Environment env; env.log_level = 0; // Disable most of the logging in the test. - env.workdir = temp_dir.path(); + env.workdir = temp_dir.path().string(); env.batch_size = 7; // Just some small number. env.require_pc_table = false; // No PC table here. SetupFailureCallbacks mock(env); @@ -1350,7 +1356,7 @@ TempDir temp_dir{test_info_->name()}; Environment env; env.log_level = 0; // Disable most of the logging in the test. - env.workdir = temp_dir.path(); + env.workdir = temp_dir.path().string(); env.batch_size = 7; // Just some small number. env.require_pc_table = false; // No PC table here. SkippedTestCallbacks mock(env); @@ -1390,7 +1396,7 @@ TempDir temp_dir{test_info_->name()}; Environment env; env.log_level = 0; // Disable most of the logging in the test. - env.workdir = temp_dir.path(); + env.workdir = temp_dir.path().string(); env.batch_size = 7; // Just some small number. env.num_runs = 100; env.require_pc_table = false; // No PC table here. @@ -1436,7 +1442,7 @@ TEST(Centipede, DoesNotReduceInputWhenTheOptionIsUnset) { TempCorpusDir tmp_dir{test_info_->name()}; Environment env; - env.workdir = tmp_dir.path(); + env.workdir = tmp_dir.path().string(); env.num_runs = 1000000; // Should be enough env.batch_size = 7; // Just some small number. env.require_pc_table = false; @@ -1457,7 +1463,7 @@ TEST(Centipede, ReducesInputWhenTheOptionIsSet) { TempCorpusDir tmp_dir{test_info_->name()}; Environment env; - env.workdir = tmp_dir.path(); + env.workdir = tmp_dir.path().string(); env.num_runs = 1000000; // Should be enough env.batch_size = 7; // Just some small number. env.require_pc_table = false; @@ -1478,7 +1484,8 @@ TEST_F(CentipedeWithTemporaryLocalDir, UsesProvidedCustomMutator) { Environment env; env.binary = GetDataDependencyFilepath( - "centipede/testing/fuzz_target_with_custom_mutator"); + "centipede/testing/fuzz_target_with_custom_mutator") + .string(); CentipedeDefaultCallbacks callbacks(env, stop_condition); const std::vector<ByteArray> inputs = {{99}}; @@ -1495,7 +1502,7 @@ env.binary = absl::StrCat(GetDataDependencyFilepath( "centipede/testing/fuzz_target_with_custom_mutator") - .c_str(), + .string(), " --simulate_failure"); StopCondition stop_condition; CentipedeDefaultCallbacks callbacks(env, stop_condition); @@ -1512,7 +1519,8 @@ TEST_F(CentipedeWithTemporaryLocalDir, FallsBackToBuiltInMutatorWhenCustomMutatorNotProvided) { Environment env; - env.binary = GetDataDependencyFilepath("centipede/testing/abort_fuzz_target"); + env.binary = + GetDataDependencyFilepath("centipede/testing/abort_fuzz_target").string(); CentipedeDefaultCallbacks callbacks(env, stop_condition); const std::vector<ByteArray> inputs = {{1}, {2}, {3}, {4}, {5}, {6}}; @@ -1541,7 +1549,8 @@ TEST_F(CentipedeWithTemporaryLocalDir, HangingFuzzTargetExitsAfterTimeout) { Environment env; env.binary = - GetDataDependencyFilepath("centipede/testing/hanging_fuzz_target"); + GetDataDependencyFilepath("centipede/testing/hanging_fuzz_target") + .string(); BatchResult batch_result; const std::vector<ByteArray> inputs = {{0}}; CentipedeDefaultCallbacks callbacks(env, stop_condition); @@ -1556,7 +1565,8 @@ TEST_F(CentipedeWithTemporaryLocalDir, ExecuteEndsAfterCustomFailure) { Environment env; - env.binary = GetDataDependencyFilepath("centipede/testing/test_fuzz_target"); + env.binary = + GetDataDependencyFilepath("centipede/testing/test_fuzz_target").string(); CentipedeDefaultCallbacks callbacks(env, stop_condition); BatchResult result; std::vector<ByteArray> inputs = { @@ -1576,7 +1586,8 @@ TEST_F(CentipedeWithTemporaryLocalDir, ToleratesAsyncFailureInMutation) { Environment env; env.binary = - GetDataDependencyFilepath("centipede/testing/async_failing_target"); + GetDataDependencyFilepath("centipede/testing/async_failing_target") + .string(); StopCondition stop_condition; CentipedeDefaultCallbacks callbacks(env, stop_condition); BatchResult result; @@ -1621,9 +1632,10 @@ TEST_F(CentipedeWithTemporaryLocalDir, EngineWorksInWorkerMode) { TempCorpusDir tmp_dir{test_info_->name()}; Environment env; - env.workdir = tmp_dir.path(); + env.workdir = tmp_dir.path().string(); env.binary = GetDataDependencyFilepath( - "centipede/testing/test_binary_for_engine_testing"); + "centipede/testing/test_binary_for_engine_testing") + .string(); env.test_name = "some_test"; env.populate_binary_info = false; env.fork_server = true;
diff --git a/centipede/command_test.cc b/centipede/command_test.cc index f31ad8b..41bb600 100644 --- a/centipede/command_test.cc +++ b/centipede/command_test.cc
@@ -166,13 +166,13 @@ TEST(CommandTest, ForkServer) { const std::filesystem::path test_tmpdir = GetTestTempDir(test_info_->name()); const std::string helper = - GetDataDependencyFilepath("centipede/command_test_helper"); + GetDataDependencyFilepath("centipede/command_test_helper").string(); // TODO(ussuri): Dedupe these testcases. { const std::string input = "success"; - const std::string log_prefix = test_tmpdir / input; + const std::string log_prefix = (test_tmpdir / input).string(); Command::Options cmd_options; cmd_options.args = {input}; cmd_options.stdout_file_prefix = log_prefix;
diff --git a/centipede/config_file.cc b/centipede/config_file.cc index 89c0613..e0d59e0 100644 --- a/centipede/config_file.cc +++ b/centipede/config_file.cc
@@ -162,7 +162,7 @@ if (!path.empty() && !std::filesystem::exists(path)) { // assume remote // Read the remote file. std::string contents; - FUZZTEST_CHECK_OK(RemoteFileGetContents(path.c_str(), contents)); + FUZZTEST_CHECK_OK(RemoteFileGetContents(path.string(), contents)); // Save a temporary local copy. const std::filesystem::path tmp_dir = TemporaryLocalDirPath(); @@ -170,11 +170,11 @@ FUZZTEST_LOG(INFO) << "Localizing remote config: " << VV(path) << VV(local_path); // NOTE: Ignore "Remote" in the API names here: the paths are always local. - FUZZTEST_CHECK_OK(RemoteMkdir(tmp_dir.c_str())); - FUZZTEST_CHECK_OK(RemoteFileSetContents(local_path.c_str(), contents)); + FUZZTEST_CHECK_OK(RemoteMkdir(tmp_dir.string())); + FUZZTEST_CHECK_OK(RemoteFileSetContents(local_path.string(), contents)); // Augment the argv to point at the local copy and ensure it is cleaned up. - replacements.emplace_back(path.c_str(), local_path.c_str()); + replacements.emplace_back(path.string(), local_path.string()); cleanup = [local_path]() { std::filesystem::remove(local_path); }; } @@ -245,7 +245,7 @@ } else { file_contents = flags_str; } - FUZZTEST_CHECK_OK(RemoteFileSetContents(path.c_str(), file_contents)); + FUZZTEST_CHECK_OK(RemoteFileSetContents(path.string(), file_contents)); } return path;
diff --git a/centipede/control_flow_test.cc b/centipede/control_flow_test.cc index 0c687c7..c4a8239 100644 --- a/centipede/control_flow_test.cc +++ b/centipede/control_flow_test.cc
@@ -182,13 +182,15 @@ // Returns path to test_fuzz_target. static std::string GetTargetPath() { - return GetDataDependencyFilepath("centipede/testing/test_fuzz_target"); + return GetDataDependencyFilepath("centipede/testing/test_fuzz_target") + .string(); } // Returns path to test_fuzz_target_trace_pc. static std::string GetTracePCTargetPath() { return GetDataDependencyFilepath( - "centipede/testing/test_fuzz_target_trace_pc"); + "centipede/testing/test_fuzz_target_trace_pc") + .string(); } // Tests GetCfTableFromBinary() on test_fuzz_target.
diff --git a/centipede/corpus_io_test.cc b/centipede/corpus_io_test.cc index f368a31..3025c04 100644 --- a/centipede/corpus_io_test.cc +++ b/centipede/corpus_io_test.cc
@@ -51,7 +51,7 @@ std::vector<ByteArray> inputs; for (const auto& file : std::filesystem::directory_iterator(dir)) { ByteArray input; - ReadFromLocalFile(file.path().c_str(), input); + ReadFromLocalFile(file.path().string(), input); inputs.push_back(std::move(input)); } return inputs; @@ -110,16 +110,16 @@ const std::filesystem::path temp_dir = GetTestTempDir(test_info_->name()); const std::filesystem::path out_dir = temp_dir / "out_dir"; FUZZTEST_CHECK(std::filesystem::create_directory(out_dir)); - const WorkDir workdir{temp_dir.c_str(), "fake_binary_name", + const WorkDir workdir{temp_dir.string(), "fake_binary_name", "fake_binary_hash", /*my_shard_index=*/0}; const auto corpus_file_paths = workdir.CorpusFilePaths(); WriteBlobsToFile(corpus_file_paths.Shard(0), {ByteArray{1, 2}, ByteArray{3}}); WriteBlobsToFile(corpus_file_paths.Shard(1), {ByteArray{4}, ByteArray{5, 6}}); ExportCorpus({corpus_file_paths.Shard(0), corpus_file_paths.Shard(1)}, - out_dir.c_str()); + out_dir.string()); - EXPECT_THAT(ReadInputsFromFiles(out_dir.c_str()), + EXPECT_THAT(ReadInputsFromFiles(out_dir.string()), UnorderedElementsAre(ByteArray{1, 2}, ByteArray{3}, ByteArray{4}, ByteArray{5, 6})); }
diff --git a/centipede/corpus_test.cc b/centipede/corpus_test.cc index 5187a60..08c7322 100644 --- a/centipede/corpus_test.cc +++ b/centipede/corpus_test.cc
@@ -66,7 +66,7 @@ corpus.Add({1, 2, 3}, features1, {}, /*stats=*/{}, fs, coverage_frontier); fs.MergeFeatures(features2); corpus.Add({4, 5}, features2, {}, /*stats=*/{}, fs, coverage_frontier); - const std::string stats_filepath = test_tmpdir / "corpus.txt"; + const std::string stats_filepath = (test_tmpdir / "corpus.txt").string(); corpus.DumpStatsToFile(fs, stats_filepath, "Test corpus"); std::string stats_file_contents; ReadFromLocalFile(stats_filepath, stats_file_contents);
diff --git a/centipede/coverage_test.cc b/centipede/coverage_test.cc index 4f3a830..b327b56 100644 --- a/centipede/coverage_test.cc +++ b/centipede/coverage_test.cc
@@ -175,12 +175,14 @@ // Returns path to test_fuzz_target. static std::string GetTargetPath() { - return GetDataDependencyFilepath("centipede/testing/test_fuzz_target"); + return GetDataDependencyFilepath("centipede/testing/test_fuzz_target") + .string(); } // Returns path to threaded_fuzz_target. static std::string GetThreadedTargetPath() { - return GetDataDependencyFilepath("centipede/testing/threaded_fuzz_target"); + return GetDataDependencyFilepath("centipede/testing/threaded_fuzz_target") + .string(); } // Tests coverage collection on test_fuzz_target
diff --git a/centipede/crash_deduplication.cc b/centipede/crash_deduplication.cc index a27f73d..156d520 100644 --- a/centipede/crash_deduplication.cc +++ b/centipede/crash_deduplication.cc
@@ -133,7 +133,7 @@ const std::filesystem::path& dir) { ASSIGN_OR_RETURN_IF_NOT_OK( std::vector<std::string> files, - RemoteListFiles(dir.c_str(), /*recursively=*/false)); + RemoteListFiles(dir.string(), /*recursively=*/false)); struct FileWithMTime { std::string path; @@ -199,7 +199,7 @@ IncubatingCrash incubating; incubating.details.input_path = input_file; incubating.details.input_signature = - std::filesystem::path(input_file).filename().c_str(); + std::filesystem::path(input_file).filename().string(); incubating_crashes.push_back(std::move(incubating)); } return incubating_crashes; @@ -480,9 +480,9 @@ GetInputFileName(bug_id, crash_signature, details.input_signature); std::filesystem::path new_input_path = crashing_dir / new_input_file_name; - if (details.input_path != new_input_path.c_str()) { + if (details.input_path != new_input_path.string()) { RETURN_IF_NOT_OK( - RemoteFileCopy(details.input_path, new_input_path.c_str())); + RemoteFileCopy(details.input_path, new_input_path.string())); } crash_summary.AddCrash( @@ -532,7 +532,7 @@ crash_summary.AddCrash({ /*id=*/std::filesystem::path(existing.crash_report.details.input_path) .filename() - .c_str(), + .string(), /*category=*/std::string(GetCrashCategory(description)), existing.crash_report.signature, description, @@ -593,7 +593,7 @@ std::filesystem::path dest_path = incubating_dir / existing.crash_report.details.input_signature; RETURN_IF_NOT_OK(RemoteFileRename( - existing.crash_report.details.input_path, dest_path.c_str())); + existing.crash_report.details.input_path, dest_path.string())); break; } @@ -615,7 +615,7 @@ FUZZTEST_LOG(INFO) << "Action: StoreNewCrash for signature '" << signature << "' (input: " << report.details.input_signature << ", bug_id: " << report.bug_id << ") to '" - << crashing_dir.c_str() + << crashing_dir.string() << "'. Reason: New crash signature discovered."; RETURN_IF_NOT_OK(WriteCrashToFile(crashing_dir, report.bug_id, report.signature, report.details, @@ -652,12 +652,12 @@ const std::filesystem::path& source_dir, const std::filesystem::path& regression_dir, absl::Duration ttl, absl::Clock& clock) { - if (!RemotePathExists(source_dir.c_str())) { + if (!RemotePathExists(source_dir.string())) { return absl::OkStatus(); } ASSIGN_OR_RETURN_IF_NOT_OK( const std::vector<std::string> active_crash_files, - RemoteListFiles(source_dir.c_str(), /*recursively=*/false)); + RemoteListFiles(source_dir.string(), /*recursively=*/false)); absl::Time now = clock.TimeNow(); @@ -670,15 +670,15 @@ if (input_file_components.ok()) { dest_filename = input_file_components->input_signature; } else { - dest_filename = std::filesystem::path(file_path).filename().c_str(); + dest_filename = std::filesystem::path(file_path).filename().string(); } std::filesystem::path dest_path = regression_dir / dest_filename; FUZZTEST_LOG(INFO) << "Action: MoveToRegression for '" << file_path - << "' -> '" << dest_path.c_str() + << "' -> '" << dest_path.string() << "'. Reason: Crash expired (not reproduced for " << (now - mtime) << " > TTL " << ttl << ")."; - RETURN_IF_NOT_OK(RemoteFileRename(file_path, dest_path.c_str())); + RETURN_IF_NOT_OK(RemoteFileRename(file_path, dest_path.string())); } } return absl::OkStatus(); @@ -704,9 +704,10 @@ for (std::string& crashing_input_path : crashing_input_paths) { std::string crashing_input_file_name = - std::filesystem::path(crashing_input_path).filename(); + std::filesystem::path(crashing_input_path).filename().string(); const std::string crash_signature_path = - crash_metadata_dir / absl::StrCat(crashing_input_file_name, ".sig"); + (crash_metadata_dir / absl::StrCat(crashing_input_file_name, ".sig")) + .string(); std::string crash_signature; const absl::Status status = RemoteFileGetContents(crash_signature_path, crash_signature); @@ -728,7 +729,8 @@ if (crashes.contains(crash_signature)) continue; const std::string crash_description_path = - crash_metadata_dir / absl::StrCat(crashing_input_file_name, ".desc"); + (crash_metadata_dir / absl::StrCat(crashing_input_file_name, ".desc")) + .string(); std::string crash_description; const absl::Status description_status = RemoteFileGetContents(crash_description_path, crash_description); @@ -769,9 +771,9 @@ new_crashes_by_signature, CrashSummary& crash_summary, StopCondition& stop_condition, absl::Duration regression_ttl, absl::Clock& clock) { - RETURN_IF_NOT_OK(RemoteMkdir(crashing_dir.c_str())); - RETURN_IF_NOT_OK(RemoteMkdir(regression_dir.c_str())); - RETURN_IF_NOT_OK(RemoteMkdir(incubating_dir.c_str())); + RETURN_IF_NOT_OK(RemoteMkdir(crashing_dir.string())); + RETURN_IF_NOT_OK(RemoteMkdir(regression_dir.string())); + RETURN_IF_NOT_OK(RemoteMkdir(incubating_dir.string())); ASSIGN_OR_RETURN_IF_NOT_OK(auto existing_crashes, ReadExistingCrashes(crashing_dir));
diff --git a/centipede/crash_deduplication_test.cc b/centipede/crash_deduplication_test.cc index 459262c..bebae22 100644 --- a/centipede/crash_deduplication_test.cc +++ b/centipede/crash_deduplication_test.cc
@@ -82,14 +82,14 @@ std::string SetContentsAndGetPath(const std::filesystem::path& dir, std::string_view file_name, std::string_view contents) { - const std::string file_path = dir / file_name; + const std::string file_path = (dir / file_name).string(); WriteToLocalFile(file_path, contents); return file_path; } TEST(GetCrashesFromWorkdirTest, ReturnsOneCrashPerCrashSignature) { TempDir test_dir; - const std::string workdir_path = test_dir.path(); + const std::string workdir_path = test_dir.path().string(); WorkDir workdir{workdir_path, "binary_name", "binary_hash", /*my_shard_index=*/0}; @@ -142,7 +142,7 @@ TEST(GetCrashesFromWorkdirTest, FailsOnEmptyCrashSignatureIfEnvVarSet) { TempDir test_dir; - const std::string workdir_path = test_dir.path(); + const std::string workdir_path = test_dir.path().string(); WorkDir workdir{workdir_path, "binary_name", "binary_hash", /*my_shard_index=*/0}; @@ -165,7 +165,7 @@ TEST(GetCrashesFromWorkdirTest, FailsOnEmptyCrashDescriptionIfEnvVarSet) { TempDir test_dir; - const std::string workdir_path = test_dir.path(); + const std::string workdir_path = test_dir.path().string(); WorkDir workdir{workdir_path, "binary_name", "binary_hash", /*my_shard_index=*/0}; @@ -200,9 +200,9 @@ std::vector<FileAndContents> files; for (const auto& f : std::filesystem::directory_iterator(dir)) { std::string contents; - ReadFromLocalFile(f.path().c_str(), contents); - files.push_back(FileAndContents{std::filesystem::path(f).filename(), - std::move(contents)}); + ReadFromLocalFile(f.path().string(), contents); + files.push_back(FileAndContents{ + std::filesystem::path(f).filename().string(), std::move(contents)}); } return files; }
diff --git a/centipede/distill_test.cc b/centipede/distill_test.cc index 047f67f..4b698a5 100644 --- a/centipede/distill_test.cc +++ b/centipede/distill_test.cc
@@ -102,7 +102,7 @@ // We need to set at least --binary_hash before `env` is constructed, // so we do this by overriding the flags. absl::FlagSaver flag_saver; - std::string dir = GetTestTempDir(test_name); + std::string dir = GetTestTempDir(test_name).string(); std::filesystem::remove_all(dir); std::filesystem::create_directories(dir); Environment env;
diff --git a/centipede/engine_worker.cc b/centipede/engine_worker.cc index df6910e..75d17df 100644 --- a/centipede/engine_worker.cc +++ b/centipede/engine_worker.cc
@@ -326,8 +326,11 @@ } const char* input_path = GetWorkerFlags().GetStringFlag(kWorkerInputsBlobSequencePathFlagHeader); - WorkerCheck(input_path != nullptr, "inputs blob sequence is missing"); - return new SharedMemoryBlobSequence(input_path, shmem_size); + if (input_path == nullptr) { + WorkerCheck(false, "inputs blob sequence is missing"); + __builtin_unreachable(); + } + return OpenSharedMemoryBlobSequence(input_path, shmem_size).release(); }(); return result; } @@ -340,8 +343,11 @@ } const char* output_path = GetWorkerFlags().GetStringFlag( kWorkerOutputsBlobSequencePathFlagHeader); - WorkerCheck(output_path != nullptr, "outputs blob sequence is missing"); - return new SharedMemoryBlobSequence(output_path, shmem_size); + if (output_path == nullptr) { + WorkerCheck(false, "outputs blob sequence is missing"); + __builtin_unreachable(); + } + return OpenSharedMemoryBlobSequence(output_path, shmem_size).release(); }(); return result; }
diff --git a/centipede/runner.cc b/centipede/runner.cc index f8f38a9..cd19be9 100644 --- a/centipede/runner.cc +++ b/centipede/runner.cc
@@ -689,10 +689,10 @@ if (!state->centipede_runner_main_executed && state->run_time_flags.shmem_size_mb != 0) { PostProcessSancov(); // TODO(xinhaoyuan): do we know our exit status? - SharedMemoryBlobSequence outputs_blobseq( + auto outputs_blobseq = OpenSharedMemoryBlobSequence( sancov_state->arg2, state->run_time_flags.shmem_size_mb << 20); - StartSendingOutputsToEngine(outputs_blobseq); - FinishSendingOutputsToEngine(outputs_blobseq); + StartSendingOutputsToEngine(*outputs_blobseq); + FinishSendingOutputsToEngine(*outputs_blobseq); } { LockGuard lock(state->execution_result_override_mu); @@ -745,10 +745,10 @@ // needed by the LLVM fuzzer runners (used by some engine tests). We // cannot remove it until the LLVM fuzzers can be migrated to use // the FuzzTest LLVM fuzzer wrapper. - SharedMemoryBlobSequence outputs_blobseq( + auto outputs_blobseq = OpenSharedMemoryBlobSequence( sancov_state->arg2, sancov_state->flag_helper.GetIntFlag("shmem_size_mb=", 0) << 20); - RunnerCheck(MutationResult::WriteHasCustomMutator(false, outputs_blobseq), + RunnerCheck(MutationResult::WriteHasCustomMutator(false, *outputs_blobseq), "Failed to write the indicator for no custom mutator"); std::_Exit(0); }
diff --git a/centipede/runner_result_test.cc b/centipede/runner_result_test.cc index f8c86cb..02e917d 100644 --- a/centipede/runner_result_test.cc +++ b/centipede/runner_result_test.cc
@@ -103,7 +103,8 @@ } TEST(ExecutionResult, WriteIntoFileThenRead) { - const std::string temp_file = GetTestTempDir(test_info_->name()) / "tmp.txt"; + const std::string temp_file = + (GetTestTempDir(test_info_->name()) / "tmp.txt").string(); std::ofstream output_stream(temp_file, std::ios::out); ASSERT_TRUE(output_stream.is_open());
diff --git a/centipede/rusage_stats.cc b/centipede/rusage_stats.cc index c5bf850..3ce6e83 100644 --- a/centipede/rusage_stats.cc +++ b/centipede/rusage_stats.cc
@@ -14,14 +14,22 @@ #include "./centipede/rusage_stats.h" +#ifdef _WIN32 +#include "./common/windows_includes.h" +#else // _WIN32 + +#include <sys/resource.h> #ifdef __APPLE__ #include <libproc.h> #include <sys/proc.h> #include <sys/sysctl.h> -#endif // __APPLE__ +#else // __APPLE__ #include <sys/syscall.h> #include <sys/types.h> #include <unistd.h> +#endif // __APPLE__ + +#endif // _WIN32 #include <array> #include <cinttypes> @@ -47,41 +55,84 @@ namespace fuzztest::internal { +namespace { + +void GetTimeUsage(double& user, double& sys) { +#ifdef _WIN32 + FILETIME creation_time, exit_time, kernel_time, user_time; + FUZZTEST_CHECK(GetProcessTimes(GetCurrentProcess(), &creation_time, + &exit_time, &kernel_time, &user_time) != 0) + << "Failed to get time usage by GetProcessTimes()"; + uint64_t user_100ns = + (static_cast<uint64_t>(user_time.dwHighDateTime) << 32) | + user_time.dwLowDateTime; + uint64_t sys_100ns = + (static_cast<uint64_t>(kernel_time.dwHighDateTime) << 32) | + kernel_time.dwLowDateTime; + static constexpr double kSecondTo100ns = 1000 * 1000 * 10; + user = user_100ns / kSecondTo100ns; + sys = sys_100ns / kSecondTo100ns; +#else + struct rusage rusage; + FUZZTEST_CHECK(getrusage(RUSAGE_SELF, &rusage) == 0) + << "Failed to get time usage by getrusage()"; + user = absl::ToDoubleSeconds(absl::DurationFromTimeval(rusage.ru_utime)); + sys = absl::ToDoubleSeconds(absl::DurationFromTimeval(rusage.ru_stime)); +#endif +} + +} // namespace + //------------------------------------------------------------------------------ // ProcessTimer //------------------------------------------------------------------------------ -ProcessTimer::ProcessTimer() : start_time_{absl::Now()}, start_rusage_{} { - getrusage(RUSAGE_SELF, &start_rusage_); +ProcessTimer::ProcessTimer() + : start_time_{absl::Now()}, usage_user_{0}, usage_sys_{0} { + GetTimeUsage(usage_user_, usage_sys_); } void ProcessTimer::Get(double& user, double& sys, double& wall) const { - struct rusage curr_rusage = {}; - getrusage(RUSAGE_SELF, &curr_rusage); - // clang-format off - user = absl::ToDoubleSeconds( - absl::DurationFromTimeval(curr_rusage.ru_utime) - - absl::DurationFromTimeval(start_rusage_.ru_utime)); - sys = absl::ToDoubleSeconds( - absl::DurationFromTimeval(curr_rusage.ru_stime) - - absl::DurationFromTimeval(start_rusage_.ru_stime)); + double cur_usage_user = 0; + double cur_usage_sys = 0; + GetTimeUsage(cur_usage_user, cur_usage_sys); + user = cur_usage_user - usage_user_; + sys = cur_usage_sys - usage_sys_; wall = absl::ToDoubleSeconds(absl::Now() - start_time_); - // clang-format on } //------------------------------------------------------------------------------ // RUsageScope //------------------------------------------------------------------------------ -#ifdef __APPLE__ +#if defined(_WIN32) class RUsageScope::PlatformInfo { public: - PlatformInfo(pid_t pid) : pid_(pid) {} - - pid_t pid() const { return pid_; } + enum ProcFile : size_t { + kSched = 0, + kStatm = 1, + kStatus = 2, + kNumDoNotUseDirectly = 3 + }; + PlatformInfo(ProcessId pid) : pid_(pid) {} + ProcessId pid() const { return pid_; } + const std::string& GetProcFilePath(ProcFile file) const { + static const std::string empty; + return empty; + } private: - pid_t pid_; + ProcessId pid_; +}; +#elif defined(__APPLE__) +class RUsageScope::PlatformInfo { + public: + PlatformInfo(ProcessId pid) : pid_(pid) {} + + ProcessId pid() const { return pid_; } + + private: + ProcessId pid_; }; #else class RUsageScope::PlatformInfo { @@ -93,7 +144,7 @@ kNumDoNotUseDirectly = 3 }; - PlatformInfo(pid_t pid) + PlatformInfo(ProcessId pid) : proc_file_paths_{ absl::StrFormat("/proc/%d/sched", pid), absl::StrFormat("/proc/%d/statm", pid), @@ -112,15 +163,19 @@ #endif RUsageScope RUsageScope::ThisProcess() { // +#if defined(_WIN32) + return RUsageScope{GetCurrentProcessId()}; +#else return RUsageScope{getpid()}; +#endif } -RUsageScope RUsageScope::Process(pid_t pid) { // +RUsageScope RUsageScope::Process(ProcessId pid) { // return RUsageScope{pid}; } -RUsageScope::RUsageScope(pid_t pid) - : description_{absl::StrFormat("PID=%d", pid)}, +RUsageScope::RUsageScope(ProcessId pid) + : description_{absl::StrCat("PID=", pid)}, info_(std::make_shared<PlatformInfo>(pid)) {} namespace detail { @@ -362,7 +417,9 @@ // TODO(b/265480321): This does not honor `scope`. timer.Get(user_time, sys_time, wall_time); double cpu_utilization = 0; -#ifdef __APPLE__ +#if defined(_WIN32) + // Not supported on Windows +#elif defined(__APPLE__) int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, scope.info().pid()}; struct kinfo_proc info = {}; size_t size = sizeof(info); @@ -517,7 +574,30 @@ RUsageMemory RUsageMemory::Snapshot(const RUsageScope& scope) { [[maybe_unused]] MemSize vsize = 0, rss = 0, shared = 0, code = 0, unused = 0, data = 0, vpeak = 0; -#ifdef __APPLE__ +#if defined(_WIN32) + HANDLE h_process = NULL; + if (scope.info().pid() == static_cast<ProcessId>(GetCurrentProcessId())) { + h_process = GetCurrentProcess(); + } else { + h_process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, + scope.info().pid()); + } + if (h_process != NULL) { + PROCESS_MEMORY_COUNTERS_EX pmc; + if (GetProcessMemoryInfo(h_process, + reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pmc), + sizeof(pmc))) { + // Getting proper v{size,peak} is too hard. Use rss for now. + vsize = static_cast<MemSize>(pmc.WorkingSetSize); + vpeak = static_cast<MemSize>(pmc.PeakWorkingSetSize); + rss = static_cast<MemSize>(pmc.WorkingSetSize); + data = static_cast<MemSize>(pmc.PrivateUsage); + } + if (h_process != GetCurrentProcess()) { + CloseHandle(h_process); + } + } +#elif defined(__APPLE__) if (scope.info().pid() != getpid()) return {}; struct proc_taskinfo pti = {}; FUZZTEST_CHECK(proc_pidinfo(scope.info().pid(), PROC_PIDTASKINFO, 0, &pti,
diff --git a/centipede/rusage_stats.h b/centipede/rusage_stats.h index d0d1cde..90a70bf 100644 --- a/centipede/rusage_stats.h +++ b/centipede/rusage_stats.h
@@ -21,8 +21,6 @@ #ifndef THIRD_PARTY_CENTIPEDE_RUSAGE_STATS_H_ #define THIRD_PARTY_CENTIPEDE_RUSAGE_STATS_H_ -#include <sys/resource.h> - #include <array> #include <cstddef> #include <cstdint> @@ -49,6 +47,13 @@ // scheduler's accounting logic. using CpuUtilization = long double; +// Platform dependent process ID type without including platform headers. +#if defined(_WIN32) +using ProcessId = unsigned int; +#else +using ProcessId = int; +#endif + //------------------------------------------------------------------------------ // RUsageScope // @@ -59,7 +64,7 @@ // Static ctors for supported use cases. If the same scope is used repeatedly, // callers should prefer caching it, as construction may involve syscalls. static RUsageScope ThisProcess(); - static RUsageScope Process(pid_t pid); + static RUsageScope Process(ProcessId pid); // Copyable and movable. RUsageScope(const RUsageScope&) = default; @@ -83,7 +88,7 @@ } private: - explicit RUsageScope(pid_t pid); + explicit RUsageScope(ProcessId pid); std::string description_; // Use shared_ptr to make the class copyable (without actually copying the @@ -108,7 +113,8 @@ private: absl::Time start_time_; - struct rusage start_rusage_; + double usage_user_; + double usage_sys_; }; //------------------------------------------------------------------------------
diff --git a/centipede/rusage_stats_test.cc b/centipede/rusage_stats_test.cc index 7f5e058..d34c34b 100644 --- a/centipede/rusage_stats_test.cc +++ b/centipede/rusage_stats_test.cc
@@ -308,7 +308,7 @@ } TEST(RUsageMemoryTest, BadScope) { - constexpr pid_t kBadPid = 999999999; + constexpr ProcessId kBadPid = 999999999; EXPECT_NO_FATAL_FAILURE( // const auto timing = RUsageTiming::Snapshot(RUsageScope::Process(kBadPid)); FUZZTEST_VLOG(1) << "Timing: " << timing;); @@ -507,11 +507,11 @@ } TEST(RUsageMemoryTest, Logging) { - RUsageMemory memory{/*mem_vsize=*/1L * 1024 * 1024 * 1024, - /*mem_vpeak=*/2L * 1024 * 1024 * 1024, - /*mem_rss=*/500L * 1024 * 1024, - /*mem_data=*/750L * 1024 * 1024, - /*mem_shared=*/250L * 1024, + RUsageMemory memory{/*mem_vsize=*/1LL * 1024 * 1024 * 1024, + /*mem_vpeak=*/2LL * 1024 * 1024 * 1024, + /*mem_rss=*/500LL * 1024 * 1024, + /*mem_data=*/750LL * 1024 * 1024, + /*mem_shared=*/250LL * 1024, /*is_delta=*/false}; std::stringstream ss;
diff --git a/centipede/seed_corpus_maker.cc b/centipede/seed_corpus_maker.cc index 01830d8..3f2b6b2 100644 --- a/centipede/seed_corpus_maker.cc +++ b/centipede/seed_corpus_maker.cc
@@ -32,7 +32,8 @@ FUZZTEST_QCHECK(!config.empty()); const std::string override_out_dir = absl::GetFlag(FLAGS_override_out_dir); const std::string binary_path = absl::GetFlag(FLAGS_coverage_binary_path); - const std::string binary_name = std::filesystem::path{binary_path}.filename(); + const std::string binary_name = + std::filesystem::path{binary_path}.filename().string(); FUZZTEST_QCHECK(!binary_name.empty()) << "--coverage_binary_path yields empty basename"; std::string binary_hash = absl::GetFlag(FLAGS_coverage_binary_hash);
diff --git a/centipede/seed_corpus_maker_lib.cc b/centipede/seed_corpus_maker_lib.cc index 702c28b..2e3a9af 100644 --- a/centipede/seed_corpus_maker_lib.cc +++ b/centipede/seed_corpus_maker_lib.cc
@@ -105,29 +105,78 @@ // `source.num_recent_dirs()` most recent ones. std::vector<std::string> src_dirs; - if (const auto match_status = RemoteGlobMatch(source.dir_glob, src_dirs); - !match_status.ok() && !absl::IsNotFound(match_status)) { - return match_status; + if (!source.dir_glob.empty()) { + if (const auto match_status = RemoteGlobMatch(source.dir_glob, src_dirs); + !match_status.ok() && !absl::IsNotFound(match_status)) { + return match_status; + } + FUZZTEST_LOG(INFO) << "Found " << src_dirs.size() + << " corpus dir(s) candidates matching " + << source.dir_glob; } - FUZZTEST_LOG(INFO) << "Found " << src_dirs.size() - << " corpus dir(s) matching " << source.dir_glob; + src_dirs.insert(src_dirs.end(), source.src_dirs.begin(), + source.src_dirs.end()); // Sort in the ascending lexicographical order. We expect that dir names // contain timestamps and therefore will be sorted from oldest to newest. std::sort(src_dirs.begin(), src_dirs.end(), std::less<std::string>()); + src_dirs.erase(std::unique(src_dirs.begin(), src_dirs.end()), src_dirs.end()); + src_dirs.erase(std::remove_if(src_dirs.begin(), src_dirs.end(), + [](const auto& path) { + return !RemotePathIsDirectory(path); + }), + src_dirs.end()); if (source.num_recent_dirs < src_dirs.size()) { src_dirs.erase(src_dirs.begin(), src_dirs.end() - source.num_recent_dirs); FUZZTEST_LOG(INFO) << "Selected " << src_dirs.size() << " corpus dir(s)"; } + FUZZTEST_LOG(INFO) + << "Reading/sampling seed corpus elements from source dir(s): "; + for (const auto& src_dir : src_dirs) { + FUZZTEST_LOG(INFO) << " " << src_dir; + } + // Find all the corpus shard and individual input files in the found dirs. std::vector<std::string> corpus_shard_fnames; std::vector<std::string> individual_input_fnames; for (const auto& dir : src_dirs) { absl::flat_hash_set<std::string> current_corpus_shard_fnames; + if (source.shard_rel_prefix.has_value()) { + if (!source.shard_rel_glob.empty()) { + return absl::InvalidArgumentError( + "Must not specify both shard_rel_prefix and shard_rel_glob"); + } + const auto shard_prefix = + std::filesystem::path{fs::path{dir} / *source.shard_rel_prefix}; + const auto candidates = + RemoteListFiles(shard_prefix.parent_path().string(), + /*recursively=*/false); + if (candidates.ok()) { + const auto shard_prefix_filename = shard_prefix.filename().string(); + size_t num_added_shards = 0; + for (const auto& candidate : *candidates) { + if (!absl::StartsWith( + std::filesystem::path{candidate}.filename().string(), + shard_prefix_filename)) { + continue; + } + ++num_added_shards; + corpus_shard_fnames.push_back(candidate); + current_corpus_shard_fnames.insert(candidate); + } + FUZZTEST_LOG(INFO) << "Found " << num_added_shards + << " shard(s) matching prefix [" + << *source.shard_rel_prefix << "]"; + } else { + FUZZTEST_LOG(ERROR) + << "Got error when listing with " << VV(*source.shard_rel_prefix) + << ": " << candidates.status(); + } + } if (!source.shard_rel_glob.empty()) { std::vector<std::string> matched_fnames; - const std::string glob = fs::path{dir} / source.shard_rel_glob; + const std::string glob = (fs::path{dir} / source.shard_rel_glob).string(); const auto match_status = RemoteGlobMatch(glob, matched_fnames); if (!match_status.ok() && !absl::IsNotFound(match_status)) { FUZZTEST_LOG(ERROR) << "Got error when glob-matching in " << dir << ": " @@ -142,9 +191,47 @@ << " shard(s) matching " << glob; } } + if (source.individual_input_rel_prefix.has_value()) { + if (!source.individual_input_rel_glob.empty()) { + return absl::InvalidArgumentError( + "Must not specify both individual_input_rel_prefix and " + "individual_input_rel_glob"); + } + const auto individual_input_prefix = std::filesystem::path{ + fs::path{dir} / *source.individual_input_rel_prefix}; + const auto candidates = + RemoteListFiles(individual_input_prefix.parent_path().string(), + /*recursively=*/false); + if (candidates.ok()) { + const auto individual_input_prefix_filename = + individual_input_prefix.filename().string(); + size_t num_added_individual_inputs = 0; + for (const auto& candidate : *candidates) { + if (RemotePathIsDirectory(candidate)) { + continue; + } + if (!absl::StartsWith( + std::filesystem::path{candidate}.filename().string(), + individual_input_prefix_filename)) { + continue; + } + if (current_corpus_shard_fnames.contains(candidate)) continue; + ++num_added_individual_inputs; + individual_input_fnames.push_back(candidate); + } + FUZZTEST_LOG(INFO) << "Found " << num_added_individual_inputs + << " individual input(s) with prefix: [" + << *source.individual_input_rel_prefix << "]"; + } else { + FUZZTEST_LOG(ERROR) << "Got error when listing with " + << VV(*source.individual_input_rel_prefix) << ": " + << candidates.status(); + } + } if (!source.individual_input_rel_glob.empty()) { std::vector<std::string> matched_fnames; - const std::string glob = fs::path{dir} / source.individual_input_rel_glob; + const std::string glob = + (fs::path{dir} / source.individual_input_rel_glob).string(); const auto match_status = RemoteGlobMatch(glob, matched_fnames); if (!match_status.ok() && !absl::IsNotFound(match_status)) { FUZZTEST_LOG(ERROR) << "Got error when glob-matching in " << dir << ": " @@ -378,10 +465,19 @@ return absl::InvalidArgumentError( "Requested number of destination shards must be > 0"); } - if (!absl::StrContains(destination.shard_rel_glob, "*")) { + if (!destination.shard_rel_glob.empty()) { + if (!absl::StrContains(destination.shard_rel_glob, "*")) { + return absl::InvalidArgumentError( + absl::StrCat("Destination shard pattern must contain '*', got ", + destination.shard_rel_glob)); + } + if (destination.shard_rel_prefix.has_value()) { + return absl::InvalidArgumentError( + "Cannot have both shard_rel_glob and shard_rel_prefix"); + } + } else if (!destination.shard_rel_prefix.has_value()) { return absl::InvalidArgumentError( - absl::StrCat("Destination shard pattern must contain '*', got ", - destination.shard_rel_glob)); + "Missing shard_rel_glob and shard_rel_prefix"); } // Compute shard sizes. If the elements can't be evenly divided between the @@ -424,9 +520,12 @@ const std::string shard_idx = absl::StrFormat("%0*d", destination.shard_index_digits, shard); const std::string corpus_rel_fname = - absl::StrReplaceAll(destination.shard_rel_glob, {{"*", shard_idx}}); + !destination.shard_rel_glob.empty() + ? absl::StrReplaceAll(destination.shard_rel_glob, + {{"*", shard_idx}}) + : absl::StrCat(*destination.shard_rel_prefix, shard_idx); const std::string corpus_fname = - fs::path{destination.dir_path} / corpus_rel_fname; + (fs::path{destination.dir_path} / corpus_rel_fname).string(); const auto work_dir = WorkDir::FromCorpusShardPath( // corpus_fname, coverage_binary_name, coverage_binary_hash);
diff --git a/centipede/seed_corpus_maker_lib.h b/centipede/seed_corpus_maker_lib.h index d551265..cea612a 100644 --- a/centipede/seed_corpus_maker_lib.h +++ b/centipede/seed_corpus_maker_lib.h
@@ -17,6 +17,7 @@ #include <cstdint> #include <iostream> +#include <optional> #include <string> #include <string_view> #include <utility> @@ -37,12 +38,18 @@ // difference is commented below. struct SeedCorpusSource { std::string dir_glob; + // Source directory in addition to scanning `dir_glob`. + std::vector<std::string> src_dirs; uint32_t num_recent_dirs; std::string shard_rel_glob; + // A path prefix relative to the source dirs used to find corpus shards. + std::optional<std::string> shard_rel_prefix; // If non-empty, will be used to glob the individual input files (with one // input in each file) in the source dirs. Any files matching `shard_rel_glob` // will be skipped. std::string individual_input_rel_glob; + // A path prefix relative to the source dirs to find individual inputs. + std::optional<std::string> individual_input_rel_prefix; std::variant<float, uint32_t> sampled_fraction_or_count; std::string features_start_point; @@ -62,6 +69,8 @@ struct SeedCorpusDestination { std::string dir_path; std::string shard_rel_glob; + // A path prefix relative to `dir_path` to generate output shards. + std::optional<std::string> shard_rel_prefix; uint32_t shard_index_digits; uint32_t num_shards; };
diff --git a/centipede/seed_corpus_maker_lib_test.cc b/centipede/seed_corpus_maker_lib_test.cc index 12d405f..41280fa 100644 --- a/centipede/seed_corpus_maker_lib_test.cc +++ b/centipede/seed_corpus_maker_lib_test.cc
@@ -14,11 +14,10 @@ #include "./centipede/seed_corpus_maker_lib.h" -#include <unistd.h> - #include <cmath> #include <cstddef> #include <filesystem> // NOLINT +#include <optional> #include <string> #include <string_view> #include <tuple> @@ -41,6 +40,7 @@ using ::testing::IsSubsetOf; using ::testing::IsSupersetOf; +using ::testing::UnitTest; inline constexpr auto kIdxDigits = WorkDir::kDigitsInShardIndex; @@ -94,9 +94,17 @@ << VV(workdir); } -TEST(SeedCorpusMakerLibTest, RoundTripWriteReadWrite) { - const fs::path test_dir = GetTestTempDir(test_info_->name()); - chdir(test_dir.c_str()); +struct SeedCorpusMakerLibTestParam { + bool use_globs; +}; + +class SeedCorpusMakerLibTest + : public testing::TestWithParam<SeedCorpusMakerLibTestParam> {}; + +TEST_P(SeedCorpusMakerLibTest, RoundTripWriteReadWrite) { + const fs::path test_dir = + GetTestTempDir(UnitTest::GetInstance()->current_test_info()->name()); + fs::current_path(test_dir); const InputAndFeaturesVec kElements = { {{0}, {}}, @@ -118,13 +126,18 @@ constexpr size_t kNumShards = 2; const SeedCorpusDestination destination = { /*dir_path=*/std::string(kRelDir1), - /*shard_rel_glob=*/absl::StrCat("distilled-", kCovBin, ".*"), + /*shard_rel_glob=*/GetParam().use_globs + ? absl::StrCat("distilled-", kCovBin, ".*") + : "", + /*shard_rel_prefix=*/GetParam().use_globs + ? std::nullopt + : std::make_optional(absl::StrCat("distilled-", kCovBin, ".")), /*shard_index_digits=*/kIdxDigits, /*num_shards=*/kNumShards, }; ASSERT_OK(WriteSeedCorpusElementsToDestination( // kElements, kCovBin, kCovHash, destination)); - const std::string workdir = (test_dir / kRelDir1).c_str(); + const std::string workdir = (test_dir / kRelDir1).string(); ASSERT_NO_FATAL_FAILURE(VerifyShardsExist( // workdir, kCovBin, kCovHash, kNumShards, ShardType::kDistilled)); } @@ -134,9 +147,14 @@ { for (const float fraction : {1.0, 0.5, 0.2}) { SeedCorpusSource source; - source.dir_glob = std::string(kRelDir1); source.num_recent_dirs = 2; - source.shard_rel_glob = absl::StrCat("distilled-", kCovBin, ".*"); + if (GetParam().use_globs) { + source.dir_glob = std::string(kRelDir1); + source.shard_rel_glob = absl::StrCat("distilled-", kCovBin, ".*"); + } else { + source.src_dirs = {std::string(kRelDir1)}; + source.shard_rel_prefix = absl::StrCat("distilled-", kCovBin, "."); + } source.sampled_fraction_or_count = fraction; InputAndFeaturesVec elements; @@ -155,16 +173,24 @@ constexpr size_t kNumShards = 3; SeedCorpusSource source; - source.dir_glob = std::string(kRelDir1); source.num_recent_dirs = 1; - source.shard_rel_glob = absl::StrCat("distilled-", kCovBin, ".*"); + if (GetParam().use_globs) { + source.dir_glob = std::string(kRelDir1); + source.shard_rel_glob = absl::StrCat("distilled-", kCovBin, ".*"); + } else { + source.src_dirs = {std::string(kRelDir1)}; + source.shard_rel_prefix = absl::StrCat("distilled-", kCovBin, "."); + } source.sampled_fraction_or_count = 1.0f; const SeedCorpusConfig config = { /*sources=*/{{source}}, /*destination=*/ { /*dir_path=*/std::string(kRelDir2), - /*shard_rel_glob=*/"corpus.*", + /*shard_rel_glob=*/GetParam().use_globs ? "corpus.*" : "", + /*shard_rel_prefix=*/GetParam().use_globs + ? std::nullopt + : std::optional<std::string>("corpus."), /*shard_index_digits=*/kIdxDigits, /*num_shards=*/kNumShards, }, @@ -173,16 +199,17 @@ { ASSERT_OK(GenerateSeedCorpusFromConfig( // config, kCovBin, kCovHash)); - const std::string workdir = (test_dir / kRelDir2).c_str(); + const std::string workdir = (test_dir / kRelDir2).string(); ASSERT_NO_FATAL_FAILURE(VerifyShardsExist( // workdir, kCovBin, kCovHash, kNumShards, ShardType::kNormal)); } } } -TEST(SeedCorpusMakerLibTest, LoadsBothIndividualInputsAndShardsFromSource) { - const fs::path test_dir = GetTestTempDir(test_info_->name()); - chdir(test_dir.c_str()); +TEST_P(SeedCorpusMakerLibTest, LoadsBothIndividualInputsAndShardsFromSource) { + const fs::path test_dir = + GetTestTempDir(UnitTest::GetInstance()->current_test_info()->name()); + fs::current_path(test_dir); const InputAndFeaturesVec kShardedInputs = { {{0}, {}}, @@ -203,13 +230,18 @@ constexpr size_t kNumShards = 2; const SeedCorpusDestination destination = { /*dir_path=*/std::string(kRelDir), - /*shard_rel_glob=*/absl::StrCat("distilled-", kCovBin, ".*"), + /*shard_rel_glob=*/GetParam().use_globs + ? absl::StrCat("distilled-", kCovBin, ".*") + : "", + /*shard_rel_prefix=*/GetParam().use_globs + ? std::nullopt + : std::make_optional(absl::StrCat("distilled-", kCovBin, ".")), /*shard_index_digits=*/kIdxDigits, /*num_shards=*/kNumShards, }; FUZZTEST_CHECK_OK(WriteSeedCorpusElementsToDestination( // kShardedInputs, kCovBin, kCovHash, destination)); - const std::string workdir = (test_dir / kRelDir).c_str(); + const std::string workdir = (test_dir / kRelDir).string(); ASSERT_NO_FATAL_FAILURE(VerifyShardsExist( // workdir, kCovBin, kCovHash, kNumShards, ShardType::kDistilled)); } @@ -227,12 +259,23 @@ InputAndFeaturesVec elements; ASSERT_OK(SampleSeedCorpusElementsFromSource( // SeedCorpusSource{ - /*dir_glob=*/std::string(kRelDir), + /*dir_glob=*/GetParam().use_globs ? std::string(kRelDir) : "", + /*src_dirs=*/GetParam().use_globs + ? std::vector<std::string>{} + : std::vector<std::string>{std::string{kRelDir}}, /*num_recent_dirs=*/1, - /*shard_rel_glob=*/absl::StrCat("distilled-", kCovBin, ".*"), + /*shard_rel_glob=*/GetParam().use_globs + ? absl::StrCat("distilled-", kCovBin, ".*") + : "", + /*shard_rel_prefix=*/GetParam().use_globs + ? std::nullopt + : std::make_optional(absl::StrCat("distilled-", kCovBin, ".")), // Intentionally try to match the shard files and test if they will // be read as individual inputs. - /*individual_input_rel_glob=*/"*", + /*individual_input_rel_glob=*/GetParam().use_globs ? "*" : "", + /*individual_input_rel_prefix=*/GetParam().use_globs + ? std::nullopt + : std::optional<std::string>{""}, /*sampled_fraction_or_count=*/1.0f, }, kCovBin, kCovHash, elements)); @@ -245,9 +288,10 @@ } } -TEST(SeedCorpusMakerLibTest, FeaturesStartPointCanDropFeatures) { - const fs::path test_dir = GetTestTempDir(test_info_->name()); - chdir(test_dir.c_str()); +TEST_P(SeedCorpusMakerLibTest, FeaturesStartPointCanDropFeatures) { + const fs::path test_dir = + GetTestTempDir(UnitTest::GetInstance()->current_test_info()->name()); + fs::current_path(test_dir); const InputAndFeaturesVec kElementsSrc1 = { {{0}, {}}, @@ -270,7 +314,12 @@ constexpr size_t kNumShards = 2; const SeedCorpusDestination destination_src1 = { /*dir_path=*/std::string(kSrcDir1), - /*shard_rel_glob=*/absl::StrCat("distilled-", kCovBin, ".*"), + /*shard_rel_glob=*/GetParam().use_globs + ? absl::StrCat("distilled-", kCovBin, ".*") + : "", + /*shard_rel_prefix=*/GetParam().use_globs + ? std::nullopt + : std::make_optional(absl::StrCat("distilled-", kCovBin, ".")), /*shard_index_digits=*/kIdxDigits, /*num_shards=*/kNumShards, }; @@ -279,7 +328,12 @@ const SeedCorpusDestination destination_src2 = { /*dir_path=*/std::string(kSrcDir2), - /*shard_rel_glob=*/absl::StrCat("distilled-", kCovBin, ".*"), + /*shard_rel_glob=*/GetParam().use_globs + ? absl::StrCat("distilled-", kCovBin, ".*") + : "", + /*shard_rel_prefix=*/GetParam().use_globs + ? std::nullopt + : std::make_optional(absl::StrCat("distilled-", kCovBin, ".")), /*shard_index_digits=*/kIdxDigits, /*num_shards=*/kNumShards, }; @@ -288,9 +342,17 @@ } SeedCorpusSource source; - source.dir_glob = std::string("dir/src/*"); + if (GetParam().use_globs) { + source.dir_glob = std::string("dir/src/*"); + } else { + source.src_dirs = {std::string{kSrcDir1}, std::string{kSrcDir2}}; + } source.num_recent_dirs = 2; - source.shard_rel_glob = absl::StrCat("distilled-", kCovBin, ".*"); + if (GetParam().use_globs) { + source.shard_rel_glob = absl::StrCat("distilled-", kCovBin, ".*"); + } else { + source.shard_rel_prefix = absl::StrCat("distilled-", kCovBin, "."); + } source.sampled_fraction_or_count = 1.0f; InputAndFeaturesVec elements; @@ -317,9 +379,10 @@ ASSERT_EQ(get_num_features(elements), get_num_features(kElementsSrc2)); } -TEST(SeedCorpusMakerLibTest, SkipsFailingSourcesThatIgnoreErrors) { - const fs::path test_dir = GetTestTempDir(test_info_->name()); - chdir(test_dir.c_str()); +TEST_P(SeedCorpusMakerLibTest, SkipsFailingSourcesThatIgnoreErrors) { + const fs::path test_dir = + GetTestTempDir(UnitTest::GetInstance()->current_test_info()->name()); + fs::current_path(test_dir); constexpr std::string_view kCovBin = "bin"; constexpr std::string_view kCovHash = "hash"; @@ -330,23 +393,32 @@ ASSERT_OK(RemoteMkdir("dir/good")); ASSERT_OK(RemoteFileSetContents("dir/good/input", kGoodInput)); - SeedCorpusSource bad_source; - bad_source.dir_glob = "dir/bad"; - bad_source.num_recent_dirs = 1; - bad_source.individual_input_rel_glob = "*"; + const auto make_input_source = [](std::string_view dir) { + SeedCorpusSource source; + if (GetParam().use_globs) { + source.dir_glob = std::string(dir); + source.individual_input_rel_glob = "*"; + } else { + source.src_dirs = {std::string(dir)}; + source.individual_input_rel_prefix = ""; + } + source.num_recent_dirs = 1; + return source; + }; + SeedCorpusSource bad_source = make_input_source("dir/bad"); // An invalid fraction makes reading the source fail. bad_source.sampled_fraction_or_count = 2.0f; - SeedCorpusSource good_source; - good_source.dir_glob = "dir/good"; - good_source.num_recent_dirs = 1; - good_source.individual_input_rel_glob = "*"; + SeedCorpusSource good_source = make_input_source("dir/good"); good_source.sampled_fraction_or_count = 1.0f; SeedCorpusConfig config = { /*sources=*/{bad_source, good_source}, /*destination=*/ { /*dir_path=*/"dir/out", - /*shard_rel_glob=*/"corpus.*", + /*shard_rel_glob=*/GetParam().use_globs ? "corpus.*" : "", + /*shard_rel_prefix=*/GetParam().use_globs + ? std::nullopt + : std::optional<std::string>("corpus."), /*shard_index_digits=*/kIdxDigits, /*num_shards=*/1, }, @@ -357,9 +429,14 @@ config.sources[0].ignore_errors = true; ASSERT_OK(GenerateSeedCorpusFromConfig(config, kCovBin, kCovHash)); SeedCorpusSource out_source; - out_source.dir_glob = "dir/out"; + if (GetParam().use_globs) { + out_source.dir_glob = "dir/out"; + out_source.shard_rel_glob = "corpus.*"; + } else { + out_source.src_dirs = {"dir/out"}; + out_source.shard_rel_prefix = "corpus."; + } out_source.num_recent_dirs = 1; - out_source.shard_rel_glob = "corpus.*"; out_source.sampled_fraction_or_count = 1.0f; InputAndFeaturesVec elements; ASSERT_OK(SampleSeedCorpusElementsFromSource(out_source, kCovBin, kCovHash, @@ -368,5 +445,10 @@ EXPECT_EQ(std::get<0>(elements[0]), kGoodInput); } +INSTANTIATE_TEST_SUITE_P( + SeedCorpusMakerLibTestWithConfigurations, SeedCorpusMakerLibTest, + testing::Values(SeedCorpusMakerLibTestParam{/*use_globs=*/false}, + SeedCorpusMakerLibTestParam{/*use_globs=*/true})); + } // namespace } // namespace fuzztest::internal
diff --git a/centipede/seed_corpus_maker_proto_lib.cc b/centipede/seed_corpus_maker_proto_lib.cc index bbf8091..50b30ac 100644 --- a/centipede/seed_corpus_maker_proto_lib.cc +++ b/centipede/seed_corpus_maker_proto_lib.cc
@@ -53,14 +53,14 @@ << VV(config_spec); RETURN_IF_NOT_OK(RemoteFileGetContents(config_spec, config_str)); FUZZTEST_LOG(INFO) << "Raw config read from file:\n" << config_str; - base_dir = std::filesystem::path{config_spec}.parent_path(); + base_dir = std::filesystem::path{config_spec}.parent_path().string(); } else { FUZZTEST_LOG(INFO) << "Config spec is not a file, or file doesn't exist; trying to " "parse textproto config verbatim: " << VV(config_spec); config_str = config_spec; - base_dir = fs::current_path(); + base_dir = fs::current_path().string(); } proto::SeedCorpusConfig config; @@ -80,7 +80,7 @@ for (auto& src : *config.mutable_sources()) { auto* dir = src.mutable_dir_glob(); if (dir->empty() || !fs::path{*dir}.is_absolute()) { - *dir = fs::path{base_dir} / *dir; + *dir = (fs::path{base_dir} / *dir).string(); } } @@ -91,7 +91,7 @@ if (!override_out_dir.empty()) { *dir = override_out_dir; } else if (dir->empty() || !fs::path{*dir}.is_absolute()) { - *dir = fs::path{base_dir} / *dir; + *dir = (fs::path{base_dir} / *dir).string(); } } @@ -148,9 +148,9 @@ /*my_shard_index=*/0, }; const std::filesystem::path debug_info_dir = workdir.DebugInfoDirPath(); - RETURN_IF_NOT_OK(RemoteMkdir(debug_info_dir.c_str())); + RETURN_IF_NOT_OK(RemoteMkdir(debug_info_dir.string())); RETURN_IF_NOT_OK(RemoteFileSetContents( - (debug_info_dir / "seeding.cfg").c_str(), absl::StrCat(config))); + (debug_info_dir / "seeding.cfg").string(), absl::StrCat(config))); return absl::OkStatus(); }
diff --git a/centipede/seed_corpus_maker_proto_lib_test.cc b/centipede/seed_corpus_maker_proto_lib_test.cc index 29ab4f6..1e88465 100644 --- a/centipede/seed_corpus_maker_proto_lib_test.cc +++ b/centipede/seed_corpus_maker_proto_lib_test.cc
@@ -16,6 +16,7 @@ #include <cstddef> #include <filesystem> // NOLINT +#include <optional> #include <string> #include <string_view> @@ -111,6 +112,7 @@ const SeedCorpusDestination destination = { /*dir_path=*/std::string(kRelDir1), /*shard_rel_glob=*/absl::StrCat("distilled-", kCovBin, ".*"), + /*shard_rel_prefix=*/std::nullopt, /*shard_index_digits=*/kIdxDigits, /*num_shards=*/2, }; @@ -142,7 +144,7 @@ ASSERT_OK(GenerateSeedCorpusFromConfigProto( // config_str, kCovBin, kCovHash, "")); - const std::string workdir = (test_dir / kRelDir2).c_str(); + const std::string workdir = (test_dir / kRelDir2).string(); ASSERT_NO_FATAL_FAILURE(VerifyDumpedConfig(workdir, kCovBin, kCovHash)); ASSERT_NO_FATAL_FAILURE(VerifyShardsExist( // workdir, kCovBin, kCovHash, kNumShards, ShardType::kNormal));
diff --git a/centipede/shared_memory_blob_sequence.cc b/centipede/shared_memory_blob_sequence.cc index 51415df..37a2ba5 100644 --- a/centipede/shared_memory_blob_sequence.cc +++ b/centipede/shared_memory_blob_sequence.cc
@@ -14,27 +14,53 @@ #include "./centipede/shared_memory_blob_sequence.h" +#if defined(_WIN32) +#include "./common/windows_includes.h" +#else #include <fcntl.h> +#include <limits.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> +#endif +#if defined(_WIN32) || defined(__APPLE__) +#include <algorithm> +#endif #include <cstdint> #include <cstdio> +#include <cstdlib> +#include <cstring> +#include <memory> #include "absl/base/nullability.h" namespace fuzztest::internal { +namespace { + // TODO(ussuri): Refactor `char *` into a `string_view`. -static void ErrorOnFailure(bool condition, const char *absl_nonnull text) { +void ErrorOnFailure(bool condition, const char* absl_nonnull text) { if (!condition) return; +#if defined(_WIN32) + // Win32 APIs report errors via `GetLastError()` instead of `errno`. + std::fprintf(stderr, "%s: Win32 error %lu\n", text, + static_cast<unsigned long>(GetLastError())); +#else std::perror(text); +#endif abort(); } +#if defined(_WIN32) || defined(__APPLE__) +// The size of a blob header (tag and size). +constexpr size_t kBlobHeaderSize = sizeof(Blob::tag) + sizeof(Blob::size); +#endif + +} // namespace + BlobSequence::BlobSequence(uint8_t *data, size_t size) : data_(data), size_(size) { ErrorOnFailure(size < sizeof(Blob::size), "Size too small"); @@ -50,6 +76,12 @@ return false; } + size_t write_end = offset_ + sizeof(blob.tag) + sizeof(blob.size) + blob.size; + if (write_end + sizeof(blob.size) + sizeof(blob.tag) <= size_) { + write_end += sizeof(blob.size) + sizeof(blob.tag); + } + if (!CommitMemory(write_end)) return false; + // Write tag. memcpy(data_ + offset_, &blob.tag, sizeof(blob.tag)); offset_ += sizeof(blob.tag); @@ -104,85 +136,222 @@ had_writes_after_reset_ = false; } -SharedMemoryBlobSequence::SharedMemoryBlobSequence(const char *name, - size_t size, - bool use_posix_shmem) { - ErrorOnFailure(size < sizeof(Blob::size), "Size too small"); - size_ = size; - if (use_posix_shmem) { - fd_ = shm_open(name, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); - ErrorOnFailure(fd_ < 0, "shm_open() failed"); - strncpy(path_, name, PATH_MAX); - ErrorOnFailure(path_[PATH_MAX - 1] != 0, - "shm_open() path length exceeds PATH_MAX."); - path_is_owned_ = true; - } else { +#if defined(_WIN32) + +namespace { + +class WindowsSharedMemoryBlobSequence : public SharedMemoryBlobSequence { + public: + WindowsSharedMemoryBlobSequence(const char* name, size_t size, + bool /*use_posix_shmem*/) { + ErrorOnFailure(size < sizeof(Blob::size), "Size too small"); + size_ = size; + CopyPath(name); + mapping_handle_ = CreateFileMappingA( + INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE | SEC_RESERVE, + static_cast<DWORD>(static_cast<uint64_t>(size_) >> 32), + static_cast<DWORD>(size_ & 0xFFFFFFFF), path_); + ErrorOnFailure(mapping_handle_ == NULL, "CreateFileMappingA() failed"); + data_ = static_cast<uint8_t*>(MapViewOfFile( + mapping_handle_, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, size_)); + ErrorOnFailure(data_ == NULL, "MapViewOfFile() failed"); + // Reading from uncommitted pages of a `SEC_RESERVE` mapping raises an + // access violation, so commit the memory for the first blob header to make + // `Read()` safe before any `Write()`. Newly committed pages are + // zero-initialized, so the header reads as an invalid blob. + CommitMemory(std::min(size_, kBlobHeaderSize)); + } + + WindowsSharedMemoryBlobSequence(const char* path, size_t size) { + ErrorOnFailure(size < sizeof(Blob::size), "Size too small"); + size_ = size; + CopyPath(path); + mapping_handle_ = + OpenFileMappingA(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, path_); + ErrorOnFailure(mapping_handle_ == NULL, "OpenFileMappingA() failed"); + data_ = static_cast<uint8_t*>(MapViewOfFile( + mapping_handle_, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0)); + ErrorOnFailure(data_ == NULL, "MapViewOfFile() failed"); + } + + ~WindowsSharedMemoryBlobSequence() override { + if (data_ != nullptr) { + UnmapViewOfFile(data_); + } + if (mapping_handle_ != nullptr) { + CloseHandle(mapping_handle_); + } + } + + // Pages of a mapped section cannot be decommitted, so instead zero the first + // blob header to prevent stale data from being read after `Reset()`. + void ReleaseSharedMemory() override { + if (committed_ >= kBlobHeaderSize) { + std::memset(data_, 0, kBlobHeaderSize); + } + } + + size_t NumBytesUsed() const override { return committed_; } + + const char* absl_nonnull path() const override { return path_; } + + protected: + bool CommitMemory(size_t write_end) override { + if (write_end <= committed_) return true; + + constexpr size_t kCommitGranularity = 4 * 1024; + const size_t target_committed = + std::min((write_end + kCommitGranularity - 1) / kCommitGranularity * + kCommitGranularity, + size_); + void* res = VirtualAlloc(data_ + committed_, target_committed - committed_, + MEM_COMMIT, PAGE_READWRITE); + ErrorOnFailure(res == nullptr, "VirtualAlloc() failed"); + committed_ = target_committed; + return true; + } + + private: + // Copies `path` into `path_`, aborting if it does not fit. + void CopyPath(const char* absl_nonnull path) { + ErrorOnFailure(strlen(path) >= sizeof(path_), + "path length exceeds MAX_PATH."); + strncpy(path_, path, sizeof(path_)); + } + + char path_[MAX_PATH] = {0}; + HANDLE mapping_handle_ = nullptr; + size_t committed_ = 0; +}; + +} // namespace + +std::unique_ptr<SharedMemoryBlobSequence> absl_nonnull +CreateSharedMemoryBlobSequence(const char* absl_nonnull name, size_t size, + bool use_posix_shmem) { + return std::make_unique<WindowsSharedMemoryBlobSequence>(name, size, + use_posix_shmem); +} + +std::unique_ptr<SharedMemoryBlobSequence> absl_nonnull +OpenSharedMemoryBlobSequence(const char* absl_nonnull path, size_t size) { + return std::make_unique<WindowsSharedMemoryBlobSequence>(path, size); +} + +#else // !_WIN32 + +namespace { + +class PosixSharedMemoryBlobSequence : public SharedMemoryBlobSequence { + public: + PosixSharedMemoryBlobSequence(const char* name, size_t size, + bool use_posix_shmem) { + ErrorOnFailure(size < sizeof(Blob::size), "Size too small"); + size_ = size; + if (use_posix_shmem) { + fd_ = shm_open(name, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + ErrorOnFailure(fd_ < 0, "shm_open() failed"); + strncpy(path_, name, sizeof(path_)); + ErrorOnFailure(path_[sizeof(path_) - 1] != 0, + "shm_open() path length exceeds PATH_MAX."); + path_is_owned_ = true; + } else { #ifdef __APPLE__ - ErrorOnFailure(true, "must use POSIX shmem"); + ErrorOnFailure(true, "must use POSIX shmem"); #else // __APPLE__ - fd_ = memfd_create(name, MFD_CLOEXEC); - ErrorOnFailure(fd_ < 0, "memfd_create() failed"); - const size_t path_size = - snprintf(path_, PATH_MAX, "/proc/%d/fd/%d", getpid(), fd_); - ErrorOnFailure(path_size >= PATH_MAX, - "internal fd path length exceeds PATH_MAX."); - // memfd_create descriptors are automatically freed on close(). - path_is_owned_ = false; + fd_ = memfd_create(name, MFD_CLOEXEC); + ErrorOnFailure(fd_ < 0, "memfd_create() failed"); + const size_t path_size = + snprintf(path_, sizeof(path_), "/proc/%d/fd/%d", getpid(), fd_); + ErrorOnFailure(path_size >= sizeof(path_), + "internal fd path length exceeds PATH_MAX."); + // memfd_create descriptors are automatically freed on close(). + path_is_owned_ = false; +#endif // __APPLE__ + } + ErrorOnFailure(ftruncate(fd_, static_cast<off_t>(size_)), + "ftruncate() failed)"); + MmapData(); + } + + PosixSharedMemoryBlobSequence(const char* path, size_t size) { + ErrorOnFailure(size < sizeof(Blob::size), "Size too small"); + size_ = size; + // This is a quick way to tell shm-allocated paths from memfd paths without + // requiring the caller to specify. + if (strncmp(path, "/proc/", 6) == 0) { + fd_ = open(path, O_RDWR, O_CLOEXEC); + } else { + fd_ = shm_open(path, O_RDWR, 0); + } + ErrorOnFailure(fd_ < 0, "open() failed"); + strncpy(path_, path, sizeof(path_)); + ErrorOnFailure(path_[sizeof(path_) - 1] != 0, + "path length exceeds PATH_MAX."); + MmapData(); + } + + ~PosixSharedMemoryBlobSequence() override { + if (data_ != nullptr) { + ErrorOnFailure(munmap(data_, size_), "munmap() failed"); + data_ = nullptr; + size_ = 0; + } + if (path_is_owned_) { + ErrorOnFailure(shm_unlink(path_), "shm_unlink() failed"); + } + ErrorOnFailure(close(fd_), "close() failed"); + } + + void ReleaseSharedMemory() override { +#ifdef __APPLE__ + // MacOS only allows ftruncate shm once + // (https://stackoverflow.com/questions/25502229/ftruncate-not-working-on-posix-shared-memory-in-mac-os-x). + // So we cannot release the memory, but zero the first blob header to + // prevent stale data from being read after `Reset()`. + std::memset(data_, 0, std::min(size_, kBlobHeaderSize)); +#else // __APPLE__ + // Setting size to 0 releases the memory to OS. + ErrorOnFailure(ftruncate(fd_, 0) != 0, "ftruncate(0) failed)"); + // Set the size back to `size`. The memory is not actually reserved. + ErrorOnFailure(ftruncate(fd_, size_) != 0, "ftruncate(size_) failed)"); #endif // __APPLE__ } - ErrorOnFailure(ftruncate(fd_, static_cast<off_t>(size_)), - "ftruncate() failed)"); - MmapData(); -} -SharedMemoryBlobSequence::SharedMemoryBlobSequence(const char* path, - size_t size) { - ErrorOnFailure(size < sizeof(Blob::size), "Size too small"); - size_ = size; - // This is a quick way to tell shm-allocated paths from memfd paths without - // requiring the caller to specify. - if (strncmp(path, "/proc/", 6) == 0) { - fd_ = open(path, O_RDWR, O_CLOEXEC); - } else { - fd_ = shm_open(path, O_RDWR, 0); + size_t NumBytesUsed() const override { + struct stat statbuf; + ErrorOnFailure(fstat(fd_, &statbuf), "fstat() failed)"); + return statbuf.st_blocks * S_BLKSIZE; } - ErrorOnFailure(fd_ < 0, "open() failed"); - strncpy(path_, path, PATH_MAX); - ErrorOnFailure(path_[PATH_MAX - 1] != 0, "path length exceeds PATH_MAX."); - MmapData(); -} -void SharedMemoryBlobSequence::MmapData() { - data_ = static_cast<uint8_t *>( - mmap(nullptr, size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0)); - ErrorOnFailure(data_ == MAP_FAILED, "mmap() failed"); -} + const char* absl_nonnull path() const override { return path_; } -SharedMemoryBlobSequence::~SharedMemoryBlobSequence() { - if (path_is_owned_) { - ErrorOnFailure(shm_unlink(path_), "shm_unlink() failed"); + private: + void MmapData() { + data_ = static_cast<uint8_t*>( + mmap(nullptr, size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0)); + ErrorOnFailure(data_ == MAP_FAILED, "mmap() failed"); } - ErrorOnFailure(munmap(data_, size_), "munmap() failed"); - ErrorOnFailure(close(fd_), "close() failed"); + + char path_[PATH_MAX] = {0}; + bool path_is_owned_ = false; + int fd_ = -1; +}; + +} // namespace + +std::unique_ptr<SharedMemoryBlobSequence> absl_nonnull +CreateSharedMemoryBlobSequence(const char* absl_nonnull name, size_t size, + bool use_posix_shmem) { + return std::make_unique<PosixSharedMemoryBlobSequence>(name, size, + use_posix_shmem); } -void SharedMemoryBlobSequence::ReleaseSharedMemory() { -#ifdef __APPLE__ - // MacOS only allows ftruncate shm once - // (https://stackoverflow.com/questions/25502229/ftruncate-not-working-on-posix-shared-memory-in-mac-os-x). - // So nothing we can do here. -#else // __APPLE__ - // Setting size to 0 releases the memory to OS. - ErrorOnFailure(ftruncate(fd_, 0) != 0, "ftruncate(0) failed)"); - // Set the size back to `size`. The memory is not actually reserved. - ErrorOnFailure(ftruncate(fd_, size_) != 0, "ftruncate(size_) failed)"); -#endif // __APPLE__ +std::unique_ptr<SharedMemoryBlobSequence> absl_nonnull +OpenSharedMemoryBlobSequence(const char* absl_nonnull path, size_t size) { + return std::make_unique<PosixSharedMemoryBlobSequence>(path, size); } -size_t SharedMemoryBlobSequence::NumBytesUsed() const { - struct stat statbuf; - ErrorOnFailure(fstat(fd_, &statbuf), "fstat() failed)"); - return statbuf.st_blocks * S_BLKSIZE; -} +#endif // _WIN32 } // namespace fuzztest::internal
diff --git a/centipede/shared_memory_blob_sequence.h b/centipede/shared_memory_blob_sequence.h index b5d781e..e2a32ff 100644 --- a/centipede/shared_memory_blob_sequence.h +++ b/centipede/shared_memory_blob_sequence.h
@@ -15,9 +15,9 @@ #ifndef THIRD_PARTY_CENTIPEDE_SHARED_MEMORY_BLOB_SEQUENCE_H_ #define THIRD_PARTY_CENTIPEDE_SHARED_MEMORY_BLOB_SEQUENCE_H_ -#include <climits> #include <cstddef> #include <cstdint> +#include <memory> #include <type_traits> #include "absl/base/nullability.h" @@ -57,6 +57,7 @@ // must be >= 8. Aborts on any failure. The amount of actual data that can be // written is slightly less. explicit BlobSequence(uint8_t *data, size_t size); + virtual ~BlobSequence() = default; // Writes the contents of `blob` to the blob sequence. // Returns true on success. @@ -93,6 +94,9 @@ // constructors of child classes. explicit BlobSequence() = default; + // Commits the memory for `size` bytes starting from `data_`. + virtual bool CommitMemory(size_t size) { return true; } + // data_ contains a sequence of {size, payload} pairs, // where size is 8 bytes and payload is size bytes. // After writing a blob, we also write 0 in place of the next blob's size, @@ -122,11 +126,12 @@ // Usage example: // void ParentProcess() { // // Create a new blob sequence. -// SharedMemoryBlobSequence parent("/foo", 1000); +// auto parent = CreateSharedMemoryBlobSequence( +// "/foo", 1000, /*use_posix_shmem=*/true); // // // Parent process writes some data to the shared blob: -// parent.Write({some_data, some_data_size}); -// parent.Write({some_other_data, some_other_data_size}); +// parent->Write({some_data, some_data_size}); +// parent->Write({some_other_data, some_other_data_size}); // // // Run the child process. // ExecuteChildProcessAndWaitUntilItIsDone(); @@ -134,11 +139,11 @@ // // void Child() { // // Open an existing blob sequence. -// SharedMemoryBlobSequence child("/foo", 1000); +// auto child = OpenSharedMemoryBlobSequence("/foo", 1000); // // // Read the data written by parent. // while (true) { -// auto blob = parent.Read(); +// auto blob = child->Read(); // if (!blob.size) break; // Use({blob.data, blob.size}); // } @@ -146,47 +151,41 @@ // class SharedMemoryBlobSequence : public BlobSequence { public: - // Creates a new shared blob sequence with `name` (for debugging only, not an - // actual path). Aborts on any failure. `size` is the size of the shared - // memory region in bytes, must be >= 8. The amount of actual data that can be - // written is slightly less. - // The `use_posix_shmem` argument specifies which API to use to allocate the - // shared memory. When true, shm_open(2) will be used, otherwise - // memfd_create(2). - SharedMemoryBlobSequence(const char *name, size_t size, bool use_posix_shmem); - - // Opens an existing shared blob sequence with the file `path` and `size`. - // Aborts on any failure. - SharedMemoryBlobSequence(const char* path, size_t size); - // Releases all resources. - ~SharedMemoryBlobSequence(); + ~SharedMemoryBlobSequence() override = default; // Releases shared memory used by `this`. - void ReleaseSharedMemory(); + virtual void ReleaseSharedMemory() = 0; // Returns the number of bytes used by the shared mapping. // It will be zero just after creation and after the call to // ReleaseSharedMemory(). - size_t NumBytesUsed() const; + virtual size_t NumBytesUsed() const = 0; // Gets the file path that can be used to create new instances. // TODO(ussuri): Refactor `char *` into a `string_view`. - const char *absl_nonnull path() const { return path_; } + virtual const char* absl_nonnull path() const = 0; - private: - // mmaps `size_` bytes from `fd_`, assigns to `data_`. Crashes if mmap failed. - void MmapData(); - - // Will be initialized as a generated internal path or a copy of `path` - // passed in. - char path_[PATH_MAX] = {0}; - int fd_ = -1; // file descriptor used to mmap the shared memory region. - // Whether the file pointed to by path_ is owned by this and needs to be - // deallocated on destruction. - bool path_is_owned_ = false; + protected: + SharedMemoryBlobSequence() = default; }; +// Creates a new shared blob sequence with `name` (for debugging only, not an +// actual path). Aborts on any failure. `size` is the size of the shared +// memory region in bytes, must be >= 8. The amount of actual data that can be +// written is slightly less. +// The `use_posix_shmem` argument specifies which API to use to allocate the +// shared memory. When true, shm_open(2) will be used, otherwise +// memfd_create(2). +std::unique_ptr<SharedMemoryBlobSequence> absl_nonnull +CreateSharedMemoryBlobSequence(const char* absl_nonnull name, size_t size, + bool use_posix_shmem); + +// Opens an existing shared blob sequence with the file `path` and `size`. +// Aborts on any failure. +std::unique_ptr<SharedMemoryBlobSequence> absl_nonnull +OpenSharedMemoryBlobSequence(const char* absl_nonnull path, size_t size); + } // namespace fuzztest::internal #endif // THIRD_PARTY_CENTIPEDE_SHARED_MEMORY_BLOB_SEQUENCE_H_
diff --git a/centipede/shared_memory_blob_sequence_test.cc b/centipede/shared_memory_blob_sequence_test.cc index f5dd4fc..32d160d 100644 --- a/centipede/shared_memory_blob_sequence_test.cc +++ b/centipede/shared_memory_blob_sequence_test.cc
@@ -14,7 +14,11 @@ #include "./centipede/shared_memory_blob_sequence.h" +#if !defined(_WIN32) #include <unistd.h> +#else +#include "./common/windows_includes.h" +#endif #include <cstdint> #include <cstdlib> @@ -30,7 +34,12 @@ std::string ShmemName() { std::ostringstream oss; +#if defined(_WIN32) + oss << "/shm_test-" << GetCurrentProcessId() << "-" + << std::this_thread::get_id(); +#else oss << "/shm_test-" << getpid() << "-" << std::this_thread::get_id(); +#endif return oss.str(); } @@ -84,21 +93,22 @@ } class SharedMemoryBlobSequenceTest - : public testing::TestWithParam</* use_shm */ bool> { - public: - void SetUp() override { -#ifdef __APPLE__ - const bool use_shm = GetParam(); - if (!use_shm) { - GTEST_SKIP() << "Skipping test that does not use POSIX shmem on MacOS"; - } -#endif // __APPLE__ - } + : public testing::TestWithParam</* use_shm */ bool> {}; + +// Defined outside of `INSTANTIATE_TEST_SUITE_P` because preprocessor directives +// within macro arguments are undefined behavior. +constexpr bool kUsePosixShmemValues[] = { +#ifndef _WIN32 + true, +#endif +#ifndef __APPLE__ + false, +#endif }; INSTANTIATE_TEST_SUITE_P(SharedMemoryBlobSequenceParametrizedTest, SharedMemoryBlobSequenceTest, - testing::Values(true, false)); + testing::ValuesIn(kUsePosixShmemValues)); TEST_P(SharedMemoryBlobSequenceTest, ParentChild) { std::vector<uint8_t> kTestData1 = {1, 2, 3}; @@ -106,32 +116,33 @@ std::vector<uint8_t> kTestData3 = {8, 9}; std::vector<uint8_t> kTestData4 = {'a', 'b', 'c', 'd', 'e'}; - SharedMemoryBlobSequence parent(ShmemName().c_str(), 1000, GetParam()); + auto parent = + CreateSharedMemoryBlobSequence(ShmemName().c_str(), 1000, GetParam()); // Parent writes data. - EXPECT_TRUE(parent.Write(BlobFromVec(kTestData1, 123))); - EXPECT_TRUE(parent.Write(BlobFromVec(kTestData2, 456))); + EXPECT_TRUE(parent->Write(BlobFromVec(kTestData1, 123))); + EXPECT_TRUE(parent->Write(BlobFromVec(kTestData2, 456))); // Child created. - SharedMemoryBlobSequence child(parent.path(), 1000); + auto child = OpenSharedMemoryBlobSequence(parent->path(), 1000); // Child reads data. - auto blob1 = child.Read(); + auto blob1 = child->Read(); EXPECT_EQ(kTestData1, Vec(blob1)); EXPECT_EQ(blob1.tag, 123); - auto blob2 = child.Read(); + auto blob2 = child->Read(); EXPECT_EQ(kTestData2, Vec(blob2)); EXPECT_EQ(blob2.tag, 456); - EXPECT_FALSE(child.Read().IsValid()); + EXPECT_FALSE(child->Read().IsValid()); // Child writes data. - child.Reset(); - EXPECT_TRUE(child.Write(BlobFromVec(kTestData3))); - EXPECT_TRUE(child.Write(BlobFromVec(kTestData4))); + child->Reset(); + EXPECT_TRUE(child->Write(BlobFromVec(kTestData3))); + EXPECT_TRUE(child->Write(BlobFromVec(kTestData4))); // Parent reads data. - parent.Reset(); - EXPECT_EQ(kTestData3, Vec(parent.Read())); - EXPECT_EQ(kTestData4, Vec(parent.Read())); - EXPECT_FALSE(parent.Read().IsValid()); + parent->Reset(); + EXPECT_EQ(kTestData3, Vec(parent->Read())); + EXPECT_EQ(kTestData4, Vec(parent->Read())); + EXPECT_FALSE(parent->Read().IsValid()); } TEST_P(SharedMemoryBlobSequenceTest, CheckForResourceLeaks) { @@ -139,117 +150,142 @@ const int kBlobSize = 1 << 30; // Some large blob size. // Create and destroy lots of parent/child blob pairs. for (int iter = 0; iter < kNumIters; iter++) { - SharedMemoryBlobSequence parent(ShmemName().c_str(), kBlobSize, GetParam()); - parent.Write(BlobFromVec({1, 2, 3})); - SharedMemoryBlobSequence child(parent.path(), kBlobSize); - EXPECT_EQ(child.Read().size, 3); + auto parent = CreateSharedMemoryBlobSequence(ShmemName().c_str(), kBlobSize, + GetParam()); + parent->Write(BlobFromVec({1, 2, 3})); + auto child = OpenSharedMemoryBlobSequence(parent->path(), kBlobSize); + EXPECT_EQ(child->Read().size, 3); } // Create a parent blob, then create and destroy lots of child blobs. - SharedMemoryBlobSequence parent(ShmemName().c_str(), kBlobSize, GetParam()); - parent.Write(BlobFromVec({1, 2, 3, 4})); + auto parent = CreateSharedMemoryBlobSequence(ShmemName().c_str(), kBlobSize, + GetParam()); + parent->Write(BlobFromVec({1, 2, 3, 4})); for (int iter = 0; iter < kNumIters; iter++) { - SharedMemoryBlobSequence child(parent.path(), kBlobSize); - EXPECT_EQ(child.Read().size, 4); + auto child = OpenSharedMemoryBlobSequence(parent->path(), kBlobSize); + EXPECT_EQ(child->Read().size, 4); } } // Tests that Read-after-Write or Write-after-Read w/o Reset crashes. TEST_P(SharedMemoryBlobSequenceTest, ReadVsWriteWithoutReset) { - SharedMemoryBlobSequence blobseq(ShmemName().c_str(), 1000, GetParam()); - blobseq.Write(BlobFromVec({1, 2, 3})); - EXPECT_DEATH(blobseq.Read(), "Had writes after reset"); - blobseq.Reset(); - EXPECT_EQ(blobseq.Read().size, 3); - EXPECT_DEATH(blobseq.Write(BlobFromVec({1, 2, 3, 4})), + auto blobseq = + CreateSharedMemoryBlobSequence(ShmemName().c_str(), 1000, GetParam()); + blobseq->Write(BlobFromVec({1, 2, 3})); + EXPECT_DEATH(blobseq->Read(), "Had writes after reset"); + blobseq->Reset(); + EXPECT_EQ(blobseq->Read().size, 3); + EXPECT_DEATH(blobseq->Write(BlobFromVec({1, 2, 3, 4})), "Had reads after reset"); - blobseq.Reset(); - blobseq.Write(BlobFromVec({1, 2, 3, 4})); + blobseq->Reset(); + blobseq->Write(BlobFromVec({1, 2, 3, 4})); } // Check cases when SharedMemoryBlobSequence is nearly full. TEST_P(SharedMemoryBlobSequenceTest, WriteToFullSequence) { // Can't create SharedMemoryBlobSequence with sizes < 8. EXPECT_DEATH( - SharedMemoryBlobSequence blobseq(ShmemName().c_str(), 7, GetParam()), + CreateSharedMemoryBlobSequence(ShmemName().c_str(), 7, GetParam()), "Size too small"); // Allocate a blob sequence with 28 bytes of storage. - SharedMemoryBlobSequence blobseq(ShmemName().c_str(), 28, GetParam()); + auto blobseq = + CreateSharedMemoryBlobSequence(ShmemName().c_str(), 28, GetParam()); // 17 bytes: 8 bytes size, 8 bytes tag, 1 byte payload. - EXPECT_TRUE(blobseq.Write(BlobFromVec({1}))); - blobseq.Reset(); - EXPECT_EQ(blobseq.Read().size, 1); - EXPECT_FALSE(blobseq.Read().IsValid()); + EXPECT_TRUE(blobseq->Write(BlobFromVec({1}))); + blobseq->Reset(); + EXPECT_EQ(blobseq->Read().size, 1); + EXPECT_FALSE(blobseq->Read().IsValid()); // 20 bytes: 4-byte payload. - blobseq.Reset(); - EXPECT_TRUE(blobseq.Write(BlobFromVec({1, 2, 3, 4}))); - blobseq.Reset(); - EXPECT_EQ(blobseq.Read().size, 4); - EXPECT_FALSE(blobseq.Read().IsValid()); + blobseq->Reset(); + EXPECT_TRUE(blobseq->Write(BlobFromVec({1, 2, 3, 4}))); + blobseq->Reset(); + EXPECT_EQ(blobseq->Read().size, 4); + EXPECT_FALSE(blobseq->Read().IsValid()); // 23 bytes: 7-byte payload. - blobseq.Reset(); - EXPECT_TRUE(blobseq.Write(BlobFromVec({1, 2, 3, 4, 5, 6, 7}))); - blobseq.Reset(); - EXPECT_EQ(blobseq.Read().size, 7); - EXPECT_FALSE(blobseq.Read().IsValid()); + blobseq->Reset(); + EXPECT_TRUE(blobseq->Write(BlobFromVec({1, 2, 3, 4, 5, 6, 7}))); + blobseq->Reset(); + EXPECT_EQ(blobseq->Read().size, 7); + EXPECT_FALSE(blobseq->Read().IsValid()); // 28 bytes: 12-byte payload. - blobseq.Reset(); + blobseq->Reset(); EXPECT_TRUE( - blobseq.Write(BlobFromVec({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}))); - blobseq.Reset(); - EXPECT_EQ(blobseq.Read().size, 12); - EXPECT_FALSE(blobseq.Read().IsValid()); + blobseq->Write(BlobFromVec({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}))); + blobseq->Reset(); + EXPECT_EQ(blobseq->Read().size, 12); + EXPECT_FALSE(blobseq->Read().IsValid()); // 13-byte payload - there is not enough space (for 13+8 bytes). - blobseq.Reset(); + blobseq->Reset(); EXPECT_FALSE( - blobseq.Write(BlobFromVec({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}))); - blobseq.Reset(); - EXPECT_EQ(blobseq.Read().size, 12); // State remained the same. + blobseq->Write(BlobFromVec({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}))); + blobseq->Reset(); + EXPECT_EQ(blobseq->Read().size, 12); // State remained the same. // 1-, and 2- byte payloads. The last one fails. - blobseq.Reset(); - EXPECT_TRUE(blobseq.Write(BlobFromVec({1}))); - EXPECT_FALSE(blobseq.Write(BlobFromVec({1, 2}))); - blobseq.Reset(); - EXPECT_EQ(blobseq.Read().size, 1); - EXPECT_FALSE(blobseq.Read().IsValid()); + blobseq->Reset(); + EXPECT_TRUE(blobseq->Write(BlobFromVec({1}))); + EXPECT_FALSE(blobseq->Write(BlobFromVec({1, 2}))); + blobseq->Reset(); + EXPECT_EQ(blobseq->Read().size, 1); + EXPECT_FALSE(blobseq->Read().IsValid()); } // Test Write-Reset-Write-Read scenario. TEST_P(SharedMemoryBlobSequenceTest, WriteAfterReset) { // Allocate a blob sequence with 28 bytes of storage. - SharedMemoryBlobSequence blobseq(ShmemName().c_str(), 100, GetParam()); + auto blobseq = + CreateSharedMemoryBlobSequence(ShmemName().c_str(), 100, GetParam()); const std::vector<uint8_t> kFirstWriteData(/*count=*/64, /*value=*/255); - EXPECT_TRUE(blobseq.Write(BlobFromVec(kFirstWriteData))); - blobseq.Reset(); // The data in shmem is unchanged. + EXPECT_TRUE(blobseq->Write(BlobFromVec(kFirstWriteData))); + blobseq->Reset(); // The data in shmem is unchanged. const std::vector<uint8_t> kSecondWriteData{42, 43}; - EXPECT_TRUE(blobseq.Write(BlobFromVec(kSecondWriteData))); - blobseq.Reset(); // The data in shmem is unchanged. - auto blob1 = blobseq.Read(); + EXPECT_TRUE(blobseq->Write(BlobFromVec(kSecondWriteData))); + blobseq->Reset(); // The data in shmem is unchanged. + auto blob1 = blobseq->Read(); EXPECT_TRUE(blob1.IsValid()); EXPECT_EQ(Vec(blob1), kSecondWriteData); - auto blob2 = blobseq.Read(); // must be invalid. + auto blob2 = blobseq->Read(); // must be invalid. EXPECT_FALSE(blob2.IsValid()); } -// MacOS does not support releasing the shm memory. -#ifndef __APPLE__ +// Test that reading a freshly created blob sequence returns an invalid blob. +TEST_P(SharedMemoryBlobSequenceTest, ReadBeforeWrite) { + auto parent = + CreateSharedMemoryBlobSequence(ShmemName().c_str(), 1000, GetParam()); + EXPECT_FALSE(parent->Read().IsValid()); + auto child = OpenSharedMemoryBlobSequence(parent->path(), 1000); + EXPECT_FALSE(child->Read().IsValid()); +} + +// Test that no stale data can be read after ReleaseSharedMemory. +TEST_P(SharedMemoryBlobSequenceTest, NoStaleReadsAfterReleaseSharedMemory) { + auto blobseq = + CreateSharedMemoryBlobSequence(ShmemName().c_str(), 1000, GetParam()); + EXPECT_TRUE(blobseq->Write(BlobFromVec({1, 2, 3, 4}))); + blobseq->ReleaseSharedMemory(); + blobseq->Reset(); + EXPECT_FALSE(blobseq->Read().IsValid()); +} + +// MacOS and Windows do not support releasing the shm memory. +#if !defined(__APPLE__) && !defined(_WIN32) // Test ReleaseSharedMemory and NumBytesUsed. TEST_P(SharedMemoryBlobSequenceTest, ReleaseSharedMemory) { // Allocate a blob sequence with 1M bytes of storage. - SharedMemoryBlobSequence blobseq(ShmemName().c_str(), 1 << 20, GetParam()); - EXPECT_EQ(blobseq.NumBytesUsed(), 0); - EXPECT_TRUE(blobseq.Write(BlobFromVec({1, 2, 3, 4}))); - EXPECT_GT(blobseq.NumBytesUsed(), 5); - blobseq.ReleaseSharedMemory(); - EXPECT_EQ(blobseq.NumBytesUsed(), 0); - EXPECT_TRUE(blobseq.Write(BlobFromVec({1, 2, 3, 4}))); - EXPECT_GT(blobseq.NumBytesUsed(), 5); + auto blobseq = + CreateSharedMemoryBlobSequence(ShmemName().c_str(), 1 << 20, GetParam()); + EXPECT_EQ(blobseq->NumBytesUsed(), 0); + EXPECT_TRUE(blobseq->Write(BlobFromVec({1, 2, 3, 4}))); + EXPECT_GT(blobseq->NumBytesUsed(), 5); + blobseq->ReleaseSharedMemory(); + EXPECT_EQ(blobseq->NumBytesUsed(), 0); + EXPECT_TRUE(blobseq->Write(BlobFromVec({1, 2, 3, 4}))); + EXPECT_GT(blobseq->NumBytesUsed(), 5); } #endif
diff --git a/centipede/stats_test.cc b/centipede/stats_test.cc index 491a428..82ce3d5 100644 --- a/centipede/stats_test.cc +++ b/centipede/stats_test.cc
@@ -451,13 +451,13 @@ } const std::vector<Environment> env_vec = { - CreateEnv(workdir.c_str(), /*experiment_name=*/"ExperimentA", + CreateEnv(workdir.string(), /*experiment_name=*/"ExperimentA", /*experiment_flags=*/"AAA"), - CreateEnv(workdir.c_str(), /*experiment_name=*/"ExperimentB", + CreateEnv(workdir.string(), /*experiment_name=*/"ExperimentB", /*experiment_flags=*/"BBB"), - CreateEnv(workdir.c_str(), /*experiment_name=*/"ExperimentA", + CreateEnv(workdir.string(), /*experiment_name=*/"ExperimentA", /*experiment_flags=*/"AAA"), - CreateEnv(workdir.c_str(), /*experiment_name=*/"ExperimentB", + CreateEnv(workdir.string(), /*experiment_name=*/"ExperimentB", /*experiment_flags=*/"BBB")}; { @@ -507,8 +507,8 @@ } const std::vector<std::string> kExpectedCsvs = { - workdir / "fuzzing-stats-.000000.ExperimentA.csv", - workdir / "fuzzing-stats-.000000.ExperimentB.csv", + (workdir / "fuzzing-stats-.000000.ExperimentA.csv").string(), + (workdir / "fuzzing-stats-.000000.ExperimentB.csv").string(), }; const std::vector<std::vector<std::string>> kExpectedCsvLines = { // CSV #1. @@ -771,15 +771,17 @@ }; const std::filesystem::path workdir = GetTestTempDir(test_info_->name()); - const std::vector<Environment> env_vec = {CreateEnv(workdir.c_str()), - CreateEnv(workdir.c_str())}; + const std::vector<Environment> env_vec = {CreateEnv(workdir.string()), + CreateEnv(workdir.string())}; std::vector<std::atomic<Stats>> stats_vec(2); stats_vec[0].store({StatsMeta{/*timestamp_unix_micros=*/1000000}}); stats_vec[1].store({StatsMeta{/*timestamp_unix_micros=*/2000000}}); - const std::string kExpectedCsv = workdir / "fuzzing-stats-.000000.csv"; - const std::string kExpectedCsvBak = workdir / "fuzzing-stats-.000000.csv.bak"; + const std::string kExpectedCsv = + (workdir / "fuzzing-stats-.000000.csv").string(); + const std::string kExpectedCsvBak = + (workdir / "fuzzing-stats-.000000.csv.bak").string(); // `StatsCsvFileAppender` creates a brand-new fuzzing-stats file and writes // the CSV header and a 1st stats line to it.
diff --git a/centipede/workdir.cc b/centipede/workdir.cc index c0f4090..676f8b6 100644 --- a/centipede/workdir.cc +++ b/centipede/workdir.cc
@@ -58,7 +58,7 @@ WorkDir::PathShards::PathShards(std::string_view base_dir, std::string_view rel_prefix, size_t my_shard_index) - : prefix_{std::filesystem::path(base_dir) / rel_prefix}, + : prefix_{(std::filesystem::path(base_dir) / rel_prefix).string()}, my_shard_index_{my_shard_index} {} std::string WorkDir::PathShards::Shard(size_t shard_index) const { @@ -97,12 +97,12 @@ std::string_view binary_name, // std::string_view binary_hash) { const std::filesystem::path path{corpus_shard_path}; - const std::string dir = path.parent_path(); - const std::string stem = path.stem(); + const std::string dir = path.parent_path().string(); + const std::string stem = path.stem().string(); FUZZTEST_CHECK(stem == kCorpusShardStem || absl::StartsWith(stem, kDistilledCorpusShardStemPrefix)) << VV(corpus_shard_path); - const std::string dot_ext = path.extension(); + const std::string dot_ext = path.extension().string(); FUZZTEST_CHECK(!dot_ext.empty() && dot_ext[0] == '.') << VV(corpus_shard_path); const std::string ext = dot_ext.substr(1); @@ -142,8 +142,9 @@ } std::string WorkDir::CoverageDirPath() const { - return std::filesystem::path(workdir_) / - absl::StrCat(binary_name_, "-", binary_hash_); + return (std::filesystem::path(workdir_) / + absl::StrCat(binary_name_, "-", binary_hash_)) + .string(); } WorkDir::PathShards WorkDir::CrashReproducerDirPaths() const { @@ -155,11 +156,11 @@ } std::string WorkDir::BinaryInfoDirPath() const { - return std::filesystem::path(CoverageDirPath()) / "binary-info"; + return (std::filesystem::path(CoverageDirPath()) / "binary-info").string(); } std::string WorkDir::DebugInfoDirPath() const { - return std::filesystem::path(workdir_) / "debug"; + return (std::filesystem::path(workdir_) / "debug").string(); } WorkDir::PathShards WorkDir::DistilledCorpusFilePaths() const { @@ -179,53 +180,60 @@ } std::string WorkDir::CoverageReportPath(std::string_view annotation) const { - return std::filesystem::path(workdir_) / - absl::StrFormat("coverage-report-%s.%0*d%s.txt", binary_name_, - kDigitsInShardIndex, my_shard_index_, - NormalizeAnnotation(annotation)); + return (std::filesystem::path(workdir_) / + absl::StrFormat("coverage-report-%s.%0*d%s.txt", binary_name_, + kDigitsInShardIndex, my_shard_index_, + NormalizeAnnotation(annotation))) + .string(); } std::string WorkDir::CorpusStatsPath(std::string_view annotation) const { - return std::filesystem::path(workdir_) / - absl::StrFormat("corpus-stats-%s.%0*d%s.json", binary_name_, - kDigitsInShardIndex, my_shard_index_, - NormalizeAnnotation(annotation)); + return (std::filesystem::path(workdir_) / + absl::StrFormat("corpus-stats-%s.%0*d%s.json", binary_name_, + kDigitsInShardIndex, my_shard_index_, + NormalizeAnnotation(annotation))) + .string(); } std::string WorkDir::FuzzingStatsPath(std::string_view annotation) const { - return std::filesystem::path(workdir_) / - absl::StrFormat("fuzzing-stats-%s.%0*d%s.csv", binary_name_, - kDigitsInShardIndex, my_shard_index_, - NormalizeAnnotation(annotation)); + return (std::filesystem::path(workdir_) / + absl::StrFormat("fuzzing-stats-%s.%0*d%s.csv", binary_name_, + kDigitsInShardIndex, my_shard_index_, + NormalizeAnnotation(annotation))) + .string(); } std::string WorkDir::SourceBasedCoverageRawProfilePath() const { // Pass %m to enable online merge mode: updates file in place instead of // replacing it %m is replaced by lprofGetLoadModuleSignature(void) which // should be consistent for a fixed binary - return std::filesystem::path(CoverageDirPath()) / - absl::StrFormat("clang_coverage.%0*d.%s.profraw", kDigitsInShardIndex, - my_shard_index_, "%m"); + return (std::filesystem::path(CoverageDirPath()) / + absl::StrFormat("clang_coverage.%0*d.%s.profraw", kDigitsInShardIndex, + my_shard_index_, "%m")) + .string(); } std::string WorkDir::SourceBasedCoverageIndexedProfilePath() const { - return std::filesystem::path(CoverageDirPath()) / - absl::StrFormat("clang_coverage.profdata"); + return (std::filesystem::path(CoverageDirPath()) / + absl::StrFormat("clang_coverage.profdata")) + .string(); } std::string WorkDir::SourceBasedCoverageReportPath( std::string_view annotation) const { - return std::filesystem::path(workdir_) / - absl::StrFormat("source-coverage-report-%s.%0*d%s", binary_name_, - kDigitsInShardIndex, my_shard_index_, - NormalizeAnnotation(annotation)); + return (std::filesystem::path(workdir_) / + absl::StrFormat("source-coverage-report-%s.%0*d%s", binary_name_, + kDigitsInShardIndex, my_shard_index_, + NormalizeAnnotation(annotation))) + .string(); } std::string WorkDir::RUsageReportPath(std::string_view annotation) const { - return std::filesystem::path(workdir_) / - (absl::StrFormat("rusage-report-%s.%0*d%s.txt", binary_name_, - kDigitsInShardIndex, my_shard_index_, - NormalizeAnnotation(annotation))); + return (std::filesystem::path(workdir_) / + (absl::StrFormat("rusage-report-%s.%0*d%s.txt", binary_name_, + kDigitsInShardIndex, my_shard_index_, + NormalizeAnnotation(annotation)))) + .string(); } std::vector<std::string> WorkDir::EnumerateRawCoverageProfiles() const { @@ -247,7 +255,7 @@ std::vector<std::string> raw_profiles; for (const auto &entry : dir_iter) { if (entry.is_regular_file() && entry.path().extension() == ".profraw") - raw_profiles.push_back(entry.path()); + raw_profiles.push_back(entry.path().string()); } return raw_profiles; }
diff --git a/centipede/workdir.h b/centipede/workdir.h index 5192b93..d8f6a1d 100644 --- a/centipede/workdir.h +++ b/centipede/workdir.h
@@ -51,6 +51,8 @@ // Returns the shard index of `path` if it is a shard parth, `nullopt` // otherwise. std::optional<size_t> GetShardIndex(std::string_view path) const; + // Gets the common prefix of the sharded path. + const std::string& prefix() const { return prefix_; } private: friend class WorkDir;
diff --git a/common/windows_includes.h b/common/windows_includes.h index e946797..f08f63a 100644 --- a/common/windows_includes.h +++ b/common/windows_includes.h
@@ -31,6 +31,7 @@ #endif #include <windows.h> +#include <psapi.h> // clang-format on