Path: blob/master/dep/googletest/src/gtest-death-test.cc
4804 views
// Copyright 2005, Google Inc.1// All rights reserved.2//3// Redistribution and use in source and binary forms, with or without4// modification, are permitted provided that the following conditions are5// met:6//7// * Redistributions of source code must retain the above copyright8// notice, this list of conditions and the following disclaimer.9// * Redistributions in binary form must reproduce the above10// copyright notice, this list of conditions and the following disclaimer11// in the documentation and/or other materials provided with the12// distribution.13// * Neither the name of Google Inc. nor the names of its14// contributors may be used to endorse or promote products derived from15// this software without specific prior written permission.16//17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.2829//30// This file implements death tests.3132#include "gtest/gtest-death-test.h"3334#include <stdlib.h>3536#include <functional>37#include <memory>38#include <sstream>39#include <string>40#include <utility>41#include <vector>4243#include "gtest/internal/custom/gtest.h"44#include "gtest/internal/gtest-port.h"4546#ifdef GTEST_HAS_DEATH_TEST4748#ifdef GTEST_OS_MAC49#include <crt_externs.h>50#endif // GTEST_OS_MAC5152#include <errno.h>53#include <fcntl.h>54#include <limits.h>5556#ifdef GTEST_OS_LINUX57#include <signal.h>58#endif // GTEST_OS_LINUX5960#include <stdarg.h>6162#ifdef GTEST_OS_WINDOWS63#include <windows.h>64#else65#include <sys/mman.h>66#include <sys/wait.h>67#endif // GTEST_OS_WINDOWS6869#ifdef GTEST_OS_QNX70#include <spawn.h>71#endif // GTEST_OS_QNX7273#ifdef GTEST_OS_FUCHSIA74#include <lib/fdio/fd.h>75#include <lib/fdio/io.h>76#include <lib/fdio/spawn.h>77#include <lib/zx/channel.h>78#include <lib/zx/port.h>79#include <lib/zx/process.h>80#include <lib/zx/socket.h>81#include <zircon/processargs.h>82#include <zircon/syscalls.h>83#include <zircon/syscalls/policy.h>84#include <zircon/syscalls/port.h>85#endif // GTEST_OS_FUCHSIA8687#endif // GTEST_HAS_DEATH_TEST8889#include "gtest/gtest-message.h"90#include "gtest/internal/gtest-string.h"91#include "src/gtest-internal-inl.h"9293namespace testing {9495// Constants.9697// The default death test style.98//99// This is defined in internal/gtest-port.h as "fast", but can be overridden by100// a definition in internal/custom/gtest-port.h. The recommended value, which is101// used internally at Google, is "threadsafe".102static const char kDefaultDeathTestStyle[] = GTEST_DEFAULT_DEATH_TEST_STYLE;103104} // namespace testing105106GTEST_DEFINE_string_(107death_test_style,108testing::internal::StringFromGTestEnv("death_test_style",109testing::kDefaultDeathTestStyle),110"Indicates how to run a death test in a forked child process: "111"\"threadsafe\" (child process re-executes the test binary "112"from the beginning, running only the specific death test) or "113"\"fast\" (child process runs the death test immediately "114"after forking).");115116GTEST_DEFINE_bool_(117death_test_use_fork,118testing::internal::BoolFromGTestEnv("death_test_use_fork", false),119"Instructs to use fork()/_Exit() instead of clone() in death tests. "120"Ignored and always uses fork() on POSIX systems where clone() is not "121"implemented. Useful when running under valgrind or similar tools if "122"those do not support clone(). Valgrind 3.3.1 will just fail if "123"it sees an unsupported combination of clone() flags. "124"It is not recommended to use this flag w/o valgrind though it will "125"work in 99% of the cases. Once valgrind is fixed, this flag will "126"most likely be removed.");127128GTEST_DEFINE_string_(129internal_run_death_test, "",130"Indicates the file, line number, temporal index of "131"the single death test to run, and a file descriptor to "132"which a success code may be sent, all separated by "133"the '|' characters. This flag is specified if and only if the "134"current process is a sub-process launched for running a thread-safe "135"death test. FOR INTERNAL USE ONLY.");136137namespace testing {138139#ifdef GTEST_HAS_DEATH_TEST140141namespace internal {142143// Valid only for fast death tests. Indicates the code is running in the144// child process of a fast style death test.145#if !defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_FUCHSIA)146static bool g_in_fast_death_test_child = false;147#endif148149// Returns a Boolean value indicating whether the caller is currently150// executing in the context of the death test child process. Tools such as151// Valgrind heap checkers may need this to modify their behavior in death152// tests. IMPORTANT: This is an internal utility. Using it may break the153// implementation of death tests. User code MUST NOT use it.154bool InDeathTestChild() {155#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_FUCHSIA)156157// On Windows and Fuchsia, death tests are thread-safe regardless of the value158// of the death_test_style flag.159return !GTEST_FLAG_GET(internal_run_death_test).empty();160161#else162163if (GTEST_FLAG_GET(death_test_style) == "threadsafe")164return !GTEST_FLAG_GET(internal_run_death_test).empty();165else166return g_in_fast_death_test_child;167#endif168}169170} // namespace internal171172// ExitedWithCode constructor.173ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {}174175// ExitedWithCode function-call operator.176bool ExitedWithCode::operator()(int exit_status) const {177#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_FUCHSIA)178179return exit_status == exit_code_;180181#else182183return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;184185#endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA186}187188#if !defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_FUCHSIA)189// KilledBySignal constructor.190KilledBySignal::KilledBySignal(int signum) : signum_(signum) {}191192// KilledBySignal function-call operator.193bool KilledBySignal::operator()(int exit_status) const {194#if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)195{196bool result;197if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {198return result;199}200}201#endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)202return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;203}204#endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA205206namespace internal {207208// Utilities needed for death tests.209210// Generates a textual description of a given exit code, in the format211// specified by wait(2).212static std::string ExitSummary(int exit_code) {213Message m;214215#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_FUCHSIA)216217m << "Exited with exit status " << exit_code;218219#else220221if (WIFEXITED(exit_code)) {222m << "Exited with exit status " << WEXITSTATUS(exit_code);223} else if (WIFSIGNALED(exit_code)) {224m << "Terminated by signal " << WTERMSIG(exit_code);225}226#ifdef WCOREDUMP227if (WCOREDUMP(exit_code)) {228m << " (core dumped)";229}230#endif231#endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA232233return m.GetString();234}235236// Returns true if exit_status describes a process that was terminated237// by a signal, or exited normally with a nonzero exit code.238bool ExitedUnsuccessfully(int exit_status) {239return !ExitedWithCode(0)(exit_status);240}241242#if !defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_FUCHSIA)243// Generates a textual failure message when a death test finds more than244// one thread running, or cannot determine the number of threads, prior245// to executing the given statement. It is the responsibility of the246// caller not to pass a thread_count of 1.247static std::string DeathTestThreadWarning(size_t thread_count) {248Message msg;249msg << "Death tests use fork(), which is unsafe particularly"250<< " in a threaded context. For this test, " << GTEST_NAME_ << " ";251if (thread_count == 0) {252msg << "couldn't detect the number of threads.";253} else {254msg << "detected " << thread_count << " threads.";255}256msg << " See "257"https://github.com/google/googletest/blob/main/docs/"258"advanced.md#death-tests-and-threads"259<< " for more explanation and suggested solutions, especially if"260<< " this is the last message you see before your test times out.";261return msg.GetString();262}263#endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA264265// Flag characters for reporting a death test that did not die.266static const char kDeathTestLived = 'L';267static const char kDeathTestReturned = 'R';268static const char kDeathTestThrew = 'T';269static const char kDeathTestInternalError = 'I';270271#ifdef GTEST_OS_FUCHSIA272273// File descriptor used for the pipe in the child process.274static const int kFuchsiaReadPipeFd = 3;275276#endif277278// An enumeration describing all of the possible ways that a death test can279// conclude. DIED means that the process died while executing the test280// code; LIVED means that process lived beyond the end of the test code;281// RETURNED means that the test statement attempted to execute a return282// statement, which is not allowed; THREW means that the test statement283// returned control by throwing an exception. IN_PROGRESS means the test284// has not yet concluded.285enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };286287// Routine for aborting the program which is safe to call from an288// exec-style death test child process, in which case the error289// message is propagated back to the parent process. Otherwise, the290// message is simply printed to stderr. In either case, the program291// then exits with status 1.292[[noreturn]] static void DeathTestAbort(const std::string& message) {293// On a POSIX system, this function may be called from a threadsafe-style294// death test child process, which operates on a very small stack. Use295// the heap for any additional non-minuscule memory requirements.296const InternalRunDeathTestFlag* const flag =297GetUnitTestImpl()->internal_run_death_test_flag();298if (flag != nullptr) {299FILE* parent = posix::FDOpen(flag->write_fd(), "w");300fputc(kDeathTestInternalError, parent);301fprintf(parent, "%s", message.c_str());302fflush(parent);303_Exit(1);304} else {305fprintf(stderr, "%s", message.c_str());306fflush(stderr);307posix::Abort();308}309}310311// A replacement for CHECK that calls DeathTestAbort if the assertion312// fails.313#define GTEST_DEATH_TEST_CHECK_(expression) \314do { \315if (!::testing::internal::IsTrue(expression)) { \316DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \317", line " + \318::testing::internal::StreamableToString(__LINE__) + \319": " + #expression); \320} \321} while (::testing::internal::AlwaysFalse())322323// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for324// evaluating any system call that fulfills two conditions: it must return325// -1 on failure, and set errno to EINTR when it is interrupted and326// should be tried again. The macro expands to a loop that repeatedly327// evaluates the expression as long as it evaluates to -1 and sets328// errno to EINTR. If the expression evaluates to -1 but errno is329// something other than EINTR, DeathTestAbort is called.330#define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \331do { \332int gtest_retval; \333do { \334gtest_retval = (expression); \335} while (gtest_retval == -1 && errno == EINTR); \336if (gtest_retval == -1) { \337DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \338", line " + \339::testing::internal::StreamableToString(__LINE__) + \340": " + #expression + " != -1"); \341} \342} while (::testing::internal::AlwaysFalse())343344// Returns the message describing the last system error in errno.345std::string GetLastErrnoDescription() {346return errno == 0 ? "" : posix::StrError(errno);347}348349// This is called from a death test parent process to read a failure350// message from the death test child process and log it with the FATAL351// severity. On Windows, the message is read from a pipe handle. On other352// platforms, it is read from a file descriptor.353static void FailFromInternalError(int fd) {354Message error;355char buffer[256];356int num_read;357358do {359while ((num_read = posix::Read(fd, buffer, 255)) > 0) {360buffer[num_read] = '\0';361error << buffer;362}363} while (num_read == -1 && errno == EINTR);364365if (num_read == 0) {366GTEST_LOG_(FATAL) << error.GetString();367} else {368const int last_error = errno;369GTEST_LOG_(FATAL) << "Error while reading death test internal: "370<< GetLastErrnoDescription() << " [" << last_error << "]";371}372}373374// Death test constructor. Increments the running death test count375// for the current test.376DeathTest::DeathTest() {377TestInfo* const info = GetUnitTestImpl()->current_test_info();378if (info == nullptr) {379DeathTestAbort(380"Cannot run a death test outside of a TEST or "381"TEST_F construct");382}383}384385// Creates and returns a death test by dispatching to the current386// death test factory.387bool DeathTest::Create(const char* statement,388Matcher<const std::string&> matcher, const char* file,389int line, DeathTest** test) {390return GetUnitTestImpl()->death_test_factory()->Create(391statement, std::move(matcher), file, line, test);392}393394const char* DeathTest::LastMessage() {395return last_death_test_message_.c_str();396}397398void DeathTest::set_last_death_test_message(const std::string& message) {399last_death_test_message_ = message;400}401402std::string DeathTest::last_death_test_message_;403404// Provides cross platform implementation for some death functionality.405class DeathTestImpl : public DeathTest {406protected:407DeathTestImpl(const char* a_statement, Matcher<const std::string&> matcher)408: statement_(a_statement),409matcher_(std::move(matcher)),410spawned_(false),411status_(-1),412outcome_(IN_PROGRESS),413read_fd_(-1),414write_fd_(-1) {}415416// read_fd_ is expected to be closed and cleared by a derived class.417~DeathTestImpl() override { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }418419void Abort(AbortReason reason) override;420bool Passed(bool status_ok) override;421422const char* statement() const { return statement_; }423bool spawned() const { return spawned_; }424void set_spawned(bool is_spawned) { spawned_ = is_spawned; }425int status() const { return status_; }426void set_status(int a_status) { status_ = a_status; }427DeathTestOutcome outcome() const { return outcome_; }428void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }429int read_fd() const { return read_fd_; }430void set_read_fd(int fd) { read_fd_ = fd; }431int write_fd() const { return write_fd_; }432void set_write_fd(int fd) { write_fd_ = fd; }433434// Called in the parent process only. Reads the result code of the death435// test child process via a pipe, interprets it to set the outcome_436// member, and closes read_fd_. Outputs diagnostics and terminates in437// case of unexpected codes.438void ReadAndInterpretStatusByte();439440// Returns stderr output from the child process.441virtual std::string GetErrorLogs();442443private:444// The textual content of the code this object is testing. This class445// doesn't own this string and should not attempt to delete it.446const char* const statement_;447// A matcher that's expected to match the stderr output by the child process.448Matcher<const std::string&> matcher_;449// True if the death test child process has been successfully spawned.450bool spawned_;451// The exit status of the child process.452int status_;453// How the death test concluded.454DeathTestOutcome outcome_;455// Descriptor to the read end of the pipe to the child process. It is456// always -1 in the child process. The child keeps its write end of the457// pipe in write_fd_.458int read_fd_;459// Descriptor to the child's write end of the pipe to the parent process.460// It is always -1 in the parent process. The parent keeps its end of the461// pipe in read_fd_.462int write_fd_;463};464465// Called in the parent process only. Reads the result code of the death466// test child process via a pipe, interprets it to set the outcome_467// member, and closes read_fd_. Outputs diagnostics and terminates in468// case of unexpected codes.469void DeathTestImpl::ReadAndInterpretStatusByte() {470char flag;471int bytes_read;472473// The read() here blocks until data is available (signifying the474// failure of the death test) or until the pipe is closed (signifying475// its success), so it's okay to call this in the parent before476// the child process has exited.477do {478bytes_read = posix::Read(read_fd(), &flag, 1);479} while (bytes_read == -1 && errno == EINTR);480481if (bytes_read == 0) {482set_outcome(DIED);483} else if (bytes_read == 1) {484switch (flag) {485case kDeathTestReturned:486set_outcome(RETURNED);487break;488case kDeathTestThrew:489set_outcome(THREW);490break;491case kDeathTestLived:492set_outcome(LIVED);493break;494case kDeathTestInternalError:495FailFromInternalError(read_fd()); // Does not return.496break;497default:498GTEST_LOG_(FATAL) << "Death test child process reported "499<< "unexpected status byte ("500<< static_cast<unsigned int>(flag) << ")";501}502} else {503GTEST_LOG_(FATAL) << "Read from death test child process failed: "504<< GetLastErrnoDescription();505}506GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));507set_read_fd(-1);508}509510std::string DeathTestImpl::GetErrorLogs() { return GetCapturedStderr(); }511512// Signals that the death test code which should have exited, didn't.513// Should be called only in a death test child process.514// Writes a status byte to the child's status file descriptor, then515// calls _Exit(1).516void DeathTestImpl::Abort(AbortReason reason) {517// The parent process considers the death test to be a failure if518// it finds any data in our pipe. So, here we write a single flag byte519// to the pipe, then exit.520const char status_ch = reason == TEST_DID_NOT_DIE ? kDeathTestLived521: reason == TEST_THREW_EXCEPTION ? kDeathTestThrew522: kDeathTestReturned;523524GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));525// We are leaking the descriptor here because on some platforms (i.e.,526// when built as Windows DLL), destructors of global objects will still527// run after calling _Exit(). On such systems, write_fd_ will be528// indirectly closed from the destructor of UnitTestImpl, causing double529// close if it is also closed here. On debug configurations, double close530// may assert. As there are no in-process buffers to flush here, we are531// relying on the OS to close the descriptor after the process terminates532// when the destructors are not run.533_Exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)534}535536// Returns an indented copy of stderr output for a death test.537// This makes distinguishing death test output lines from regular log lines538// much easier.539static ::std::string FormatDeathTestOutput(const ::std::string& output) {540::std::string ret;541for (size_t at = 0;;) {542const size_t line_end = output.find('\n', at);543ret += "[ DEATH ] ";544if (line_end == ::std::string::npos) {545ret += output.substr(at);546break;547}548ret += output.substr(at, line_end + 1 - at);549at = line_end + 1;550}551return ret;552}553554// Assesses the success or failure of a death test, using both private555// members which have previously been set, and one argument:556//557// Private data members:558// outcome: An enumeration describing how the death test559// concluded: DIED, LIVED, THREW, or RETURNED. The death test560// fails in the latter three cases.561// status: The exit status of the child process. On *nix, it is in the562// in the format specified by wait(2). On Windows, this is the563// value supplied to the ExitProcess() API or a numeric code564// of the exception that terminated the program.565// matcher_: A matcher that's expected to match the stderr output by the child566// process.567//568// Argument:569// status_ok: true if exit_status is acceptable in the context of570// this particular death test, which fails if it is false571//572// Returns true if and only if all of the above conditions are met. Otherwise,573// the first failing condition, in the order given above, is the one that is574// reported. Also sets the last death test message string.575bool DeathTestImpl::Passed(bool status_ok) {576if (!spawned()) return false;577578const std::string error_message = GetErrorLogs();579580bool success = false;581Message buffer;582583buffer << "Death test: " << statement() << "\n";584switch (outcome()) {585case LIVED:586buffer << " Result: failed to die.\n"587<< " Error msg:\n"588<< FormatDeathTestOutput(error_message);589break;590case THREW:591buffer << " Result: threw an exception.\n"592<< " Error msg:\n"593<< FormatDeathTestOutput(error_message);594break;595case RETURNED:596buffer << " Result: illegal return in test statement.\n"597<< " Error msg:\n"598<< FormatDeathTestOutput(error_message);599break;600case DIED:601if (status_ok) {602if (matcher_.Matches(error_message)) {603success = true;604} else {605std::ostringstream stream;606matcher_.DescribeTo(&stream);607buffer << " Result: died but not with expected error.\n"608<< " Expected: " << stream.str() << "\n"609<< "Actual msg:\n"610<< FormatDeathTestOutput(error_message);611}612} else {613buffer << " Result: died but not with expected exit code:\n"614<< " " << ExitSummary(status()) << "\n"615<< "Actual msg:\n"616<< FormatDeathTestOutput(error_message);617}618break;619case IN_PROGRESS:620default:621GTEST_LOG_(FATAL)622<< "DeathTest::Passed somehow called before conclusion of test";623}624625DeathTest::set_last_death_test_message(buffer.GetString());626return success;627}628629#ifndef GTEST_OS_WINDOWS630// Note: The return value points into args, so the return value's lifetime is631// bound to that of args.632static std::vector<char*> CreateArgvFromArgs(std::vector<std::string>& args) {633std::vector<char*> result;634result.reserve(args.size() + 1);635for (auto& arg : args) {636result.push_back(&arg[0]);637}638result.push_back(nullptr); // Extra null terminator.639return result;640}641#endif642643#ifdef GTEST_OS_WINDOWS644// WindowsDeathTest implements death tests on Windows. Due to the645// specifics of starting new processes on Windows, death tests there are646// always threadsafe, and Google Test considers the647// --gtest_death_test_style=fast setting to be equivalent to648// --gtest_death_test_style=threadsafe there.649//650// A few implementation notes: Like the Linux version, the Windows651// implementation uses pipes for child-to-parent communication. But due to652// the specifics of pipes on Windows, some extra steps are required:653//654// 1. The parent creates a communication pipe and stores handles to both655// ends of it.656// 2. The parent starts the child and provides it with the information657// necessary to acquire the handle to the write end of the pipe.658// 3. The child acquires the write end of the pipe and signals the parent659// using a Windows event.660// 4. Now the parent can release the write end of the pipe on its side. If661// this is done before step 3, the object's reference count goes down to662// 0 and it is destroyed, preventing the child from acquiring it. The663// parent now has to release it, or read operations on the read end of664// the pipe will not return when the child terminates.665// 5. The parent reads child's output through the pipe (outcome code and666// any possible error messages) from the pipe, and its stderr and then667// determines whether to fail the test.668//669// Note: to distinguish Win32 API calls from the local method and function670// calls, the former are explicitly resolved in the global namespace.671//672class WindowsDeathTest : public DeathTestImpl {673public:674WindowsDeathTest(const char* a_statement, Matcher<const std::string&> matcher,675const char* file, int line)676: DeathTestImpl(a_statement, std::move(matcher)),677file_(file),678line_(line) {}679680// All of these virtual functions are inherited from DeathTest.681virtual int Wait();682virtual TestRole AssumeRole();683684private:685// The name of the file in which the death test is located.686const char* const file_;687// The line number on which the death test is located.688const int line_;689// Handle to the write end of the pipe to the child process.690AutoHandle write_handle_;691// Child process handle.692AutoHandle child_handle_;693// Event the child process uses to signal the parent that it has694// acquired the handle to the write end of the pipe. After seeing this695// event the parent can release its own handles to make sure its696// ReadFile() calls return when the child terminates.697AutoHandle event_handle_;698};699700// Waits for the child in a death test to exit, returning its exit701// status, or 0 if no child process exists. As a side effect, sets the702// outcome data member.703int WindowsDeathTest::Wait() {704if (!spawned()) return 0;705706// Wait until the child either signals that it has acquired the write end707// of the pipe or it dies.708const HANDLE wait_handles[2] = {child_handle_.Get(), event_handle_.Get()};709switch (::WaitForMultipleObjects(2, wait_handles,710FALSE, // Waits for any of the handles.711INFINITE)) {712case WAIT_OBJECT_0:713case WAIT_OBJECT_0 + 1:714break;715default:716GTEST_DEATH_TEST_CHECK_(false); // Should not get here.717}718719// The child has acquired the write end of the pipe or exited.720// We release the handle on our side and continue.721write_handle_.Reset();722event_handle_.Reset();723724ReadAndInterpretStatusByte();725726// Waits for the child process to exit if it haven't already. This727// returns immediately if the child has already exited, regardless of728// whether previous calls to WaitForMultipleObjects synchronized on this729// handle or not.730GTEST_DEATH_TEST_CHECK_(WAIT_OBJECT_0 ==731::WaitForSingleObject(child_handle_.Get(), INFINITE));732DWORD status_code;733GTEST_DEATH_TEST_CHECK_(734::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);735child_handle_.Reset();736set_status(static_cast<int>(status_code));737return status();738}739740// The AssumeRole process for a Windows death test. It creates a child741// process with the same executable as the current process to run the742// death test. The child process is given the --gtest_filter and743// --gtest_internal_run_death_test flags such that it knows to run the744// current death test only.745DeathTest::TestRole WindowsDeathTest::AssumeRole() {746const UnitTestImpl* const impl = GetUnitTestImpl();747const InternalRunDeathTestFlag* const flag =748impl->internal_run_death_test_flag();749const TestInfo* const info = impl->current_test_info();750const int death_test_index = info->result()->death_test_count();751752if (flag != nullptr) {753// ParseInternalRunDeathTestFlag() has performed all the necessary754// processing.755set_write_fd(flag->write_fd());756return EXECUTE_TEST;757}758759// WindowsDeathTest uses an anonymous pipe to communicate results of760// a death test.761SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES),762nullptr, TRUE};763HANDLE read_handle, write_handle;764GTEST_DEATH_TEST_CHECK_(::CreatePipe(&read_handle, &write_handle,765&handles_are_inheritable,7660) // Default buffer size.767!= FALSE);768set_read_fd(769::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle), O_RDONLY));770write_handle_.Reset(write_handle);771event_handle_.Reset(::CreateEvent(772&handles_are_inheritable,773TRUE, // The event will automatically reset to non-signaled state.774FALSE, // The initial state is non-signalled.775nullptr)); // The even is unnamed.776GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != nullptr);777const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +778"filter=" + info->test_suite_name() + "." +779info->name();780const std::string internal_flag =781std::string("--") + GTEST_FLAG_PREFIX_ +782"internal_run_death_test=" + file_ + "|" + StreamableToString(line_) +783"|" + StreamableToString(death_test_index) + "|" +784StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +785// size_t has the same width as pointers on both 32-bit and 64-bit786// Windows platforms.787// See https://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.788"|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) + "|" +789StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));790791char executable_path[_MAX_PATH + 1]; // NOLINT792GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(nullptr,793executable_path,794_MAX_PATH));795796std::string command_line = std::string(::GetCommandLineA()) + " " +797filter_flag + " \"" + internal_flag + "\"";798799DeathTest::set_last_death_test_message("");800801CaptureStderr();802// Flush the log buffers since the log streams are shared with the child.803FlushInfoLog();804805// The child process will share the standard handles with the parent.806STARTUPINFOA startup_info;807memset(&startup_info, 0, sizeof(STARTUPINFO));808startup_info.dwFlags = STARTF_USESTDHANDLES;809startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);810startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);811startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);812813PROCESS_INFORMATION process_info;814GTEST_DEATH_TEST_CHECK_(815::CreateProcessA(816executable_path, const_cast<char*>(command_line.c_str()),817nullptr, // Returned process handle is not inheritable.818nullptr, // Returned thread handle is not inheritable.819TRUE, // Child inherits all inheritable handles (for write_handle_).8200x0, // Default creation flags.821nullptr, // Inherit the parent's environment.822UnitTest::GetInstance()->original_working_dir(), &startup_info,823&process_info) != FALSE);824child_handle_.Reset(process_info.hProcess);825::CloseHandle(process_info.hThread);826set_spawned(true);827return OVERSEE_TEST;828}829830#elif defined(GTEST_OS_FUCHSIA)831832class FuchsiaDeathTest : public DeathTestImpl {833public:834FuchsiaDeathTest(const char* a_statement, Matcher<const std::string&> matcher,835const char* file, int line)836: DeathTestImpl(a_statement, std::move(matcher)),837file_(file),838line_(line) {}839840// All of these virtual functions are inherited from DeathTest.841int Wait() override;842TestRole AssumeRole() override;843std::string GetErrorLogs() override;844845private:846// The name of the file in which the death test is located.847const char* const file_;848// The line number on which the death test is located.849const int line_;850// The stderr data captured by the child process.851std::string captured_stderr_;852853zx::process child_process_;854zx::channel exception_channel_;855zx::socket stderr_socket_;856};857858// Waits for the child in a death test to exit, returning its exit859// status, or 0 if no child process exists. As a side effect, sets the860// outcome data member.861int FuchsiaDeathTest::Wait() {862const int kProcessKey = 0;863const int kSocketKey = 1;864const int kExceptionKey = 2;865866if (!spawned()) return 0;867868// Create a port to wait for socket/task/exception events.869zx_status_t status_zx;870zx::port port;871status_zx = zx::port::create(0, &port);872GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);873874// Register to wait for the child process to terminate.875status_zx =876child_process_.wait_async(port, kProcessKey, ZX_PROCESS_TERMINATED, 0);877GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);878879// Register to wait for the socket to be readable or closed.880status_zx = stderr_socket_.wait_async(881port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0);882GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);883884// Register to wait for an exception.885status_zx = exception_channel_.wait_async(port, kExceptionKey,886ZX_CHANNEL_READABLE, 0);887GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);888889bool process_terminated = false;890bool socket_closed = false;891do {892zx_port_packet_t packet = {};893status_zx = port.wait(zx::time::infinite(), &packet);894GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);895896if (packet.key == kExceptionKey) {897// Process encountered an exception. Kill it directly rather than898// letting other handlers process the event. We will get a kProcessKey899// event when the process actually terminates.900status_zx = child_process_.kill();901GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);902} else if (packet.key == kProcessKey) {903// Process terminated.904GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));905GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED);906process_terminated = true;907} else if (packet.key == kSocketKey) {908GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));909if (packet.signal.observed & ZX_SOCKET_READABLE) {910// Read data from the socket.911constexpr size_t kBufferSize = 1024;912do {913size_t old_length = captured_stderr_.length();914size_t bytes_read = 0;915captured_stderr_.resize(old_length + kBufferSize);916status_zx =917stderr_socket_.read(0, &captured_stderr_.front() + old_length,918kBufferSize, &bytes_read);919captured_stderr_.resize(old_length + bytes_read);920} while (status_zx == ZX_OK);921if (status_zx == ZX_ERR_PEER_CLOSED) {922socket_closed = true;923} else {924GTEST_DEATH_TEST_CHECK_(status_zx == ZX_ERR_SHOULD_WAIT);925status_zx = stderr_socket_.wait_async(926port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0);927GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);928}929} else {930GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_SOCKET_PEER_CLOSED);931socket_closed = true;932}933}934} while (!process_terminated && !socket_closed);935936ReadAndInterpretStatusByte();937938zx_info_process_t buffer;939status_zx = child_process_.get_info(ZX_INFO_PROCESS, &buffer, sizeof(buffer),940nullptr, nullptr);941GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);942943GTEST_DEATH_TEST_CHECK_(buffer.flags & ZX_INFO_PROCESS_FLAG_EXITED);944set_status(static_cast<int>(buffer.return_code));945return status();946}947948// The AssumeRole process for a Fuchsia death test. It creates a child949// process with the same executable as the current process to run the950// death test. The child process is given the --gtest_filter and951// --gtest_internal_run_death_test flags such that it knows to run the952// current death test only.953DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {954const UnitTestImpl* const impl = GetUnitTestImpl();955const InternalRunDeathTestFlag* const flag =956impl->internal_run_death_test_flag();957const TestInfo* const info = impl->current_test_info();958const int death_test_index = info->result()->death_test_count();959960if (flag != nullptr) {961// ParseInternalRunDeathTestFlag() has performed all the necessary962// processing.963set_write_fd(kFuchsiaReadPipeFd);964return EXECUTE_TEST;965}966967// Flush the log buffers since the log streams are shared with the child.968FlushInfoLog();969970// Build the child process command line.971const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +972"filter=" + info->test_suite_name() + "." +973info->name();974const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ +975kInternalRunDeathTestFlag + "=" + file_ +976"|" + StreamableToString(line_) + "|" +977StreamableToString(death_test_index);978979std::vector<std::string> args = GetInjectableArgvs();980args.push_back(filter_flag);981args.push_back(internal_flag);982983// Build the pipe for communication with the child.984zx_status_t status;985zx_handle_t child_pipe_handle;986int child_pipe_fd;987status = fdio_pipe_half(&child_pipe_fd, &child_pipe_handle);988GTEST_DEATH_TEST_CHECK_(status == ZX_OK);989set_read_fd(child_pipe_fd);990991// Set the pipe handle for the child.992fdio_spawn_action_t spawn_actions[2] = {};993fdio_spawn_action_t* add_handle_action = &spawn_actions[0];994add_handle_action->action = FDIO_SPAWN_ACTION_ADD_HANDLE;995add_handle_action->h.id = PA_HND(PA_FD, kFuchsiaReadPipeFd);996add_handle_action->h.handle = child_pipe_handle;997998// Create a socket pair will be used to receive the child process' stderr.999zx::socket stderr_producer_socket;1000status = zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);1001GTEST_DEATH_TEST_CHECK_(status >= 0);1002int stderr_producer_fd = -1;1003status =1004fdio_fd_create(stderr_producer_socket.release(), &stderr_producer_fd);1005GTEST_DEATH_TEST_CHECK_(status >= 0);10061007// Make the stderr socket nonblocking.1008GTEST_DEATH_TEST_CHECK_(fcntl(stderr_producer_fd, F_SETFL, 0) == 0);10091010fdio_spawn_action_t* add_stderr_action = &spawn_actions[1];1011add_stderr_action->action = FDIO_SPAWN_ACTION_CLONE_FD;1012add_stderr_action->fd.local_fd = stderr_producer_fd;1013add_stderr_action->fd.target_fd = STDERR_FILENO;10141015// Create a child job.1016zx_handle_t child_job = ZX_HANDLE_INVALID;1017status = zx_job_create(zx_job_default(), 0, &child_job);1018GTEST_DEATH_TEST_CHECK_(status == ZX_OK);1019zx_policy_basic_t policy;1020policy.condition = ZX_POL_NEW_ANY;1021policy.policy = ZX_POL_ACTION_ALLOW;1022status = zx_job_set_policy(child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC,1023&policy, 1);1024GTEST_DEATH_TEST_CHECK_(status == ZX_OK);10251026// Create an exception channel attached to the |child_job|, to allow1027// us to suppress the system default exception handler from firing.1028status = zx_task_create_exception_channel(1029child_job, 0, exception_channel_.reset_and_get_address());1030GTEST_DEATH_TEST_CHECK_(status == ZX_OK);10311032// Spawn the child process.1033// Note: The test component must have `fuchsia.process.Launcher` declared1034// in its manifest. (Fuchsia integration tests require creating a1035// "Fuchsia Test Component" which contains a "Fuchsia Component Manifest")1036// Launching processes is a privileged operation in Fuchsia, and the1037// declaration indicates that the ability is required for the component.1038std::vector<char*> argv = CreateArgvFromArgs(args);1039status = fdio_spawn_etc(child_job, FDIO_SPAWN_CLONE_ALL, argv[0], argv.data(),1040nullptr, 2, spawn_actions,1041child_process_.reset_and_get_address(), nullptr);1042GTEST_DEATH_TEST_CHECK_(status == ZX_OK);10431044set_spawned(true);1045return OVERSEE_TEST;1046}10471048std::string FuchsiaDeathTest::GetErrorLogs() { return captured_stderr_; }10491050#else // We are neither on Windows, nor on Fuchsia.10511052// ForkingDeathTest provides implementations for most of the abstract1053// methods of the DeathTest interface. Only the AssumeRole method is1054// left undefined.1055class ForkingDeathTest : public DeathTestImpl {1056public:1057ForkingDeathTest(const char* statement, Matcher<const std::string&> matcher);10581059// All of these virtual functions are inherited from DeathTest.1060int Wait() override;10611062protected:1063void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }10641065private:1066// PID of child process during death test; 0 in the child process itself.1067pid_t child_pid_;1068};10691070// Constructs a ForkingDeathTest.1071ForkingDeathTest::ForkingDeathTest(const char* a_statement,1072Matcher<const std::string&> matcher)1073: DeathTestImpl(a_statement, std::move(matcher)), child_pid_(-1) {}10741075// Waits for the child in a death test to exit, returning its exit1076// status, or 0 if no child process exists. As a side effect, sets the1077// outcome data member.1078int ForkingDeathTest::Wait() {1079if (!spawned()) return 0;10801081ReadAndInterpretStatusByte();10821083int status_value;1084GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));1085set_status(status_value);1086return status_value;1087}10881089// A concrete death test class that forks, then immediately runs the test1090// in the child process.1091class NoExecDeathTest : public ForkingDeathTest {1092public:1093NoExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher)1094: ForkingDeathTest(a_statement, std::move(matcher)) {}1095TestRole AssumeRole() override;1096};10971098// The AssumeRole process for a fork-and-run death test. It implements a1099// straightforward fork, with a simple pipe to transmit the status byte.1100DeathTest::TestRole NoExecDeathTest::AssumeRole() {1101const size_t thread_count = GetThreadCount();1102if (thread_count != 1) {1103GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);1104}11051106int pipe_fd[2];1107GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);11081109DeathTest::set_last_death_test_message("");1110CaptureStderr();1111// When we fork the process below, the log file buffers are copied, but the1112// file descriptors are shared. We flush all log files here so that closing1113// the file descriptors in the child process doesn't throw off the1114// synchronization between descriptors and buffers in the parent process.1115// This is as close to the fork as possible to avoid a race condition in case1116// there are multiple threads running before the death test, and another1117// thread writes to the log file.1118FlushInfoLog();11191120const pid_t child_pid = fork();1121GTEST_DEATH_TEST_CHECK_(child_pid != -1);1122set_child_pid(child_pid);1123if (child_pid == 0) {1124GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));1125set_write_fd(pipe_fd[1]);1126// Redirects all logging to stderr in the child process to prevent1127// concurrent writes to the log files. We capture stderr in the parent1128// process and append the child process' output to a log.1129LogToStderr();1130// Event forwarding to the listeners of event listener API mush be shut1131// down in death test subprocesses.1132GetUnitTestImpl()->listeners()->SuppressEventForwarding(true);1133g_in_fast_death_test_child = true;1134return EXECUTE_TEST;1135} else {1136GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));1137set_read_fd(pipe_fd[0]);1138set_spawned(true);1139return OVERSEE_TEST;1140}1141}11421143// A concrete death test class that forks and re-executes the main1144// program from the beginning, with command-line flags set that cause1145// only this specific death test to be run.1146class ExecDeathTest : public ForkingDeathTest {1147public:1148ExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher,1149const char* file, int line)1150: ForkingDeathTest(a_statement, std::move(matcher)),1151file_(file),1152line_(line) {}1153TestRole AssumeRole() override;11541155private:1156static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {1157::std::vector<std::string> args = GetInjectableArgvs();1158#if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)1159::std::vector<std::string> extra_args =1160GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();1161args.insert(args.end(), extra_args.begin(), extra_args.end());1162#endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)1163return args;1164}1165// The name of the file in which the death test is located.1166const char* const file_;1167// The line number on which the death test is located.1168const int line_;1169};11701171// A struct that encompasses the arguments to the child process of a1172// threadsafe-style death test process.1173struct ExecDeathTestArgs {1174char* const* argv; // Command-line arguments for the child's call to exec1175int close_fd; // File descriptor to close; the read end of a pipe1176};11771178#ifdef GTEST_OS_QNX1179extern "C" char** environ;1180#else // GTEST_OS_QNX1181// The main function for a threadsafe-style death test child process.1182// This function is called in a clone()-ed process and thus must avoid1183// any potentially unsafe operations like malloc or libc functions.1184static int ExecDeathTestChildMain(void* child_arg) {1185ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);1186GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));11871188// We need to execute the test program in the same environment where1189// it was originally invoked. Therefore we change to the original1190// working directory first.1191const char* const original_dir =1192UnitTest::GetInstance()->original_working_dir();1193// We can safely call chdir() as it's a direct system call.1194if (chdir(original_dir) != 0) {1195DeathTestAbort(std::string("chdir(\"") + original_dir +1196"\") failed: " + GetLastErrnoDescription());1197return EXIT_FAILURE;1198}11991200// We can safely call execv() as it's almost a direct system call. We1201// cannot use execvp() as it's a libc function and thus potentially1202// unsafe. Since execv() doesn't search the PATH, the user must1203// invoke the test program via a valid path that contains at least1204// one path separator.1205execv(args->argv[0], args->argv);1206DeathTestAbort(std::string("execv(") + args->argv[0] + ", ...) in " +1207original_dir + " failed: " + GetLastErrnoDescription());1208return EXIT_FAILURE;1209}1210#endif // GTEST_OS_QNX12111212#if GTEST_HAS_CLONE1213// Two utility routines that together determine the direction the stack1214// grows.1215// This could be accomplished more elegantly by a single recursive1216// function, but we want to guard against the unlikely possibility of1217// a smart compiler optimizing the recursion away.1218//1219// GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining1220// StackLowerThanAddress into StackGrowsDown, which then doesn't give1221// correct answer.1222static void StackLowerThanAddress(const void* ptr,1223bool* result) GTEST_NO_INLINE_;1224// Make sure sanitizers do not tamper with the stack here.1225// Ideally, we want to use `__builtin_frame_address` instead of a local variable1226// address with sanitizer disabled, but it does not work when the1227// compiler optimizes the stack frame out, which happens on PowerPC targets.1228// HWAddressSanitizer add a random tag to the MSB of the local variable address,1229// making comparison result unpredictable.1230GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_1231GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_1232static void StackLowerThanAddress(const void* ptr, bool* result) {1233int dummy = 0;1234*result = std::less<const void*>()(&dummy, ptr);1235}12361237// Make sure AddressSanitizer does not tamper with the stack here.1238GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_1239GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_1240static bool StackGrowsDown() {1241int dummy = 0;1242bool result;1243StackLowerThanAddress(&dummy, &result);1244return result;1245}1246#endif // GTEST_HAS_CLONE12471248// Spawns a child process with the same executable as the current process in1249// a thread-safe manner and instructs it to run the death test. The1250// implementation uses fork(2) + exec. On systems where clone(2) is1251// available, it is used instead, being slightly more thread-safe. On QNX,1252// fork supports only single-threaded environments, so this function uses1253// spawn(2) there instead. The function dies with an error message if1254// anything goes wrong.1255static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {1256ExecDeathTestArgs args = {argv, close_fd};1257pid_t child_pid = -1;12581259#ifdef GTEST_OS_QNX1260// Obtains the current directory and sets it to be closed in the child1261// process.1262const int cwd_fd = open(".", O_RDONLY);1263GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);1264GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));1265// We need to execute the test program in the same environment where1266// it was originally invoked. Therefore we change to the original1267// working directory first.1268const char* const original_dir =1269UnitTest::GetInstance()->original_working_dir();1270// We can safely call chdir() as it's a direct system call.1271if (chdir(original_dir) != 0) {1272DeathTestAbort(std::string("chdir(\"") + original_dir +1273"\") failed: " + GetLastErrnoDescription());1274return EXIT_FAILURE;1275}12761277int fd_flags;1278// Set close_fd to be closed after spawn.1279GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));1280GTEST_DEATH_TEST_CHECK_SYSCALL_(1281fcntl(close_fd, F_SETFD, fd_flags | FD_CLOEXEC));1282struct inheritance inherit = {0};1283// spawn is a system call.1284child_pid = spawn(args.argv[0], 0, nullptr, &inherit, args.argv, environ);1285// Restores the current working directory.1286GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);1287GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));12881289#else // GTEST_OS_QNX1290#ifdef GTEST_OS_LINUX1291// When a SIGPROF signal is received while fork() or clone() are executing,1292// the process may hang. To avoid this, we ignore SIGPROF here and re-enable1293// it after the call to fork()/clone() is complete.1294struct sigaction saved_sigprof_action;1295struct sigaction ignore_sigprof_action;1296memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));1297sigemptyset(&ignore_sigprof_action.sa_mask);1298ignore_sigprof_action.sa_handler = SIG_IGN;1299GTEST_DEATH_TEST_CHECK_SYSCALL_(1300sigaction(SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));1301#endif // GTEST_OS_LINUX13021303#if GTEST_HAS_CLONE1304const bool use_fork = GTEST_FLAG_GET(death_test_use_fork);13051306if (!use_fork) {1307static const bool stack_grows_down = StackGrowsDown();1308const auto stack_size = static_cast<size_t>(getpagesize() * 2);1309// MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.1310void* const stack = mmap(nullptr, stack_size, PROT_READ | PROT_WRITE,1311MAP_ANON | MAP_PRIVATE, -1, 0);1312GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);13131314// Maximum stack alignment in bytes: For a downward-growing stack, this1315// amount is subtracted from size of the stack space to get an address1316// that is within the stack space and is aligned on all systems we care1317// about. As far as I know there is no ABI with stack alignment greater1318// than 64. We assume stack and stack_size already have alignment of1319// kMaxStackAlignment.1320const size_t kMaxStackAlignment = 64;1321void* const stack_top =1322static_cast<char*>(stack) +1323(stack_grows_down ? stack_size - kMaxStackAlignment : 0);1324GTEST_DEATH_TEST_CHECK_(1325static_cast<size_t>(stack_size) > kMaxStackAlignment &&1326reinterpret_cast<uintptr_t>(stack_top) % kMaxStackAlignment == 0);13271328child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);13291330GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);1331}1332#else1333const bool use_fork = true;1334#endif // GTEST_HAS_CLONE13351336if (use_fork && (child_pid = fork()) == 0) {1337_Exit(ExecDeathTestChildMain(&args));1338}1339#endif // GTEST_OS_QNX1340#ifdef GTEST_OS_LINUX1341GTEST_DEATH_TEST_CHECK_SYSCALL_(1342sigaction(SIGPROF, &saved_sigprof_action, nullptr));1343#endif // GTEST_OS_LINUX13441345GTEST_DEATH_TEST_CHECK_(child_pid != -1);1346return child_pid;1347}13481349// The AssumeRole process for a fork-and-exec death test. It re-executes the1350// main program from the beginning, setting the --gtest_filter1351// and --gtest_internal_run_death_test flags to cause only the current1352// death test to be re-run.1353DeathTest::TestRole ExecDeathTest::AssumeRole() {1354const UnitTestImpl* const impl = GetUnitTestImpl();1355const InternalRunDeathTestFlag* const flag =1356impl->internal_run_death_test_flag();1357const TestInfo* const info = impl->current_test_info();1358const int death_test_index = info->result()->death_test_count();13591360if (flag != nullptr) {1361set_write_fd(flag->write_fd());1362return EXECUTE_TEST;1363}13641365int pipe_fd[2];1366GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);1367// Clear the close-on-exec flag on the write end of the pipe, lest1368// it be closed when the child process does an exec:1369GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);13701371const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +1372"filter=" + info->test_suite_name() + "." +1373info->name();1374const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ +1375"internal_run_death_test=" + file_ + "|" +1376StreamableToString(line_) + "|" +1377StreamableToString(death_test_index) + "|" +1378StreamableToString(pipe_fd[1]);1379std::vector<std::string> args = GetArgvsForDeathTestChildProcess();1380args.push_back(filter_flag);1381args.push_back(internal_flag);13821383DeathTest::set_last_death_test_message("");13841385CaptureStderr();1386// See the comment in NoExecDeathTest::AssumeRole for why the next line1387// is necessary.1388FlushInfoLog();13891390std::vector<char*> argv = CreateArgvFromArgs(args);1391const pid_t child_pid = ExecDeathTestSpawnChild(argv.data(), pipe_fd[0]);1392GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));1393set_child_pid(child_pid);1394set_read_fd(pipe_fd[0]);1395set_spawned(true);1396return OVERSEE_TEST;1397}13981399#endif // !GTEST_OS_WINDOWS14001401// Creates a concrete DeathTest-derived class that depends on the1402// --gtest_death_test_style flag, and sets the pointer pointed to1403// by the "test" argument to its address. If the test should be1404// skipped, sets that pointer to NULL. Returns true, unless the1405// flag is set to an invalid value.1406bool DefaultDeathTestFactory::Create(const char* statement,1407Matcher<const std::string&> matcher,1408const char* file, int line,1409DeathTest** test) {1410UnitTestImpl* const impl = GetUnitTestImpl();1411const InternalRunDeathTestFlag* const flag =1412impl->internal_run_death_test_flag();1413const int death_test_index =1414impl->current_test_info()->increment_death_test_count();14151416if (flag != nullptr) {1417if (death_test_index > flag->index()) {1418DeathTest::set_last_death_test_message(1419"Death test count (" + StreamableToString(death_test_index) +1420") somehow exceeded expected maximum (" +1421StreamableToString(flag->index()) + ")");1422return false;1423}14241425if (!(flag->file() == file && flag->line() == line &&1426flag->index() == death_test_index)) {1427*test = nullptr;1428return true;1429}1430}14311432#ifdef GTEST_OS_WINDOWS14331434if (GTEST_FLAG_GET(death_test_style) == "threadsafe" ||1435GTEST_FLAG_GET(death_test_style) == "fast") {1436*test = new WindowsDeathTest(statement, std::move(matcher), file, line);1437}14381439#elif defined(GTEST_OS_FUCHSIA)14401441if (GTEST_FLAG_GET(death_test_style) == "threadsafe" ||1442GTEST_FLAG_GET(death_test_style) == "fast") {1443*test = new FuchsiaDeathTest(statement, std::move(matcher), file, line);1444}14451446#else14471448if (GTEST_FLAG_GET(death_test_style) == "threadsafe") {1449*test = new ExecDeathTest(statement, std::move(matcher), file, line);1450} else if (GTEST_FLAG_GET(death_test_style) == "fast") {1451*test = new NoExecDeathTest(statement, std::move(matcher));1452}14531454#endif // GTEST_OS_WINDOWS14551456else { // NOLINT - this is more readable than unbalanced brackets inside #if.1457DeathTest::set_last_death_test_message("Unknown death test style \"" +1458GTEST_FLAG_GET(death_test_style) +1459"\" encountered");1460return false;1461}14621463return true;1464}14651466#ifdef GTEST_OS_WINDOWS1467// Recreates the pipe and event handles from the provided parameters,1468// signals the event, and returns a file descriptor wrapped around the pipe1469// handle. This function is called in the child process only.1470static int GetStatusFileDescriptor(unsigned int parent_process_id,1471size_t write_handle_as_size_t,1472size_t event_handle_as_size_t) {1473AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,1474FALSE, // Non-inheritable.1475parent_process_id));1476if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {1477DeathTestAbort("Unable to open parent process " +1478StreamableToString(parent_process_id));1479}14801481GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));14821483const HANDLE write_handle = reinterpret_cast<HANDLE>(write_handle_as_size_t);1484HANDLE dup_write_handle;14851486// The newly initialized handle is accessible only in the parent1487// process. To obtain one accessible within the child, we need to use1488// DuplicateHandle.1489if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,1490::GetCurrentProcess(), &dup_write_handle,14910x0, // Requested privileges ignored since1492// DUPLICATE_SAME_ACCESS is used.1493FALSE, // Request non-inheritable handler.1494DUPLICATE_SAME_ACCESS)) {1495DeathTestAbort("Unable to duplicate the pipe handle " +1496StreamableToString(write_handle_as_size_t) +1497" from the parent process " +1498StreamableToString(parent_process_id));1499}15001501const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);1502HANDLE dup_event_handle;15031504if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,1505::GetCurrentProcess(), &dup_event_handle, 0x0, FALSE,1506DUPLICATE_SAME_ACCESS)) {1507DeathTestAbort("Unable to duplicate the event handle " +1508StreamableToString(event_handle_as_size_t) +1509" from the parent process " +1510StreamableToString(parent_process_id));1511}15121513const int write_fd =1514::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);1515if (write_fd == -1) {1516DeathTestAbort("Unable to convert pipe handle " +1517StreamableToString(write_handle_as_size_t) +1518" to a file descriptor");1519}15201521// Signals the parent that the write end of the pipe has been acquired1522// so the parent can release its own write end.1523::SetEvent(dup_event_handle);15241525return write_fd;1526}1527#endif // GTEST_OS_WINDOWS15281529// Returns a newly created InternalRunDeathTestFlag object with fields1530// initialized from the GTEST_FLAG(internal_run_death_test) flag if1531// the flag is specified; otherwise returns NULL.1532InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {1533if (GTEST_FLAG_GET(internal_run_death_test).empty()) return nullptr;15341535// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we1536// can use it here.1537int line = -1;1538int index = -1;1539::std::vector< ::std::string> fields;1540SplitString(GTEST_FLAG_GET(internal_run_death_test), '|', &fields);1541int write_fd = -1;15421543#ifdef GTEST_OS_WINDOWS15441545unsigned int parent_process_id = 0;1546size_t write_handle_as_size_t = 0;1547size_t event_handle_as_size_t = 0;15481549if (fields.size() != 6 || !ParseNaturalNumber(fields[1], &line) ||1550!ParseNaturalNumber(fields[2], &index) ||1551!ParseNaturalNumber(fields[3], &parent_process_id) ||1552!ParseNaturalNumber(fields[4], &write_handle_as_size_t) ||1553!ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {1554DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +1555GTEST_FLAG_GET(internal_run_death_test));1556}1557write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t,1558event_handle_as_size_t);15591560#elif defined(GTEST_OS_FUCHSIA)15611562if (fields.size() != 3 || !ParseNaturalNumber(fields[1], &line) ||1563!ParseNaturalNumber(fields[2], &index)) {1564DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +1565GTEST_FLAG_GET(internal_run_death_test));1566}15671568#else15691570if (fields.size() != 4 || !ParseNaturalNumber(fields[1], &line) ||1571!ParseNaturalNumber(fields[2], &index) ||1572!ParseNaturalNumber(fields[3], &write_fd)) {1573DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +1574GTEST_FLAG_GET(internal_run_death_test));1575}15761577#endif // GTEST_OS_WINDOWS15781579return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);1580}15811582} // namespace internal15831584#endif // GTEST_HAS_DEATH_TEST15851586} // namespace testing158715881589