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