gtest-death-test.cc
Go to the documentation of this file.
00001 // Copyright 2005, Google Inc.
00002 // All rights reserved.
00003 //
00004 // Redistribution and use in source and binary forms, with or without
00005 // modification, are permitted provided that the following conditions are
00006 // met:
00007 //
00008 //     * Redistributions of source code must retain the above copyright
00009 // notice, this list of conditions and the following disclaimer.
00010 //     * Redistributions in binary form must reproduce the above
00011 // copyright notice, this list of conditions and the following disclaimer
00012 // in the documentation and/or other materials provided with the
00013 // distribution.
00014 //     * Neither the name of Google Inc. nor the names of its
00015 // contributors may be used to endorse or promote products derived from
00016 // this software without specific prior written permission.
00017 //
00018 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00019 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00020 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00021 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
00022 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
00023 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00024 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
00025 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
00026 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00027 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00028 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00029 //
00030 // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
00031 //
00032 // This file implements death tests.
00033 
00034 #include "gtest/gtest-death-test.h"
00035 #include "gtest/internal/gtest-port.h"
00036 
00037 #if GTEST_HAS_DEATH_TEST
00038 
00039 # if GTEST_OS_MAC
00040 #  include <crt_externs.h>
00041 # endif  // GTEST_OS_MAC
00042 
00043 # include <errno.h>
00044 # include <fcntl.h>
00045 # include <limits.h>
00046 
00047 # if GTEST_OS_LINUX
00048 #  include <signal.h>
00049 # endif  // GTEST_OS_LINUX
00050 
00051 # include <stdarg.h>
00052 
00053 # if GTEST_OS_WINDOWS
00054 #  include <windows.h>
00055 # else
00056 #  include <sys/mman.h>
00057 #  include <sys/wait.h>
00058 # endif  // GTEST_OS_WINDOWS
00059 
00060 # if GTEST_OS_QNX
00061 #  include <spawn.h>
00062 # endif  // GTEST_OS_QNX
00063 
00064 #endif  // GTEST_HAS_DEATH_TEST
00065 
00066 #include "gtest/gtest-message.h"
00067 #include "gtest/internal/gtest-string.h"
00068 
00069 // Indicates that this translation unit is part of Google Test's
00070 // implementation.  It must come before gtest-internal-inl.h is
00071 // included, or there will be a compiler error.  This trick exists to
00072 // prevent the accidental inclusion of gtest-internal-inl.h in the
00073 // user's code.
00074 #define GTEST_IMPLEMENTATION_ 1
00075 #include "src/gtest-internal-inl.h"
00076 #undef GTEST_IMPLEMENTATION_
00077 
00078 namespace testing {
00079 
00080 // Constants.
00081 
00082 // The default death test style.
00083 static const char kDefaultDeathTestStyle[] = "fast";
00084 
00085 GTEST_DEFINE_string_(
00086     death_test_style,
00087     internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
00088     "Indicates how to run a death test in a forked child process: "
00089     "\"threadsafe\" (child process re-executes the test binary "
00090     "from the beginning, running only the specific death test) or "
00091     "\"fast\" (child process runs the death test immediately "
00092     "after forking).");
00093 
00094 GTEST_DEFINE_bool_(
00095     death_test_use_fork,
00096     internal::BoolFromGTestEnv("death_test_use_fork", false),
00097     "Instructs to use fork()/_exit() instead of clone() in death tests. "
00098     "Ignored and always uses fork() on POSIX systems where clone() is not "
00099     "implemented. Useful when running under valgrind or similar tools if "
00100     "those do not support clone(). Valgrind 3.3.1 will just fail if "
00101     "it sees an unsupported combination of clone() flags. "
00102     "It is not recommended to use this flag w/o valgrind though it will "
00103     "work in 99% of the cases. Once valgrind is fixed, this flag will "
00104     "most likely be removed.");
00105 
00106 namespace internal {
00107 GTEST_DEFINE_string_(
00108     internal_run_death_test, "",
00109     "Indicates the file, line number, temporal index of "
00110     "the single death test to run, and a file descriptor to "
00111     "which a success code may be sent, all separated by "
00112     "the '|' characters.  This flag is specified if and only if the current "
00113     "process is a sub-process launched for running a thread-safe "
00114     "death test.  FOR INTERNAL USE ONLY.");
00115 }  // namespace internal
00116 
00117 #if GTEST_HAS_DEATH_TEST
00118 
00119 namespace internal {
00120 
00121 // Valid only for fast death tests. Indicates the code is running in the
00122 // child process of a fast style death test.
00123 static bool g_in_fast_death_test_child = false;
00124 
00125 // Returns a Boolean value indicating whether the caller is currently
00126 // executing in the context of the death test child process.  Tools such as
00127 // Valgrind heap checkers may need this to modify their behavior in death
00128 // tests.  IMPORTANT: This is an internal utility.  Using it may break the
00129 // implementation of death tests.  User code MUST NOT use it.
00130 bool InDeathTestChild() {
00131 # if GTEST_OS_WINDOWS
00132 
00133   // On Windows, death tests are thread-safe regardless of the value of the
00134   // death_test_style flag.
00135   return !GTEST_FLAG(internal_run_death_test).empty();
00136 
00137 # else
00138 
00139   if (GTEST_FLAG(death_test_style) == "threadsafe")
00140     return !GTEST_FLAG(internal_run_death_test).empty();
00141   else
00142     return g_in_fast_death_test_child;
00143 #endif
00144 }
00145 
00146 }  // namespace internal
00147 
00148 // ExitedWithCode constructor.
00149 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
00150 }
00151 
00152 // ExitedWithCode function-call operator.
00153 bool ExitedWithCode::operator()(int exit_status) const {
00154 # if GTEST_OS_WINDOWS
00155 
00156   return exit_status == exit_code_;
00157 
00158 # else
00159 
00160   return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
00161 
00162 # endif  // GTEST_OS_WINDOWS
00163 }
00164 
00165 # if !GTEST_OS_WINDOWS
00166 // KilledBySignal constructor.
00167 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
00168 }
00169 
00170 // KilledBySignal function-call operator.
00171 bool KilledBySignal::operator()(int exit_status) const {
00172   return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
00173 }
00174 # endif  // !GTEST_OS_WINDOWS
00175 
00176 namespace internal {
00177 
00178 // Utilities needed for death tests.
00179 
00180 // Generates a textual description of a given exit code, in the format
00181 // specified by wait(2).
00182 static std::string ExitSummary(int exit_code) {
00183   Message m;
00184 
00185 # if GTEST_OS_WINDOWS
00186 
00187   m << "Exited with exit status " << exit_code;
00188 
00189 # else
00190 
00191   if (WIFEXITED(exit_code)) {
00192     m << "Exited with exit status " << WEXITSTATUS(exit_code);
00193   } else if (WIFSIGNALED(exit_code)) {
00194     m << "Terminated by signal " << WTERMSIG(exit_code);
00195   }
00196 #  ifdef WCOREDUMP
00197   if (WCOREDUMP(exit_code)) {
00198     m << " (core dumped)";
00199   }
00200 #  endif
00201 # endif  // GTEST_OS_WINDOWS
00202 
00203   return m.GetString();
00204 }
00205 
00206 // Returns true if exit_status describes a process that was terminated
00207 // by a signal, or exited normally with a nonzero exit code.
00208 bool ExitedUnsuccessfully(int exit_status) {
00209   return !ExitedWithCode(0)(exit_status);
00210 }
00211 
00212 # if !GTEST_OS_WINDOWS
00213 // Generates a textual failure message when a death test finds more than
00214 // one thread running, or cannot determine the number of threads, prior
00215 // to executing the given statement.  It is the responsibility of the
00216 // caller not to pass a thread_count of 1.
00217 static std::string DeathTestThreadWarning(size_t thread_count) {
00218   Message msg;
00219   msg << "Death tests use fork(), which is unsafe particularly"
00220       << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
00221   if (thread_count == 0)
00222     msg << "couldn't detect the number of threads.";
00223   else
00224     msg << "detected " << thread_count << " threads.";
00225   return msg.GetString();
00226 }
00227 # endif  // !GTEST_OS_WINDOWS
00228 
00229 // Flag characters for reporting a death test that did not die.
00230 static const char kDeathTestLived = 'L';
00231 static const char kDeathTestReturned = 'R';
00232 static const char kDeathTestThrew = 'T';
00233 static const char kDeathTestInternalError = 'I';
00234 
00235 // An enumeration describing all of the possible ways that a death test can
00236 // conclude.  DIED means that the process died while executing the test
00237 // code; LIVED means that process lived beyond the end of the test code;
00238 // RETURNED means that the test statement attempted to execute a return
00239 // statement, which is not allowed; THREW means that the test statement
00240 // returned control by throwing an exception.  IN_PROGRESS means the test
00241 // has not yet concluded.
00242 // TODO(vladl@google.com): Unify names and possibly values for
00243 // AbortReason, DeathTestOutcome, and flag characters above.
00244 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
00245 
00246 // Routine for aborting the program which is safe to call from an
00247 // exec-style death test child process, in which case the error
00248 // message is propagated back to the parent process.  Otherwise, the
00249 // message is simply printed to stderr.  In either case, the program
00250 // then exits with status 1.
00251 void DeathTestAbort(const std::string& message) {
00252   // On a POSIX system, this function may be called from a threadsafe-style
00253   // death test child process, which operates on a very small stack.  Use
00254   // the heap for any additional non-minuscule memory requirements.
00255   const InternalRunDeathTestFlag* const flag =
00256       GetUnitTestImpl()->internal_run_death_test_flag();
00257   if (flag != NULL) {
00258     FILE* parent = posix::FDOpen(flag->write_fd(), "w");
00259     fputc(kDeathTestInternalError, parent);
00260     fprintf(parent, "%s", message.c_str());
00261     fflush(parent);
00262     _exit(1);
00263   } else {
00264     fprintf(stderr, "%s", message.c_str());
00265     fflush(stderr);
00266     posix::Abort();
00267   }
00268 }
00269 
00270 // A replacement for CHECK that calls DeathTestAbort if the assertion
00271 // fails.
00272 # define GTEST_DEATH_TEST_CHECK_(expression) \
00273   do { \
00274     if (!::testing::internal::IsTrue(expression)) { \
00275       DeathTestAbort( \
00276           ::std::string("CHECK failed: File ") + __FILE__ +  ", line " \
00277           + ::testing::internal::StreamableToString(__LINE__) + ": " \
00278           + #expression); \
00279     } \
00280   } while (::testing::internal::AlwaysFalse())
00281 
00282 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
00283 // evaluating any system call that fulfills two conditions: it must return
00284 // -1 on failure, and set errno to EINTR when it is interrupted and
00285 // should be tried again.  The macro expands to a loop that repeatedly
00286 // evaluates the expression as long as it evaluates to -1 and sets
00287 // errno to EINTR.  If the expression evaluates to -1 but errno is
00288 // something other than EINTR, DeathTestAbort is called.
00289 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
00290   do { \
00291     int gtest_retval; \
00292     do { \
00293       gtest_retval = (expression); \
00294     } while (gtest_retval == -1 && errno == EINTR); \
00295     if (gtest_retval == -1) { \
00296       DeathTestAbort( \
00297           ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
00298           + ::testing::internal::StreamableToString(__LINE__) + ": " \
00299           + #expression + " != -1"); \
00300     } \
00301   } while (::testing::internal::AlwaysFalse())
00302 
00303 // Returns the message describing the last system error in errno.
00304 std::string GetLastErrnoDescription() {
00305     return errno == 0 ? "" : posix::StrError(errno);
00306 }
00307 
00308 // This is called from a death test parent process to read a failure
00309 // message from the death test child process and log it with the FATAL
00310 // severity. On Windows, the message is read from a pipe handle. On other
00311 // platforms, it is read from a file descriptor.
00312 static void FailFromInternalError(int fd) {
00313   Message error;
00314   char buffer[256];
00315   int num_read;
00316 
00317   do {
00318     while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
00319       buffer[num_read] = '\0';
00320       error << buffer;
00321     }
00322   } while (num_read == -1 && errno == EINTR);
00323 
00324   if (num_read == 0) {
00325     GTEST_LOG_(FATAL) << error.GetString();
00326   } else {
00327     const int last_error = errno;
00328     GTEST_LOG_(FATAL) << "Error while reading death test internal: "
00329                       << GetLastErrnoDescription() << " [" << last_error << "]";
00330   }
00331 }
00332 
00333 // Death test constructor.  Increments the running death test count
00334 // for the current test.
00335 DeathTest::DeathTest() {
00336   TestInfo* const info = GetUnitTestImpl()->current_test_info();
00337   if (info == NULL) {
00338     DeathTestAbort("Cannot run a death test outside of a TEST or "
00339                    "TEST_F construct");
00340   }
00341 }
00342 
00343 // Creates and returns a death test by dispatching to the current
00344 // death test factory.
00345 bool DeathTest::Create(const char* statement, const RE* regex,
00346                        const char* file, int line, DeathTest** test) {
00347   return GetUnitTestImpl()->death_test_factory()->Create(
00348       statement, regex, file, line, test);
00349 }
00350 
00351 const char* DeathTest::LastMessage() {
00352   return last_death_test_message_.c_str();
00353 }
00354 
00355 void DeathTest::set_last_death_test_message(const std::string& message) {
00356   last_death_test_message_ = message;
00357 }
00358 
00359 std::string DeathTest::last_death_test_message_;
00360 
00361 // Provides cross platform implementation for some death functionality.
00362 class DeathTestImpl : public DeathTest {
00363  protected:
00364   DeathTestImpl(const char* a_statement, const RE* a_regex)
00365       : statement_(a_statement),
00366         regex_(a_regex),
00367         spawned_(false),
00368         status_(-1),
00369         outcome_(IN_PROGRESS),
00370         read_fd_(-1),
00371         write_fd_(-1) {}
00372 
00373   // read_fd_ is expected to be closed and cleared by a derived class.
00374   ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
00375 
00376   void Abort(AbortReason reason);
00377   virtual bool Passed(bool status_ok);
00378 
00379   const char* statement() const { return statement_; }
00380   const RE* regex() const { return regex_; }
00381   bool spawned() const { return spawned_; }
00382   void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
00383   int status() const { return status_; }
00384   void set_status(int a_status) { status_ = a_status; }
00385   DeathTestOutcome outcome() const { return outcome_; }
00386   void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
00387   int read_fd() const { return read_fd_; }
00388   void set_read_fd(int fd) { read_fd_ = fd; }
00389   int write_fd() const { return write_fd_; }
00390   void set_write_fd(int fd) { write_fd_ = fd; }
00391 
00392   // Called in the parent process only. Reads the result code of the death
00393   // test child process via a pipe, interprets it to set the outcome_
00394   // member, and closes read_fd_.  Outputs diagnostics and terminates in
00395   // case of unexpected codes.
00396   void ReadAndInterpretStatusByte();
00397 
00398  private:
00399   // The textual content of the code this object is testing.  This class
00400   // doesn't own this string and should not attempt to delete it.
00401   const char* const statement_;
00402   // The regular expression which test output must match.  DeathTestImpl
00403   // doesn't own this object and should not attempt to delete it.
00404   const RE* const regex_;
00405   // True if the death test child process has been successfully spawned.
00406   bool spawned_;
00407   // The exit status of the child process.
00408   int status_;
00409   // How the death test concluded.
00410   DeathTestOutcome outcome_;
00411   // Descriptor to the read end of the pipe to the child process.  It is
00412   // always -1 in the child process.  The child keeps its write end of the
00413   // pipe in write_fd_.
00414   int read_fd_;
00415   // Descriptor to the child's write end of the pipe to the parent process.
00416   // It is always -1 in the parent process.  The parent keeps its end of the
00417   // pipe in read_fd_.
00418   int write_fd_;
00419 };
00420 
00421 // Called in the parent process only. Reads the result code of the death
00422 // test child process via a pipe, interprets it to set the outcome_
00423 // member, and closes read_fd_.  Outputs diagnostics and terminates in
00424 // case of unexpected codes.
00425 void DeathTestImpl::ReadAndInterpretStatusByte() {
00426   char flag;
00427   int bytes_read;
00428 
00429   // The read() here blocks until data is available (signifying the
00430   // failure of the death test) or until the pipe is closed (signifying
00431   // its success), so it's okay to call this in the parent before
00432   // the child process has exited.
00433   do {
00434     bytes_read = posix::Read(read_fd(), &flag, 1);
00435   } while (bytes_read == -1 && errno == EINTR);
00436 
00437   if (bytes_read == 0) {
00438     set_outcome(DIED);
00439   } else if (bytes_read == 1) {
00440     switch (flag) {
00441       case kDeathTestReturned:
00442         set_outcome(RETURNED);
00443         break;
00444       case kDeathTestThrew:
00445         set_outcome(THREW);
00446         break;
00447       case kDeathTestLived:
00448         set_outcome(LIVED);
00449         break;
00450       case kDeathTestInternalError:
00451         FailFromInternalError(read_fd());  // Does not return.
00452         break;
00453       default:
00454         GTEST_LOG_(FATAL) << "Death test child process reported "
00455                           << "unexpected status byte ("
00456                           << static_cast<unsigned int>(flag) << ")";
00457     }
00458   } else {
00459     GTEST_LOG_(FATAL) << "Read from death test child process failed: "
00460                       << GetLastErrnoDescription();
00461   }
00462   GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
00463   set_read_fd(-1);
00464 }
00465 
00466 // Signals that the death test code which should have exited, didn't.
00467 // Should be called only in a death test child process.
00468 // Writes a status byte to the child's status file descriptor, then
00469 // calls _exit(1).
00470 void DeathTestImpl::Abort(AbortReason reason) {
00471   // The parent process considers the death test to be a failure if
00472   // it finds any data in our pipe.  So, here we write a single flag byte
00473   // to the pipe, then exit.
00474   const char status_ch =
00475       reason == TEST_DID_NOT_DIE ? kDeathTestLived :
00476       reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
00477 
00478   GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
00479   // We are leaking the descriptor here because on some platforms (i.e.,
00480   // when built as Windows DLL), destructors of global objects will still
00481   // run after calling _exit(). On such systems, write_fd_ will be
00482   // indirectly closed from the destructor of UnitTestImpl, causing double
00483   // close if it is also closed here. On debug configurations, double close
00484   // may assert. As there are no in-process buffers to flush here, we are
00485   // relying on the OS to close the descriptor after the process terminates
00486   // when the destructors are not run.
00487   _exit(1);  // Exits w/o any normal exit hooks (we were supposed to crash)
00488 }
00489 
00490 // Returns an indented copy of stderr output for a death test.
00491 // This makes distinguishing death test output lines from regular log lines
00492 // much easier.
00493 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
00494   ::std::string ret;
00495   for (size_t at = 0; ; ) {
00496     const size_t line_end = output.find('\n', at);
00497     ret += "[  DEATH   ] ";
00498     if (line_end == ::std::string::npos) {
00499       ret += output.substr(at);
00500       break;
00501     }
00502     ret += output.substr(at, line_end + 1 - at);
00503     at = line_end + 1;
00504   }
00505   return ret;
00506 }
00507 
00508 // Assesses the success or failure of a death test, using both private
00509 // members which have previously been set, and one argument:
00510 //
00511 // Private data members:
00512 //   outcome:  An enumeration describing how the death test
00513 //             concluded: DIED, LIVED, THREW, or RETURNED.  The death test
00514 //             fails in the latter three cases.
00515 //   status:   The exit status of the child process. On *nix, it is in the
00516 //             in the format specified by wait(2). On Windows, this is the
00517 //             value supplied to the ExitProcess() API or a numeric code
00518 //             of the exception that terminated the program.
00519 //   regex:    A regular expression object to be applied to
00520 //             the test's captured standard error output; the death test
00521 //             fails if it does not match.
00522 //
00523 // Argument:
00524 //   status_ok: true if exit_status is acceptable in the context of
00525 //              this particular death test, which fails if it is false
00526 //
00527 // Returns true iff all of the above conditions are met.  Otherwise, the
00528 // first failing condition, in the order given above, is the one that is
00529 // reported. Also sets the last death test message string.
00530 bool DeathTestImpl::Passed(bool status_ok) {
00531   if (!spawned())
00532     return false;
00533 
00534   const std::string error_message = GetCapturedStderr();
00535 
00536   bool success = false;
00537   Message buffer;
00538 
00539   buffer << "Death test: " << statement() << "\n";
00540   switch (outcome()) {
00541     case LIVED:
00542       buffer << "    Result: failed to die.\n"
00543              << " Error msg:\n" << FormatDeathTestOutput(error_message);
00544       break;
00545     case THREW:
00546       buffer << "    Result: threw an exception.\n"
00547              << " Error msg:\n" << FormatDeathTestOutput(error_message);
00548       break;
00549     case RETURNED:
00550       buffer << "    Result: illegal return in test statement.\n"
00551              << " Error msg:\n" << FormatDeathTestOutput(error_message);
00552       break;
00553     case DIED:
00554       if (status_ok) {
00555         const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
00556         if (matched) {
00557           success = true;
00558         } else {
00559           buffer << "    Result: died but not with expected error.\n"
00560                  << "  Expected: " << regex()->pattern() << "\n"
00561                  << "Actual msg:\n" << FormatDeathTestOutput(error_message);
00562         }
00563       } else {
00564         buffer << "    Result: died but not with expected exit code:\n"
00565                << "            " << ExitSummary(status()) << "\n"
00566                << "Actual msg:\n" << FormatDeathTestOutput(error_message);
00567       }
00568       break;
00569     case IN_PROGRESS:
00570     default:
00571       GTEST_LOG_(FATAL)
00572           << "DeathTest::Passed somehow called before conclusion of test";
00573   }
00574 
00575   DeathTest::set_last_death_test_message(buffer.GetString());
00576   return success;
00577 }
00578 
00579 # if GTEST_OS_WINDOWS
00580 // WindowsDeathTest implements death tests on Windows. Due to the
00581 // specifics of starting new processes on Windows, death tests there are
00582 // always threadsafe, and Google Test considers the
00583 // --gtest_death_test_style=fast setting to be equivalent to
00584 // --gtest_death_test_style=threadsafe there.
00585 //
00586 // A few implementation notes:  Like the Linux version, the Windows
00587 // implementation uses pipes for child-to-parent communication. But due to
00588 // the specifics of pipes on Windows, some extra steps are required:
00589 //
00590 // 1. The parent creates a communication pipe and stores handles to both
00591 //    ends of it.
00592 // 2. The parent starts the child and provides it with the information
00593 //    necessary to acquire the handle to the write end of the pipe.
00594 // 3. The child acquires the write end of the pipe and signals the parent
00595 //    using a Windows event.
00596 // 4. Now the parent can release the write end of the pipe on its side. If
00597 //    this is done before step 3, the object's reference count goes down to
00598 //    0 and it is destroyed, preventing the child from acquiring it. The
00599 //    parent now has to release it, or read operations on the read end of
00600 //    the pipe will not return when the child terminates.
00601 // 5. The parent reads child's output through the pipe (outcome code and
00602 //    any possible error messages) from the pipe, and its stderr and then
00603 //    determines whether to fail the test.
00604 //
00605 // Note: to distinguish Win32 API calls from the local method and function
00606 // calls, the former are explicitly resolved in the global namespace.
00607 //
00608 class WindowsDeathTest : public DeathTestImpl {
00609  public:
00610   WindowsDeathTest(const char* a_statement,
00611                    const RE* a_regex,
00612                    const char* file,
00613                    int line)
00614       : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
00615 
00616   // All of these virtual functions are inherited from DeathTest.
00617   virtual int Wait();
00618   virtual TestRole AssumeRole();
00619 
00620  private:
00621   // The name of the file in which the death test is located.
00622   const char* const file_;
00623   // The line number on which the death test is located.
00624   const int line_;
00625   // Handle to the write end of the pipe to the child process.
00626   AutoHandle write_handle_;
00627   // Child process handle.
00628   AutoHandle child_handle_;
00629   // Event the child process uses to signal the parent that it has
00630   // acquired the handle to the write end of the pipe. After seeing this
00631   // event the parent can release its own handles to make sure its
00632   // ReadFile() calls return when the child terminates.
00633   AutoHandle event_handle_;
00634 };
00635 
00636 // Waits for the child in a death test to exit, returning its exit
00637 // status, or 0 if no child process exists.  As a side effect, sets the
00638 // outcome data member.
00639 int WindowsDeathTest::Wait() {
00640   if (!spawned())
00641     return 0;
00642 
00643   // Wait until the child either signals that it has acquired the write end
00644   // of the pipe or it dies.
00645   const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
00646   switch (::WaitForMultipleObjects(2,
00647                                    wait_handles,
00648                                    FALSE,  // Waits for any of the handles.
00649                                    INFINITE)) {
00650     case WAIT_OBJECT_0:
00651     case WAIT_OBJECT_0 + 1:
00652       break;
00653     default:
00654       GTEST_DEATH_TEST_CHECK_(false);  // Should not get here.
00655   }
00656 
00657   // The child has acquired the write end of the pipe or exited.
00658   // We release the handle on our side and continue.
00659   write_handle_.Reset();
00660   event_handle_.Reset();
00661 
00662   ReadAndInterpretStatusByte();
00663 
00664   // Waits for the child process to exit if it haven't already. This
00665   // returns immediately if the child has already exited, regardless of
00666   // whether previous calls to WaitForMultipleObjects synchronized on this
00667   // handle or not.
00668   GTEST_DEATH_TEST_CHECK_(
00669       WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
00670                                              INFINITE));
00671   DWORD status_code;
00672   GTEST_DEATH_TEST_CHECK_(
00673       ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
00674   child_handle_.Reset();
00675   set_status(static_cast<int>(status_code));
00676   return status();
00677 }
00678 
00679 // The AssumeRole process for a Windows death test.  It creates a child
00680 // process with the same executable as the current process to run the
00681 // death test.  The child process is given the --gtest_filter and
00682 // --gtest_internal_run_death_test flags such that it knows to run the
00683 // current death test only.
00684 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
00685   const UnitTestImpl* const impl = GetUnitTestImpl();
00686   const InternalRunDeathTestFlag* const flag =
00687       impl->internal_run_death_test_flag();
00688   const TestInfo* const info = impl->current_test_info();
00689   const int death_test_index = info->result()->death_test_count();
00690 
00691   if (flag != NULL) {
00692     // ParseInternalRunDeathTestFlag() has performed all the necessary
00693     // processing.
00694     set_write_fd(flag->write_fd());
00695     return EXECUTE_TEST;
00696   }
00697 
00698   // WindowsDeathTest uses an anonymous pipe to communicate results of
00699   // a death test.
00700   SECURITY_ATTRIBUTES handles_are_inheritable = {
00701     sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
00702   HANDLE read_handle, write_handle;
00703   GTEST_DEATH_TEST_CHECK_(
00704       ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
00705                    0)  // Default buffer size.
00706       != FALSE);
00707   set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
00708                                 O_RDONLY));
00709   write_handle_.Reset(write_handle);
00710   event_handle_.Reset(::CreateEvent(
00711       &handles_are_inheritable,
00712       TRUE,    // The event will automatically reset to non-signaled state.
00713       FALSE,   // The initial state is non-signalled.
00714       NULL));  // The even is unnamed.
00715   GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
00716   const std::string filter_flag =
00717       std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
00718       info->test_case_name() + "." + info->name();
00719   const std::string internal_flag =
00720       std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
00721       "=" + file_ + "|" + StreamableToString(line_) + "|" +
00722       StreamableToString(death_test_index) + "|" +
00723       StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
00724       // size_t has the same width as pointers on both 32-bit and 64-bit
00725       // Windows platforms.
00726       // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
00727       "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
00728       "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
00729 
00730   char executable_path[_MAX_PATH + 1];  // NOLINT
00731   GTEST_DEATH_TEST_CHECK_(
00732       _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
00733                                             executable_path,
00734                                             _MAX_PATH));
00735 
00736   std::string command_line =
00737       std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
00738       internal_flag + "\"";
00739 
00740   DeathTest::set_last_death_test_message("");
00741 
00742   CaptureStderr();
00743   // Flush the log buffers since the log streams are shared with the child.
00744   FlushInfoLog();
00745 
00746   // The child process will share the standard handles with the parent.
00747   STARTUPINFOA startup_info;
00748   memset(&startup_info, 0, sizeof(STARTUPINFO));
00749   startup_info.dwFlags = STARTF_USESTDHANDLES;
00750   startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
00751   startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
00752   startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
00753 
00754   PROCESS_INFORMATION process_info;
00755   GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
00756       executable_path,
00757       const_cast<char*>(command_line.c_str()),
00758       NULL,   // Retuned process handle is not inheritable.
00759       NULL,   // Retuned thread handle is not inheritable.
00760       TRUE,   // Child inherits all inheritable handles (for write_handle_).
00761       0x0,    // Default creation flags.
00762       NULL,   // Inherit the parent's environment.
00763       UnitTest::GetInstance()->original_working_dir(),
00764       &startup_info,
00765       &process_info) != FALSE);
00766   child_handle_.Reset(process_info.hProcess);
00767   ::CloseHandle(process_info.hThread);
00768   set_spawned(true);
00769   return OVERSEE_TEST;
00770 }
00771 # else  // We are not on Windows.
00772 
00773 // ForkingDeathTest provides implementations for most of the abstract
00774 // methods of the DeathTest interface.  Only the AssumeRole method is
00775 // left undefined.
00776 class ForkingDeathTest : public DeathTestImpl {
00777  public:
00778   ForkingDeathTest(const char* statement, const RE* regex);
00779 
00780   // All of these virtual functions are inherited from DeathTest.
00781   virtual int Wait();
00782 
00783  protected:
00784   void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
00785 
00786  private:
00787   // PID of child process during death test; 0 in the child process itself.
00788   pid_t child_pid_;
00789 };
00790 
00791 // Constructs a ForkingDeathTest.
00792 ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
00793     : DeathTestImpl(a_statement, a_regex),
00794       child_pid_(-1) {}
00795 
00796 // Waits for the child in a death test to exit, returning its exit
00797 // status, or 0 if no child process exists.  As a side effect, sets the
00798 // outcome data member.
00799 int ForkingDeathTest::Wait() {
00800   if (!spawned())
00801     return 0;
00802 
00803   ReadAndInterpretStatusByte();
00804 
00805   int status_value;
00806   GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
00807   set_status(status_value);
00808   return status_value;
00809 }
00810 
00811 // A concrete death test class that forks, then immediately runs the test
00812 // in the child process.
00813 class NoExecDeathTest : public ForkingDeathTest {
00814  public:
00815   NoExecDeathTest(const char* a_statement, const RE* a_regex) :
00816       ForkingDeathTest(a_statement, a_regex) { }
00817   virtual TestRole AssumeRole();
00818 };
00819 
00820 // The AssumeRole process for a fork-and-run death test.  It implements a
00821 // straightforward fork, with a simple pipe to transmit the status byte.
00822 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
00823   const size_t thread_count = GetThreadCount();
00824   if (thread_count != 1) {
00825     GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
00826   }
00827 
00828   int pipe_fd[2];
00829   GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
00830 
00831   DeathTest::set_last_death_test_message("");
00832   CaptureStderr();
00833   // When we fork the process below, the log file buffers are copied, but the
00834   // file descriptors are shared.  We flush all log files here so that closing
00835   // the file descriptors in the child process doesn't throw off the
00836   // synchronization between descriptors and buffers in the parent process.
00837   // This is as close to the fork as possible to avoid a race condition in case
00838   // there are multiple threads running before the death test, and another
00839   // thread writes to the log file.
00840   FlushInfoLog();
00841 
00842   const pid_t child_pid = fork();
00843   GTEST_DEATH_TEST_CHECK_(child_pid != -1);
00844   set_child_pid(child_pid);
00845   if (child_pid == 0) {
00846     GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
00847     set_write_fd(pipe_fd[1]);
00848     // Redirects all logging to stderr in the child process to prevent
00849     // concurrent writes to the log files.  We capture stderr in the parent
00850     // process and append the child process' output to a log.
00851     LogToStderr();
00852     // Event forwarding to the listeners of event listener API mush be shut
00853     // down in death test subprocesses.
00854     GetUnitTestImpl()->listeners()->SuppressEventForwarding();
00855     g_in_fast_death_test_child = true;
00856     return EXECUTE_TEST;
00857   } else {
00858     GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
00859     set_read_fd(pipe_fd[0]);
00860     set_spawned(true);
00861     return OVERSEE_TEST;
00862   }
00863 }
00864 
00865 // A concrete death test class that forks and re-executes the main
00866 // program from the beginning, with command-line flags set that cause
00867 // only this specific death test to be run.
00868 class ExecDeathTest : public ForkingDeathTest {
00869  public:
00870   ExecDeathTest(const char* a_statement, const RE* a_regex,
00871                 const char* file, int line) :
00872       ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
00873   virtual TestRole AssumeRole();
00874  private:
00875   static ::std::vector<testing::internal::string>
00876   GetArgvsForDeathTestChildProcess() {
00877     ::std::vector<testing::internal::string> args = GetInjectableArgvs();
00878     return args;
00879   }
00880   // The name of the file in which the death test is located.
00881   const char* const file_;
00882   // The line number on which the death test is located.
00883   const int line_;
00884 };
00885 
00886 // Utility class for accumulating command-line arguments.
00887 class Arguments {
00888  public:
00889   Arguments() {
00890     args_.push_back(NULL);
00891   }
00892 
00893   ~Arguments() {
00894     for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
00895          ++i) {
00896       free(*i);
00897     }
00898   }
00899   void AddArgument(const char* argument) {
00900     args_.insert(args_.end() - 1, posix::StrDup(argument));
00901   }
00902 
00903   template <typename Str>
00904   void AddArguments(const ::std::vector<Str>& arguments) {
00905     for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
00906          i != arguments.end();
00907          ++i) {
00908       args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
00909     }
00910   }
00911   char* const* Argv() {
00912     return &args_[0];
00913   }
00914 
00915  private:
00916   std::vector<char*> args_;
00917 };
00918 
00919 // A struct that encompasses the arguments to the child process of a
00920 // threadsafe-style death test process.
00921 struct ExecDeathTestArgs {
00922   char* const* argv;  // Command-line arguments for the child's call to exec
00923   int close_fd;       // File descriptor to close; the read end of a pipe
00924 };
00925 
00926 #  if GTEST_OS_MAC
00927 inline char** GetEnviron() {
00928   // When Google Test is built as a framework on MacOS X, the environ variable
00929   // is unavailable. Apple's documentation (man environ) recommends using
00930   // _NSGetEnviron() instead.
00931   return *_NSGetEnviron();
00932 }
00933 #  else
00934 // Some POSIX platforms expect you to declare environ. extern "C" makes
00935 // it reside in the global namespace.
00936 extern "C" char** environ;
00937 inline char** GetEnviron() { return environ; }
00938 #  endif  // GTEST_OS_MAC
00939 
00940 #  if !GTEST_OS_QNX
00941 // The main function for a threadsafe-style death test child process.
00942 // This function is called in a clone()-ed process and thus must avoid
00943 // any potentially unsafe operations like malloc or libc functions.
00944 static int ExecDeathTestChildMain(void* child_arg) {
00945   ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
00946   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
00947 
00948   // We need to execute the test program in the same environment where
00949   // it was originally invoked.  Therefore we change to the original
00950   // working directory first.
00951   const char* const original_dir =
00952       UnitTest::GetInstance()->original_working_dir();
00953   // We can safely call chdir() as it's a direct system call.
00954   if (chdir(original_dir) != 0) {
00955     DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
00956                    GetLastErrnoDescription());
00957     return EXIT_FAILURE;
00958   }
00959 
00960   // We can safely call execve() as it's a direct system call.  We
00961   // cannot use execvp() as it's a libc function and thus potentially
00962   // unsafe.  Since execve() doesn't search the PATH, the user must
00963   // invoke the test program via a valid path that contains at least
00964   // one path separator.
00965   execve(args->argv[0], args->argv, GetEnviron());
00966   DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
00967                  original_dir + " failed: " +
00968                  GetLastErrnoDescription());
00969   return EXIT_FAILURE;
00970 }
00971 #  endif  // !GTEST_OS_QNX
00972 
00973 // Two utility routines that together determine the direction the stack
00974 // grows.
00975 // This could be accomplished more elegantly by a single recursive
00976 // function, but we want to guard against the unlikely possibility of
00977 // a smart compiler optimizing the recursion away.
00978 //
00979 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
00980 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
00981 // correct answer.
00982 void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;
00983 void StackLowerThanAddress(const void* ptr, bool* result) {
00984   int dummy;
00985   *result = (&dummy < ptr);
00986 }
00987 
00988 // Make sure AddressSanitizer does not tamper with the stack here.
00989 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
00990 bool StackGrowsDown() {
00991   int dummy;
00992   bool result;
00993   StackLowerThanAddress(&dummy, &result);
00994   return result;
00995 }
00996 
00997 // Spawns a child process with the same executable as the current process in
00998 // a thread-safe manner and instructs it to run the death test.  The
00999 // implementation uses fork(2) + exec.  On systems where clone(2) is
01000 // available, it is used instead, being slightly more thread-safe.  On QNX,
01001 // fork supports only single-threaded environments, so this function uses
01002 // spawn(2) there instead.  The function dies with an error message if
01003 // anything goes wrong.
01004 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
01005   ExecDeathTestArgs args = { argv, close_fd };
01006   pid_t child_pid = -1;
01007 
01008 #  if GTEST_OS_QNX
01009   // Obtains the current directory and sets it to be closed in the child
01010   // process.
01011   const int cwd_fd = open(".", O_RDONLY);
01012   GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
01013   GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
01014   // We need to execute the test program in the same environment where
01015   // it was originally invoked.  Therefore we change to the original
01016   // working directory first.
01017   const char* const original_dir =
01018       UnitTest::GetInstance()->original_working_dir();
01019   // We can safely call chdir() as it's a direct system call.
01020   if (chdir(original_dir) != 0) {
01021     DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
01022                    GetLastErrnoDescription());
01023     return EXIT_FAILURE;
01024   }
01025 
01026   int fd_flags;
01027   // Set close_fd to be closed after spawn.
01028   GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
01029   GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
01030                                         fd_flags | FD_CLOEXEC));
01031   struct inheritance inherit = {0};
01032   // spawn is a system call.
01033   child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
01034   // Restores the current working directory.
01035   GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
01036   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
01037 
01038 #  else   // GTEST_OS_QNX
01039 #   if GTEST_OS_LINUX
01040   // When a SIGPROF signal is received while fork() or clone() are executing,
01041   // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
01042   // it after the call to fork()/clone() is complete.
01043   struct sigaction saved_sigprof_action;
01044   struct sigaction ignore_sigprof_action;
01045   memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
01046   sigemptyset(&ignore_sigprof_action.sa_mask);
01047   ignore_sigprof_action.sa_handler = SIG_IGN;
01048   GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
01049       SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
01050 #   endif  // GTEST_OS_LINUX
01051 
01052 #   if GTEST_HAS_CLONE
01053   const bool use_fork = GTEST_FLAG(death_test_use_fork);
01054 
01055   if (!use_fork) {
01056     static const bool stack_grows_down = StackGrowsDown();
01057     const size_t stack_size = getpagesize();
01058     // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
01059     void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
01060                              MAP_ANON | MAP_PRIVATE, -1, 0);
01061     GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
01062 
01063     // Maximum stack alignment in bytes:  For a downward-growing stack, this
01064     // amount is subtracted from size of the stack space to get an address
01065     // that is within the stack space and is aligned on all systems we care
01066     // about.  As far as I know there is no ABI with stack alignment greater
01067     // than 64.  We assume stack and stack_size already have alignment of
01068     // kMaxStackAlignment.
01069     const size_t kMaxStackAlignment = 64;
01070     void* const stack_top =
01071         static_cast<char*>(stack) +
01072             (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
01073     GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
01074         reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
01075 
01076     child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
01077 
01078     GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
01079   }
01080 #   else
01081   const bool use_fork = true;
01082 #   endif  // GTEST_HAS_CLONE
01083 
01084   if (use_fork && (child_pid = fork()) == 0) {
01085       ExecDeathTestChildMain(&args);
01086       _exit(0);
01087   }
01088 #  endif  // GTEST_OS_QNX
01089 #  if GTEST_OS_LINUX
01090   GTEST_DEATH_TEST_CHECK_SYSCALL_(
01091       sigaction(SIGPROF, &saved_sigprof_action, NULL));
01092 #  endif  // GTEST_OS_LINUX
01093 
01094   GTEST_DEATH_TEST_CHECK_(child_pid != -1);
01095   return child_pid;
01096 }
01097 
01098 // The AssumeRole process for a fork-and-exec death test.  It re-executes the
01099 // main program from the beginning, setting the --gtest_filter
01100 // and --gtest_internal_run_death_test flags to cause only the current
01101 // death test to be re-run.
01102 DeathTest::TestRole ExecDeathTest::AssumeRole() {
01103   const UnitTestImpl* const impl = GetUnitTestImpl();
01104   const InternalRunDeathTestFlag* const flag =
01105       impl->internal_run_death_test_flag();
01106   const TestInfo* const info = impl->current_test_info();
01107   const int death_test_index = info->result()->death_test_count();
01108 
01109   if (flag != NULL) {
01110     set_write_fd(flag->write_fd());
01111     return EXECUTE_TEST;
01112   }
01113 
01114   int pipe_fd[2];
01115   GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
01116   // Clear the close-on-exec flag on the write end of the pipe, lest
01117   // it be closed when the child process does an exec:
01118   GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
01119 
01120   const std::string filter_flag =
01121       std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
01122       + info->test_case_name() + "." + info->name();
01123   const std::string internal_flag =
01124       std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
01125       + file_ + "|" + StreamableToString(line_) + "|"
01126       + StreamableToString(death_test_index) + "|"
01127       + StreamableToString(pipe_fd[1]);
01128   Arguments args;
01129   args.AddArguments(GetArgvsForDeathTestChildProcess());
01130   args.AddArgument(filter_flag.c_str());
01131   args.AddArgument(internal_flag.c_str());
01132 
01133   DeathTest::set_last_death_test_message("");
01134 
01135   CaptureStderr();
01136   // See the comment in NoExecDeathTest::AssumeRole for why the next line
01137   // is necessary.
01138   FlushInfoLog();
01139 
01140   const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
01141   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
01142   set_child_pid(child_pid);
01143   set_read_fd(pipe_fd[0]);
01144   set_spawned(true);
01145   return OVERSEE_TEST;
01146 }
01147 
01148 # endif  // !GTEST_OS_WINDOWS
01149 
01150 // Creates a concrete DeathTest-derived class that depends on the
01151 // --gtest_death_test_style flag, and sets the pointer pointed to
01152 // by the "test" argument to its address.  If the test should be
01153 // skipped, sets that pointer to NULL.  Returns true, unless the
01154 // flag is set to an invalid value.
01155 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
01156                                      const char* file, int line,
01157                                      DeathTest** test) {
01158   UnitTestImpl* const impl = GetUnitTestImpl();
01159   const InternalRunDeathTestFlag* const flag =
01160       impl->internal_run_death_test_flag();
01161   const int death_test_index = impl->current_test_info()
01162       ->increment_death_test_count();
01163 
01164   if (flag != NULL) {
01165     if (death_test_index > flag->index()) {
01166       DeathTest::set_last_death_test_message(
01167           "Death test count (" + StreamableToString(death_test_index)
01168           + ") somehow exceeded expected maximum ("
01169           + StreamableToString(flag->index()) + ")");
01170       return false;
01171     }
01172 
01173     if (!(flag->file() == file && flag->line() == line &&
01174           flag->index() == death_test_index)) {
01175       *test = NULL;
01176       return true;
01177     }
01178   }
01179 
01180 # if GTEST_OS_WINDOWS
01181 
01182   if (GTEST_FLAG(death_test_style) == "threadsafe" ||
01183       GTEST_FLAG(death_test_style) == "fast") {
01184     *test = new WindowsDeathTest(statement, regex, file, line);
01185   }
01186 
01187 # else
01188 
01189   if (GTEST_FLAG(death_test_style) == "threadsafe") {
01190     *test = new ExecDeathTest(statement, regex, file, line);
01191   } else if (GTEST_FLAG(death_test_style) == "fast") {
01192     *test = new NoExecDeathTest(statement, regex);
01193   }
01194 
01195 # endif  // GTEST_OS_WINDOWS
01196 
01197   else {  // NOLINT - this is more readable than unbalanced brackets inside #if.
01198     DeathTest::set_last_death_test_message(
01199         "Unknown death test style \"" + GTEST_FLAG(death_test_style)
01200         + "\" encountered");
01201     return false;
01202   }
01203 
01204   return true;
01205 }
01206 
01207 // Splits a given string on a given delimiter, populating a given
01208 // vector with the fields.  GTEST_HAS_DEATH_TEST implies that we have
01209 // ::std::string, so we can use it here.
01210 static void SplitString(const ::std::string& str, char delimiter,
01211                         ::std::vector< ::std::string>* dest) {
01212   ::std::vector< ::std::string> parsed;
01213   ::std::string::size_type pos = 0;
01214   while (::testing::internal::AlwaysTrue()) {
01215     const ::std::string::size_type colon = str.find(delimiter, pos);
01216     if (colon == ::std::string::npos) {
01217       parsed.push_back(str.substr(pos));
01218       break;
01219     } else {
01220       parsed.push_back(str.substr(pos, colon - pos));
01221       pos = colon + 1;
01222     }
01223   }
01224   dest->swap(parsed);
01225 }
01226 
01227 # if GTEST_OS_WINDOWS
01228 // Recreates the pipe and event handles from the provided parameters,
01229 // signals the event, and returns a file descriptor wrapped around the pipe
01230 // handle. This function is called in the child process only.
01231 int GetStatusFileDescriptor(unsigned int parent_process_id,
01232                             size_t write_handle_as_size_t,
01233                             size_t event_handle_as_size_t) {
01234   AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
01235                                                    FALSE,  // Non-inheritable.
01236                                                    parent_process_id));
01237   if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
01238     DeathTestAbort("Unable to open parent process " +
01239                    StreamableToString(parent_process_id));
01240   }
01241 
01242   // TODO(vladl@google.com): Replace the following check with a
01243   // compile-time assertion when available.
01244   GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
01245 
01246   const HANDLE write_handle =
01247       reinterpret_cast<HANDLE>(write_handle_as_size_t);
01248   HANDLE dup_write_handle;
01249 
01250   // The newly initialized handle is accessible only in in the parent
01251   // process. To obtain one accessible within the child, we need to use
01252   // DuplicateHandle.
01253   if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
01254                          ::GetCurrentProcess(), &dup_write_handle,
01255                          0x0,    // Requested privileges ignored since
01256                                  // DUPLICATE_SAME_ACCESS is used.
01257                          FALSE,  // Request non-inheritable handler.
01258                          DUPLICATE_SAME_ACCESS)) {
01259     DeathTestAbort("Unable to duplicate the pipe handle " +
01260                    StreamableToString(write_handle_as_size_t) +
01261                    " from the parent process " +
01262                    StreamableToString(parent_process_id));
01263   }
01264 
01265   const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
01266   HANDLE dup_event_handle;
01267 
01268   if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
01269                          ::GetCurrentProcess(), &dup_event_handle,
01270                          0x0,
01271                          FALSE,
01272                          DUPLICATE_SAME_ACCESS)) {
01273     DeathTestAbort("Unable to duplicate the event handle " +
01274                    StreamableToString(event_handle_as_size_t) +
01275                    " from the parent process " +
01276                    StreamableToString(parent_process_id));
01277   }
01278 
01279   const int write_fd =
01280       ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
01281   if (write_fd == -1) {
01282     DeathTestAbort("Unable to convert pipe handle " +
01283                    StreamableToString(write_handle_as_size_t) +
01284                    " to a file descriptor");
01285   }
01286 
01287   // Signals the parent that the write end of the pipe has been acquired
01288   // so the parent can release its own write end.
01289   ::SetEvent(dup_event_handle);
01290 
01291   return write_fd;
01292 }
01293 # endif  // GTEST_OS_WINDOWS
01294 
01295 // Returns a newly created InternalRunDeathTestFlag object with fields
01296 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
01297 // the flag is specified; otherwise returns NULL.
01298 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
01299   if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
01300 
01301   // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
01302   // can use it here.
01303   int line = -1;
01304   int index = -1;
01305   ::std::vector< ::std::string> fields;
01306   SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
01307   int write_fd = -1;
01308 
01309 # if GTEST_OS_WINDOWS
01310 
01311   unsigned int parent_process_id = 0;
01312   size_t write_handle_as_size_t = 0;
01313   size_t event_handle_as_size_t = 0;
01314 
01315   if (fields.size() != 6
01316       || !ParseNaturalNumber(fields[1], &line)
01317       || !ParseNaturalNumber(fields[2], &index)
01318       || !ParseNaturalNumber(fields[3], &parent_process_id)
01319       || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
01320       || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
01321     DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
01322                    GTEST_FLAG(internal_run_death_test));
01323   }
01324   write_fd = GetStatusFileDescriptor(parent_process_id,
01325                                      write_handle_as_size_t,
01326                                      event_handle_as_size_t);
01327 # else
01328 
01329   if (fields.size() != 4
01330       || !ParseNaturalNumber(fields[1], &line)
01331       || !ParseNaturalNumber(fields[2], &index)
01332       || !ParseNaturalNumber(fields[3], &write_fd)) {
01333     DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
01334         + GTEST_FLAG(internal_run_death_test));
01335   }
01336 
01337 # endif  // GTEST_OS_WINDOWS
01338 
01339   return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
01340 }
01341 
01342 }  // namespace internal
01343 
01344 #endif  // GTEST_HAS_DEATH_TEST
01345 
01346 }  // namespace testing


rc_visard_driver
Author(s): Heiko Hirschmueller , Christian Emmerich , Felix Ruess
autogenerated on Thu Jun 6 2019 20:43:03