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