gtest-death-test.cc 49.9 KB
Newer Older
shiqian's avatar
shiqian committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Copyright 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
30
// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
shiqian's avatar
shiqian committed
31
32
33
//
// This file implements death tests.

34
35
#include "gtest/gtest-death-test.h"
#include "gtest/internal/gtest-port.h"
36
#include "gtest/internal/custom/gtest.h"
shiqian's avatar
shiqian committed
37

zhanyong.wan's avatar
zhanyong.wan committed
38
#if GTEST_HAS_DEATH_TEST
39

40
41
42
43
44
45
46
# if GTEST_OS_MAC
#  include <crt_externs.h>
# endif  // GTEST_OS_MAC

# include <errno.h>
# include <fcntl.h>
# include <limits.h>
47
48
49
50
51

# if GTEST_OS_LINUX
#  include <signal.h>
# endif  // GTEST_OS_LINUX

52
53
54
55
56
57
58
59
# include <stdarg.h>

# if GTEST_OS_WINDOWS
#  include <windows.h>
# else
#  include <sys/mman.h>
#  include <sys/wait.h>
# endif  // GTEST_OS_WINDOWS
60

61
62
63
64
# if GTEST_OS_QNX
#  include <spawn.h>
# endif  // GTEST_OS_QNX

65
#endif  // GTEST_HAS_DEATH_TEST
shiqian's avatar
shiqian committed
66

67
68
#include "gtest/gtest-message.h"
#include "gtest/internal/gtest-string.h"
69
#include "src/gtest-internal-inl.h"
shiqian's avatar
shiqian committed
70
71
72
73
74
75

namespace testing {

// Constants.

// The default death test style.
76
77
78
79
80
//
// This is defined in internal/gtest-port.h as "fast", but can be overridden by
// a definition in internal/custom/gtest-port.h. The recommended value, which is
// used internally at Google, is "threadsafe".
static const char kDefaultDeathTestStyle[] = GTEST_DEFAULT_DEATH_TEST_STYLE;
shiqian's avatar
shiqian committed
81

shiqian's avatar
shiqian committed
82
GTEST_DEFINE_string_(
shiqian's avatar
shiqian committed
83
84
85
86
87
88
89
90
    death_test_style,
    internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
    "Indicates how to run a death test in a forked child process: "
    "\"threadsafe\" (child process re-executes the test binary "
    "from the beginning, running only the specific death test) or "
    "\"fast\" (child process runs the death test immediately "
    "after forking).");

91
92
93
94
GTEST_DEFINE_bool_(
    death_test_use_fork,
    internal::BoolFromGTestEnv("death_test_use_fork", false),
    "Instructs to use fork()/_exit() instead of clone() in death tests. "
95
96
97
    "Ignored and always uses fork() on POSIX systems where clone() is not "
    "implemented. Useful when running under valgrind or similar tools if "
    "those do not support clone(). Valgrind 3.3.1 will just fail if "
98
99
100
101
102
    "it sees an unsupported combination of clone() flags. "
    "It is not recommended to use this flag w/o valgrind though it will "
    "work in 99% of the cases. Once valgrind is fixed, this flag will "
    "most likely be removed.");

shiqian's avatar
shiqian committed
103
namespace internal {
shiqian's avatar
shiqian committed
104
GTEST_DEFINE_string_(
shiqian's avatar
shiqian committed
105
106
107
108
    internal_run_death_test, "",
    "Indicates the file, line number, temporal index of "
    "the single death test to run, and a file descriptor to "
    "which a success code may be sent, all separated by "
109
    "the '|' characters.  This flag is specified if and only if the current "
shiqian's avatar
shiqian committed
110
111
112
113
    "process is a sub-process launched for running a thread-safe "
    "death test.  FOR INTERNAL USE ONLY.");
}  // namespace internal

zhanyong.wan's avatar
zhanyong.wan committed
114
#if GTEST_HAS_DEATH_TEST
shiqian's avatar
shiqian committed
115

116
117
118
119
namespace internal {

// Valid only for fast death tests. Indicates the code is running in the
// child process of a fast style death test.
120
# if !GTEST_OS_WINDOWS
121
static bool g_in_fast_death_test_child = false;
122
# endif
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146

// Returns a Boolean value indicating whether the caller is currently
// executing in the context of the death test child process.  Tools such as
// Valgrind heap checkers may need this to modify their behavior in death
// tests.  IMPORTANT: This is an internal utility.  Using it may break the
// implementation of death tests.  User code MUST NOT use it.
bool InDeathTestChild() {
# if GTEST_OS_WINDOWS

  // On Windows, death tests are thread-safe regardless of the value of the
  // death_test_style flag.
  return !GTEST_FLAG(internal_run_death_test).empty();

# else

  if (GTEST_FLAG(death_test_style) == "threadsafe")
    return !GTEST_FLAG(internal_run_death_test).empty();
  else
    return g_in_fast_death_test_child;
#endif
}

}  // namespace internal

shiqian's avatar
shiqian committed
147
148
149
150
151
152
// ExitedWithCode constructor.
ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
}

// ExitedWithCode function-call operator.
bool ExitedWithCode::operator()(int exit_status) const {
153
154
# if GTEST_OS_WINDOWS

155
  return exit_status == exit_code_;
156
157
158

# else

shiqian's avatar
shiqian committed
159
  return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
160
161

# endif  // GTEST_OS_WINDOWS
shiqian's avatar
shiqian committed
162
163
}

164
# if !GTEST_OS_WINDOWS
shiqian's avatar
shiqian committed
165
166
167
168
169
170
// KilledBySignal constructor.
KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
}

// KilledBySignal function-call operator.
bool KilledBySignal::operator()(int exit_status) const {
171
172
173
174
175
176
177
178
#  if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
  {
    bool result;
    if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
      return result;
    }
  }
#  endif  // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
shiqian's avatar
shiqian committed
179
180
  return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
}
181
# endif  // !GTEST_OS_WINDOWS
shiqian's avatar
shiqian committed
182
183
184
185
186
187
188

