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