• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2005, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 //
30 // Author: wan@google.com (Zhanyong Wan)
31 //
32 // This file implements death tests.
33 
34 #include <gtest/gtest-death-test.h>
35 #include <gtest/internal/gtest-port.h>
36 
37 #include <errno.h>
38 #include <limits.h>
39 #include <stdarg.h>
40 
41 #include <gtest/gtest-message.h>
42 #include <gtest/internal/gtest-string.h>
43 
44 // Indicates that this translation unit is part of Google Test's
45 // implementation.  It must come before gtest-internal-inl.h is
46 // included, or there will be a compiler error.  This trick is to
47 // prevent a user from accidentally including gtest-internal-inl.h in
48 // his code.
49 #define GTEST_IMPLEMENTATION
50 #include "src/gtest-internal-inl.h"
51 #undef GTEST_IMPLEMENTATION
52 
53 namespace testing {
54 
55 // Constants.
56 
57 // The default death test style.
58 static const char kDefaultDeathTestStyle[] = "fast";
59 
60 GTEST_DEFINE_string(
61     death_test_style,
62     internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
63     "Indicates how to run a death test in a forked child process: "
64     "\"threadsafe\" (child process re-executes the test binary "
65     "from the beginning, running only the specific death test) or "
66     "\"fast\" (child process runs the death test immediately "
67     "after forking).");
68 
69 namespace internal {
70 GTEST_DEFINE_string(
71     internal_run_death_test, "",
72     "Indicates the file, line number, temporal index of "
73     "the single death test to run, and a file descriptor to "
74     "which a success code may be sent, all separated by "
75     "colons.  This flag is specified if and only if the current "
76     "process is a sub-process launched for running a thread-safe "
77     "death test.  FOR INTERNAL USE ONLY.");
78 }  // namespace internal
79 
80 #ifdef GTEST_HAS_DEATH_TEST
81 
82 // ExitedWithCode constructor.
ExitedWithCode(int exit_code)83 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
84 }
85 
86 // ExitedWithCode function-call operator.
operator ()(int exit_status) const87 bool ExitedWithCode::operator()(int exit_status) const {
88   return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
89 }
90 
91 // KilledBySignal constructor.
KilledBySignal(int signum)92 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
93 }
94 
95 // KilledBySignal function-call operator.
operator ()(int exit_status) const96 bool KilledBySignal::operator()(int exit_status) const {
97   return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
98 }
99 
100 namespace internal {
101 
102 // Utilities needed for death tests.
103 
104 // Generates a textual description of a given exit code, in the format
105 // specified by wait(2).
ExitSummary(int exit_code)106 static String ExitSummary(int exit_code) {
107   Message m;
108   if (WIFEXITED(exit_code)) {
109     m << "Exited with exit status " << WEXITSTATUS(exit_code);
110   } else if (WIFSIGNALED(exit_code)) {
111     m << "Terminated by signal " << WTERMSIG(exit_code);
112   }
113 #ifdef WCOREDUMP
114   if (WCOREDUMP(exit_code)) {
115     m << " (core dumped)";
116   }
117 #endif
118   return m.GetString();
119 }
120 
121 // Returns true if exit_status describes a process that was terminated
122 // by a signal, or exited normally with a nonzero exit code.
ExitedUnsuccessfully(int exit_status)123 bool ExitedUnsuccessfully(int exit_status) {
124   return !ExitedWithCode(0)(exit_status);
125 }
126 
127 // Generates a textual failure message when a death test finds more than
128 // one thread running, or cannot determine the number of threads, prior
129 // to executing the given statement.  It is the responsibility of the
130 // caller not to pass a thread_count of 1.
DeathTestThreadWarning(size_t thread_count)131 static String DeathTestThreadWarning(size_t thread_count) {
132   Message msg;
133   msg << "Death tests use fork(), which is unsafe particularly"
134       << " in a threaded context. For this test, " << GTEST_NAME << " ";
135   if (thread_count == 0)
136     msg << "couldn't detect the number of threads.";
137   else
138     msg << "detected " << thread_count << " threads.";
139   return msg.GetString();
140 }
141 
142 // Static string containing a description of the outcome of the
143 // last death test.
144 static String last_death_test_message;
145 
146 // Flag characters for reporting a death test that did not die.
147 static const char kDeathTestLived = 'L';
148 static const char kDeathTestReturned = 'R';
149 static const char kDeathTestInternalError = 'I';
150 
151 // An enumeration describing all of the possible ways that a death test
152 // can conclude.  DIED means that the process died while executing the
153 // test code; LIVED means that process lived beyond the end of the test
154 // code; and RETURNED means that the test statement attempted a "return,"
155 // which is not allowed.  IN_PROGRESS means the test has not yet
156 // concluded.
157 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED };
158 
159 // Routine for aborting the program which is safe to call from an
160 // exec-style death test child process, in which case the the error
161 // message is propagated back to the parent process.  Otherwise, the
162 // message is simply printed to stderr.  In either case, the program
163 // then exits with status 1.
DeathTestAbort(const char * format,...)164 void DeathTestAbort(const char* format, ...) {
165   // This function may be called from a threadsafe-style death test
166   // child process, which operates on a very small stack.  Use the
167   // heap for any additional non-miniscule memory requirements.
168   const InternalRunDeathTestFlag* const flag =
169       GetUnitTestImpl()->internal_run_death_test_flag();
170   va_list args;
171   va_start(args, format);
172 
173   if (flag != NULL) {
174     FILE* parent = fdopen(flag->status_fd, "w");
175     fputc(kDeathTestInternalError, parent);
176     vfprintf(parent, format, args);
177     fclose(parent);
178     va_end(args);
179     _exit(1);
180   } else {
181     vfprintf(stderr, format, args);
182     va_end(args);
183     abort();
184   }
185 }
186 
187 // A replacement for CHECK that calls DeathTestAbort if the assertion
188 // fails.
189 #define GTEST_DEATH_TEST_CHECK(expression) \
190   do { \
191     if (!(expression)) { \
192       DeathTestAbort("CHECK failed: File %s, line %d: %s", \
193                      __FILE__, __LINE__, #expression); \
194     } \
195   } while (0)
196 
197 // This macro is similar to GTEST_DEATH_TEST_CHECK, but it is meant for
198 // evaluating any system call that fulfills two conditions: it must return
199 // -1 on failure, and set errno to EINTR when it is interrupted and
200 // should be tried again.  The macro expands to a loop that repeatedly
201 // evaluates the expression as long as it evaluates to -1 and sets
202 // errno to EINTR.  If the expression evaluates to -1 but errno is
203 // something other than EINTR, DeathTestAbort is called.
204 #define GTEST_DEATH_TEST_CHECK_SYSCALL(expression) \
205   do { \
206     int retval; \
207     do { \
208       retval = (expression); \
209     } while (retval == -1 && errno == EINTR); \
210     if (retval == -1) { \
211       DeathTestAbort("CHECK failed: File %s, line %d: %s != -1", \
212                      __FILE__, __LINE__, #expression); \
213     } \
214   } while (0)
215 
216 // Death test constructor.  Increments the running death test count
217 // for the current test.
DeathTest()218 DeathTest::DeathTest() {
219   TestInfo* const info = GetUnitTestImpl()->current_test_info();
220   if (info == NULL) {
221     DeathTestAbort("Cannot run a death test outside of a TEST or "
222                    "TEST_F construct");
223   }
224 }
225 
226 // Creates and returns a death test by dispatching to the current
227 // death test factory.
Create(const char * statement,const RE * regex,const char * file,int line,DeathTest ** test)228 bool DeathTest::Create(const char* statement, const RE* regex,
229                        const char* file, int line, DeathTest** test) {
230   return GetUnitTestImpl()->death_test_factory()->Create(
231       statement, regex, file, line, test);
232 }
233 
LastMessage()234 const char* DeathTest::LastMessage() {
235   return last_death_test_message.c_str();
236 }
237 
238 // ForkingDeathTest provides implementations for most of the abstract
239 // methods of the DeathTest interface.  Only the AssumeRole method is
240 // left undefined.
241 class ForkingDeathTest : public DeathTest {
242  public:
243   ForkingDeathTest(const char* statement, const RE* regex);
244 
245   // All of these virtual functions are inherited from DeathTest.
246   virtual int Wait();
247   virtual bool Passed(bool status_ok);
248   virtual void Abort(AbortReason reason);
249 
250  protected:
set_forked(bool forked)251   void set_forked(bool forked) { forked_ = forked; }
set_child_pid(pid_t child_pid)252   void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
set_read_fd(int fd)253   void set_read_fd(int fd) { read_fd_ = fd; }
set_write_fd(int fd)254   void set_write_fd(int fd) { write_fd_ = fd; }
255 
256  private:
257   // The textual content of the code this object is testing.
258   const char* const statement_;
259   // The regular expression which test output must match.
260   const RE* const regex_;
261   // True if the death test successfully forked.
262   bool forked_;
263   // PID of child process during death test; 0 in the child process itself.
264   pid_t child_pid_;
265   // File descriptors for communicating the death test's status byte.
266   int read_fd_;   // Always -1 in the child process.
267   int write_fd_;  // Always -1 in the parent process.
268   // The exit status of the child process.
269   int status_;
270   // How the death test concluded.
271   DeathTestOutcome outcome_;
272 };
273 
274 // Constructs a ForkingDeathTest.
ForkingDeathTest(const char * statement,const RE * regex)275 ForkingDeathTest::ForkingDeathTest(const char* statement, const RE* regex)
276     : DeathTest(),
277       statement_(statement),
278       regex_(regex),
279       forked_(false),
280       child_pid_(-1),
281       read_fd_(-1),
282       write_fd_(-1),
283       status_(-1),
284       outcome_(IN_PROGRESS) {
285 }
286 
287 // Reads an internal failure message from a file descriptor, then calls
288 // LOG(FATAL) with that message.  Called from a death test parent process
289 // to read a failure message from the death test child process.
FailFromInternalError(int fd)290 static void FailFromInternalError(int fd) {
291   Message error;
292   char buffer[256];
293   ssize_t num_read;
294 
295   do {
296     while ((num_read = read(fd, buffer, 255)) > 0) {
297       buffer[num_read] = '\0';
298       error << buffer;
299     }
300   } while (num_read == -1 && errno == EINTR);
301 
302   // TODO(smcafee):  Maybe just FAIL the test instead?
303   if (num_read == 0) {
304     GTEST_LOG(FATAL, error);
305   } else {
306     GTEST_LOG(FATAL,
307               Message() << "Error while reading death test internal: "
308               << strerror(errno) << " [" << errno << "]");
309   }
310 }
311 
312 // Waits for the child in a death test to exit, returning its exit
313 // status, or 0 if no child process exists.  As a side effect, sets the
314 // outcome data member.
Wait()315 int ForkingDeathTest::Wait() {
316   if (!forked_)
317     return 0;
318 
319   // The read() here blocks until data is available (signifying the
320   // failure of the death test) or until the pipe is closed (signifying
321   // its success), so it's okay to call this in the parent before
322   // the child process has exited.
323   char flag;
324   ssize_t bytes_read;
325 
326   do {
327     bytes_read = read(read_fd_, &flag, 1);
328   } while (bytes_read == -1 && errno == EINTR);
329 
330   if (bytes_read == 0) {
331     outcome_ = DIED;
332   } else if (bytes_read == 1) {
333     switch (flag) {
334       case kDeathTestReturned:
335         outcome_ = RETURNED;
336         break;
337       case kDeathTestLived:
338         outcome_ = LIVED;
339         break;
340       case kDeathTestInternalError:
341         FailFromInternalError(read_fd_);  // Does not return.
342         break;
343       default:
344         GTEST_LOG(FATAL,
345                   Message() << "Death test child process reported unexpected "
346                   << "status byte (" << static_cast<unsigned int>(flag)
347                   << ")");
348     }
349   } else {
350     GTEST_LOG(FATAL,
351               Message() << "Read from death test child process failed: "
352               << strerror(errno));
353   }
354 
355   GTEST_DEATH_TEST_CHECK_SYSCALL(close(read_fd_));
356   GTEST_DEATH_TEST_CHECK_SYSCALL(waitpid(child_pid_, &status_, 0));
357   return status_;
358 }
359 
360 // Assesses the success or failure of a death test, using both private
361 // members which have previously been set, and one argument:
362 //
363 // Private data members:
364 //   outcome:  an enumeration describing how the death test
365 //             concluded: DIED, LIVED, or RETURNED.  The death test fails
366 //             in the latter two cases
367 //   status:   the exit status of the child process, in the format
368 //             specified by wait(2)
369 //   regex:    a regular expression object to be applied to
370 //             the test's captured standard error output; the death test
371 //             fails if it does not match
372 //
373 // Argument:
374 //   status_ok: true if exit_status is acceptable in the context of
375 //              this particular death test, which fails if it is false
376 //
377 // Returns true iff all of the above conditions are met.  Otherwise, the
378 // first failing condition, in the order given above, is the one that is
379 // reported. Also sets the static variable last_death_test_message.
Passed(bool status_ok)380 bool ForkingDeathTest::Passed(bool status_ok) {
381   if (!forked_)
382     return false;
383 
384 #if GTEST_HAS_GLOBAL_STRING
385   const ::string error_message = GetCapturedStderr();
386 #else
387   const ::std::string error_message = GetCapturedStderr();
388 #endif  // GTEST_HAS_GLOBAL_STRING
389 
390   bool success = false;
391   Message buffer;
392 
393   buffer << "Death test: " << statement_ << "\n";
394   switch (outcome_) {
395     case LIVED:
396       buffer << "    Result: failed to die.\n"
397              << " Error msg: " << error_message;
398       break;
399     case RETURNED:
400       buffer << "    Result: illegal return in test statement.\n"
401              << " Error msg: " << error_message;
402       break;
403     case DIED:
404       if (status_ok) {
405         if (RE::PartialMatch(error_message, *regex_)) {
406           success = true;
407         } else {
408           buffer << "    Result: died but not with expected error.\n"
409                  << "  Expected: " << regex_->pattern() << "\n"
410                  << "Actual msg: " << error_message;
411         }
412       } else {
413         buffer << "    Result: died but not with expected exit code:\n"
414                << "            " << ExitSummary(status_) << "\n";
415       }
416       break;
417     default:
418       GTEST_LOG(FATAL,
419                 "DeathTest::Passed somehow called before conclusion of test");
420   }
421 
422   last_death_test_message = buffer.GetString();
423   return success;
424 }
425 
426 // Signals that the death test code which should have exited, didn't.
427 // Should be called only in a death test child process.
428 // Writes a status byte to the child's status file desriptor, then
429 // calls _exit(1).
Abort(AbortReason reason)430 void ForkingDeathTest::Abort(AbortReason reason) {
431   // The parent process considers the death test to be a failure if
432   // it finds any data in our pipe.  So, here we write a single flag byte
433   // to the pipe, then exit.
434   const char flag =
435       reason == TEST_DID_NOT_DIE ? kDeathTestLived : kDeathTestReturned;
436   GTEST_DEATH_TEST_CHECK_SYSCALL(write(write_fd_, &flag, 1));
437   GTEST_DEATH_TEST_CHECK_SYSCALL(close(write_fd_));
438   _exit(1);  // Exits w/o any normal exit hooks (we were supposed to crash)
439 }
440 
441 // A concrete death test class that forks, then immediately runs the test
442 // in the child process.
443 class NoExecDeathTest : public ForkingDeathTest {
444  public:
NoExecDeathTest(const char * statement,const RE * regex)445   NoExecDeathTest(const char* statement, const RE* regex) :
446       ForkingDeathTest(statement, regex) { }
447   virtual TestRole AssumeRole();
448 };
449 
450 // The AssumeRole process for a fork-and-run death test.  It implements a
451 // straightforward fork, with a simple pipe to transmit the status byte.
AssumeRole()452 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
453   const size_t thread_count = GetThreadCount();
454   if (thread_count != 1) {
455     GTEST_LOG(WARNING, DeathTestThreadWarning(thread_count));
456   }
457 
458   int pipe_fd[2];
459   GTEST_DEATH_TEST_CHECK(pipe(pipe_fd) != -1);
460 
461   last_death_test_message = "";
462   CaptureStderr();
463   // When we fork the process below, the log file buffers are copied, but the
464   // file descriptors are shared.  We flush all log files here so that closing
465   // the file descriptors in the child process doesn't throw off the
466   // synchronization between descriptors and buffers in the parent process.
467   // This is as close to the fork as possible to avoid a race condition in case
468   // there are multiple threads running before the death test, and another
469   // thread writes to the log file.
470   FlushInfoLog();
471 
472   const pid_t child_pid = fork();
473   GTEST_DEATH_TEST_CHECK(child_pid != -1);
474   set_child_pid(child_pid);
475   if (child_pid == 0) {
476     GTEST_DEATH_TEST_CHECK_SYSCALL(close(pipe_fd[0]));
477     set_write_fd(pipe_fd[1]);
478     // Redirects all logging to stderr in the child process to prevent
479     // concurrent writes to the log files.  We capture stderr in the parent
480     // process and append the child process' output to a log.
481     LogToStderr();
482     return EXECUTE_TEST;
483   } else {
484     GTEST_DEATH_TEST_CHECK_SYSCALL(close(pipe_fd[1]));
485     set_read_fd(pipe_fd[0]);
486     set_forked(true);
487     return OVERSEE_TEST;
488   }
489 }
490 
491 // A concrete death test class that forks and re-executes the main
492 // program from the beginning, with command-line flags set that cause
493 // only this specific death test to be run.
494 class ExecDeathTest : public ForkingDeathTest {
495  public:
ExecDeathTest(const char * statement,const RE * regex,const char * file,int line)496   ExecDeathTest(const char* statement, const RE* regex,
497                 const char* file, int line) :
498       ForkingDeathTest(statement, regex), file_(file), line_(line) { }
499   virtual TestRole AssumeRole();
500  private:
501   // The name of the file in which the death test is located.
502   const char* const file_;
503   // The line number on which the death test is located.
504   const int line_;
505 };
506 
507 // Utility class for accumulating command-line arguments.
508 class Arguments {
509  public:
Arguments()510   Arguments() {
511     args_.push_back(NULL);
512   }
~Arguments()513   ~Arguments() {
514     for (std::vector<char*>::iterator i = args_.begin();
515          i + 1 != args_.end();
516          ++i) {
517       free(*i);
518     }
519   }
AddArgument(const char * argument)520   void AddArgument(const char* argument) {
521     args_.insert(args_.end() - 1, strdup(argument));
522   }
523 
524   template <typename Str>
AddArguments(const::std::vector<Str> & arguments)525   void AddArguments(const ::std::vector<Str>& arguments) {
526     for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
527          i != arguments.end();
528          ++i) {
529       args_.insert(args_.end() - 1, strdup(i->c_str()));
530     }
531   }
Argv()532   char* const* Argv() {
533     return &args_[0];
534   }
535  private:
536   std::vector<char*> args_;
537 };
538 
539 // A struct that encompasses the arguments to the child process of a
540 // threadsafe-style death test process.
541 struct ExecDeathTestArgs {
542   char* const* argv;  // Command-line arguments for the child's call to exec
543   int close_fd;       // File descriptor to close; the read end of a pipe
544 };
545 
546 // The main function for a threadsafe-style death test child process.
ExecDeathTestChildMain(void * child_arg)547 static int ExecDeathTestChildMain(void* child_arg) {
548   ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
549   GTEST_DEATH_TEST_CHECK_SYSCALL(close(args->close_fd));
550   execve(args->argv[0], args->argv, environ);
551   DeathTestAbort("execve failed: %s", strerror(errno));
552   return EXIT_FAILURE;
553 }
554 
555 // Two utility routines that together determine the direction the stack
556 // grows.
557 // This could be accomplished more elegantly by a single recursive
558 // function, but we want to guard against the unlikely possibility of
559 // a smart compiler optimizing the recursion away.
StackLowerThanAddress(const void * ptr)560 static bool StackLowerThanAddress(const void* ptr) {
561   int dummy;
562   return &dummy < ptr;
563 }
564 
StackGrowsDown()565 static bool StackGrowsDown() {
566   int dummy;
567   return StackLowerThanAddress(&dummy);
568 }
569 
570 // A threadsafe implementation of fork(2) for threadsafe-style death tests
571 // that uses clone(2).  It dies with an error message if anything goes
572 // wrong.
ExecDeathTestFork(char * const * argv,int close_fd)573 static pid_t ExecDeathTestFork(char* const* argv, int close_fd) {
574   static const bool stack_grows_down = StackGrowsDown();
575   const size_t stack_size = getpagesize();
576   void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
577                            MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
578   GTEST_DEATH_TEST_CHECK(stack != MAP_FAILED);
579   void* const stack_top =
580       static_cast<char*>(stack) + (stack_grows_down ? stack_size : 0);
581   ExecDeathTestArgs args = { argv, close_fd };
582   const pid_t child_pid = clone(&ExecDeathTestChildMain, stack_top,
583                                 SIGCHLD, &args);
584   GTEST_DEATH_TEST_CHECK(child_pid != -1);
585   GTEST_DEATH_TEST_CHECK(munmap(stack, stack_size) != -1);
586   return child_pid;
587 }
588 
589 // The AssumeRole process for a fork-and-exec death test.  It re-executes the
590 // main program from the beginning, setting the --gtest_filter
591 // and --gtest_internal_run_death_test flags to cause only the current
592 // death test to be re-run.
AssumeRole()593 DeathTest::TestRole ExecDeathTest::AssumeRole() {
594   const UnitTestImpl* const impl = GetUnitTestImpl();
595   const InternalRunDeathTestFlag* const flag =
596       impl->internal_run_death_test_flag();
597   const TestInfo* const info = impl->current_test_info();
598   const int death_test_index = info->result()->death_test_count();
599 
600   if (flag != NULL) {
601     set_write_fd(flag->status_fd);
602     return EXECUTE_TEST;
603   }
604 
605   int pipe_fd[2];
606   GTEST_DEATH_TEST_CHECK(pipe(pipe_fd) != -1);
607   // Clear the close-on-exec flag on the write end of the pipe, lest
608   // it be closed when the child process does an exec:
609   GTEST_DEATH_TEST_CHECK(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
610 
611   const String filter_flag =
612       String::Format("--%s%s=%s.%s",
613                      GTEST_FLAG_PREFIX, kFilterFlag,
614                      info->test_case_name(), info->name());
615   const String internal_flag =
616       String::Format("--%s%s=%s:%d:%d:%d",
617                      GTEST_FLAG_PREFIX, kInternalRunDeathTestFlag, file_, line_,
618                      death_test_index, pipe_fd[1]);
619   Arguments args;
620   args.AddArguments(GetArgvs());
621   args.AddArgument("--logtostderr");
622   args.AddArgument(filter_flag.c_str());
623   args.AddArgument(internal_flag.c_str());
624 
625   last_death_test_message = "";
626 
627   CaptureStderr();
628   // See the comment in NoExecDeathTest::AssumeRole for why the next line
629   // is necessary.
630   FlushInfoLog();
631 
632   const pid_t child_pid = ExecDeathTestFork(args.Argv(), pipe_fd[0]);
633   GTEST_DEATH_TEST_CHECK_SYSCALL(close(pipe_fd[1]));
634   set_child_pid(child_pid);
635   set_read_fd(pipe_fd[0]);
636   set_forked(true);
637   return OVERSEE_TEST;
638 }
639 
640 // Creates a concrete DeathTest-derived class that depends on the
641 // --gtest_death_test_style flag, and sets the pointer pointed to
642 // by the "test" argument to its address.  If the test should be
643 // skipped, sets that pointer to NULL.  Returns true, unless the
644 // flag is set to an invalid value.
Create(const char * statement,const RE * regex,const char * file,int line,DeathTest ** test)645 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
646                                      const char* file, int line,
647                                      DeathTest** test) {
648   UnitTestImpl* const impl = GetUnitTestImpl();
649   const InternalRunDeathTestFlag* const flag =
650       impl->internal_run_death_test_flag();
651   const int death_test_index = impl->current_test_info()
652       ->increment_death_test_count();
653 
654   if (flag != NULL) {
655     if (death_test_index > flag->index) {
656       last_death_test_message = String::Format(
657           "Death test count (%d) somehow exceeded expected maximum (%d)",
658           death_test_index, flag->index);
659       return false;
660     }
661 
662     if (!(flag->file == file && flag->line == line &&
663           flag->index == death_test_index)) {
664       *test = NULL;
665       return true;
666     }
667   }
668 
669   if (GTEST_FLAG(death_test_style) == "threadsafe") {
670     *test = new ExecDeathTest(statement, regex, file, line);
671   } else if (GTEST_FLAG(death_test_style) == "fast") {
672     *test = new NoExecDeathTest(statement, regex);
673   } else {
674     last_death_test_message = String::Format(
675         "Unknown death test style \"%s\" encountered",
676         GTEST_FLAG(death_test_style).c_str());
677     return false;
678   }
679 
680   return true;
681 }
682 
683 // Splits a given string on a given delimiter, populating a given
684 // vector with the fields.  GTEST_HAS_DEATH_TEST implies that we have
685 // ::std::string, so we can use it here.
SplitString(const::std::string & str,char delimiter,::std::vector<::std::string> * dest)686 static void SplitString(const ::std::string& str, char delimiter,
687                         ::std::vector< ::std::string>* dest) {
688   ::std::vector< ::std::string> parsed;
689   ::std::string::size_type pos = 0;
690   while (true) {
691     const ::std::string::size_type colon = str.find(delimiter, pos);
692     if (colon == ::std::string::npos) {
693       parsed.push_back(str.substr(pos));
694       break;
695     } else {
696       parsed.push_back(str.substr(pos, colon - pos));
697       pos = colon + 1;
698     }
699   }
700   dest->swap(parsed);
701 }
702 
703 // Attempts to parse a string into a positive integer.  Returns true
704 // if that is possible.  GTEST_HAS_DEATH_TEST implies that we have
705 // ::std::string, so we can use it here.
ParsePositiveInt(const::std::string & str,int * number)706 static bool ParsePositiveInt(const ::std::string& str, int* number) {
707   // Fail fast if the given string does not begin with a digit;
708   // this bypasses strtol's "optional leading whitespace and plus
709   // or minus sign" semantics, which are undesirable here.
710   if (str.empty() || !isdigit(str[0])) {
711     return false;
712   }
713   char* endptr;
714   const long parsed = strtol(str.c_str(), &endptr, 10);  // NOLINT
715   if (*endptr == '\0' && parsed <= INT_MAX) {
716     *number = static_cast<int>(parsed);
717     return true;
718   } else {
719     return false;
720   }
721 }
722 
723 // Returns a newly created InternalRunDeathTestFlag object with fields
724 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
725 // the flag is specified; otherwise returns NULL.
ParseInternalRunDeathTestFlag()726 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
727   if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
728 
729   InternalRunDeathTestFlag* const internal_run_death_test_flag =
730       new InternalRunDeathTestFlag;
731   // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
732   // can use it here.
733   ::std::vector< ::std::string> fields;
734   SplitString(GTEST_FLAG(internal_run_death_test).c_str(), ':', &fields);
735   if (fields.size() != 4
736       || !ParsePositiveInt(fields[1], &internal_run_death_test_flag->line)
737       || !ParsePositiveInt(fields[2], &internal_run_death_test_flag->index)
738       || !ParsePositiveInt(fields[3],
739                            &internal_run_death_test_flag->status_fd)) {
740     DeathTestAbort("Bad --gtest_internal_run_death_test flag: %s",
741                    GTEST_FLAG(internal_run_death_test).c_str());
742   }
743   internal_run_death_test_flag->file = fields[0].c_str();
744   return internal_run_death_test_flag;
745 }
746 
747 }  // namespace internal
748 
749 #endif  // GTEST_HAS_DEATH_TEST
750 
751 }  // namespace testing
752