namespace internal {

// Utilities needed for death tests.

// Generates a textual description of a given exit code, in the format
// specified by wait(2).
189
static std::string ExitSummary(int exit_code) {
shiqian's avatar
shiqian committed
190
  Message m;
191
192
193

# if GTEST_OS_WINDOWS

194
  m << "Exited with exit status " << exit_code;
195
196
197

# else

shiqian's avatar
shiqian committed
198
199
200
201
202
  if (WIFEXITED(exit_code)) {
    m << "Exited with exit status " << WEXITSTATUS(exit_code);
  } else if (WIFSIGNALED(exit_code)) {
    m << "Terminated by signal " << WTERMSIG(exit_code);
  }
203
#  ifdef WCOREDUMP
shiqian's avatar
shiqian committed
204
205
206
  if (WCOREDUMP(exit_code)) {
    m << " (core dumped)";
  }
207
208
209
#  endif
# endif  // GTEST_OS_WINDOWS

shiqian's avatar
shiqian committed
210
211
212
213
214
215
216
217
218
  return m.GetString();
}

// Returns true if exit_status describes a process that was terminated
// by a signal, or exited normally with a nonzero exit code.
bool ExitedUnsuccessfully(int exit_status) {
  return !ExitedWithCode(0)(exit_status);
}

219
# if !GTEST_OS_WINDOWS
shiqian's avatar
shiqian committed
220
221
222
223
// Generates a textual failure message when a death test finds more than
// one thread running, or cannot determine the number of threads, prior
// to executing the given statement.  It is the responsibility of the
// caller not to pass a thread_count of 1.
224
static std::string DeathTestThreadWarning(size_t thread_count) {
shiqian's avatar
shiqian committed
225
226
  Message msg;
  msg << "Death tests use fork(), which is unsafe particularly"
zhanyong.wan's avatar
zhanyong.wan committed
227
      << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
shiqian's avatar
shiqian committed
228
229
230
231
232
233
  if (thread_count == 0)
    msg << "couldn't detect the number of threads.";
  else
    msg << "detected " << thread_count << " threads.";
  return msg.GetString();
}
234
# endif  // !GTEST_OS_WINDOWS
shiqian's avatar
shiqian committed
235
236
237
238

// Flag characters for reporting a death test that did not die.
static const char kDeathTestLived = 'L';
static const char kDeathTestReturned = 'R';
239
static const char kDeathTestThrew = 'T';
shiqian's avatar
shiqian committed
240
241
static const char kDeathTestInternalError = 'I';

242
243
244
245
246
247
248
249
250
251
// An enumeration describing all of the possible ways that a death test can
// conclude.  DIED means that the process died while executing the test
// code; LIVED means that process lived beyond the end of the test code;
// RETURNED means that the test statement attempted to execute a return
// statement, which is not allowed; THREW means that the test statement
// returned control by throwing an exception.  IN_PROGRESS means the test
// has not yet concluded.
// TODO(vladl@google.com): Unify names and possibly values for
// AbortReason, DeathTestOutcome, and flag characters above.
enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
shiqian's avatar
shiqian committed
252
253

// Routine for aborting the program which is safe to call from an
254
// exec-style death test child process, in which case the error
shiqian's avatar
shiqian committed
255
256
257
// message is propagated back to the parent process.  Otherwise, the
// message is simply printed to stderr.  In either case, the program
// then exits with status 1.
258
static void DeathTestAbort(const std::string& message) {
259
260
261
  // On a POSIX system, this function may be called from a threadsafe-style
  // death test child process, which operates on a very small stack.  Use
  // the heap for any additional non-minuscule memory requirements.
shiqian's avatar
shiqian committed
262
263
264
  const InternalRunDeathTestFlag* const flag =
      GetUnitTestImpl()->internal_run_death_test_flag();
  if (flag != NULL) {
265
    FILE* parent = posix::FDOpen(flag->write_fd(), "w");
shiqian's avatar
shiqian committed
266
    fputc(kDeathTestInternalError, parent);
267
268
    fprintf(parent, "%s", message.c_str());
    fflush(parent);
shiqian's avatar
shiqian committed
269
270
    _exit(1);
  } else {
271
272
    fprintf(stderr, "%s", message.c_str());
    fflush(stderr);
273
    posix::Abort();
shiqian's avatar
shiqian committed
274
275
276
277
278
  }
}

// A replacement for CHECK that calls DeathTestAbort if the assertion
// fails.
279
# define GTEST_DEATH_TEST_CHECK_(expression) \
shiqian's avatar
shiqian committed
280
  do { \
281
    if (!::testing::internal::IsTrue(expression)) { \
282
283
284
285
      DeathTestAbort( \
          ::std::string("CHECK failed: File ") + __FILE__ +  ", line " \
          + ::testing::internal::StreamableToString(__LINE__) + ": " \
          + #expression); \
shiqian's avatar
shiqian committed
286
    } \
287
  } while (::testing::internal::AlwaysFalse())
shiqian's avatar
shiqian committed
288

shiqian's avatar
shiqian committed
289
// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
shiqian's avatar
shiqian committed
290
291
292
293
294
295
// evaluating any system call that fulfills two conditions: it must return
// -1 on failure, and set errno to EINTR when it is interrupted and
// should be tried again.  The macro expands to a loop that repeatedly
// evaluates the expression as long as it evaluates to -1 and sets
// errno to EINTR.  If the expression evaluates to -1 but errno is
// something other than EINTR, DeathTestAbort is called.
296
# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
shiqian's avatar
shiqian committed
297
  do { \
298
    int gtest_retval; \
shiqian's avatar
shiqian committed
299
    do { \
300
301
302
      gtest_retval = (expression); \
    } while (gtest_retval == -1 && errno == EINTR); \
    if (gtest_retval == -1) { \
303
304
305
306
      DeathTestAbort( \
          ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
          + ::testing::internal::StreamableToString(__LINE__) + ": " \
          + #expression + " != -1"); \
shiqian's avatar
shiqian committed
307
    } \
308
  } while (::testing::internal::AlwaysFalse())
shiqian's avatar
shiqian committed
309

310
// Returns the message describing the last system error in errno.
311
312
std::string GetLastErrnoDescription() {
    return errno == 0 ? "" : posix::StrError(errno);
313
314
}

315
316
317
318
319
320
321
322
323
324
// This is called from a death test parent process to read a failure
// message from the death test child process and log it with the FATAL
// severity. On Windows, the message is read from a pipe handle. On other
// platforms, it is read from a file descriptor.
static void FailFromInternalError(int fd) {
  Message error;
  char buffer[256];
  int num_read;

  do {
325
    while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
326
327
328
329
330
331
      buffer[num_read] = '\0';
      error << buffer;
    }
  } while (num_read == -1 && errno == EINTR);

  if (num_read == 0) {
332
    GTEST_LOG_(FATAL) << error.GetString();
333
334
  } else {
    const int last_error = errno;
335
    GTEST_LOG_(FATAL) << "Error while reading death test internal: "
336
                      << GetLastErrnoDescription() << " [" << last_error << "]";
337
338
  }
}
339

shiqian's avatar
shiqian committed
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
// Death test constructor.  Increments the running death test count
// for the current test.
DeathTest::DeathTest() {
  TestInfo* const info = GetUnitTestImpl()->current_test_info();
  if (info == NULL) {
    DeathTestAbort("Cannot run a death test outside of a TEST or "
                   "TEST_F construct");
  }
}

// Creates and returns a death test by dispatching to the current
// death test factory.
bool DeathTest::Create(const char* statement, const RE* regex,
                       const char* file, int line, DeathTest** test) {
  return GetUnitTestImpl()->death_test_factory()->Create(
      statement, regex, file, line, test);
}

const char* DeathTest::LastMessage() {
359
360
361
  return last_death_test_message_.c_str();
}

362
void DeathTest::set_last_death_test_message(const std::string& message) {
363
  last_death_test_message_ = message;
shiqian's avatar
shiqian committed
364
365
}

366
std::string DeathTest::last_death_test_message_;
367
368
369
370

// Provides cross platform implementation for some death functionality.
class DeathTestImpl : public DeathTest {
 protected:
371
372
373
  DeathTestImpl(const char* a_statement, const RE* a_regex)
      : statement_(a_statement),
        regex_(a_regex),
374
375
        spawned_(false),
        status_(-1),
376
377
378
        outcome_(IN_PROGRESS),
        read_fd_(-1),
        write_fd_(-1) {}
379

380
381
382
383
  // read_fd_ is expected to be closed and cleared by a derived class.
  ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }

  void Abort(AbortReason reason);
384
385
386
387
388
  virtual bool Passed(bool status_ok);

  const char* statement() const { return statement_; }
  const RE* regex() const { return regex_; }
  bool spawned() const { return spawned_; }
389
  void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
390
  int status() const { return status_; }
391
  void set_status(int a_status) { status_ = a_status; }
392
  DeathTestOutcome outcome() const { return outcome_; }
393
  void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
394
395
396
397
398
399
400
401
402
403
  int read_fd() const { return read_fd_; }
  void set_read_fd(int fd) { read_fd_ = fd; }
  int write_fd() const { return write_fd_; }
  void set_write_fd(int fd) { write_fd_ = fd; }

  // Called in the parent process only. Reads the result code of the death
  // test child process via a pipe, interprets it to set the outcome_
  // member, and closes read_fd_.  Outputs diagnostics and terminates in
  // case of unexpected codes.
  void ReadAndInterpretStatusByte();
404
405
406
407
408
409
410
411
412
413
414
415
416
417

 private:
  // The textual content of the code this object is testing.  This class
  // doesn't own this string and should not attempt to delete it.
  const char* const statement_;
  // The regular expression which test output must match.  DeathTestImpl
  // doesn't own this object and should not attempt to delete it.
  const RE* const regex_;
  // True if the death test child process has been successfully spawned.
  bool spawned_;
  // The exit status of the child process.
  int status_;
  // How the death test concluded.
  DeathTestOutcome outcome_;
418
419
420
421
422
423
424
425
  // Descriptor to the read end of the pipe to the child process.  It is
  // always -1 in the child process.  The child keeps its write end of the
  // pipe in write_fd_.
  int read_fd_;
  // Descriptor to the child's write end of the pipe to the parent process.
  // It is always -1 in the parent process.  The parent keeps its end of the
  // pipe in read_fd_.
  int write_fd_;
426
427
};

428
429
430
431
432
433
434
435
436
437
438
439
440
// Called in the parent process only. Reads the result code of the death
// test child process via a pipe, interprets it to set the outcome_
// member, and closes read_fd_.  Outputs diagnostics and terminates in
// case of unexpected codes.
void DeathTestImpl::ReadAndInterpretStatusByte() {
  char flag;
  int bytes_read;

  // The read() here blocks until data is available (signifying the
  // failure of the death test) or until the pipe is closed (signifying
  // its success), so it's okay to call this in the parent before
  // the child process has exited.
  do {
441
    bytes_read = posix::Read(read_fd(), &flag, 1);
442
443
444
445
446
447
448
449
450
  } while (bytes_read == -1 && errno == EINTR);

  if (bytes_read == 0) {
    set_outcome(DIED);
  } else if (bytes_read == 1) {
    switch (flag) {
      case kDeathTestReturned:
        set_outcome(RETURNED);
        break;
451
452
453
      case kDeathTestThrew:
        set_outcome(THREW);
        break;
454
455
456
457
458
459
460
      case kDeathTestLived:
        set_outcome(LIVED);
        break;
      case kDeathTestInternalError:
        FailFromInternalError(read_fd());  // Does not return.
        break;
      default:
461
462
463
        GTEST_LOG_(FATAL) << "Death test child process reported "
                          << "unexpected status byte ("
                          << static_cast<unsigned int>(flag) << ")";
464
465
    }
  } else {
466
    GTEST_LOG_(FATAL) << "Read from death test child process failed: "
467
                      << GetLastErrnoDescription();
468
  }
469
  GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
470
471
472
473
474
475
476
477
478
479
480
481
  set_read_fd(-1);
}

// Signals that the death test code which should have exited, didn't.
// Should be called only in a death test child process.
// Writes a status byte to the child's status file descriptor, then
// calls _exit(1).
void DeathTestImpl::Abort(AbortReason reason) {
  // The parent process considers the death test to be a failure if
  // it finds any data in our pipe.  So, here we write a single flag byte
  // to the pipe, then exit.
  const char status_ch =
482
483
484
      reason == TEST_DID_NOT_DIE ? kDeathTestLived :
      reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;

485
  GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
486
487
488
489
490
491
492
493
  // We are leaking the descriptor here because on some platforms (i.e.,
  // when built as Windows DLL), destructors of global objects will still
  // run after calling _exit(). On such systems, write_fd_ will be
  // indirectly closed from the destructor of UnitTestImpl, causing double
  // close if it is also closed here. On debug configurations, double close
  // may assert. As there are no in-process buffers to flush here, we are
  // relying on the OS to close the descriptor after the process terminates
  // when the destructors are not run.
494
495
496
  _exit(1);  // Exits w/o any normal exit hooks (we were supposed to crash)
}

497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
// Returns an indented copy of stderr output for a death test.
// This makes distinguishing death test output lines from regular log lines
// much easier.
static ::std::string FormatDeathTestOutput(const ::std::string& output) {
  ::std::string ret;
  for (size_t at = 0; ; ) {
    const size_t line_end = output.find('\n', at);
    ret += "[  DEATH   ] ";
    if (line_end == ::std::string::npos) {
      ret += output.substr(at);
      break;
    }
    ret += output.substr(at, line_end + 1 - at);
    at = line_end + 1;
  }
  return ret;
}

515
516
517
518
519
// Assesses the success or failure of a death test, using both private
// members which have previously been set, and one argument:
//
// Private data members:
//   outcome:  An enumeration describing how the death test
520
521
//             concluded: DIED, LIVED, THREW, or RETURNED.  The death test
//             fails in the latter three cases.
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//   status:   The exit status of the child process. On *nix, it is in the
//             in the format specified by wait(2). On Windows, this is the
//             value supplied to the ExitProcess() API or a numeric code
//             of the exception that terminated the program.
//   regex:    A regular expression object to be applied to
//             the test's captured standard error output; the death test
//             fails if it does not match.
//
// Argument:
//   status_ok: true if exit_status is acceptable in the context of
//              this particular death test, which fails if it is false
//
// Returns true iff all of the above conditions are met.  Otherwise, the
// first failing condition, in the order given above, is the one that is
// reported. Also sets the last death test message string.
bool DeathTestImpl::Passed(bool status_ok) {
  if (!spawned())
    return false;

541
  const std::string error_message = GetCapturedStderr();
542
543
544
545
546
547
548
549

  bool success = false;
  Message buffer;

  buffer << "Death test: " << statement() << "\n";
  switch (outcome()) {
    case LIVED:
      buffer << "    Result: failed to die.\n"
550
             << " Error msg:\n" << FormatDeathTestOutput(error_message);
551
      break;
552
553
    case THREW:
      buffer << "    Result: threw an exception.\n"
554
             << " Error msg:\n" << FormatDeathTestOutput(error_message);
555
      break;
556
557
    case RETURNED:
      buffer << "    Result: illegal return in test statement.\n"
558
             << " Error msg:\n" << FormatDeathTestOutput(error_message);
559
560
561
      break;
    case DIED:
      if (status_ok) {
Gennadiy Civil's avatar
merges  
Gennadiy Civil committed
562
563
564
565
566
# if GTEST_USES_PCRE
        // PCRE regexes support embedded NULs.
        // GTEST_USES_PCRE is defined only in google3 mode
        const bool matched = RE::PartialMatch(error_message, *regex());
# else
567
        const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
Gennadiy Civil's avatar
merges  
Gennadiy Civil committed
568
# endif  // GTEST_USES_PCRE
569
        if (matched) {
570
571
572
573
          success = true;
        } else {
          buffer << "    Result: died but not with expected error.\n"
                 << "  Expected: " << regex()->pattern() << "\n"
574
                 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
575
576
577
        }
      } else {
        buffer << "    Result: died but not with expected exit code:\n"
578
579
               << "            " << ExitSummary(status()) << "\n"
               << "Actual msg:\n" << FormatDeathTestOutput(error_message);
580
581
582
583
      }
      break;
    case IN_PROGRESS:
    default:
584
585
      GTEST_LOG_(FATAL)
          << "DeathTest::Passed somehow called before conclusion of test";
586
587
588
589
590
  }

  DeathTest::set_last_death_test_message(buffer.GetString());
  return success;
}
591

592
# if GTEST_OS_WINDOWS
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
// WindowsDeathTest implements death tests on Windows. Due to the
// specifics of starting new processes on Windows, death tests there are
// always threadsafe, and Google Test considers the
// --gtest_death_test_style=fast setting to be equivalent to
// --gtest_death_test_style=threadsafe there.
//
// A few implementation notes:  Like the Linux version, the Windows
// implementation uses pipes for child-to-parent communication. But due to
// the specifics of pipes on Windows, some extra steps are required:
//
// 1. The parent creates a communication pipe and stores handles to both
//    ends of it.
// 2. The parent starts the child and provides it with the information
//    necessary to acquire the handle to the write end of the pipe.
// 3. The child acquires the write end of the pipe and signals the parent
//    using a Windows event.
// 4. Now the parent can release the write end of the pipe on its side. If
//    this is done before step 3, the object's reference count goes down to
//    0 and it is destroyed, preventing the child from acquiring it. The
//    parent now has to release it, or read operations on the read end of
//    the pipe will not return when the child terminates.
// 5. The parent reads child's output through the pipe (outcome code and
//    any possible error messages) from the pipe, and its stderr and then
//    determines whether to fail the test.
//
// Note: to distinguish Win32 API calls from the local method and function
// calls, the former are explicitly resolved in the global namespace.
//
class WindowsDeathTest : public DeathTestImpl {
 public:
623
624
  WindowsDeathTest(const char* a_statement,
                   const RE* a_regex,
625
626
                   const char* file,
                   int line)
627
      : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674

