1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
31//
32// This file implements death tests.
33
34#include "gtest/gtest-death-test.h"
35#include "gtest/internal/gtest-port.h"
36
37#if GTEST_HAS_DEATH_TEST
38
39# if GTEST_OS_MAC
40#  include <crt_externs.h>
41# endif  // GTEST_OS_MAC
42
43# include <errno.h>
44# include <fcntl.h>
45# include <limits.h>
46
47# if GTEST_OS_LINUX
48#  include <signal.h>
49# endif  // GTEST_OS_LINUX
50
51# include <stdarg.h>
52
53# if GTEST_OS_WINDOWS
54#  include <windows.h>
55# else
56#  include <sys/mman.h>
57#  include <sys/wait.h>
58# endif  // GTEST_OS_WINDOWS
59
60# if GTEST_OS_QNX
61#  include <spawn.h>
62# endif  // GTEST_OS_QNX
63
64#endif  // GTEST_HAS_DEATH_TEST
65
66#include "gtest/gtest-message.h"
67#include "gtest/internal/gtest-string.h"
68
69// Indicates that this translation unit is part of Google Test's
70// implementation.  It must come before gtest-internal-inl.h is
71// included, or there will be a compiler error.  This trick is to
72// prevent a user from accidentally including gtest-internal-inl.h in
73// his code.
74#define GTEST_IMPLEMENTATION_ 1
75#include "src/gtest-internal-inl.h"
76#undef GTEST_IMPLEMENTATION_
77
78namespace testing {
79
80// Constants.
81
82// The default death test style.
83static const char kDefaultDeathTestStyle[] = "fast";
84
85GTEST_DEFINE_string_(
86    death_test_style,
87    internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
88    "Indicates how to run a death test in a forked child process: "
89    "\"threadsafe\" (child process re-executes the test binary "
90    "from the beginning, running only the specific death test) or "
91    "\"fast\" (child process runs the death test immediately "
92    "after forking).");
93
94GTEST_DEFINE_bool_(
95    death_test_use_fork,
96    internal::BoolFromGTestEnv("death_test_use_fork", false),
97    "Instructs to use fork()/_exit() instead of clone() in death tests. "
98    "Ignored and always uses fork() on POSIX systems where clone() is not "
99    "implemented. Useful when running under valgrind or similar tools if "
100    "those do not support clone(). Valgrind 3.3.1 will just fail if "
101    "it sees an unsupported combination of clone() flags. "
102    "It is not recommended to use this flag w/o valgrind though it will "
103    "work in 99% of the cases. Once valgrind is fixed, this flag will "
104    "most likely be removed.");
105
106namespace internal {
107GTEST_DEFINE_string_(
108    internal_run_death_test, "",
109    "Indicates the file, line number, temporal index of "
110    "the single death test to run, and a file descriptor to "
111    "which a success code may be sent, all separated by "
112    "the '|' characters.  This flag is specified if and only if the current "
113    "process is a sub-process launched for running a thread-safe "
114    "death test.  FOR INTERNAL USE ONLY.");
115}  // namespace internal
116
117#if GTEST_HAS_DEATH_TEST
118
119namespace internal {
120
121// Valid only for fast death tests. Indicates the code is running in the
122// child process of a fast style death test.
123static bool g_in_fast_death_test_child = false;
124
125// Returns a Boolean value indicating whether the caller is currently
126// executing in the context of the death test child process.  Tools such as
127// Valgrind heap checkers may need this to modify their behavior in death
128// tests.  IMPORTANT: This is an internal utility.  Using it may break the
129// implementation of death tests.  User code MUST NOT use it.
130bool InDeathTestChild() {
131# if GTEST_OS_WINDOWS
132
133  // On Windows, death tests are thread-safe regardless of the value of the
134  // death_test_style flag.
135  return !GTEST_FLAG(internal_run_death_test).empty();
136
137# else
138
139  if (GTEST_FLAG(death_test_style) == "threadsafe")
140    return !GTEST_FLAG(internal_run_death_test).empty();
141  else
142    return g_in_fast_death_test_child;
143#endif
144}
145
146}  // namespace internal
147
148// ExitedWithCode constructor.
149ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
150}
151
152// ExitedWithCode function-call operator.
153bool ExitedWithCode::operator()(int exit_status) const {
154# if GTEST_OS_WINDOWS
155
156  return exit_status == exit_code_;
157
158# else
159
160  return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
161
162# endif  // GTEST_OS_WINDOWS
163}
164
165# if !GTEST_OS_WINDOWS
166// KilledBySignal constructor.
167KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
168}
169
170// KilledBySignal function-call operator.
171bool KilledBySignal::operator()(int exit_status) const {
172  return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
173}
174# endif  // !GTEST_OS_WINDOWS
175
176namespace internal {
177
178// Utilities needed for death tests.
179
180// Generates a textual description of a given exit code, in the format
181// specified by wait(2).
182static String ExitSummary(int exit_code) {
183  Message m;
184
185# if GTEST_OS_WINDOWS
186
187  m << "Exited with exit status " << exit_code;
188
189# else
190
191  if (WIFEXITED(exit_code)) {
192    m << "Exited with exit status " << WEXITSTATUS(exit_code);
193  } else if (WIFSIGNALED(exit_code)) {
194    m << "Terminated by signal " << WTERMSIG(exit_code);
195  }
196#  ifdef WCOREDUMP
197  if (WCOREDUMP(exit_code)) {
198    m << " (core dumped)";
199  }
200#  endif
201# endif  // GTEST_OS_WINDOWS
202
203  return m.GetString();
204}
205
206// Returns true if exit_status describes a process that was terminated
207// by a signal, or exited normally with a nonzero exit code.
208bool ExitedUnsuccessfully(int exit_status) {
209  return !ExitedWithCode(0)(exit_status);
210}
211
212# if !GTEST_OS_WINDOWS
213// Generates a textual failure message when a death test finds more than
214// one thread running, or cannot determine the number of threads, prior
215// to executing the given statement.  It is the responsibility of the
216// caller not to pass a thread_count of 1.
217static String DeathTestThreadWarning(size_t thread_count) {
218  Message msg;
219  msg << "Death tests use fork(), which is unsafe particularly"
220      << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
221  if (thread_count == 0)
222    msg << "couldn't detect the number of threads.";
223  else
224    msg << "detected " << thread_count << " threads.";
225  return msg.GetString();
226}
227# endif  // !GTEST_OS_WINDOWS
228
229// Flag characters for reporting a death test that did not die.
230static const char kDeathTestLived = 'L';
231static const char kDeathTestReturned = 'R';
232static const char kDeathTestThrew = 'T';
233static const char kDeathTestInternalError = 'I';
234
235// An enumeration describing all of the possible ways that a death test can
236// conclude.  DIED means that the process died while executing the test
237// code; LIVED means that process lived beyond the end of the test code;
238// RETURNED means that the test statement attempted to execute a return
239// statement, which is not allowed; THREW means that the test statement
240// returned control by throwing an exception.  IN_PROGRESS means the test
241// has not yet concluded.
242// TODO(vladl@google.com): Unify names and possibly values for
243// AbortReason, DeathTestOutcome, and flag characters above.
244enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
245
246// Routine for aborting the program which is safe to call from an
247// exec-style death test child process, in which case the error
248// message is propagated back to the parent process.  Otherwise, the
249// message is simply printed to stderr.  In either case, the program
250// then exits with status 1.
251void DeathTestAbort(const String& message) {
252  // On a POSIX system, this function may be called from a threadsafe-style
253  // death test child process, which operates on a very small stack.  Use
254  // the heap for any additional non-minuscule memory requirements.
255  const InternalRunDeathTestFlag* const flag =
256      GetUnitTestImpl()->internal_run_death_test_flag();
257  if (flag != NULL) {
258    FILE* parent = posix::FDOpen(flag->write_fd(), "w");
259    fputc(kDeathTestInternalError, parent);
260    fprintf(parent, "%s", message.c_str());
261    fflush(parent);
262    _exit(1);
263  } else {
264    fprintf(stderr, "%s", message.c_str());
265    fflush(stderr);
266    posix::Abort();
267  }
268}
269
270// A replacement for CHECK that calls DeathTestAbort if the assertion
271// fails.
272# define GTEST_DEATH_TEST_CHECK_(expression) \
273  do { \
274    if (!::testing::internal::IsTrue(expression)) { \
275      DeathTestAbort(::testing::internal::String::Format( \
276          "CHECK failed: File %s, line %d: %s", \
277          __FILE__, __LINE__, #expression)); \
278    } \
279  } while (::testing::internal::AlwaysFalse())
280
281// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
282// evaluating any system call that fulfills two conditions: it must return
283// -1 on failure, and set errno to EINTR when it is interrupted and
284// should be tried again.  The macro expands to a loop that repeatedly
285// evaluates the expression as long as it evaluates to -1 and sets
286// errno to EINTR.  If the expression evaluates to -1 but errno is
287// something other than EINTR, DeathTestAbort is called.
288# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
289  do { \
290    int gtest_retval; \
291    do { \
292      gtest_retval = (expression); \
293    } while (gtest_retval == -1 && errno == EINTR); \
294    if (gtest_retval == -1) { \
295      DeathTestAbort(::testing::internal::String::Format( \
296          "CHECK failed: File %s, line %d: %s != -1", \
297          __FILE__, __LINE__, #expression)); \
298    } \
299  } while (::testing::internal::AlwaysFalse())
300
301// Returns the message describing the last system error in errno.
302String GetLastErrnoDescription() {
303    return String(errno == 0 ? "" : posix::StrError(errno));
304}
305
306// This is called from a death test parent process to read a failure
307// message from the death test child process and log it with the FATAL
308// severity. On Windows, the message is read from a pipe handle. On other
309// platforms, it is read from a file descriptor.
310static void FailFromInternalError(int fd) {
311  Message error;
312  char buffer[256];
313  int num_read;
314
315  do {
316    while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
317      buffer[num_read] = '\0';
318      error << buffer;
319    }
320  } while (num_read == -1 && errno == EINTR);
321
322  if (num_read == 0) {
323    GTEST_LOG_(FATAL) << error.GetString();
324  } else {
325    const int last_error = errno;
326    GTEST_LOG_(FATAL) << "Error while reading death test internal: "
327                      << GetLastErrnoDescription() << " [" << last_error << "]";
328  }
329}
330
331// Death test constructor.  Increments the running death test count
332// for the current test.
333DeathTest::DeathTest() {
334  TestInfo* const info = GetUnitTestImpl()->current_test_info();
335  if (info == NULL) {
336    DeathTestAbort("Cannot run a death test outside of a TEST or "
337                   "TEST_F construct");
338  }
339}
340
341// Creates and returns a death test by dispatching to the current
342// death test factory.
343bool DeathTest::Create(const char* statement, const RE* regex,
344                       const char* file, int line, DeathTest** test) {
345  return GetUnitTestImpl()->death_test_factory()->Create(
346      statement, regex, file, line, test);
347}
348
349const char* DeathTest::LastMessage() {
350  return last_death_test_message_.c_str();
351}
352
353void DeathTest::set_last_death_test_message(const String& message) {
354  last_death_test_message_ = message;
355}
356
357String DeathTest::last_death_test_message_;
358
359// Provides cross platform implementation for some death functionality.
360class DeathTestImpl : public DeathTest {
361 protected:
362  DeathTestImpl(const char* a_statement, const RE* a_regex)
363      : statement_(a_statement),
364        regex_(a_regex),
365        spawned_(false),
366        status_(-1),
367        outcome_(IN_PROGRESS),
368        read_fd_(-1),
369        write_fd_(-1) {}
370
371  // read_fd_ is expected to be closed and cleared by a derived class.
372  ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
373
374  void Abort(AbortReason reason);
375  virtual bool Passed(bool status_ok);
376
377  const char* statement() const { return statement_; }
378  const RE* regex() const { return regex_; }
379  bool spawned() const { return spawned_; }
380  void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
381  int status() const { return status_; }
382  void set_status(int a_status) { status_ = a_status; }
383  DeathTestOutcome outcome() const { return outcome_; }
384  void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
385  int read_fd() const { return read_fd_; }
386  void set_read_fd(int fd) { read_fd_ = fd; }
387  int write_fd() const { return write_fd_; }
388  void set_write_fd(int fd) { write_fd_ = fd; }
389
390  // Called in the parent process only. Reads the result code of the death
391  // test child process via a pipe, interprets it to set the outcome_
392  // member, and closes read_fd_.  Outputs diagnostics and terminates in
393  // case of unexpected codes.
394  void ReadAndInterpretStatusByte();
395
396 private:
397  // The textual content of the code this object is testing.  This class
398  // doesn't own this string and should not attempt to delete it.
399  const char* const statement_;
400  // The regular expression which test output must match.  DeathTestImpl
401  // doesn't own this object and should not attempt to delete it.
402  const RE* const regex_;
403  // True if the death test child process has been successfully spawned.
404  bool spawned_;
405  // The exit status of the child process.
406  int status_;
407  // How the death test concluded.
408  DeathTestOutcome outcome_;
409  // Descriptor to the read end of the pipe to the child process.  It is
410  // always -1 in the child process.  The child keeps its write end of the
411  // pipe in write_fd_.
412  int read_fd_;
413  // Descriptor to the child's write end of the pipe to the parent process.
414  // It is always -1 in the parent process.  The parent keeps its end of the
415  // pipe in read_fd_.
416  int write_fd_;
417};
418
419// Called in the parent process only. Reads the result code of the death
420// test child process via a pipe, interprets it to set the outcome_
421// member, and closes read_fd_.  Outputs diagnostics and terminates in
422// case of unexpected codes.
423void DeathTestImpl::ReadAndInterpretStatusByte() {
424  char flag;
425  int bytes_read;
426
427  // The read() here blocks until data is available (signifying the
428  // failure of the death test) or until the pipe is closed (signifying
429  // its success), so it's okay to call this in the parent before
430  // the child process has exited.
431  do {
432    bytes_read = posix::Read(read_fd(), &flag, 1);
433  } while (bytes_read == -1 && errno == EINTR);
434
435  if (bytes_read == 0) {
436    set_outcome(DIED);
437  } else if (bytes_read == 1) {
438    switch (flag) {
439      case kDeathTestReturned:
440        set_outcome(RETURNED);
441        break;
442      case kDeathTestThrew:
443        set_outcome(THREW);
444        break;
445      case kDeathTestLived:
446        set_outcome(LIVED);
447        break;
448      case kDeathTestInternalError:
449        FailFromInternalError(read_fd());  // Does not return.
450        break;
451      default:
452        GTEST_LOG_(FATAL) << "Death test child process reported "
453                          << "unexpected status byte ("
454                          << static_cast<unsigned int>(flag) << ")";
455    }
456  } else {
457    GTEST_LOG_(FATAL) << "Read from death test child process failed: "
458                      << GetLastErrnoDescription();
459  }
460  GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
461  set_read_fd(-1);
462}
463
464// Signals that the death test code which should have exited, didn't.
465// Should be called only in a death test child process.
466// Writes a status byte to the child's status file descriptor, then
467// calls _exit(1).
468void DeathTestImpl::Abort(AbortReason reason) {
469  // The parent process considers the death test to be a failure if
470  // it finds any data in our pipe.  So, here we write a single flag byte
471  // to the pipe, then exit.
472  const char status_ch =
473      reason == TEST_DID_NOT_DIE ? kDeathTestLived :
474      reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
475
476  GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
477  // We are leaking the descriptor here because on some platforms (i.e.,
478  // when built as Windows DLL), destructors of global objects will still
479  // run after calling _exit(). On such systems, write_fd_ will be
480  // indirectly closed from the destructor of UnitTestImpl, causing double
481  // close if it is also closed here. On debug configurations, double close
482  // may assert. As there are no in-process buffers to flush here, we are
483  // relying on the OS to close the descriptor after the process terminates
484  // when the destructors are not run.
485  _exit(1);  // Exits w/o any normal exit hooks (we were supposed to crash)
486}
487
488// Returns an indented copy of stderr output for a death test.
489// This makes distinguishing death test output lines from regular log lines
490// much easier.
491static ::std::string FormatDeathTestOutput(const ::std::string& output) {
492  ::std::string ret;
493  for (size_t at = 0; ; ) {
494    const size_t line_end = output.find('\n', at);
495    ret += "[  DEATH   ] ";
496    if (line_end == ::std::string::npos) {
497      ret += output.substr(at);
498      break;
499    }
500    ret += output.substr(at, line_end + 1 - at);
501    at = line_end + 1;
502  }
503  return ret;
504}
505
506// Assesses the success or failure of a death test, using both private
507// members which have previously been set, and one argument:
508//
509// Private data members:
510//   outcome:  An enumeration describing how the death test
511//             concluded: DIED, LIVED, THREW, or RETURNED.  The death test
512//             fails in the latter three cases.
513//   status:   The exit status of the child process. On *nix, it is in the
514//             in the format specified by wait(2). On Windows, this is the
515//             value supplied to the ExitProcess() API or a numeric code
516//             of the exception that terminated the program.
517//   regex:    A regular expression object to be applied to
518//             the test's captured standard error output; the death test
519//             fails if it does not match.
520//
521// Argument:
522//   status_ok: true if exit_status is acceptable in the context of
523//              this particular death test, which fails if it is false
524//
525// Returns true iff all of the above conditions are met.  Otherwise, the
526// first failing condition, in the order given above, is the one that is
527// reported. Also sets the last death test message string.
528bool DeathTestImpl::Passed(bool status_ok) {
529  if (!spawned())
530    return false;
531
532  const String error_message = GetCapturedStderr();
533
534  bool success = false;
535  Message buffer;
536
537  buffer << "Death test: " << statement() << "\n";
538  switch (outcome()) {
539    case LIVED:
540      buffer << "    Result: failed to die.\n"
541             << " Error msg:\n" << FormatDeathTestOutput(error_message);
542      break;
543    case THREW:
544      buffer << "    Result: threw an exception.\n"
545             << " Error msg:\n" << FormatDeathTestOutput(error_message);
546      break;
547    case RETURNED:
548      buffer << "    Result: illegal return in test statement.\n"
549             << " Error msg:\n" << FormatDeathTestOutput(error_message);
550      break;
551    case DIED:
552      if (status_ok) {
553        const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
554        if (matched) {
555          success = true;
556        } else {
557          buffer << "    Result: died but not with expected error.\n"
558                 << "  Expected: " << regex()->pattern() << "\n"
559                 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
560        }
561      } else {
562        buffer << "    Result: died but not with expected exit code:\n"
563               << "            " << ExitSummary(status()) << "\n"
564               << "Actual msg:\n" << FormatDeathTestOutput(error_message);
565      }
566      break;
567    case IN_PROGRESS:
568    default:
569      GTEST_LOG_(FATAL)
570          << "DeathTest::Passed somehow called before conclusion of test";
571  }
572
573  DeathTest::set_last_death_test_message(buffer.GetString());
574  return success;
575}
576
577# if GTEST_OS_WINDOWS
578// WindowsDeathTest implements death tests on Windows. Due to the
579// specifics of starting new processes on Windows, death tests there are
580// always threadsafe, and Google Test considers the
581// --gtest_death_test_style=fast setting to be equivalent to
582// --gtest_death_test_style=threadsafe there.
583//
584// A few implementation notes:  Like the Linux version, the Windows
585// implementation uses pipes for child-to-parent communication. But due to
586// the specifics of pipes on Windows, some extra steps are required:
587//
588// 1. The parent creates a communication pipe and stores handles to both
589//    ends of it.
590// 2. The parent starts the child and provides it with the information
591//    necessary to acquire the handle to the write end of the pipe.
592// 3. The child acquires the write end of the pipe and signals the parent
593//    using a Windows event.
594// 4. Now the parent can release the write end of the pipe on its side. If
595//    this is done before step 3, the object's reference count goes down to
596//    0 and it is destroyed, preventing the child from acquiring it. The
597//    parent now has to release it, or read operations on the read end of
598//    the pipe will not return when the child terminates.
599// 5. The parent reads child's output through the pipe (outcome code and
600//    any possible error messages) from the pipe, and its stderr and then
601//    determines whether to fail the test.
602//
603// Note: to distinguish Win32 API calls from the local method and function
604// calls, the former are explicitly resolved in the global namespace.
605//
606class WindowsDeathTest : public DeathTestImpl {
607 public:
608  WindowsDeathTest(const char* a_statement,
609                   const RE* a_regex,
610                   const char* file,
611                   int line)
612      : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
613
614  // All of these virtual functions are inherited from DeathTest.
615  virtual int Wait();
616  virtual TestRole AssumeRole();
617
618 private:
619  // The name of the file in which the death test is located.
620  const char* const file_;
621  // The line number on which the death test is located.
622  const int line_;
623  // Handle to the write end of the pipe to the child process.
624  AutoHandle write_handle_;
625  // Child process handle.
626  AutoHandle child_handle_;
627  // Event the child process uses to signal the parent that it has
628  // acquired the handle to the write end of the pipe. After seeing this
629  // event the parent can release its own handles to make sure its
630  // ReadFile() calls return when the child terminates.
631  AutoHandle event_handle_;
632};
633
634// Waits for the child in a death test to exit, returning its exit
635// status, or 0 if no child process exists.  As a side effect, sets the
636// outcome data member.
637int WindowsDeathTest::Wait() {
638  if (!spawned())
639    return 0;
640
641  // Wait until the child either signals that it has acquired the write end
642  // of the pipe or it dies.
643  const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
644  switch (::WaitForMultipleObjects(2,
645                                   wait_handles,
646                                   FALSE,  // Waits for any of the handles.
647                                   INFINITE)) {
648    case WAIT_OBJECT_0:
649    case WAIT_OBJECT_0 + 1:
650      break;
651    default:
652      GTEST_DEATH_TEST_CHECK_(false);  // Should not get here.
653  }
654
655  // The child has acquired the write end of the pipe or exited.
656  // We release the handle on our side and continue.
657  write_handle_.Reset();
658  event_handle_.Reset();
659
660  ReadAndInterpretStatusByte();
661
662  // Waits for the child process to exit if it haven't already. This
663  // returns immediately if the child has already exited, regardless of
664  // whether previous calls to WaitForMultipleObjects synchronized on this
665  // handle or not.
666  GTEST_DEATH_TEST_CHECK_(
667      WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
668                                             INFINITE));
669  DWORD status_code;
670  GTEST_DEATH_TEST_CHECK_(
671      ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
672  child_handle_.Reset();
673  set_status(static_cast<int>(status_code));
674  return status();
675}
676
677// The AssumeRole process for a Windows death test.  It creates a child
678// process with the same executable as the current process to run the
679// death test.  The child process is given the --gtest_filter and
680// --gtest_internal_run_death_test flags such that it knows to run the
681// current death test only.
682DeathTest::TestRole WindowsDeathTest::AssumeRole() {
683  const UnitTestImpl* const impl = GetUnitTestImpl();
684  const InternalRunDeathTestFlag* const flag =
685      impl->internal_run_death_test_flag();
686  const TestInfo* const info = impl->current_test_info();
687  const int death_test_index = info->result()->death_test_count();
688
689  if (flag != NULL) {
690    // ParseInternalRunDeathTestFlag() has performed all the necessary
691    // processing.
692    set_write_fd(flag->write_fd());
693    return EXECUTE_TEST;
694  }
695
696  // WindowsDeathTest uses an anonymous pipe to communicate results of
697  // a death test.
698  SECURITY_ATTRIBUTES handles_are_inheritable = {
699    sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
700  HANDLE read_handle, write_handle;
701  GTEST_DEATH_TEST_CHECK_(
702      ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
703                   0)  // Default buffer size.
704      != FALSE);
705  set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
706                                O_RDONLY));
707  write_handle_.Reset(write_handle);
708  event_handle_.Reset(::CreateEvent(
709      &handles_are_inheritable,
710      TRUE,    // The event will automatically reset to non-signaled state.
711      FALSE,   // The initial state is non-signalled.
712      NULL));  // The even is unnamed.
713  GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
714  const String filter_flag = String::Format("--%s%s=%s.%s",
715                                            GTEST_FLAG_PREFIX_, kFilterFlag,
716                                            info->test_case_name(),
717                                            info->name());
718  const String internal_flag = String::Format(
719    "--%s%s=%s|%d|%d|%u|%Iu|%Iu",
720      GTEST_FLAG_PREFIX_,
721      kInternalRunDeathTestFlag,
722      file_, line_,
723      death_test_index,
724      static_cast<unsigned int>(::GetCurrentProcessId()),
725      // size_t has the same with as pointers on both 32-bit and 64-bit
726      // Windows platforms.
727      // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
728      reinterpret_cast<size_t>(write_handle),
729      reinterpret_cast<size_t>(event_handle_.Get()));
730
731  char executable_path[_MAX_PATH + 1];  // NOLINT
732  GTEST_DEATH_TEST_CHECK_(
733      _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
734                                            executable_path,
735                                            _MAX_PATH));
736
737  String command_line = String::Format("%s %s \"%s\"",
738                                       ::GetCommandLineA(),
739                                       filter_flag.c_str(),
740                                       internal_flag.c_str());
741
742  DeathTest::set_last_death_test_message("");
743
744  CaptureStderr();
745  // Flush the log buffers since the log streams are shared with the child.
746  FlushInfoLog();
747
748  // The child process will share the standard handles with the parent.
749  STARTUPINFOA startup_info;
750  memset(&startup_info, 0, sizeof(STARTUPINFO));
751  startup_info.dwFlags = STARTF_USESTDHANDLES;
752  startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
753  startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
754  startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
755
756  PROCESS_INFORMATION process_info;
757  GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
758      executable_path,
759      const_cast<char*>(command_line.c_str()),
760      NULL,   // Retuned process handle is not inheritable.
761      NULL,   // Retuned thread handle is not inheritable.
762      TRUE,   // Child inherits all inheritable handles (for write_handle_).
763      0x0,    // Default creation flags.
764      NULL,   // Inherit the parent's environment.
765      UnitTest::GetInstance()->original_working_dir(),
766      &startup_info,
767      &process_info) != FALSE);
768  child_handle_.Reset(process_info.hProcess);
769  ::CloseHandle(process_info.hThread);
770  set_spawned(true);
771  return OVERSEE_TEST;
772}
773# else  // We are not on Windows.
774
775// ForkingDeathTest provides implementations for most of the abstract
776// methods of the DeathTest interface.  Only the AssumeRole method is
777// left undefined.
778class ForkingDeathTest : public DeathTestImpl {
779 public:
780  ForkingDeathTest(const char* statement, const RE* regex);
781
782  // All of these virtual functions are inherited from DeathTest.
783  virtual int Wait();
784
785 protected:
786  void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
787
788 private:
789  // PID of child process during death test; 0 in the child process itself.
790  pid_t child_pid_;
791};
792
793// Constructs a ForkingDeathTest.
794ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
795    : DeathTestImpl(a_statement, a_regex),
796      child_pid_(-1) {}
797
798// Waits for the child in a death test to exit, returning its exit
799// status, or 0 if no child process exists.  As a side effect, sets the
800// outcome data member.
801int ForkingDeathTest::Wait() {
802  if (!spawned())
803    return 0;
804
805  ReadAndInterpretStatusByte();
806
807  int status_value;
808  GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
809  set_status(status_value);
810  return status_value;
811}
812
813// A concrete death test class that forks, then immediately runs the test
814// in the child process.
815class NoExecDeathTest : public ForkingDeathTest {
816 public:
817  NoExecDeathTest(const char* a_statement, const RE* a_regex) :
818      ForkingDeathTest(a_statement, a_regex) { }
819  virtual TestRole AssumeRole();
820};
821
822// The AssumeRole process for a fork-and-run death test.  It implements a
823// straightforward fork, with a simple pipe to transmit the status byte.
824DeathTest::TestRole NoExecDeathTest::AssumeRole() {
825  const size_t thread_count = GetThreadCount();
826  if (thread_count != 1) {
827    GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
828  }
829
830  int pipe_fd[2];
831  GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
832
833  DeathTest::set_last_death_test_message("");
834  CaptureStderr();
835  // When we fork the process below, the log file buffers are copied, but the
836  // file descriptors are shared.  We flush all log files here so that closing
837  // the file descriptors in the child process doesn't throw off the
838  // synchronization between descriptors and buffers in the parent process.
839  // This is as close to the fork as possible to avoid a race condition in case
840  // there are multiple threads running before the death test, and another
841  // thread writes to the log file.
842  FlushInfoLog();
843
844  const pid_t child_pid = fork();
845  GTEST_DEATH_TEST_CHECK_(child_pid != -1);
846  set_child_pid(child_pid);
847  if (child_pid == 0) {
848    GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
849    set_write_fd(pipe_fd[1]);
850    // Redirects all logging to stderr in the child process to prevent
851    // concurrent writes to the log files.  We capture stderr in the parent
852    // process and append the child process' output to a log.
853    LogToStderr();
854    // Event forwarding to the listeners of event listener API mush be shut
855    // down in death test subprocesses.
856    GetUnitTestImpl()->listeners()->SuppressEventForwarding();
857    g_in_fast_death_test_child = true;
858    return EXECUTE_TEST;
859  } else {
860    GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
861    set_read_fd(pipe_fd[0]);
862    set_spawned(true);
863    return OVERSEE_TEST;
864  }
865}
866
867// A concrete death test class that forks and re-executes the main
868// program from the beginning, with command-line flags set that cause
869// only this specific death test to be run.
870class ExecDeathTest : public ForkingDeathTest {
871 public:
872  ExecDeathTest(const char* a_statement, const RE* a_regex,
873                const char* file, int line) :
874      ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
875  virtual TestRole AssumeRole();
876 private:
877  static ::std::vector<testing::internal::string>
878  GetArgvsForDeathTestChildProcess() {
879    ::std::vector<testing::internal::string> args = GetInjectableArgvs();
880    return args;
881  }
882  // The name of the file in which the death test is located.
883  const char* const file_;
884  // The line number on which the death test is located.
885  const int line_;
886};
887
888// Utility class for accumulating command-line arguments.
889class Arguments {
890 public:
891  Arguments() {
892    args_.push_back(NULL);
893  }
894
895  ~Arguments() {
896    for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
897         ++i) {
898      free(*i);
899    }
900  }
901  void AddArgument(const char* argument) {
902    args_.insert(args_.end() - 1, posix::StrDup(argument));
903  }
904
905  template <typename Str>
906  void AddArguments(const ::std::vector<Str>& arguments) {
907    for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
908         i != arguments.end();
909         ++i) {
910      args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
911    }
912  }
913  char* const* Argv() {
914    return &args_[0];
915  }
916
917 private:
918  std::vector<char*> args_;
919};
920
921// A struct that encompasses the arguments to the child process of a
922// threadsafe-style death test process.
923struct ExecDeathTestArgs {
924  char* const* argv;  // Command-line arguments for the child's call to exec
925  int close_fd;       // File descriptor to close; the read end of a pipe
926};
927
928#  if GTEST_OS_MAC
929inline char** GetEnviron() {
930  // When Google Test is built as a framework on MacOS X, the environ variable
931  // is unavailable. Apple's documentation (man environ) recommends using
932  // _NSGetEnviron() instead.
933  return *_NSGetEnviron();
934}
935#  else
936// Some POSIX platforms expect you to declare environ. extern "C" makes
937// it reside in the global namespace.
938extern "C" char** environ;
939inline char** GetEnviron() { return environ; }
940#  endif  // GTEST_OS_MAC
941
942#  if !GTEST_OS_QNX
943// The main function for a threadsafe-style death test child process.
944// This function is called in a clone()-ed process and thus must avoid
945// any potentially unsafe operations like malloc or libc functions.
946static int ExecDeathTestChildMain(void* child_arg) {
947  ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
948  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
949
950  // We need to execute the test program in the same environment where
951  // it was originally invoked.  Therefore we change to the original
952  // working directory first.
953  const char* const original_dir =
954      UnitTest::GetInstance()->original_working_dir();
955  // We can safely call chdir() as it's a direct system call.
956  if (chdir(original_dir) != 0) {
957    DeathTestAbort(String::Format("chdir(\"%s\") failed: %s",
958                                  original_dir,
959                                  GetLastErrnoDescription().c_str()));
960    return EXIT_FAILURE;
961  }
962
963  // We can safely call execve() as it's a direct system call.  We
964  // cannot use execvp() as it's a libc function and thus potentially
965  // unsafe.  Since execve() doesn't search the PATH, the user must
966  // invoke the test program via a valid path that contains at least
967  // one path separator.
968  execve(args->argv[0], args->argv, GetEnviron());
969  DeathTestAbort(String::Format("execve(%s, ...) in %s failed: %s",
970                                args->argv[0],
971                                original_dir,
972                                GetLastErrnoDescription().c_str()));
973  return EXIT_FAILURE;
974}
975#  endif  // !GTEST_OS_QNX
976
977// Two utility routines that together determine the direction the stack
978// grows.
979// This could be accomplished more elegantly by a single recursive
980// function, but we want to guard against the unlikely possibility of
981// a smart compiler optimizing the recursion away.
982//
983// GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
984// StackLowerThanAddress into StackGrowsDown, which then doesn't give
985// correct answer.
986void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;
987void StackLowerThanAddress(const void* ptr, bool* result) {
988  int dummy;
989  *result = (&dummy < ptr);
990}
991
992bool StackGrowsDown() {
993  int dummy;
994  bool result;
995  StackLowerThanAddress(&dummy, &result);
996  return result;
997}
998
999// Spawns a child process with the same executable as the current process in
1000// a thread-safe manner and instructs it to run the death test.  The
1001// implementation uses fork(2) + exec.  On systems where clone(2) is
1002// available, it is used instead, being slightly more thread-safe.  On QNX,
1003// fork supports only single-threaded environments, so this function uses
1004// spawn(2) there instead.  The function dies with an error message if
1005// anything goes wrong.
1006static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
1007  ExecDeathTestArgs args = { argv, close_fd };
1008  pid_t child_pid = -1;
1009
1010#  if GTEST_OS_QNX
1011  // Obtains the current directory and sets it to be closed in the child
1012  // process.
1013  const int cwd_fd = open(".", O_RDONLY);
1014  GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
1015  GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
1016  // We need to execute the test program in the same environment where
1017  // it was originally invoked.  Therefore we change to the original
1018  // working directory first.
1019  const char* const original_dir =
1020      UnitTest::GetInstance()->original_working_dir();
1021  // We can safely call chdir() as it's a direct system call.
1022  if (chdir(original_dir) != 0) {
1023    DeathTestAbort(String::Format("chdir(\"%s\") failed: %s",
1024                                  original_dir,
1025                                  GetLastErrnoDescription().c_str()));
1026    return EXIT_FAILURE;
1027  }
1028
1029  int fd_flags;
1030  // Set close_fd to be closed after spawn.
1031  GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
1032  GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
1033                                        fd_flags | FD_CLOEXEC));
1034  struct inheritance inherit = {0};
1035  // spawn is a system call.
1036  child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
1037  // Restores the current working directory.
1038  GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
1039  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
1040
1041#  else   // GTEST_OS_QNX
1042#   if GTEST_OS_LINUX
1043  // When a SIGPROF signal is received while fork() or clone() are executing,
1044  // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
1045  // it after the call to fork()/clone() is complete.
1046  struct sigaction saved_sigprof_action;
1047  struct sigaction ignore_sigprof_action;
1048  memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
1049  sigemptyset(&ignore_sigprof_action.sa_mask);
1050  ignore_sigprof_action.sa_handler = SIG_IGN;
1051  GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
1052      SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
1053#   endif  // GTEST_OS_LINUX
1054
1055#   if GTEST_HAS_CLONE
1056  const bool use_fork = GTEST_FLAG(death_test_use_fork);
1057
1058  if (!use_fork) {
1059    static const bool stack_grows_down = StackGrowsDown();
1060    const size_t stack_size = getpagesize();
1061    // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
1062    void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
1063                             MAP_ANON | MAP_PRIVATE, -1, 0);
1064    GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
1065    void* const stack_top =
1066        static_cast<char*>(stack) + (stack_grows_down ? stack_size : 0);
1067
1068    child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
1069
1070    GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
1071  }
1072#   else
1073  const bool use_fork = true;
1074#   endif  // GTEST_HAS_CLONE
1075
1076  if (use_fork && (child_pid = fork()) == 0) {
1077      ExecDeathTestChildMain(&args);
1078      _exit(0);
1079  }
1080#  endif  // GTEST_OS_QNX
1081#  if GTEST_OS_LINUX
1082  GTEST_DEATH_TEST_CHECK_SYSCALL_(
1083      sigaction(SIGPROF, &saved_sigprof_action, NULL));
1084#  endif  // GTEST_OS_LINUX
1085
1086  GTEST_DEATH_TEST_CHECK_(child_pid != -1);
1087  return child_pid;
1088}
1089
1090// The AssumeRole process for a fork-and-exec death test.  It re-executes the
1091// main program from the beginning, setting the --gtest_filter
1092// and --gtest_internal_run_death_test flags to cause only the current
1093// death test to be re-run.
1094DeathTest::TestRole ExecDeathTest::AssumeRole() {
1095  const UnitTestImpl* const impl = GetUnitTestImpl();
1096  const InternalRunDeathTestFlag* const flag =
1097      impl->internal_run_death_test_flag();
1098  const TestInfo* const info = impl->current_test_info();
1099  const int death_test_index = info->result()->death_test_count();
1100
1101  if (flag != NULL) {
1102    set_write_fd(flag->write_fd());
1103    return EXECUTE_TEST;
1104  }
1105
1106  int pipe_fd[2];
1107  GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
1108  // Clear the close-on-exec flag on the write end of the pipe, lest
1109  // it be closed when the child process does an exec:
1110  GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
1111
1112  const String filter_flag =
1113      String::Format("--%s%s=%s.%s",
1114                     GTEST_FLAG_PREFIX_, kFilterFlag,
1115                     info->test_case_name(), info->name());
1116  const String internal_flag =
1117      String::Format("--%s%s=%s|%d|%d|%d",
1118                     GTEST_FLAG_PREFIX_, kInternalRunDeathTestFlag,
1119                     file_, line_, death_test_index, pipe_fd[1]);
1120  Arguments args;
1121  args.AddArguments(GetArgvsForDeathTestChildProcess());
1122  args.AddArgument(filter_flag.c_str());
1123  args.AddArgument(internal_flag.c_str());
1124
1125  DeathTest::set_last_death_test_message("");
1126
1127  CaptureStderr();
1128  // See the comment in NoExecDeathTest::AssumeRole for why the next line
1129  // is necessary.
1130  FlushInfoLog();
1131
1132  const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
1133  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
1134  set_child_pid(child_pid);
1135  set_read_fd(pipe_fd[0]);
1136  set_spawned(true);
1137  return OVERSEE_TEST;
1138}
1139
1140# endif  // !GTEST_OS_WINDOWS
1141
1142// Creates a concrete DeathTest-derived class that depends on the
1143// --gtest_death_test_style flag, and sets the pointer pointed to
1144// by the "test" argument to its address.  If the test should be
1145// skipped, sets that pointer to NULL.  Returns true, unless the
1146// flag is set to an invalid value.
1147bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
1148                                     const char* file, int line,
1149                                     DeathTest** test) {
1150  UnitTestImpl* const impl = GetUnitTestImpl();
1151  const InternalRunDeathTestFlag* const flag =
1152      impl->internal_run_death_test_flag();
1153  const int death_test_index = impl->current_test_info()
1154      ->increment_death_test_count();
1155
1156  if (flag != NULL) {
1157    if (death_test_index > flag->index()) {
1158      DeathTest::set_last_death_test_message(String::Format(
1159          "Death test count (%d) somehow exceeded expected maximum (%d)",
1160          death_test_index, flag->index()));
1161      return false;
1162    }
1163
1164    if (!(flag->file() == file && flag->line() == line &&
1165          flag->index() == death_test_index)) {
1166      *test = NULL;
1167      return true;
1168    }
1169  }
1170
1171# if GTEST_OS_WINDOWS
1172
1173  if (GTEST_FLAG(death_test_style) == "threadsafe" ||
1174      GTEST_FLAG(death_test_style) == "fast") {
1175    *test = new WindowsDeathTest(statement, regex, file, line);
1176  }
1177
1178# else
1179
1180  if (GTEST_FLAG(death_test_style) == "threadsafe") {
1181    *test = new ExecDeathTest(statement, regex, file, line);
1182  } else if (GTEST_FLAG(death_test_style) == "fast") {
1183    *test = new NoExecDeathTest(statement, regex);
1184  }
1185
1186# endif  // GTEST_OS_WINDOWS
1187
1188  else {  // NOLINT - this is more readable than unbalanced brackets inside #if.
1189    DeathTest::set_last_death_test_message(String::Format(
1190        "Unknown death test style \"%s\" encountered",
1191        GTEST_FLAG(death_test_style).c_str()));
1192    return false;
1193  }
1194
1195  return true;
1196}
1197
1198// Splits a given string on a given delimiter, populating a given
1199// vector with the fields.  GTEST_HAS_DEATH_TEST implies that we have
1200// ::std::string, so we can use it here.
1201static void SplitString(const ::std::string& str, char delimiter,
1202                        ::std::vector< ::std::string>* dest) {
1203  ::std::vector< ::std::string> parsed;
1204  ::std::string::size_type pos = 0;
1205  while (::testing::internal::AlwaysTrue()) {
1206    const ::std::string::size_type colon = str.find(delimiter, pos);
1207    if (colon == ::std::string::npos) {
1208      parsed.push_back(str.substr(pos));
1209      break;
1210    } else {
1211      parsed.push_back(str.substr(pos, colon - pos));
1212      pos = colon + 1;
1213    }
1214  }
1215  dest->swap(parsed);
1216}
1217
1218# if GTEST_OS_WINDOWS
1219// Recreates the pipe and event handles from the provided parameters,
1220// signals the event, and returns a file descriptor wrapped around the pipe
1221// handle. This function is called in the child process only.
1222int GetStatusFileDescriptor(unsigned int parent_process_id,
1223                            size_t write_handle_as_size_t,
1224                            size_t event_handle_as_size_t) {
1225  AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
1226                                                   FALSE,  // Non-inheritable.
1227                                                   parent_process_id));
1228  if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
1229    DeathTestAbort(String::Format("Unable to open parent process %u",
1230                                  parent_process_id));
1231  }
1232
1233  // TODO(vladl@google.com): Replace the following check with a
1234  // compile-time assertion when available.
1235  GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
1236
1237  const HANDLE write_handle =
1238      reinterpret_cast<HANDLE>(write_handle_as_size_t);
1239  HANDLE dup_write_handle;
1240
1241  // The newly initialized handle is accessible only in in the parent
1242  // process. To obtain one accessible within the child, we need to use
1243  // DuplicateHandle.
1244  if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
1245                         ::GetCurrentProcess(), &dup_write_handle,
1246                         0x0,    // Requested privileges ignored since
1247                                 // DUPLICATE_SAME_ACCESS is used.
1248                         FALSE,  // Request non-inheritable handler.
1249                         DUPLICATE_SAME_ACCESS)) {
1250    DeathTestAbort(String::Format(
1251        "Unable to duplicate the pipe handle %Iu from the parent process %u",
1252        write_handle_as_size_t, parent_process_id));
1253  }
1254
1255  const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
1256  HANDLE dup_event_handle;
1257
1258  if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
1259                         ::GetCurrentProcess(), &dup_event_handle,
1260                         0x0,
1261                         FALSE,
1262                         DUPLICATE_SAME_ACCESS)) {
1263    DeathTestAbort(String::Format(
1264        "Unable to duplicate the event handle %Iu from the parent process %u",
1265        event_handle_as_size_t, parent_process_id));
1266  }
1267
1268  const int write_fd =
1269      ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
1270  if (write_fd == -1) {
1271    DeathTestAbort(String::Format(
1272        "Unable to convert pipe handle %Iu to a file descriptor",
1273        write_handle_as_size_t));
1274  }
1275
1276  // Signals the parent that the write end of the pipe has been acquired
1277  // so the parent can release its own write end.
1278  ::SetEvent(dup_event_handle);
1279
1280  return write_fd;
1281}
1282# endif  // GTEST_OS_WINDOWS
1283
1284// Returns a newly created InternalRunDeathTestFlag object with fields
1285// initialized from the GTEST_FLAG(internal_run_death_test) flag if
1286// the flag is specified; otherwise returns NULL.
1287InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
1288  if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
1289
1290  // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
1291  // can use it here.
1292  int line = -1;
1293  int index = -1;
1294  ::std::vector< ::std::string> fields;
1295  SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
1296  int write_fd = -1;
1297
1298# if GTEST_OS_WINDOWS
1299
1300  unsigned int parent_process_id = 0;
1301  size_t write_handle_as_size_t = 0;
1302  size_t event_handle_as_size_t = 0;
1303
1304  if (fields.size() != 6
1305      || !ParseNaturalNumber(fields[1], &line)
1306      || !ParseNaturalNumber(fields[2], &index)
1307      || !ParseNaturalNumber(fields[3], &parent_process_id)
1308      || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
1309      || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
1310    DeathTestAbort(String::Format(
1311        "Bad --gtest_internal_run_death_test flag: %s",
1312        GTEST_FLAG(internal_run_death_test).c_str()));
1313  }
1314  write_fd = GetStatusFileDescriptor(parent_process_id,
1315                                     write_handle_as_size_t,
1316                                     event_handle_as_size_t);
1317# else
1318
1319  if (fields.size() != 4
1320      || !ParseNaturalNumber(fields[1], &line)
1321      || !ParseNaturalNumber(fields[2], &index)
1322      || !ParseNaturalNumber(fields[3], &write_fd)) {
1323    DeathTestAbort(String::Format(
1324        "Bad --gtest_internal_run_death_test flag: %s",
1325        GTEST_FLAG(internal_run_death_test).c_str()));
1326  }
1327
1328# endif  // GTEST_OS_WINDOWS
1329
1330  return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
1331}
1332
1333}  // namespace internal
1334
1335#endif  // GTEST_HAS_DEATH_TEST
1336
1337}  // namespace testing
1338