Windows support 1/x: centipede:command. `Command` previously relied on `posix_spawn` with `/bin/sh`, the POSIX `env` utility for environment variable modifications, and shell `<` redirection syntax in arguments. These mechanisms are not portable to Windows. Refactor `Command` to support native Windows process management alongside POSIX: - Introduce `Command::PlatformContext` to encapsulate platform-specific process handles (`HANDLE` on Windows vs. `pid_t` and `ForkServerProps` on POSIX). - Implement Windows process creation, environment block construction (`Options::env_diff`), and standard stream redirection in `Command::ExecuteAsync()` using `CreateProcessA`. - Add `Options::stdin_file_path` to handle input redirection directly rather than appending `"<"` to command arguments, and update `SymbolTable` to use it. - Escape command-line arguments, environment variables, and file paths in `Command::ToString()` on both POSIX (`ShellEscape`) and Windows. - Update `command_test_helper` and `command_test` to verify arguments, environment variables, standard input, and signals portably without relying on `bash`, and enable `centipede:command_test` on Windows CI. - Update `GetDataDependencyFilepath` to return executable path suffixed with `.exe` under Windows. PiperOrigin-RevId: 1022836478
diff --git a/.github/workflows/bazel_test_centipede.yml b/.github/workflows/bazel_test_centipede.yml index 1a6b40e..9a16bf6 100644 --- a/.github/workflows/bazel_test_centipede.yml +++ b/.github/workflows/bazel_test_centipede.yml
@@ -196,7 +196,8 @@ <# 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 -- centipede:util_test + --extra_execution_platforms=//:x64_windows-clang-cl --enable_runfiles ` + -- centipede:util_test centipede:command_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 930e2d2..6238cc0 100644 --- a/centipede/BUILD +++ b/centipede/BUILD
@@ -599,6 +599,8 @@ ":stop", ":util", "@abseil-cpp//absl/base:core_headers", + "@abseil-cpp//absl/cleanup", + "@abseil-cpp//absl/container:btree", "@abseil-cpp//absl/status", "@abseil-cpp//absl/status:statusor", "@abseil-cpp//absl/strings", @@ -606,6 +608,8 @@ "@abseil-cpp//absl/synchronization", "@abseil-cpp//absl/time", "@com_google_fuzztest//common:logging", + "@com_google_fuzztest//common:windows_includes", + "@com_google_fuzztest//fuzztest/internal:escaping", ], ) @@ -1438,6 +1442,7 @@ "@com_google_fuzztest//common:defs", "@com_google_fuzztest//common:hash", "@com_google_fuzztest//common:logging", + "@com_google_fuzztest//common:test_util", "@googletest//:gtest_main", ], ) @@ -1778,10 +1783,14 @@ name = "command_test_helper", srcs = ["command_test_helper.cc"], deps = [ - ":runner_fork_server", "@abseil-cpp//absl/base:nullability", + "@abseil-cpp//absl/strings", "@abseil-cpp//absl/time", - ], + "@com_google_fuzztest//common:windows_includes", + ] + select({ + "@platforms//os:windows": [], + "//conditions:default": [":runner_fork_server"], + }), ) cc_test(
diff --git a/centipede/command.cc b/centipede/command.cc index 43100e4..4342776 100644 --- a/centipede/command.cc +++ b/centipede/command.cc
@@ -14,6 +14,7 @@ #include "./centipede/command.h" +#ifndef _WIN32 #include <errno.h> #include <fcntl.h> #include <spawn.h> @@ -22,6 +23,7 @@ #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> +#endif // _WIN32 #ifdef __APPLE__ #include <inttypes.h> @@ -35,6 +37,7 @@ #include <cstdlib> #include <filesystem> // NOLINT #include <fstream> +#include <memory> #include <optional> #include <string> #include <string_view> @@ -58,8 +61,15 @@ #include "./centipede/stop.h" #include "./centipede/util.h" #include "./common/logging.h" +#include "./fuzztest/internal/escaping.h" +#ifdef _WIN32 +#include "absl/cleanup/cleanup.h" +#include "absl/container/btree_map.h" +#include "absl/strings/ascii.h" // NOLINT +#include "./common/windows_includes.h" +#endif -#if !defined(_MSC_VER) +#ifndef _WIN32 // Needed to pass the current environment to posix_spawn, which needs an // explicit envp without an option to inherit implicitly. extern char** environ; @@ -72,8 +82,11 @@ constexpr std::string_view kCommandLineSeparator(" \\\n"); constexpr std::string_view kNoForkServerRequestPrefix("%f"); +#ifdef _WIN32 +// Do not define `GetProcessCreationStamp`, which is for fork servers. +#else absl::StatusOr<std::string> GetProcessCreationStamp(pid_t pid) { -#ifdef __APPLE__ +#if defined(__APPLE__) struct proc_bsdinfo info = {}; if (proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, PROC_PIDTBSDINFO_SIZE) != PROC_PIDTBSDINFO_SIZE) { @@ -110,8 +123,9 @@ ": ", proc_stat_line)); } return std::string(fields[kFieldIndexOfStartTimeAfterComm]); -#endif +#endif // __APPLE__ } +#endif // _WIN32 std::string GetUniqueSuffix() { static std::atomic<uint64_t> suffix_counter = {0}; @@ -122,7 +136,17 @@ // TODO(ussuri): Encapsulate as much of the fork server functionality from // this source as possible in this struct, and make it a class. -struct Command::ForkServerProps { +#ifdef _WIN32 +struct Command::PlatformContext { + HANDLE win_process_handle = INVALID_HANDLE_VALUE; + ~PlatformContext() { + if (win_process_handle != INVALID_HANDLE_VALUE) { + CloseHandle(win_process_handle); + } + } +}; +#else +struct ForkServerProps { // The file paths of the comms pipes. std::string fifo_path_[2]; // The file descriptors of the comms pipes. @@ -177,17 +201,31 @@ } }; +struct Command::PlatformContext { + pid_t pid = -1; + std::unique_ptr<ForkServerProps> fork_server; +}; +#endif // _WIN32 + // NOTE: Because std::unique_ptr<T> requires T to be a complete type wherever // the deleter is instantiated, the special member functions must be defined -// out-of-line here, now that ForkServerProps is complete (that's by-the-book +// out-of-line here, now that PlatformContext is complete (that's by-the-book // PIMPL). Command::~Command() { if (is_executing()) { FUZZTEST_LOG(WARNING) << "Destructing Command object for " << path() << " with " - << (fork_server_ ? absl::StrCat("fork server PID ", - fork_server_->pid_) - : absl::StrCat("PID ", pid_)) +#ifdef _WIN32 + << "PID " + << GetProcessId(platform_context_->win_process_handle) +#else + << (platform_context_->fork_server + ? absl::StrCat( + "fork server PID ", + platform_context_->fork_server->pid_) + : absl::StrCat("PID ", + platform_context_->pid)) +#endif << " still running. Requesting it to force-stop " "without waiting for it..."; RequestStop(/*force=*/true); @@ -196,14 +234,51 @@ } Command::Command(std::string_view path, Options options) - : path_(path), options_(std::move(options)) {} + : path_(path), + options_(std::move(options)), + platform_context_(std::make_unique<PlatformContext>()) {} Command::Command(std::string_view path) : Command{path, {}} {} std::string Command::ToString() const { +#ifdef _WIN32 + std::string path = path_; + if (absl::StartsWith(path, kNoForkServerRequestPrefix)) { + path = path.substr(kNoForkServerRequestPrefix.size()); + } + constexpr std::string_view kTempFileWildCard = "@@"; + if (absl::StrContains(path, kTempFileWildCard)) { + FUZZTEST_CHECK(!options_.temp_file_path.empty()); + std::string temp_file = options_.temp_file_path; + path = absl::StrReplaceAll(path, {{kTempFileWildCard, temp_file}}); + } + std::string binary_cmd = path; + auto Escape = [](std::string_view s) { + std::string r = "\""; + size_t num_bs = 0; + for (size_t i = 0; i < s.size(); ++i) { + if (s[i] == '"') { + r.append(num_bs + 1, '\\'); + num_bs = 0; + } else if (s[i] == '\\') { + ++num_bs; + } else { + num_bs = 0; + } + r += s[i]; + } + r.append(num_bs, '\\'); + r += '"'; + return r; + }; + for (const auto& arg : options_.args) { + absl::StrAppend(&binary_cmd, " ", Escape(arg)); + } + return binary_cmd; +#else // _WIN32 std::vector<std::string> ss; ss.reserve(/*env*/ 1 + options_.env_diff.size() + /*path*/ 1 + - /*args*/ options_.args.size() + /*out/err*/ 2); + /*args*/ options_.args.size() + /*in/out/err*/ 3); // env. ss.push_back("exec env"); std::vector<std::string> env_to_set; @@ -217,7 +292,7 @@ } } for (auto& var : env_to_set) { - ss.push_back(std::move(var)); + ss.push_back(ShellEscape(var)); } // path. std::string path = path_; @@ -235,46 +310,57 @@ ss.push_back(std::move(path)); // args. for (const auto& arg : options_.args) { - ss.push_back(arg); + ss.push_back(ShellEscape(arg)); } - // out/err. + // in/out/err. + if (!options_.stdin_file_path.empty()) { + ss.push_back(absl::StrCat("< ", ShellEscape(options_.stdin_file_path))); + } if (!stdout_file_.empty()) { - ss.push_back(absl::StrCat("> ", stdout_file_)); + ss.push_back(absl::StrCat("> ", ShellEscape(stdout_file_))); } if (!stderr_file_.empty()) { if (stdout_file_ != stderr_file_) { - ss.push_back(absl::StrCat("2> ", stderr_file_)); + ss.push_back(absl::StrCat("2> ", ShellEscape(stderr_file_))); } else { ss.push_back("2>&1"); } } // Trim trailing space and return. return absl::StrJoin(ss, kCommandLineSeparator); +#endif // _WIN32 } bool Command::StartForkServer(std::string_view temp_dir_path, std::string_view prefix) { +#ifdef _WIN32 + return false; +#else if (absl::StartsWith(path_, kNoForkServerRequestPrefix)) { FUZZTEST_VLOG(2) << "Fork server disabled for " << path(); return false; } - FUZZTEST_CHECK(!is_executing_ && !fork_server_); + FUZZTEST_CHECK(!is_executing_ && !platform_context_->fork_server); FUZZTEST_VLOG(2) << "Starting fork server for " << path(); ResetRedirectionFiles(GetUniqueSuffix()); command_line_ = ToString(); - fork_server_.reset(new ForkServerProps); - fork_server_->fifo_path_[0] = std::filesystem::path(temp_dir_path) - .append(absl::StrCat(prefix, "_FIFO0")); - fork_server_->fifo_path_[1] = std::filesystem::path(temp_dir_path) - .append(absl::StrCat(prefix, "_FIFO1")); + platform_context_->fork_server = std::make_unique<ForkServerProps>(); + platform_context_->fork_server->fifo_path_[0] = + std::filesystem::path(temp_dir_path) + .append(absl::StrCat(prefix, "_FIFO0")); + platform_context_->fork_server->fifo_path_[1] = + std::filesystem::path(temp_dir_path) + .append(absl::StrCat(prefix, "_FIFO1")); const std::string pid_file_path = std::filesystem::path(temp_dir_path).append("pid"); (void)std::filesystem::create_directory(temp_dir_path); // it may not exist. for (int i = 0; i < 2; ++i) { - FUZZTEST_PCHECK(mkfifo(fork_server_->fifo_path_[i].c_str(), 0600) == 0) - << VV(i) << VV(fork_server_->fifo_path_[i]); + FUZZTEST_PCHECK( + mkfifo(platform_context_->fork_server->fifo_path_[i].c_str(), 0600) == + 0) + << VV(i) << VV(platform_context_->fork_server->fifo_path_[i]); } // NOTE: A background process does not return its exit status to the subshell, @@ -290,8 +376,9 @@ printf "%%s" $! > "%s" )sh"; const std::string fork_server_command = absl::StrFormat( - kForkServerCommandStub, fork_server_->fifo_path_[0], - fork_server_->fifo_path_[1], command_line_, pid_file_path); + kForkServerCommandStub, platform_context_->fork_server->fifo_path_[0], + platform_context_->fork_server->fifo_path_[1], command_line_, + pid_file_path); FUZZTEST_VLOG(1) << "Fork server command:" << fork_server_command; const int exit_code = system(fork_server_command.c_str()); @@ -316,10 +403,12 @@ // it. // See more at // https://www.gnu.org/software/libc/manual/html_node/Operating-Modes.html. - if ((fork_server_->pipe_[0] = open(fork_server_->fifo_path_[0].c_str(), - O_RDWR | O_NONBLOCK)) < 0 || - (fork_server_->pipe_[1] = open(fork_server_->fifo_path_[1].c_str(), - O_RDONLY | O_NONBLOCK)) < 0) { + if ((platform_context_->fork_server->pipe_[0] = + open(platform_context_->fork_server->fifo_path_[0].c_str(), + O_RDWR | O_NONBLOCK)) < 0 || + (platform_context_->fork_server->pipe_[1] = + open(platform_context_->fork_server->fifo_path_[1].c_str(), + O_RDONLY | O_NONBLOCK)) < 0) { LogProblemInfo( "Failed to establish communication with fork server; will proceed " "without it"); @@ -328,8 +417,11 @@ std::string pid_str; ReadFromLocalFile(pid_file_path, pid_str); - FUZZTEST_CHECK(absl::SimpleAtoi(pid_str, &fork_server_->pid_)) << VV(pid_str); - auto creation_stamp = GetProcessCreationStamp(fork_server_->pid_); + FUZZTEST_CHECK( + absl::SimpleAtoi(pid_str, &platform_context_->fork_server->pid_)) + << VV(pid_str); + auto creation_stamp = + GetProcessCreationStamp(platform_context_->fork_server->pid_); if (!creation_stamp.ok()) { LogProblemInfo( absl::StrCat("Failed to get the fork server's creation stamp; will " @@ -338,8 +430,9 @@ creation_stamp.status(), ")")); return false; } - fork_server_->creation_stamp = *std::move(creation_stamp); + platform_context_->fork_server->creation_stamp = *std::move(creation_stamp); return true; +#endif // _WIN32 } void Command::ResetRedirectionFiles(std::string_view new_suffix) { @@ -364,37 +457,218 @@ } absl::Status Command::VerifyForkServerIsHealthy() { +#ifdef _WIN32 + return absl::UnimplementedError("Fork server not supported on Windows"); +#else // Preconditions: the callers (`Execute()`) should call us only when the fork // server is presumed to be running (`fork_server_pid_` >= 0). If it is, the // comms pipes are guaranteed to be opened by `StartForkServer()`. - FUZZTEST_CHECK(fork_server_ != nullptr) << "Fork server wasn't started"; - FUZZTEST_CHECK(fork_server_->pid_ >= 0) + FUZZTEST_CHECK(platform_context_->fork_server != nullptr) + << "Fork server wasn't started"; + FUZZTEST_CHECK(platform_context_->fork_server->pid_ >= 0) << "Fork server process failed to start"; - FUZZTEST_CHECK(fork_server_->pipe_[0] >= 0 && fork_server_->pipe_[1] >= 0) + FUZZTEST_CHECK(platform_context_->fork_server->pipe_[0] >= 0 && + platform_context_->fork_server->pipe_[1] >= 0) << "Failed to connect to fork server"; // A process with the fork server PID exists (_some_ process, possibly with a // recycled PID)... - if (kill(fork_server_->pid_, 0) != EXIT_SUCCESS) { - return absl::UnknownError(absl::StrCat( - "Can't communicate with fork server, PID=", fork_server_->pid_)); + if (kill(platform_context_->fork_server->pid_, 0) != EXIT_SUCCESS) { + return absl::UnknownError( + absl::StrCat("Can't communicate with fork server, PID=", + platform_context_->fork_server->pid_)); } // ...and it is a process has the same creation stamp, so it's practically // guaranteed to be our original fork server process. - const auto creation_stamp = GetProcessCreationStamp(fork_server_->pid_); + const auto creation_stamp = + GetProcessCreationStamp(platform_context_->fork_server->pid_); if (!creation_stamp.ok()) return creation_stamp.status(); - if (*creation_stamp != fork_server_->creation_stamp) { + if (*creation_stamp != platform_context_->fork_server->creation_stamp) { return absl::UnknownError(absl::StrCat( "Fork server's creation stamp changed (new process?) - expected ", - fork_server_->creation_stamp, ", but got ", *creation_stamp)); + platform_context_->fork_server->creation_stamp, ", but got ", + *creation_stamp)); } return absl::OkStatus(); +#endif // _WIN32 } bool Command::ExecuteAsync() { FUZZTEST_CHECK(!is_executing()); - if (fork_server_ != nullptr) { +#ifdef _WIN32 + FUZZTEST_CHECK_EQ(platform_context_->win_process_handle, + INVALID_HANDLE_VALUE); + ResetRedirectionFiles(GetUniqueSuffix()); + command_line_ = ToString(); + + struct CaseInsensitiveCompare { + using is_transparent = void; + bool operator()(std::string_view a, std::string_view b) const { + return std::lexicographical_compare( + a.begin(), a.end(), b.begin(), b.end(), + [](unsigned char ca, unsigned char cb) { + return static_cast<unsigned char>(absl::ascii_tolower(ca)) < + static_cast<unsigned char>(absl::ascii_tolower(cb)); + }); + } + }; + + absl::btree_map<std::string, std::string, CaseInsensitiveCompare> env_map; + + LPCH env_strings = GetEnvironmentStringsA(); + if (env_strings != nullptr) { + const char* ptr = env_strings; + while (*ptr != '\0') { + std::string_view entry(ptr); + ptr += entry.size() + 1; + size_t eq_pos = entry.find('=', 1); + if (eq_pos != entry.npos) { + env_map[entry.substr(0, eq_pos)] = + std::string(entry.substr(eq_pos + 1)); + } else { + env_map[entry] = ""; + } + } + FreeEnvironmentStringsA(env_strings); + } + + for (std::string_view env_var : options_.env_diff) { + if (absl::StartsWith(env_var, "-")) { + std::string_view key = env_var.substr(1); + if (absl::EndsWith(key, "=")) { + key = key.substr(0, key.size() - 1); + } + env_map.erase(key); + } else { + auto pos = env_var.find('='); + if (pos != env_var.npos) { + env_map[env_var.substr(0, pos)] = std::string(env_var.substr(pos + 1)); + } + } + } + + std::string env_block = absl::StrJoin(env_map, absl::string_view("\0", 1), + absl::PairFormatter("=")); + env_block.append(2, '\0'); + + STARTUPINFOEXA si = {}; + si.StartupInfo.cb = sizeof(si); + si.StartupInfo.dwFlags = STARTF_USESTDHANDLES; + PROCESS_INFORMATION pi = {}; + + SECURITY_ATTRIBUTES sa = {sizeof(sa), NULL, TRUE}; + HANDLE handle_in = INVALID_HANDLE_VALUE; + HANDLE handle_out = INVALID_HANDLE_VALUE; + HANDLE handle_err = INVALID_HANDLE_VALUE; + + absl::Cleanup close_handles = [&] { + if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in); + if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out); + if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err); + }; + + if (!options_.stdin_file_path.empty()) { + handle_in = CreateFileA(options_.stdin_file_path.c_str(), GENERIC_READ, + FILE_SHARE_READ, &sa, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, NULL); + if (handle_in == INVALID_HANDLE_VALUE) { + FUZZTEST_LOG(ERROR) << "Failed to open stdin file: " + << options_.stdin_file_path; + return false; + } + si.StartupInfo.hStdInput = handle_in; + } else { + si.StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE); + } + + if (!stdout_file_.empty()) { + handle_out = + CreateFileA(stdout_file_.c_str(), GENERIC_WRITE, FILE_SHARE_READ, &sa, + CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (handle_out == INVALID_HANDLE_VALUE) { + FUZZTEST_LOG(ERROR) << "Failed to open stdout file: " << stdout_file_; + return false; + } + si.StartupInfo.hStdOutput = handle_out; + } else { + si.StartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); + } + + if (!stderr_file_.empty()) { + if (stderr_file_ == stdout_file_) { + si.StartupInfo.hStdError = si.StartupInfo.hStdOutput; + } else { + handle_err = + CreateFileA(stderr_file_.c_str(), GENERIC_WRITE, FILE_SHARE_READ, &sa, + CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (handle_err == INVALID_HANDLE_VALUE) { + FUZZTEST_LOG(ERROR) << "Failed to open stderr file: " << stderr_file_; + return false; + } + si.StartupInfo.hStdError = handle_err; + } + } else { + si.StartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE); + } + + std::vector<HANDLE> handles_to_inherit; + for (HANDLE h : {si.StartupInfo.hStdInput, si.StartupInfo.hStdOutput, + si.StartupInfo.hStdError}) { + if (h != nullptr && h != INVALID_HANDLE_VALUE && + std::find(handles_to_inherit.begin(), handles_to_inherit.end(), h) == + handles_to_inherit.end()) { + SetHandleInformation(h, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); + handles_to_inherit.push_back(h); + } + } + + SIZE_T attr_list_size = 0; + InitializeProcThreadAttributeList(nullptr, 1, 0, &attr_list_size); + auto attr_list_buffer = std::make_unique<uint8_t[]>(attr_list_size); + si.lpAttributeList = + reinterpret_cast<PPROC_THREAD_ATTRIBUTE_LIST>(attr_list_buffer.get()); + if (!InitializeProcThreadAttributeList(si.lpAttributeList, 1, 0, + &attr_list_size)) { + DWORD err = GetLastError(); + FUZZTEST_LOG(ERROR) << "InitializeProcThreadAttributeList failed: " << err; + return false; + } + absl::Cleanup delete_attr_list = [&] { + DeleteProcThreadAttributeList(si.lpAttributeList); + }; + + if (!handles_to_inherit.empty()) { + if (!UpdateProcThreadAttribute( + si.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, + handles_to_inherit.data(), + handles_to_inherit.size() * sizeof(HANDLE), nullptr, nullptr)) { + DWORD err = GetLastError(); + FUZZTEST_LOG(ERROR) << "UpdateProcThreadAttribute failed: " << err; + return false; + } + } + + std::string cmd = command_line_; + const BOOL cp_res = CreateProcessA( + NULL, cmd.data(), NULL, NULL, + /*bInheritHandles=*/!handles_to_inherit.empty(), + EXTENDED_STARTUPINFO_PRESENT, env_block.empty() ? NULL : env_block.data(), + NULL, &si.StartupInfo, &pi); + + if (!cp_res) { + DWORD err = GetLastError(); + FUZZTEST_LOG(ERROR) << "CreateProcessA failed for '" << cmd + << "': error=" << err; + return false; + } + + platform_context_->win_process_handle = pi.hProcess; + CloseHandle(pi.hThread); + is_executing_ = true; + return true; +#else // _WIN32 + if (platform_context_->fork_server != nullptr) { FUZZTEST_VLOG(1) << "Sending execution request to fork server"; if (const auto status = VerifyForkServerIsHealthy(); !status.ok()) { @@ -405,7 +679,7 @@ // Wake up the fork server. char x = ' '; - if (write(fork_server_->pipe_[0], &x, 1) != 1) { + if (write(platform_context_->fork_server->pipe_[0], &x, 1) != 1) { LogProblemInfo( absl::StrCat("Failed to write to fork server pipe. Errno: ", errno)); return false; @@ -413,12 +687,13 @@ // Read the one-byte ack. // Use 60s as an arbitrary duration to wait for the process to load and // enter the fork server. - if (!fork_server_->ReadPipe(absl::Now() + absl::Seconds(60), x)) { + if (!platform_context_->fork_server->ReadPipe( + absl::Now() + absl::Seconds(60), x)) { LogProblemInfo("Failed to read from fork server pipe."); return false; } } else { - FUZZTEST_CHECK_EQ(pid_, -1); + FUZZTEST_CHECK_EQ(platform_context_->pid, -1); ResetRedirectionFiles(GetUniqueSuffix()); command_line_ = ToString(); @@ -431,24 +706,63 @@ argv.push_back(argv_str.data()); } argv.push_back(nullptr); - FUZZTEST_PCHECK(posix_spawn(&pid_, argv[0], /*file_actions=*/nullptr, + FUZZTEST_PCHECK(posix_spawn(&platform_context_->pid, argv[0], + /*file_actions=*/nullptr, /*attrp=*/nullptr, argv.data(), environ) == 0); } is_executing_ = true; return true; +#endif // _WIN32 } std::optional<int> Command::Wait(absl::Time deadline, StopCondition* stop_condition) { FUZZTEST_CHECK(is_executing()); +#ifdef _WIN32 + FUZZTEST_CHECK_NE(platform_context_->win_process_handle, + INVALID_HANDLE_VALUE); + DWORD timeout_ms = INFINITE; + if (deadline != absl::InfiniteFuture()) { + // Round up so that we do not time out before `deadline`, and clamp to + // avoid wrapping around or accidentally passing `INFINITE`. + const int64_t ms = absl::ToInt64Milliseconds( + absl::Ceil(std::max(deadline - absl::Now(), absl::ZeroDuration()), + absl::Milliseconds(1))); + timeout_ms = + static_cast<DWORD>(std::min<int64_t>(ms, int64_t{INFINITE} - 1)); + } + const DWORD res = + WaitForSingleObject(platform_context_->win_process_handle, timeout_ms); + if (res == WAIT_TIMEOUT) { + VlogProblemInfo( + absl::StrCat("Timeout while waiting for command process: deadline is ", + deadline), + /*vlog_level=*/1); + return std::nullopt; + } + FUZZTEST_CHECK_EQ(res, WAIT_OBJECT_0) + << "WaitForSingleObject failed: error=" << GetLastError(); + DWORD exit_code = 0; + FUZZTEST_CHECK( + GetExitCodeProcess(platform_context_->win_process_handle, &exit_code)) + << "GetExitCodeProcess failed: error=" << GetLastError(); + CloseHandle(platform_context_->win_process_handle); + platform_context_->win_process_handle = INVALID_HANDLE_VALUE; + is_executing_ = false; + if (exit_code == STATUS_CONTROL_C_EXIT && stop_condition != nullptr) { + stop_condition->RequestStop( + EXIT_FAILURE, "Command killed: signal=SIGINT (likely Ctrl-C)"); + } + return static_cast<int>(exit_code); +#else // _WIN32 int exit_code = EXIT_SUCCESS; - if (fork_server_ != nullptr) { + if (platform_context_->fork_server != nullptr) { // The fork server forks, the child is running. Block until some readable // data appears in the pipe (that is, after the fork server writes the // execution result to it). - if (!fork_server_->ReadPipe(deadline, exit_code)) { + if (!platform_context_->fork_server->ReadPipe(deadline, exit_code)) { VlogProblemInfo( absl::StrCat("Waiting for fork server failed, deadline is ", deadline), @@ -456,11 +770,13 @@ return std::nullopt; } } else { - FUZZTEST_CHECK_NE(pid_, -1); + FUZZTEST_CHECK_NE(platform_context_->pid, -1); while (true) { - const pid_t r = waitpid(pid_, &exit_code, WNOHANG); + const pid_t r = waitpid(platform_context_->pid, &exit_code, WNOHANG); FUZZTEST_CHECK_NE(r, -1); - if (r == pid_ && (WIFEXITED(exit_code) || WIFSIGNALED(exit_code))) break; + if (r == platform_context_->pid && + (WIFEXITED(exit_code) || WIFSIGNALED(exit_code))) + break; FUZZTEST_CHECK_EQ(r, 0); const auto timeout = deadline - absl::Now(); if (timeout > absl::ZeroDuration()) { @@ -477,7 +793,7 @@ return std::nullopt; } } - pid_ = -1; + platform_context_->pid = -1; } is_executing_ = false; @@ -535,20 +851,27 @@ } return exit_code; +#endif // _WIN32 } void Command::RequestStop(bool force) { FUZZTEST_CHECK(is_executing()); - if (fork_server_) { - FUZZTEST_CHECK_NE(fork_server_->pid_, -1); +#ifdef _WIN32 + FUZZTEST_CHECK_NE(platform_context_->win_process_handle, + INVALID_HANDLE_VALUE); + TerminateProcess(platform_context_->win_process_handle, 1); +#else + if (platform_context_->fork_server) { + FUZZTEST_CHECK_NE(platform_context_->fork_server->pid_, -1); // Cannot send SIGKILL to the fork server as it kills only the parent // process, but not the child. The fork server would send SIGKILL to the // child on SIGUSR1. - kill(fork_server_->pid_, force ? SIGUSR1 : SIGTERM); + kill(platform_context_->fork_server->pid_, force ? SIGUSR1 : SIGTERM); return; } - FUZZTEST_CHECK_NE(pid_, -1); - kill(pid_, force ? SIGKILL : SIGTERM); + FUZZTEST_CHECK_NE(platform_context_->pid, -1); + kill(platform_context_->pid, force ? SIGKILL : SIGTERM); +#endif // _WIN32 } std::string Command::ReadRedirectedStdout() const {
diff --git a/centipede/command.h b/centipede/command.h index 33c1d14..c369cdd 100644 --- a/centipede/command.h +++ b/centipede/command.h
@@ -31,9 +31,8 @@ class Command final { public: struct Options { - // Arguments to pass to the executed command. The command is executed by the - // shell, so the arguments need to be shell-escaped. - // TODO(b/381910257): Escape the arguments for passing to the shell. + // Arguments to pass to the executed command. The arguments are escaped + // automatically, so callers should pass them verbatim (unescaped). std::vector<std::string> args; // Environment variables to set or unset in the subprocess, relative to the // environment of the parent process. The variables in the form "KEY=VALUE" @@ -52,6 +51,8 @@ // `Command` automatically unlinks any previous redirected files on // execution and destruction. std::string stderr_file_prefix; + // Redirect stdin from this file path if non-empty. + std::string stdin_file_path; // "@@" in the command will be replaced with `temp_file_path`. std::string temp_file_path; }; @@ -125,9 +126,8 @@ const std::string& stderr_file() const { return stderr_file_; } private: - struct ForkServerProps; + struct PlatformContext; - int pid_ = -1; bool is_executing_ = false; // Derived from Options::{stdout,stderr}_file_prefix, with the realized suffix @@ -163,7 +163,7 @@ const Options options_; std::string command_line_; - std::unique_ptr<ForkServerProps> fork_server_; + std::unique_ptr<PlatformContext> platform_context_; }; // Get the shared mutex for execution logging for preventing confusing
diff --git a/centipede/command_test.cc b/centipede/command_test.cc index 48f4d07..f31ad8b 100644 --- a/centipede/command_test.cc +++ b/centipede/command_test.cc
@@ -15,7 +15,9 @@ #include "./centipede/command.h" #include <signal.h> +#ifndef _WIN32 #include <sys/wait.h> // NOLINT(for WTERMSIG) +#endif #include <cstdlib> #include <filesystem> // NOLINT @@ -26,6 +28,7 @@ #include "gmock/gmock.h" #include "gtest/gtest.h" +#include "absl/strings/str_cat.h" #include "absl/strings/substitute.h" #include "absl/time/clock.h" #include "absl/time/time.h" @@ -36,55 +39,132 @@ namespace fuzztest::internal { namespace { +using ::testing::AllOf; +using ::testing::HasSubstr; using ::testing::Optional; -TEST(CommandTest, ToString) { - EXPECT_EQ(Command{"x"}.ToString(), "exec env \\\nx"); - { - Command::Options cmd_options; - cmd_options.args = {"arg1", "arg2"}; - EXPECT_EQ((Command{"path", std::move(cmd_options)}.ToString()), - "exec env \\\npath \\\narg1 \\\narg2"); - } - { - Command::Options cmd_options; - cmd_options.env_diff = {"K1=V1", "K2=V2", "-K3"}; - EXPECT_EQ((Command{"x", std::move(cmd_options)}.ToString()), - "exec env \\\n-u K3 \\\nK1=V1 \\\nK2=V2 \\\nx"); - } -} - TEST(CommandTest, Execute) { + const std::string helper = + GetDataDependencyFilepath("centipede/command_test_helper").string(); StopCondition stop_condition; // Check for default exit code. - Command echo{"echo"}; - EXPECT_EQ(echo.Execute(&stop_condition), 0); + Command::Options options_success; + options_success.args = {"success"}; + Command success_cmd{helper, std::move(options_success)}; + EXPECT_EQ(success_cmd.Execute(&stop_condition), 0); EXPECT_FALSE(stop_condition.ShouldStop()); // Check for exit code 7. - Command exit7{"bash -c 'exit 7'"}; + Command::Options options_ret7; + options_ret7.args = {"ret7"}; + Command exit7{helper, std::move(options_ret7)}; EXPECT_EQ(exit7.Execute(&stop_condition), 7); EXPECT_FALSE(stop_condition.ShouldStop()); } TEST(CommandTest, HandlesInterruptedCommand) { + const std::string helper = + GetDataDependencyFilepath("centipede/command_test_helper").string(); StopCondition stop_condition; - Command self_sigint{"bash -c 'kill -SIGINT $$'"}; - self_sigint.ExecuteAsync(); - self_sigint.Wait(absl::InfiniteFuture(), &stop_condition); + Command::Options options_ctrlc; + options_ctrlc.args = {"ctrlc"}; + Command self_ctrlc{helper, std::move(options_ctrlc)}; + // Cannot set to SIG_IGN as the command would inherit that. + signal(SIGINT, [](int) {}); + self_ctrlc.ExecuteAsync(); + self_ctrlc.Wait(absl::InfiniteFuture(), &stop_condition); + signal(SIGINT, SIG_DFL); EXPECT_TRUE(stop_condition.ShouldStop()); } -TEST(CommandTest, InputFileWildCard) { - Command::Options cmd_options; - cmd_options.temp_file_path = "TEMP_FILE"; - Command cmd{"foo bar @@ baz", std::move(cmd_options)}; - EXPECT_EQ(cmd.ToString(), "exec env \\\nfoo bar TEMP_FILE baz"); +TEST(CommandTest, ExecuteWithOptions) { + const std::filesystem::path test_tmpdir = GetTestTempDir(test_info_->name()); + const std::string helper = + GetDataDependencyFilepath("centipede/command_test_helper").string(); + + { + const std::string log_prefix = (test_tmpdir / "args").string(); + Command::Options cmd_options; + cmd_options.args = {"echo_args", "arg1", "arg2", + "arg with \"quotes\" and \\\\"}; + cmd_options.stdout_file_prefix = log_prefix; + Command cmd{helper, std::move(cmd_options)}; + EXPECT_EQ(cmd.Execute(), 0); + std::string log_contents; + ReadFromLocalFile(cmd.stdout_file(), log_contents); + EXPECT_THAT(log_contents, + AllOf(HasSubstr("arg[0]=arg1\n"), HasSubstr("arg[1]=arg2\n"), + HasSubstr("arg[2]=arg with \"quotes\" and \\\\\n"))); + } + + { + SetEnv("K3", "V3"); + const std::string log_prefix = (test_tmpdir / "env").string(); + Command::Options cmd_options; + cmd_options.args = {"echo_env", "K1", "K2", "K3"}; + cmd_options.env_diff = {"K1=V1", "K2=V2", "-K3"}; + cmd_options.stdout_file_prefix = log_prefix; + Command cmd{helper, std::move(cmd_options)}; + EXPECT_EQ(cmd.Execute(), 0); + std::string log_contents; + ReadFromLocalFile(cmd.stdout_file(), log_contents); + EXPECT_THAT(log_contents, AllOf(HasSubstr("K1=V1\n"), HasSubstr("K2=V2\n"), + HasSubstr("K3=<UNSET>\n"))); + } + + { + const std::string stdin_file = (test_tmpdir / "input.txt").string(); + WriteToLocalFile(stdin_file, "hello stdin"); + const std::string log_prefix = (test_tmpdir / "stdin").string(); + Command::Options cmd_options; + cmd_options.args = {"echo_stdin"}; + cmd_options.stdin_file_path = stdin_file; + cmd_options.stdout_file_prefix = log_prefix; + Command cmd{helper, std::move(cmd_options)}; + EXPECT_EQ(cmd.Execute(), 0); + std::string log_contents; + ReadFromLocalFile(cmd.stdout_file(), log_contents); + EXPECT_THAT(log_contents, HasSubstr("hello stdin")); + } } +TEST(CommandTest, InputFileWildCard) { + const std::filesystem::path test_tmpdir = GetTestTempDir(test_info_->name()); + const std::string helper = + GetDataDependencyFilepath("centipede/command_test_helper").string(); + const std::string log_prefix = (test_tmpdir / "wildcard").string(); + + Command::Options cmd_options; + cmd_options.temp_file_path = "TEMP_FILE"; + cmd_options.stdout_file_prefix = log_prefix; + Command cmd{absl::StrCat(helper, " @@"), std::move(cmd_options)}; + EXPECT_EQ(cmd.Execute(), 17); + std::string log_contents; + ReadFromLocalFile(cmd.stdout_file(), log_contents); + EXPECT_EQ(log_contents, "Got input: TEMP_FILE\n"); +} + +TEST(CommandTest, WaitTimesOutAndRequestStopTerminates) { + const std::string helper = + GetDataDependencyFilepath("centipede/command_test_helper").string(); + Command::Options cmd_options; + cmd_options.args = {"sleep"}; + Command cmd{helper, std::move(cmd_options)}; + ASSERT_TRUE(cmd.ExecuteAsync()); + EXPECT_EQ(cmd.Wait(absl::Now() + absl::Milliseconds(500)), std::nullopt); + cmd.RequestStop(/*force=*/true); +#ifdef _WIN32 + // `RequestStop()` calls `TerminateProcess()` with exit code 1. + EXPECT_THAT(cmd.Wait(absl::Now() + absl::Seconds(2)), Optional(1)); +#else + EXPECT_THAT(cmd.Wait(absl::Now() + absl::Seconds(2)), Optional(SIGKILL)); +#endif +} + +#ifndef _WIN32 TEST(CommandTest, ForkServer) { - const std::string test_tmpdir = GetTestTempDir(test_info_->name()); + const std::filesystem::path test_tmpdir = GetTestTempDir(test_info_->name()); const std::string helper = GetDataDependencyFilepath("centipede/command_test_helper"); @@ -92,93 +172,93 @@ { const std::string input = "success"; - const std::string log_prefix = std::filesystem::path{test_tmpdir} / input; + const std::string log_prefix = test_tmpdir / input; Command::Options cmd_options; cmd_options.args = {input}; cmd_options.stdout_file_prefix = log_prefix; cmd_options.stderr_file_prefix = log_prefix; Command cmd{helper, std::move(cmd_options)}; - EXPECT_TRUE(cmd.StartForkServer(test_tmpdir, "ForkServer")); + EXPECT_TRUE(cmd.StartForkServer(test_tmpdir.string(), "ForkServer")); EXPECT_EQ(cmd.Execute(), EXIT_SUCCESS); std::string log_contents; ReadFromLocalFile(cmd.stdout_file(), log_contents); - EXPECT_EQ(log_contents, absl::Substitute("Got input: $0", input)); + EXPECT_EQ(log_contents, absl::Substitute("Got input: $0\n", input)); } { const std::string input = "fail"; - const std::string log_prefix = std::filesystem::path{test_tmpdir} / input; + const std::string log_prefix = test_tmpdir / input; Command::Options cmd_options; cmd_options.args = {input}; cmd_options.stdout_file_prefix = log_prefix; cmd_options.stderr_file_prefix = log_prefix; Command cmd{helper, std::move(cmd_options)}; - EXPECT_TRUE(cmd.StartForkServer(test_tmpdir, "ForkServer")); + EXPECT_TRUE(cmd.StartForkServer(test_tmpdir.string(), "ForkServer")); EXPECT_EQ(cmd.Execute(), EXIT_FAILURE); std::string log_contents; ReadFromLocalFile(cmd.stdout_file(), log_contents); - EXPECT_EQ(log_contents, absl::Substitute("Got input: $0", input)); + EXPECT_EQ(log_contents, absl::Substitute("Got input: $0\n", input)); } { const std::string input = "ret42"; - const std::string log_prefix = std::filesystem::path{test_tmpdir} / input; + const std::string log_prefix = test_tmpdir / input; Command::Options cmd_options; cmd_options.args = {input}; cmd_options.stdout_file_prefix = log_prefix; cmd_options.stderr_file_prefix = log_prefix; Command cmd{helper, std::move(cmd_options)}; - EXPECT_TRUE(cmd.StartForkServer(test_tmpdir, "ForkServer")); + EXPECT_TRUE(cmd.StartForkServer(test_tmpdir.string(), "ForkServer")); EXPECT_EQ(cmd.Execute(), 42); std::string log_contents; ReadFromLocalFile(cmd.stdout_file(), log_contents); - EXPECT_EQ(log_contents, absl::Substitute("Got input: $0", input)); + EXPECT_EQ(log_contents, absl::Substitute("Got input: $0\n", input)); } { const std::string input = "abort"; - const std::string log_prefix = std::filesystem::path{test_tmpdir} / input; + const std::string log_prefix = test_tmpdir / input; Command::Options cmd_options; cmd_options.args = {input}; cmd_options.stdout_file_prefix = log_prefix; cmd_options.stderr_file_prefix = log_prefix; Command cmd{helper, std::move(cmd_options)}; - EXPECT_TRUE(cmd.StartForkServer(test_tmpdir, "ForkServer")); + EXPECT_TRUE(cmd.StartForkServer(test_tmpdir.string(), "ForkServer")); // WTERMSIG() needs an lvalue on some platforms. const int ret = cmd.Execute(); EXPECT_EQ(WTERMSIG(ret), SIGABRT); std::string log_contents; ReadFromLocalFile(cmd.stdout_file(), log_contents); - EXPECT_EQ(log_contents, absl::Substitute("Got input: $0", input)); + EXPECT_EQ(log_contents, absl::Substitute("Got input: $0\n", input)); } { const std::string input = "sleep"; - const std::string log_prefix = std::filesystem::path{test_tmpdir} / input; + const std::string log_prefix = test_tmpdir / input; Command::Options cmd_options; cmd_options.args = {input}; cmd_options.stdout_file_prefix = log_prefix; cmd_options.stderr_file_prefix = log_prefix; Command cmd{helper, std::move(cmd_options)}; - ASSERT_TRUE(cmd.StartForkServer(test_tmpdir, "ForkServer")); + ASSERT_TRUE(cmd.StartForkServer(test_tmpdir.string(), "ForkServer")); ASSERT_TRUE(cmd.ExecuteAsync()); EXPECT_EQ(cmd.Wait(absl::Now() + absl::Seconds(2)), std::nullopt); cmd.RequestStop(/*force=*/false); EXPECT_THAT(cmd.Wait(absl::Now() + absl::Seconds(2)), Optional(SIGTERM)); std::string log_contents; ReadFromLocalFile(cmd.stdout_file(), log_contents); - EXPECT_EQ(log_contents, absl::Substitute("Got input: $0", input)); + EXPECT_EQ(log_contents, absl::Substitute("Got input: $0\n", input)); } { const std::string input = "hang"; - const std::string log_prefix = std::filesystem::path{test_tmpdir} / input; + const std::string log_prefix = test_tmpdir / input; Command::Options cmd_options; cmd_options.args = {input}; cmd_options.stdout_file_prefix = log_prefix; cmd_options.stderr_file_prefix = log_prefix; Command cmd{helper, std::move(cmd_options)}; - ASSERT_TRUE(cmd.StartForkServer(test_tmpdir, "ForkServer")); + ASSERT_TRUE(cmd.StartForkServer(test_tmpdir.string(), "ForkServer")); ASSERT_TRUE(cmd.ExecuteAsync()); EXPECT_EQ(cmd.Wait(absl::Now() + absl::Seconds(2)), std::nullopt); cmd.RequestStop(/*force=*/false); @@ -187,11 +267,12 @@ EXPECT_THAT(cmd.Wait(absl::Now() + absl::Seconds(2)), Optional(SIGKILL)); std::string log_contents; ReadFromLocalFile(cmd.stdout_file(), log_contents); - EXPECT_EQ(log_contents, absl::Substitute("Got input: $0", input)); + EXPECT_EQ(log_contents, absl::Substitute("Got input: $0\n", input)); } // TODO(kcc): [impl] test what happens if the child is interrupted. } +#endif } // namespace } // namespace fuzztest::internal
diff --git a/centipede/command_test_helper.cc b/centipede/command_test_helper.cc index d3153a8..75fe519 100644 --- a/centipede/command_test_helper.cc +++ b/centipede/command_test_helper.cc
@@ -12,33 +12,92 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include <unistd.h> - #include <cassert> #include <csignal> #include <cstdio> #include <cstdlib> #include <cstring> +#ifdef _WIN32 +#include <fcntl.h> +#include <io.h> + +#include "./common/windows_includes.h" +#endif + #include "absl/base/nullability.h" +#include "absl/strings/match.h" +#include "absl/strings/numbers.h" +#include "absl/strings/string_view.h" #include "absl/time/clock.h" #include "absl/time/time.h" // A binary linked with the fork server that exits/crashes in different ways. int main(int argc, char** absl_nonnull argv) { - assert(argc == 2); - printf("Got input: %s", argv[1]); +#ifdef _WIN32 + // Disable the automatic \n -> \r\n conversion. + _setmode(_fileno(stdout), _O_BINARY); +#endif + + assert(argc >= 2); + printf("Got input: %s\n", argv[1]); + + if (!strcmp(argv[1], "echo_args")) { + for (int i = 2; i < argc; ++i) { + printf("arg[%d]=%s\n", i - 2, argv[i]); + } + fflush(stdout); + return EXIT_SUCCESS; + } + + if (!strcmp(argv[1], "echo_env")) { + for (int i = 2; i < argc; ++i) { + const char* val = getenv(argv[i]); + printf("%s=%s\n", argv[i], val ? val : "<UNSET>"); + } + fflush(stdout); + return EXIT_SUCCESS; + } + + if (!strcmp(argv[1], "echo_stdin")) { + char buf[1024]; + while (fgets(buf, sizeof(buf), stdin)) { + fputs(buf, stdout); + } + fflush(stdout); + return EXIT_SUCCESS; + } + fflush(stdout); + if (!strcmp(argv[1], "success")) return EXIT_SUCCESS; if (!strcmp(argv[1], "fail")) return EXIT_FAILURE; - if (!strcmp(argv[1], "ret42")) return 42; + + int ret_code = 0; + if (absl::StartsWith(argv[1], "ret") && + absl::SimpleAtoi(argv[1] + 3, &ret_code)) { + return ret_code; + } + if (!strcmp(argv[1], "abort")) abort(); + if (!strcmp(argv[1], "ctrlc")) { +#ifdef _WIN32 + SetConsoleCtrlHandler(NULL, FALSE); + GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0); + Sleep(INFINITE); +#else + raise(SIGINT); +#endif + return EXIT_SUCCESS; + } // Sleep longer than kTimeout in CommandDeathTest_ForkServerHangingBinary. if (!strcmp(argv[1], "sleep")) absl::SleepFor(absl::Seconds(5)); if (!strcmp(argv[1], "hang")) { +#ifndef _WIN32 struct sigaction act{}; act.sa_handler = [](int) {}; sigaction(SIGTERM, &act, nullptr); +#endif absl::SleepFor(absl::Seconds(10)); }
diff --git a/centipede/symbol_table.cc b/centipede/symbol_table.cc index e693b48..6e58ebd 100644 --- a/centipede/symbol_table.cc +++ b/centipede/symbol_table.cc
@@ -120,10 +120,9 @@ "--no-inlines", "-e", std::string(dso_path), - "<", - std::string(pcs_file.path()), }; - cmd_options.stdout_file_prefix = symbols_file_prefix; + cmd_options.stdin_file_path = std::string(pcs_file.path()); + cmd_options.stdout_file_prefix = symbols_file_prefix.string(); Command cmd{symbolizer_path, std::move(cmd_options)}; int exit_code = cmd.Execute(); if (exit_code != EXIT_SUCCESS) {
diff --git a/centipede/util_test.cc b/centipede/util_test.cc index be2dec3..27facf7 100644 --- a/centipede/util_test.cc +++ b/centipede/util_test.cc
@@ -31,19 +31,9 @@ #include "./common/defs.h" #include "./common/hash.h" #include "./common/logging.h" +#include "./common/test_util.h" namespace fuzztest::internal { -namespace { - -void SetEnv(const char* name, const char* value) { -#ifdef _WIN32 - _putenv_s(name, value); -#else - setenv(name, value, /*overwrite=*/1); -#endif -} - -} // namespace TEST(UtilTest, AsString) { EXPECT_EQ(AsPrintableString({'a', 'b', 'c'}, 3), "abc");
diff --git a/common/BUILD b/common/BUILD index 1ed76c7..296b140 100644 --- a/common/BUILD +++ b/common/BUILD
@@ -208,6 +208,7 @@ ":blob_file", ":defs", ":logging", + ":windows_includes", "@abseil-cpp//absl/strings", "@abseil-cpp//absl/strings:str_format", "@googletest//:gtest",
diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 007440d..b775763 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt
@@ -150,6 +150,13 @@ fuzztest_cc_library( NAME + windows_includes + HDRS + "windows_includes.h" +) + +fuzztest_cc_library( + NAME test_util HDRS "test_util.h" @@ -159,6 +166,7 @@ fuzztest::common_logging fuzztest::blob_file fuzztest::defs + fuzztest::windows_includes absl::strings absl::str_format GTest::gtest @@ -178,13 +186,6 @@ absl::strings ) -fuzztest_cc_library( - NAME - windows_includes - HDRS - "windows_includes.h" -) - ### Tests fuzztest_cc_test(
diff --git a/common/test_util.cc b/common/test_util.cc index 3232d55..eaa59a7 100644 --- a/common/test_util.cc +++ b/common/test_util.cc
@@ -12,12 +12,20 @@ // See the License for the specific language governing permissions and // limitations under the License. +#include "./common/test_util.h" + #include <cstdlib> #include <filesystem> // NOLINT #include <string> #include <string_view> #include <system_error> // NOLINT +#ifdef _WIN32 +#include "./common/windows_includes.h" +#else +#include <unistd.h> +#endif + #include "gtest/gtest.h" #include "absl/strings/str_cat.h" #include "./common/logging.h" @@ -35,11 +43,18 @@ FUZZTEST_CHECK(!error) << "Failed to create dir: " VV(dir) << error.message(); } - return std::filesystem::canonical(dir); + return std::filesystem::absolute(dir); } std::string GetTempFilePath(std::string_view subdir, size_t i) { - return GetTestTempDir(subdir) / absl::StrCat("tmp.", getpid(), ".", i); + return (GetTestTempDir(subdir) / absl::StrCat("tmp.", +#ifdef _WIN32 + GetCurrentProcessId(), +#else + getpid(), +#endif + ".", i)) + .string(); } std::filesystem::path GetTestRunfilesDir() { @@ -59,8 +74,15 @@ const auto runfiles_dir = GetTestRunfilesDir(); auto path = runfiles_dir; path.append(rel_path); - FUZZTEST_CHECK(std::filesystem::exists(path)) // - << "No such path: " << VV(path) << VV(runfiles_dir) << VV(rel_path); + std::error_code ec; +#ifdef _WIN32 + auto win_path = path; + win_path += ".exe"; + if (std::filesystem::exists(win_path, ec)) return win_path; +#endif + FUZZTEST_CHECK(std::filesystem::exists(path, ec)) // + << "No such path: " << VV(path) << VV(runfiles_dir) << VV(rel_path) + << VV(ec); return path; } @@ -78,8 +100,28 @@ void PrependDirToPathEnvvar(std::string_view dir) { const std::string new_path_envvar = absl::StrCat(dir, ":", getenv("PATH")); - setenv("PATH", new_path_envvar.c_str(), /*replace*/ 1); + SetEnv("PATH", new_path_envvar.c_str()); FUZZTEST_LOG(INFO) << "New PATH: " << new_path_envvar; } +void SetEnv(const char* name, const char* value) { +#ifdef _WIN32 + FUZZTEST_CHECK_EQ(_putenv_s(name, value), 0) + << "Failed to set envvar " << name; +#else + FUZZTEST_CHECK_EQ(setenv(name, value, /*overwrite=*/1), 0) + << "Failed to set envvar " << name; +#endif +} + +void UnsetEnv(const char* name) { +#ifdef _WIN32 + // Setting an empty value removes the envvar on Windows. + FUZZTEST_CHECK_EQ(_putenv_s(name, ""), 0) + << "Failed to unset envvar " << name; +#else + FUZZTEST_CHECK_EQ(unsetenv(name), 0) << "Failed to unset envvar " << name; +#endif +} + } // namespace fuzztest::internal
diff --git a/common/test_util.h b/common/test_util.h index c859bff..bb64b43 100644 --- a/common/test_util.h +++ b/common/test_util.h
@@ -65,6 +65,13 @@ // Resets the PATH envvar to "`dir`:$PATH". void PrependDirToPathEnvvar(std::string_view dir); +// Sets the envvar `name` to `value`, overwriting any existing value. +// FUZZTEST_CHECK-fails on error. +void SetEnv(const char* name, const char* value); + +// Removes the envvar `name`. FUZZTEST_CHECK-fails on error. +void UnsetEnv(const char* name); + // Creates or clears a tmp dir in CTOR. The dir will end with `leaf` subdir. // // TODO(b/393384208): Merge this with TempDir in temp_dir.h. @@ -79,7 +86,7 @@ const std::filesystem::path& path() const { return path_; } std::string GetFilePath(std::string_view file_name) const { - return path_ / file_name; + return (path_ / file_name).string(); } std::string CreateSubdir(std::string_view name) const {