  // All of these virtual functions are inherited from DeathTest.
  virtual int Wait();
  virtual TestRole AssumeRole();

 private:
  // The name of the file in which the death test is located.
  const char* const file_;
  // The line number on which the death test is located.
  const int line_;
  // Handle to the write end of the pipe to the child process.
  AutoHandle write_handle_;
  // Child process handle.
  AutoHandle child_handle_;
  // Event the child process uses to signal the parent that it has
  // acquired the handle to the write end of the pipe. After seeing this
  // event the parent can release its own handles to make sure its
  // ReadFile() calls return when the child terminates.
  AutoHandle event_handle_;
};

// Waits for the child in a death test to exit, returning its exit
// status, or 0 if no child process exists.  As a side effect, sets the
// outcome data member.
int WindowsDeathTest::Wait() {
  if (!spawned())
    return 0;

  // Wait until the child either signals that it has acquired the write end
  // of the pipe or it dies.
  const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
  switch (::WaitForMultipleObjects(2,
                                   wait_handles,
                                   FALSE,  // Waits for any of the handles.
                                   INFINITE)) {
    case WAIT_OBJECT_0:
    case WAIT_OBJECT_0 + 1:
      break;
    default:
      GTEST_DEATH_TEST_CHECK_(false);  // Should not get here.
  }

  // The child has acquired the write end of the pipe or exited.
  // We release the handle on our side and continue.
  write_handle_.Reset();
  event_handle_.Reset();

675
  ReadAndInterpretStatusByte();
676
677
678
679
680
681
682
683

  // Waits for the child process to exit if it haven't already. This
  // returns immediately if the child has already exited, regardless of
  // whether previous calls to WaitForMultipleObjects synchronized on this
  // handle or not.
  GTEST_DEATH_TEST_CHECK_(
      WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
                                             INFINITE));
684
685
686
  DWORD status_code;
  GTEST_DEATH_TEST_CHECK_(
      ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
687
  child_handle_.Reset();
688
689
  set_status(static_cast<int>(status_code));
  return status();
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
}

// The AssumeRole process for a Windows death test.  It creates a child
// process with the same executable as the current process to run the
// death test.  The child process is given the --gtest_filter and
// --gtest_internal_run_death_test flags such that it knows to run the
// current death test only.
DeathTest::TestRole WindowsDeathTest::AssumeRole() {
  const UnitTestImpl* const impl = GetUnitTestImpl();
  const InternalRunDeathTestFlag* const flag =
      impl->internal_run_death_test_flag();
  const TestInfo* const info = impl->current_test_info();
  const int death_test_index = info->result()->death_test_count();

  if (flag != NULL) {
    // ParseInternalRunDeathTestFlag() has performed all the necessary
    // processing.
707
    set_write_fd(flag->write_fd());
708
709
710
711
712
713
714
715
    return EXECUTE_TEST;
  }

  // WindowsDeathTest uses an anonymous pipe to communicate results of
  // a death test.
  SECURITY_ATTRIBUTES handles_are_inheritable = {
    sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
  HANDLE read_handle, write_handle;
716
717
718
719
  GTEST_DEATH_TEST_CHECK_(
      ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
                   0)  // Default buffer size.
      != FALSE);
720
721
  set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
                                O_RDONLY));
