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