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


pcl
Author(s): Open Perception
autogenerated on Wed Aug 26 2015 15:24:39