722
723
724
725
726
727
728
  write_handle_.Reset(write_handle);
  event_handle_.Reset(::CreateEvent(
      &handles_are_inheritable,
      TRUE,    // The event will automatically reset to non-signaled state.
      FALSE,   // The initial state is non-signalled.
      NULL));  // The even is unnamed.
  GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
729
730
731
732
733
  const std::string filter_flag =
      std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
      info->test_case_name() + "." + info->name();
  const std::string internal_flag =
      std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
734
735
736
737
      "=" + file_ + "|" + StreamableToString(line_) + "|" +
      StreamableToString(death_test_index) + "|" +
      StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
      // size_t has the same width as pointers on both 32-bit and 64-bit
738
739
      // Windows platforms.
      // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
740
741
      "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
      "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
742
743
744
745
746
747
748

  char executable_path[_MAX_PATH + 1];  // NOLINT
  GTEST_DEATH_TEST_CHECK_(
      _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
                                            executable_path,
                                            _MAX_PATH));

749
750
751
  std::string command_line =
      std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
      internal_flag + "\"";
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777

  DeathTest::set_last_death_test_message("");

  CaptureStderr();
  // Flush the log buffers since the log streams are shared with the child.
  FlushInfoLog();

  // The child process will share the standard handles with the parent.
  STARTUPINFOA startup_info;
  memset(&startup_info, 0, sizeof(STARTUPINFO));
  startup_info.dwFlags = STARTF_USESTDHANDLES;
  startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
  startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
  startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);

  PROCESS_INFORMATION process_info;
  GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
      executable_path,
      const_cast<char*>(command_line.c_str()),
      NULL,   // Retuned process handle is not inheritable.
      NULL,   // Retuned thread handle is not inheritable.
      TRUE,   // Child inherits all inheritable handles (for write_handle_).
      0x0,    // Default creation flags.
      NULL,   // Inherit the parent's environment.
      UnitTest::GetInstance()->original_working_dir(),
      &startup_info,
