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 is to
00072 // prevent a user from accidentally including gtest-internal-inl.h in
00073 // his 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 bool StackGrowsDown() {
00989   int dummy;
00990   bool result;
00991   StackLowerThanAddress(&dummy, &result);
00992   return result;
00993 }
00994 
00995 // Spawns a child process with the same executable as the current process in
00996 // a thread-safe manner and instructs it to run the death test.  The
00997 // implementation uses fork(2) + exec.  On systems where clone(2) is
00998 // available, it is used instead, being slightly more thread-safe.  On QNX,
00999 // fork supports only single-threaded environments, so this function uses
01000 // spawn(2) there instead.  The function dies with an error message if
01001 // anything goes wrong.
01002 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
01003   ExecDeathTestArgs args = { argv, close_fd };
01004   pid_t child_pid = -1;
01005 
01006 #  if GTEST_OS_QNX
01007   // Obtains the current directory and sets it to be closed in the child
01008   // process.
01009   const int cwd_fd = open(".", O_RDONLY);
01010   GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
01011   GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
01012   // We need to execute the test program in the same environment where
01013   // it was originally invoked.  Therefore we change to the original
01014   // working directory first.
01015   const char* const original_dir =
01016       UnitTest::GetInstance()->original_working_dir();
01017   // We can safely call chdir() as it's a direct system call.
01018   if (chdir(original_dir) != 0) {
01019     DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
01020                    GetLastErrnoDescription());
01021     return EXIT_FAILURE;
01022   }
01023 
01024   int fd_flags;
01025   // Set close_fd to be closed after spawn.
01026   GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
01027   GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
01028                                         fd_flags | FD_CLOEXEC));
01029   struct inheritance inherit = {0};
01030   // spawn is a system call.
01031   child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
01032   // Restores the current working directory.
01033   GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
01034   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
01035 
01036 #  else   // GTEST_OS_QNX
01037 #   if GTEST_OS_LINUX
01038   // When a SIGPROF signal is received while fork() or clone() are executing,
01039   // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
01040   // it after the call to fork()/clone() is complete.
01041   struct sigaction saved_sigprof_action;
01042   struct sigaction ignore_sigprof_action;
01043   memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
01044   sigemptyset(&ignore_sigprof_action.sa_mask);
01045   ignore_sigprof_action.sa_handler = SIG_IGN;
01046   GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
01047       SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
01048 #   endif  // GTEST_OS_LINUX
01049 
01050 #   if GTEST_HAS_CLONE
01051   const bool use_fork = GTEST_FLAG(death_test_use_fork);
01052 
01053   if (!use_fork) {
01054     static const bool stack_grows_down = StackGrowsDown();
01055     const size_t stack_size = getpagesize();
01056     // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
01057     void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
01058                              MAP_ANON | MAP_PRIVATE, -1, 0);
01059     GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
01060 
01061     // Maximum stack alignment in bytes:  For a downward-growing stack, this
01062     // amount is subtracted from size of the stack space to get an address
01063     // that is within the stack space and is aligned on all systems we care
01064     // about.  As far as I know there is no ABI with stack alignment greater
01065     // than 64.  We assume stack and stack_size already have alignment of
01066     // kMaxStackAlignment.
01067     const size_t kMaxStackAlignment = 64;
01068     void* const stack_top =
01069         static_cast<char*>(stack) +
01070             (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
01071     GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
01072         reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
01073 
01074     child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
01075 
01076     GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
01077   }
01078 #   else
01079   const bool use_fork = true;
01080 #   endif  // GTEST_HAS_CLONE
01081 
01082   if (use_fork && (child_pid = fork()) == 0) {
01083       ExecDeathTestChildMain(&args);
01084       _exit(0);
01085   }
01086 #  endif  // GTEST_OS_QNX
01087 #  if GTEST_OS_LINUX
01088   GTEST_DEATH_TEST_CHECK_SYSCALL_(
01089       sigaction(SIGPROF, &saved_sigprof_action, NULL));
01090 #  endif  // GTEST_OS_LINUX
01091 
01092   GTEST_DEATH_TEST_CHECK_(child_pid != -1);
01093   return child_pid;
01094 }
01095 
01096 // The AssumeRole process for a fork-and-exec death test.  It re-executes the
01097 // main program from the beginning, setting the --gtest_filter
01098 // and --gtest_internal_run_death_test flags to cause only the current
01099 // death test to be re-run.
01100 DeathTest::TestRole ExecDeathTest::AssumeRole() {
01101   const UnitTestImpl* const impl = GetUnitTestImpl();
01102   const InternalRunDeathTestFlag* const flag =
01103       impl->internal_run_death_test_flag();
01104   const TestInfo* const info = impl->current_test_info();
01105   const int death_test_index = info->result()->death_test_count();
01106 
01107   if (flag != NULL) {
01108     set_write_fd(flag->write_fd());
01109     return EXECUTE_TEST;
01110   }
01111 
01112   int pipe_fd[2];
01113   GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
01114   // Clear the close-on-exec flag on the write end of the pipe, lest
01115   // it be closed when the child process does an exec:
01116   GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
01117 
01118   const std::string filter_flag =
01119       std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
01120       + info->test_case_name() + "." + info->name();
01121   const std::string internal_flag =
01122       std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
01123       + file_ + "|" + StreamableToString(line_) + "|"
01124       + StreamableToString(death_test_index) + "|"
01125       + StreamableToString(pipe_fd[1]);
01126   Arguments args;
01127   args.AddArguments(GetArgvsForDeathTestChildProcess());
01128   args.AddArgument(filter_flag.c_str());
01129   args.AddArgument(internal_flag.c_str());
01130 
01131   DeathTest::set_last_death_test_message("");
01132 
01133   CaptureStderr();
01134   // See the comment in NoExecDeathTest::AssumeRole for why the next line
01135   // is necessary.
01136   FlushInfoLog();
01137 
01138   const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
01139   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
01140   set_child_pid(child_pid);
01141   set_read_fd(pipe_fd[0]);
01142   set_spawned(true);
01143   return OVERSEE_TEST;
01144 }
01145 
01146 # endif  // !GTEST_OS_WINDOWS
01147 
01148 // Creates a concrete DeathTest-derived class that depends on the
01149 // --gtest_death_test_style flag, and sets the pointer pointed to
01150 // by the "test" argument to its address.  If the test should be
01151 // skipped, sets that pointer to NULL.  Returns true, unless the
01152 // flag is set to an invalid value.
01153 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
01154                                      const char* file, int line,
01155                                      DeathTest** test) {
01156   UnitTestImpl* const impl = GetUnitTestImpl();
01157   const InternalRunDeathTestFlag* const flag =
01158       impl->internal_run_death_test_flag();
01159   const int death_test_index = impl->current_test_info()
01160       ->increment_death_test_count();
01161 
01162   if (flag != NULL) {
01163     if (death_test_index > flag->index()) {
01164       DeathTest::set_last_death_test_message(
01165           "Death test count (" + StreamableToString(death_test_index)
01166           + ") somehow exceeded expected maximum ("
01167           + StreamableToString(flag->index()) + ")");
01168       return false;
01169     }
01170 
01171     if (!(flag->file() == file && flag->line() == line &&
01172           flag->index() == death_test_index)) {
01173       *test = NULL;
01174       return true;
01175     }
01176   }
01177 
01178 # if GTEST_OS_WINDOWS
01179 
01180   if (GTEST_FLAG(death_test_style) == "threadsafe" ||
01181       GTEST_FLAG(death_test_style) == "fast") {
01182     *test = new WindowsDeathTest(statement, regex, file, line);
01183   }
01184 
01185 # else
01186 
01187   if (GTEST_FLAG(death_test_style) == "threadsafe") {
01188     *test = new ExecDeathTest(statement, regex, file, line);
01189   } else if (GTEST_FLAG(death_test_style) == "fast") {
01190     *test = new NoExecDeathTest(statement, regex);
01191   }
01192 
01193 # endif  // GTEST_OS_WINDOWS
01194 
01195   else {  // NOLINT - this is more readable than unbalanced brackets inside #if.
01196     DeathTest::set_last_death_test_message(
01197         "Unknown death test style \"" + GTEST_FLAG(death_test_style)
01198         + "\" encountered");
01199     return false;
01200   }
01201 
01202   return true;
01203 }
01204 
01205 // Splits a given string on a given delimiter, populating a given
01206 // vector with the fields.  GTEST_HAS_DEATH_TEST implies that we have
01207 // ::std::string, so we can use it here.
01208 static void SplitString(const ::std::string& str, char delimiter,
01209                         ::std::vector< ::std::string>* dest) {
01210   ::std::vector< ::std::string> parsed;
01211   ::std::string::size_type pos = 0;
01212   while (::testing::internal::AlwaysTrue()) {
01213     const ::std::string::size_type colon = str.find(delimiter, pos);
01214     if (colon == ::std::string::npos) {
01215       parsed.push_back(str.substr(pos));
01216       break;
01217     } else {
01218       parsed.push_back(str.substr(pos, colon - pos));
01219       pos = colon + 1;
01220     }
01221   }
01222   dest->swap(parsed);
01223 }
01224 
01225 # if GTEST_OS_WINDOWS
01226 // Recreates the pipe and event handles from the provided parameters,
01227 // signals the event, and returns a file descriptor wrapped around the pipe
01228 // handle. This function is called in the child process only.
01229 int GetStatusFileDescriptor(unsigned int parent_process_id,
01230                             size_t write_handle_as_size_t,
01231                             size_t event_handle_as_size_t) {
01232   AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
01233                                                    FALSE,  // Non-inheritable.
01234                                                    parent_process_id));
01235   if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
01236     DeathTestAbort("Unable to open parent process " +
01237                    StreamableToString(parent_process_id));
01238   }
01239 
01240   // TODO(vladl@google.com): Replace the following check with a
01241   // compile-time assertion when available.
01242   GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
01243 
01244   const HANDLE write_handle =
01245       reinterpret_cast<HANDLE>(write_handle_as_size_t);
01246   HANDLE dup_write_handle;
01247 
01248   // The newly initialized handle is accessible only in in the parent
01249   // process. To obtain one accessible within the child, we need to use
01250   // DuplicateHandle.
01251   if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
01252                          ::GetCurrentProcess(), &dup_write_handle,
01253                          0x0,    // Requested privileges ignored since
01254                                  // DUPLICATE_SAME_ACCESS is used.
01255                          FALSE,  // Request non-inheritable handler.
01256                          DUPLICATE_SAME_ACCESS)) {
01257     DeathTestAbort("Unable to duplicate the pipe handle " +
01258                    StreamableToString(write_handle_as_size_t) +
01259                    " from the parent process " +
01260                    StreamableToString(parent_process_id));
01261   }
01262 
01263   const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
01264   HANDLE dup_event_handle;
01265 
01266   if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
01267                          ::GetCurrentProcess(), &dup_event_handle,
01268                          0x0,
01269                          FALSE,
01270                          DUPLICATE_SAME_ACCESS)) {
01271     DeathTestAbort("Unable to duplicate the event handle " +
01272                    StreamableToString(event_handle_as_size_t) +
01273                    " from the parent process " +
01274                    StreamableToString(parent_process_id));
01275   }
01276 
01277   const int write_fd =
01278       ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
01279   if (write_fd == -1) {
01280     DeathTestAbort("Unable to convert pipe handle " +
01281                    StreamableToString(write_handle_as_size_t) +
01282                    " to a file descriptor");
01283   }
01284 
01285   // Signals the parent that the write end of the pipe has been acquired
01286   // so the parent can release its own write end.
01287   ::SetEvent(dup_event_handle);
01288 
01289   return write_fd;
01290 }
01291 # endif  // GTEST_OS_WINDOWS
01292 
01293 // Returns a newly created InternalRunDeathTestFlag object with fields
01294 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
01295 // the flag is specified; otherwise returns NULL.
01296 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
01297   if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
01298 
01299   // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
01300   // can use it here.
01301   int line = -1;
01302   int index = -1;
01303   ::std::vector< ::std::string> fields;
01304   SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
01305   int write_fd = -1;
01306 
01307 # if GTEST_OS_WINDOWS
01308 
01309   unsigned int parent_process_id = 0;
01310   size_t write_handle_as_size_t = 0;
01311   size_t event_handle_as_size_t = 0;
01312 
01313   if (fields.size() != 6
01314       || !ParseNaturalNumber(fields[1], &line)
01315       || !ParseNaturalNumber(fields[2], &index)
01316       || !ParseNaturalNumber(fields[3], &parent_process_id)
01317       || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
01318       || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
01319     DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
01320                    GTEST_FLAG(internal_run_death_test));
01321   }
01322   write_fd = GetStatusFileDescriptor(parent_process_id,
01323                                      write_handle_as_size_t,
01324                                      event_handle_as_size_t);
01325 # else
01326 
01327   if (fields.size() != 4
01328       || !ParseNaturalNumber(fields[1], &line)
01329       || !ParseNaturalNumber(fields[2], &index)
01330       || !ParseNaturalNumber(fields[3], &write_fd)) {
01331     DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
01332         + GTEST_FLAG(internal_run_death_test));
01333   }
01334 
01335 # endif  // GTEST_OS_WINDOWS
01336 
01337   return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
01338 }
01339 
01340 }  // namespace internal
01341 
01342 #endif  // GTEST_HAS_DEATH_TEST
01343 
01344 }  // namespace testing


ros_opcua_impl_freeopcua
Author(s): Denis Štogl
autogenerated on Sat Jun 8 2019 18:24:44