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