778
      &process_info) != FALSE);
779
780
781
782
783
  child_handle_.Reset(process_info.hProcess);
  ::CloseHandle(process_info.hThread);
  set_spawned(true);
  return OVERSEE_TEST;
}
784
# else  // We are not on Windows.
785

shiqian's avatar
shiqian committed
786
787
788
// ForkingDeathTest provides implementations for most of the abstract
// methods of the DeathTest interface.  Only the AssumeRole method is
// left undefined.
789
class ForkingDeathTest : public DeathTestImpl {
shiqian's avatar
shiqian committed
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
 public:
  ForkingDeathTest(const char* statement, const RE* regex);

  // All of these virtual functions are inherited from DeathTest.
  virtual int Wait();

 protected:
  void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }

 private:
  // PID of child process during death test; 0 in the child process itself.
  pid_t child_pid_;
};

// Constructs a ForkingDeathTest.
805
806
ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
    : DeathTestImpl(a_statement, a_regex),
807
      child_pid_(-1) {}
shiqian's avatar
shiqian committed
808
809
810
811
812

// Waits for the child in a death test to exit, returning its exit
// status, or 0 if no child process exists.  As a side effect, sets the
// outcome data member.
int ForkingDeathTest::Wait() {
813
  if (!spawned())
shiqian's avatar
shiqian committed
814
815
    return 0;

816
  ReadAndInterpretStatusByte();
shiqian's avatar
shiqian committed
817

818
819
820
821
  int status_value;
  GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
  set_status(status_value);
  return status_value;
shiqian's avatar
shiqian committed
822
823
824
825
826
827
}

// A concrete death test class that forks, then immediately runs the test
// in the child process.
class NoExecDeathTest : public ForkingDeathTest {
 public:
828
829
  NoExecDeathTest(const char* a_statement, const RE* a_regex) :
      ForkingDeathTest(a_statement, a_regex) { }
shiqian's avatar
shiqian committed
830
831
832
833
834
835
836
837
  virtual TestRole AssumeRole();
};

// The AssumeRole process for a fork-and-run death test.  It implements a
// straightforward fork, with a simple pipe to transmit the status byte.
DeathTest::TestRole NoExecDeathTest::AssumeRole() {
  const size_t thread_count = GetThreadCount();
  if (thread_count != 1) {
838
    GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
shiqian's avatar
shiqian committed
839
840
841
  }

  int pipe_fd[2];
shiqian's avatar
shiqian committed
842
  GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
shiqian's avatar
shiqian committed
843

844
  DeathTest::set_last_death_test_message("");
shiqian's avatar
shiqian committed
845
846
847
848
849
850
851
852
853
854
855
  CaptureStderr();
  // When we fork the process below, the log file buffers are copied, but the
  // file descriptors are shared.  We flush all log files here so that closing
  // the file descriptors in the child process doesn't throw off the
  // synchronization between descriptors and buffers in the parent process.
  // This is as close to the fork as possible to avoid a race condition in case
  // there are multiple threads running before the death test, and another
  // thread writes to the log file.
  FlushInfoLog();

  const pid_t child_pid = fork();
shiqian's avatar
shiqian committed
856
  GTEST_DEATH_TEST_CHECK_(child_pid != -1);
shiqian's avatar
shiqian committed
857
858
  set_child_pid(child_pid);
  if (child_pid == 0) {
shiqian's avatar
shiqian committed
859
    GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
shiqian's avatar
shiqian committed
860
861
862
863
864
    set_write_fd(pipe_fd[1]);
    // Redirects all logging to stderr in the child process to prevent
    // concurrent writes to the log files.  We capture stderr in the parent
    // process and append the child process' output to a log.
    LogToStderr();
865
866
867
    // Event forwarding to the listeners of event listener API mush be shut
    // down in death test subprocesses.
    GetUnitTestImpl()->listeners()->SuppressEventForwarding();
868
    g_in_fast_death_test_child = true;
shiqian's avatar
shiqian committed
869
870
    return EXECUTE_TEST;
  } else {
shiqian's avatar
shiqian committed
871
    GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
shiqian's avatar
shiqian committed
872
    set_read_fd(pipe_fd[0]);
873
    set_spawned(true);
shiqian's avatar
shiqian committed
874
875
876
877
878
879
880
881
882
    return OVERSEE_TEST;
  }
}

// A concrete death test class that forks and re-executes the main
// program from the beginning, with command-line flags set that cause
// only this specific death test to be run.
class ExecDeathTest : public ForkingDeathTest {
 public:
883
  ExecDeathTest(const char* a_statement, const RE* a_regex,
shiqian's avatar
shiqian committed
884
                const char* file, int line) :
885
      ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
shiqian's avatar
shiqian committed
886
887
  virtual TestRole AssumeRole();
 private:
888
889
  static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {
    ::std::vector<std::string> args = GetInjectableArgvs();
890
#  if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
891
    ::std::vector<std::string> extra_args =
892
893
894
        GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
    args.insert(args.end(), extra_args.begin(), extra_args.end());
#  endif  // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
895
896
    return args;
  }
shiqian's avatar
shiqian committed
897
898
899
900
901
902
903
904
905
906
907
908
  // The name of the file in which the death test is located.
  const char* const file_;
  // The line number on which the death test is located.
  const int line_;
};

// Utility class for accumulating command-line arguments.
class Arguments {
 public:
  Arguments() {
    args_.push_back(NULL);
  }
909

shiqian's avatar
shiqian committed
910
  ~Arguments() {
911
    for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
shiqian's avatar
shiqian committed
912
913
914
915
916
         ++i) {
      free(*i);
    }
  }
  void AddArgument(const char* argument) {
917
    args_.insert(args_.end() - 1, posix::StrDup(argument));
shiqian's avatar
shiqian committed
918
919
920
921
922
923
924
  }

  template <typename Str>
  void AddArguments(const ::std::vector<Str>& arguments) {
    for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
         i != arguments.end();
         ++i) {
925
      args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
shiqian's avatar
shiqian committed
926
927
928
929
930
    }
  }
  char* const* Argv() {
    return &args_[0];
  }
931

shiqian's avatar
shiqian committed
932
933
934
935
936
937
938
939
940
941
942
 private:
  std::vector<char*> args_;
};

// A struct that encompasses the arguments to the child process of a
// threadsafe-style death test process.
struct ExecDeathTestArgs {
  char* const* argv;  // Command-line arguments for the child's call to exec
  int close_fd;       // File descriptor to close; the read end of a pipe
};

943
#  if GTEST_OS_MAC
944
945
946
947
948
949
inline char** GetEnviron() {
  // When Google Test is built as a framework on MacOS X, the environ variable
  // is unavailable. Apple's documentation (man environ) recommends using
  // _NSGetEnviron() instead.
  return *_NSGetEnviron();
}
950
#  else
951
952
953
954
// Some POSIX platforms expect you to declare environ. extern "C" makes
// it reside in the global namespace.
extern "C" char** environ;
inline char** GetEnviron() { return environ; }
955
#  endif  // GTEST_OS_MAC
956

957
#  if !GTEST_OS_QNX
shiqian's avatar
shiqian committed
958
// The main function for a threadsafe-style death test child process.
959
960
// This function is called in a clone()-ed process and thus must avoid
// any potentially unsafe operations like malloc or libc functions.
shiqian's avatar
shiqian committed
961
962
static int ExecDeathTestChildMain(void* child_arg) {
  ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
shiqian's avatar
shiqian committed
963
  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
964
965
966
967
968
969
970
971

  // We need to execute the test program in the same environment where
  // it was originally invoked.  Therefore we change to the original
  // working directory first.
  const char* const original_dir =
      UnitTest::GetInstance()->original_working_dir();
  // We can safely call chdir() as it's a direct system call.
  if (chdir(original_dir) != 0) {
972
973
    DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
                   GetLastErrnoDescription());
974
975
976
977
978
979
980
981
    return EXIT_FAILURE;
  }

  // We can safely call execve() as it's a direct system call.  We
  // cannot use execvp() as it's a libc function and thus potentially
  // unsafe.  Since execve() doesn't search the PATH, the user must
  // invoke the test program via a valid path that contains at least
  // one path separator.
982
  execve(args->argv[0], args->argv, GetEnviron());
983
984
985
  DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
                 original_dir + " failed: " +
                 GetLastErrnoDescription());
shiqian's avatar
shiqian committed
986
987
  return EXIT_FAILURE;
}
988
#  endif  // !GTEST_OS_QNX
shiqian's avatar
shiqian committed
989

990
#  if GTEST_HAS_CLONE
shiqian's avatar
shiqian committed
991
992
993
994
995
// Two utility routines that together determine the direction the stack
// grows.
// This could be accomplished more elegantly by a single recursive
// function, but we want to guard against the unlikely possibility of
// a smart compiler optimizing the recursion away.
996
997
998
999
//
// GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
// StackLowerThanAddress into StackGrowsDown, which then doesn't give
// correct answer.
1000
1001
1002
static void StackLowerThanAddress(const void* ptr,
                                  bool* result) GTEST_NO_INLINE_;
static void StackLowerThanAddress(const void* ptr, bool* result) {
shiqian's avatar
shiqian committed
1003
  int dummy;
1004
  *result = (&dummy < ptr);
shiqian's avatar
shiqian committed
1005
1006
}

1007
1008
// Make sure AddressSanitizer does not tamper with the stack here.
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
1009
static bool StackGrowsDown() {
shiqian's avatar
shiqian committed
1010
  int dummy;
1011
1012
1013
  bool result;
  StackLowerThanAddress(&dummy, &result);
  return result;
shiqian's avatar
shiqian committed
1014
}
1015
#  endif  // GTEST_HAS_CLONE
shiqian's avatar
shiqian committed
1016

1017
1018
1019
1020
1021
1022
1023
1024
// Spawns a child process with the same executable as the current process in
// a thread-safe manner and instructs it to run the death test.  The
// implementation uses fork(2) + exec.  On systems where clone(2) is
// available, it is used instead, being slightly more thread-safe.  On QNX,
// fork supports only single-threaded environments, so this function uses
// spawn(2) there instead.  The function dies with an error message if
// anything goes wrong.
static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
shiqian's avatar
shiqian committed
1025
  ExecDeathTestArgs args = { argv, close_fd };
1026
  pid_t child_pid = -1;
1027

1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
#  if GTEST_OS_QNX
  // Obtains the current directory and sets it to be closed in the child
  // process.
  const int cwd_fd = open(".", O_RDONLY);
  GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
  GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
  // We need to execute the test program in the same environment where
  // it was originally invoked.  Therefore we change to the original
  // working directory first.
  const char* const original_dir =
      UnitTest::GetInstance()->original_working_dir();
  // We can safely call chdir() as it's a direct system call.
  if (chdir(original_dir) != 0) {
1041
1042
    DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
                   GetLastErrnoDescription());
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
    return EXIT_FAILURE;
  }

  int fd_flags;
  // Set close_fd to be closed after spawn.
  GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
  GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
                                        fd_flags | FD_CLOEXEC));
  struct inheritance inherit = {0};
  // spawn is a system call.
  child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
  // Restores the current working directory.
  GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));

#  else   // GTEST_OS_QNX
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
#   if GTEST_OS_LINUX
  // When a SIGPROF signal is received while fork() or clone() are executing,
  // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
  // it after the call to fork()/clone() is complete.
  struct sigaction saved_sigprof_action;
  struct sigaction ignore_sigprof_action;
  memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
  sigemptyset(&ignore_sigprof_action.sa_mask);
  ignore_sigprof_action.sa_handler = SIG_IGN;
  GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
      SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
#   endif  // GTEST_OS_LINUX
1071
1072

#   if GTEST_HAS_CLONE
1073
1074
1075
1076
1077
1078
1079
1080
1081
  const bool use_fork = GTEST_FLAG(death_test_use_fork);

  if (!use_fork) {
    static const bool stack_grows_down = StackGrowsDown();
    const size_t stack_size = getpagesize();
    // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
    void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
                             MAP_ANON | MAP_PRIVATE, -1, 0);
    GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
1082
1083
1084
1085
1086
1087
1088
1089

    // Maximum stack alignment in bytes:  For a downward-growing stack, this
    // amount is subtracted from size of the stack space to get an address
    // that is within the stack space and is aligned on all systems we care
    // about.  As far as I know there is no ABI with stack alignment greater
    // than 64.  We assume stack and stack_size already have alignment of
    // kMaxStackAlignment.
    const size_t kMaxStackAlignment = 64;
1090
    void* const stack_top =
1091
1092
1093
1094
        static_cast<char*>(stack) +
            (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
    GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
        reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
1095
1096
1097
1098
1099

    child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);

    GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
  }
1100
#   else
1101
  const bool use_fork = true;
1102
#   endif  // GTEST_HAS_CLONE
1103
1104

  if (use_fork && (child_pid = fork()) == 0) {
1105
1106
1107
      ExecDeathTestChildMain(&args);
      _exit(0);
  }
1108
#  endif  // GTEST_OS_QNX
1109
1110
1111
1112
#  if GTEST_OS_LINUX
  GTEST_DEATH_TEST_CHECK_SYSCALL_(
      sigaction(SIGPROF, &saved_sigprof_action, NULL));
#  endif  // GTEST_OS_LINUX
1113

shiqian's avatar
shiqian committed
1114
  GTEST_DEATH_TEST_CHECK_(child_pid != -1);
shiqian's avatar
shiqian committed
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
  return child_pid;
}

// The AssumeRole process for a fork-and-exec death test.  It re-executes the
// main program from the beginning, setting the --gtest_filter
// and --gtest_internal_run_death_test flags to cause only the current
// death test to be re-run.
DeathTest::TestRole ExecDeathTest::AssumeRole() {
  const UnitTestImpl* const impl = GetUnitTestImpl();
  const InternalRunDeathTestFlag* const flag =
      impl->internal_run_death_test_flag();
  const TestInfo* const info = impl->current_test_info();
  const int death_test_index = info->result()->death_test_count();

  if (flag != NULL) {
1130
    set_write_fd(flag->write_fd());
shiqian's avatar
shiqian committed
1131
1132
1133
1134
    return EXECUTE_TEST;
  }

  int pipe_fd[2];
shiqian's avatar
shiqian committed
1135
  GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
shiqian's avatar
shiqian committed
1136
1137
  // Clear the close-on-exec flag on the write end of the pipe, lest
  // it be closed when the child process does an exec:
shiqian's avatar
shiqian committed
1138
  GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
shiqian's avatar
shiqian committed
1139

1140
  const std::string filter_flag =
1141
1142
      std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
      + info->test_case_name() + "." + info->name();
1143
  const std::string internal_flag =
1144
1145
1146
1147
      std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
      + file_ + "|" + StreamableToString(line_) + "|"
      + StreamableToString(death_test_index) + "|"
      + StreamableToString(pipe_fd[1]);
shiqian's avatar
shiqian committed
1148
  Arguments args;
1149
  args.AddArguments(GetArgvsForDeathTestChildProcess());
shiqian's avatar
shiqian committed
1150
1151
1152
  args.AddArgument(filter_flag.c_str());
  args.AddArgument(internal_flag.c_str());

1153
  DeathTest::set_last_death_test_message("");
shiqian's avatar
shiqian committed
1154
1155
1156
1157
1158
1159

  CaptureStderr();
  // See the comment in NoExecDeathTest::AssumeRole for why the next line
  // is necessary.
  FlushInfoLog();

1160
  const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
shiqian's avatar
shiqian committed
1161
  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
shiqian's avatar
shiqian committed
1162
1163
  set_child_pid(child_pid);
  set_read_fd(pipe_fd[0]);
1164
  set_spawned(true);
shiqian's avatar
shiqian committed
1165
1166
1167
  return OVERSEE_TEST;
}

1168
# endif  // !GTEST_OS_WINDOWS
1169

shiqian's avatar
shiqian committed
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
// Creates a concrete DeathTest-derived class that depends on the
// --gtest_death_test_style flag, and sets the pointer pointed to
// by the "test" argument to its address.  If the test should be
// skipped, sets that pointer to NULL.  Returns true, unless the
// flag is set to an invalid value.
bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
                                     const char* file, int line,
                                     DeathTest** test) {
  UnitTestImpl* const impl = GetUnitTestImpl();
  const InternalRunDeathTestFlag* const flag =
      impl->internal_run_death_test_flag();
  const int death_test_index = impl->current_test_info()
      ->increment_death_test_count();

  if (flag != NULL) {
1185
    if (death_test_index > flag->index()) {
1186
1187
1188
1189
      DeathTest::set_last_death_test_message(
          "Death test count (" + StreamableToString(death_test_index)
          + ") somehow exceeded expected maximum ("
          + StreamableToString(flag->index()) + ")");
shiqian's avatar
shiqian committed
1190
1191
1192
      return false;
    }

1193
1194
    if (!(flag->file() == file && flag->line() == line &&
          flag->index() == death_test_index)) {
shiqian's avatar
shiqian committed
1195
1196
1197
1198
1199
      *test = NULL;
      return true;
    }
  }

1200
1201
# if GTEST_OS_WINDOWS

1202
1203
1204
1205
  if (GTEST_FLAG(death_test_style) == "threadsafe" ||
      GTEST_FLAG(death_test_style) == "fast") {
    *test = new WindowsDeathTest(statement, regex, file, line);
  }
1206
1207
1208

# else

shiqian's avatar
shiqian committed
1209
1210
1211
1212
  if (GTEST_FLAG(death_test_style) == "threadsafe") {
    *test = new ExecDeathTest(statement, regex, file, line);
  } else if (GTEST_FLAG(death_test_style) == "fast") {
    *test = new NoExecDeathTest(statement, regex);
1213
  }
1214
1215
1216

# endif  // GTEST_OS_WINDOWS

1217
  else {  // NOLINT - this is more readable than unbalanced brackets inside #if.
1218
1219
1220
    DeathTest::set_last_death_test_message(
        "Unknown death test style \"" + GTEST_FLAG(death_test_style)
        + "\" encountered");
shiqian's avatar
shiqian committed
1221
1222
1223
1224
1225
1226
    return false;
  }

  return true;
}

1227
# if GTEST_OS_WINDOWS
1228
1229
1230
// Recreates the pipe and event handles from the provided parameters,
// signals the event, and returns a file descriptor wrapped around the pipe
// handle. This function is called in the child process only.
1231
static int GetStatusFileDescriptor(unsigned int parent_process_id,
Gennadiy Civil's avatar
Gennadiy Civil committed
1232
1233
                            size_t write_handle_as_size_t,
                            size_t event_handle_as_size_t) {
1234
  AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
Gennadiy Civil's avatar
Gennadiy Civil committed
1235
1236
                                                   FALSE,  // Non-inheritable.
                                                   parent_process_id));
1237
  if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
1238
1239
    DeathTestAbort("Unable to open parent process " +
                   StreamableToString(parent_process_id));
shiqian's avatar
shiqian committed
1240
  }
1241
1242
1243
1244
1245

  // TODO(vladl@google.com): Replace the following check with a
  // compile-time assertion when available.
  GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));

1246
1247
1248
  const HANDLE write_handle =
      reinterpret_cast<HANDLE>(write_handle_as_size_t);
  HANDLE dup_write_handle;
1249

Li Peng's avatar
Li Peng committed
1250
  // The newly initialized handle is accessible only in the parent
1251
1252
  // process. To obtain one accessible within the child, we need to use
  // DuplicateHandle.
1253
1254
  if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
                         ::GetCurrentProcess(), &dup_write_handle,
1255
1256
1257
1258
                         0x0,    // Requested privileges ignored since
                                 // DUPLICATE_SAME_ACCESS is used.
                         FALSE,  // Request non-inheritable handler.
                         DUPLICATE_SAME_ACCESS)) {
1259
1260
1261
1262
    DeathTestAbort("Unable to duplicate the pipe handle " +
                   StreamableToString(write_handle_as_size_t) +
                   " from the parent process " +
                   StreamableToString(parent_process_id));
shiqian's avatar
shiqian committed
1263
  }
1264
1265
1266
1267
1268
1269
1270
1271
1272

  const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
  HANDLE dup_event_handle;

  if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
                         ::GetCurrentProcess(), &dup_event_handle,
                         0x0,
                         FALSE,
                         DUPLICATE_SAME_ACCESS)) {
1273
1274
1275
1276
    DeathTestAbort("Unable to duplicate the event handle " +
                   StreamableToString(event_handle_as_size_t) +
                   " from the parent process " +
                   StreamableToString(parent_process_id));
1277
1278
  }

1279
1280
1281
  const int write_fd =
      ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
  if (write_fd == -1) {
1282
1283
1284
    DeathTestAbort("Unable to convert pipe handle " +
                   StreamableToString(write_handle_as_size_t) +
                   " to a file descriptor");
1285
1286
1287
1288
1289
1290
  }

  // Signals the parent that the write end of the pipe has been acquired
  // so the parent can release its own write end.
  ::SetEvent(dup_event_handle);

1291
  return write_fd;
shiqian's avatar
shiqian committed
1292
}
1293
# endif  // GTEST_OS_WINDOWS
shiqian's avatar
shiqian committed
1294
1295
1296
1297
1298
1299
1300
1301
1302

// Returns a newly created InternalRunDeathTestFlag object with fields
// initialized from the GTEST_FLAG(internal_run_death_test) flag if
// the flag is specified; otherwise returns NULL.
InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
  if (GTEST_FLAG(internal_run_death_test) == "") return NULL;

  // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
  // can use it here.
1303
1304
  int line = -1;
  int index = -1;
shiqian's avatar
shiqian committed
1305
  ::std::vector< ::std::string> fields;
1306
  SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
1307
  int write_fd = -1;
1308

1309
1310
# if GTEST_OS_WINDOWS

1311
  unsigned int parent_process_id = 0;
1312
  size_t write_handle_as_size_t = 0;
1313
1314
1315
1316
1317
1318
  size_t event_handle_as_size_t = 0;

  if (fields.size() != 6
      || !ParseNaturalNumber(fields[1], &line)
      || !ParseNaturalNumber(fields[2], &index)
      || !ParseNaturalNumber(fields[3], &parent_process_id)
1319
      || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
1320
      || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
1321
1322
    DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
                   GTEST_FLAG(internal_run_death_test));
1323
  }
1324
1325
1326
  write_fd = GetStatusFileDescriptor(parent_process_id,
                                     write_handle_as_size_t,
                                     event_handle_as_size_t);
1327
1328
# else

shiqian's avatar
shiqian committed
1329
  if (fields.size() != 4
1330
1331
      || !ParseNaturalNumber(fields[1], &line)
      || !ParseNaturalNumber(fields[2], &index)
1332
      || !ParseNaturalNumber(fields[3], &write_fd)) {
1333
1334
    DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
        + GTEST_FLAG(internal_run_death_test));
1335
  }
1336
1337
1338

# endif  // GTEST_OS_WINDOWS

1339
  return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
shiqian's avatar
shiqian committed
1340
1341
1342
1343
1344
1345
1346
}

}  // namespace internal

#endif  // GTEST_HAS_DEATH_TEST

}  // namespace testing