It's ok to spill a tGPR register as long as it's still allocated a low register.
[llvm/avr.git] / utils / unittest / googletest / gtest-death-test.cc
blob617e3010f23a5aa393e945221337213c0759c9cc
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.
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.
30 // Author: wan@google.com (Zhanyong Wan)
32 // This file implements death tests.
34 #include <gtest/gtest-death-test.h>
35 #include <gtest/internal/gtest-port.h>
37 #ifdef GTEST_HAS_DEATH_TEST
38 #include <errno.h>
39 #include <limits.h>
40 #include <stdarg.h>
41 #endif // GTEST_HAS_DEATH_TEST
43 #include <gtest/gtest-message.h>
44 #include <gtest/internal/gtest-string.h>
46 // Indicates that this translation unit is part of Google Test's
47 // implementation. It must come before gtest-internal-inl.h is
48 // included, or there will be a compiler error. This trick is to
49 // prevent a user from accidentally including gtest-internal-inl.h in
50 // his code.
51 #define GTEST_IMPLEMENTATION
52 #include "gtest/internal/gtest-internal-inl.h"
53 #undef GTEST_IMPLEMENTATION
55 namespace testing {
57 // Constants.
59 // The default death test style.
60 static const char kDefaultDeathTestStyle[] = "fast";
62 GTEST_DEFINE_string_(
63 death_test_style,
64 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
65 "Indicates how to run a death test in a forked child process: "
66 "\"threadsafe\" (child process re-executes the test binary "
67 "from the beginning, running only the specific death test) or "
68 "\"fast\" (child process runs the death test immediately "
69 "after forking).");
71 namespace internal {
72 GTEST_DEFINE_string_(
73 internal_run_death_test, "",
74 "Indicates the file, line number, temporal index of "
75 "the single death test to run, and a file descriptor to "
76 "which a success code may be sent, all separated by "
77 "colons. This flag is specified if and only if the current "
78 "process is a sub-process launched for running a thread-safe "
79 "death test. FOR INTERNAL USE ONLY.");
80 } // namespace internal
82 #ifdef GTEST_HAS_DEATH_TEST
84 // ExitedWithCode constructor.
85 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
88 // ExitedWithCode function-call operator.
89 bool ExitedWithCode::operator()(int exit_status) const {
90 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
93 // KilledBySignal constructor.
94 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
97 // KilledBySignal function-call operator.
98 bool KilledBySignal::operator()(int exit_status) const {
99 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
102 namespace internal {
104 // Utilities needed for death tests.
106 // Generates a textual description of a given exit code, in the format
107 // specified by wait(2).
108 static String ExitSummary(int exit_code) {
109 Message m;
110 if (WIFEXITED(exit_code)) {
111 m << "Exited with exit status " << WEXITSTATUS(exit_code);
112 } else if (WIFSIGNALED(exit_code)) {
113 m << "Terminated by signal " << WTERMSIG(exit_code);
115 #ifdef WCOREDUMP
116 if (WCOREDUMP(exit_code)) {
117 m << " (core dumped)";
119 #endif
120 return m.GetString();
123 // Returns true if exit_status describes a process that was terminated
124 // by a signal, or exited normally with a nonzero exit code.
125 bool ExitedUnsuccessfully(int exit_status) {
126 return !ExitedWithCode(0)(exit_status);
129 // Generates a textual failure message when a death test finds more than
130 // one thread running, or cannot determine the number of threads, prior
131 // to executing the given statement. It is the responsibility of the
132 // caller not to pass a thread_count of 1.
133 static String DeathTestThreadWarning(size_t thread_count) {
134 Message msg;
135 msg << "Death tests use fork(), which is unsafe particularly"
136 << " in a threaded context. For this test, " << GTEST_NAME << " ";
137 if (thread_count == 0)
138 msg << "couldn't detect the number of threads.";
139 else
140 msg << "detected " << thread_count << " threads.";
141 return msg.GetString();
144 // Static string containing a description of the outcome of the
145 // last death test.
146 static String last_death_test_message;
148 // Flag characters for reporting a death test that did not die.
149 static const char kDeathTestLived = 'L';
150 static const char kDeathTestReturned = 'R';
151 static const char kDeathTestInternalError = 'I';
153 // An enumeration describing all of the possible ways that a death test
154 // can conclude. DIED means that the process died while executing the
155 // test code; LIVED means that process lived beyond the end of the test
156 // code; and RETURNED means that the test statement attempted a "return,"
157 // which is not allowed. IN_PROGRESS means the test has not yet
158 // concluded.
159 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED };
161 // Routine for aborting the program which is safe to call from an
162 // exec-style death test child process, in which case the the error
163 // message is propagated back to the parent process. Otherwise, the
164 // message is simply printed to stderr. In either case, the program
165 // then exits with status 1.
166 void DeathTestAbort(const char* format, ...) {
167 // This function may be called from a threadsafe-style death test
168 // child process, which operates on a very small stack. Use the
169 // heap for any additional non-miniscule memory requirements.
170 const InternalRunDeathTestFlag* const flag =
171 GetUnitTestImpl()->internal_run_death_test_flag();
172 va_list args;
173 va_start(args, format);
175 if (flag != NULL) {
176 FILE* parent = fdopen(flag->status_fd, "w");
177 fputc(kDeathTestInternalError, parent);
178 vfprintf(parent, format, args);
179 fclose(parent);
180 va_end(args);
181 _exit(1);
182 } else {
183 vfprintf(stderr, format, args);
184 va_end(args);
185 abort();
189 // A replacement for CHECK that calls DeathTestAbort if the assertion
190 // fails.
191 #define GTEST_DEATH_TEST_CHECK_(expression) \
192 do { \
193 if (!(expression)) { \
194 DeathTestAbort("CHECK failed: File %s, line %d: %s", \
195 __FILE__, __LINE__, #expression); \
197 } while (0)
199 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
200 // evaluating any system call that fulfills two conditions: it must return
201 // -1 on failure, and set errno to EINTR when it is interrupted and
202 // should be tried again. The macro expands to a loop that repeatedly
203 // evaluates the expression as long as it evaluates to -1 and sets
204 // errno to EINTR. If the expression evaluates to -1 but errno is
205 // something other than EINTR, DeathTestAbort is called.
206 #define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
207 do { \
208 int retval; \
209 do { \
210 retval = (expression); \
211 } while (retval == -1 && errno == EINTR); \
212 if (retval == -1) { \
213 DeathTestAbort("CHECK failed: File %s, line %d: %s != -1", \
214 __FILE__, __LINE__, #expression); \
216 } while (0)
218 // Death test constructor. Increments the running death test count
219 // for the current test.
220 DeathTest::DeathTest() {
221 TestInfo* const info = GetUnitTestImpl()->current_test_info();
222 if (info == NULL) {
223 DeathTestAbort("Cannot run a death test outside of a TEST or "
224 "TEST_F construct");
228 // Creates and returns a death test by dispatching to the current
229 // death test factory.
230 bool DeathTest::Create(const char* statement, const RE* regex,
231 const char* file, int line, DeathTest** test) {
232 return GetUnitTestImpl()->death_test_factory()->Create(
233 statement, regex, file, line, test);
236 const char* DeathTest::LastMessage() {
237 return last_death_test_message.c_str();
240 // ForkingDeathTest provides implementations for most of the abstract
241 // methods of the DeathTest interface. Only the AssumeRole method is
242 // left undefined.
243 class ForkingDeathTest : public DeathTest {
244 public:
245 ForkingDeathTest(const char* statement, const RE* regex);
247 // All of these virtual functions are inherited from DeathTest.
248 virtual int Wait();
249 virtual bool Passed(bool status_ok);
250 virtual void Abort(AbortReason reason);
252 protected:
253 void set_forked(bool forked) { forked_ = forked; }
254 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
255 void set_read_fd(int fd) { read_fd_ = fd; }
256 void set_write_fd(int fd) { write_fd_ = fd; }
258 private:
259 // The textual content of the code this object is testing.
260 const char* const statement_;
261 // The regular expression which test output must match.
262 const RE* const regex_;
263 // True if the death test successfully forked.
264 bool forked_;
265 // PID of child process during death test; 0 in the child process itself.
266 pid_t child_pid_;
267 // File descriptors for communicating the death test's status byte.
268 int read_fd_; // Always -1 in the child process.
269 int write_fd_; // Always -1 in the parent process.
270 // The exit status of the child process.
271 int status_;
272 // How the death test concluded.
273 DeathTestOutcome outcome_;
276 // Constructs a ForkingDeathTest.
277 ForkingDeathTest::ForkingDeathTest(const char* statement, const RE* regex)
278 : DeathTest(),
279 statement_(statement),
280 regex_(regex),
281 forked_(false),
282 child_pid_(-1),
283 read_fd_(-1),
284 write_fd_(-1),
285 status_(-1),
286 outcome_(IN_PROGRESS) {
289 // Reads an internal failure message from a file descriptor, then calls
290 // LOG(FATAL) with that message. Called from a death test parent process
291 // to read a failure message from the death test child process.
292 static void FailFromInternalError(int fd) {
293 Message error;
294 char buffer[256];
295 ssize_t num_read;
297 do {
298 while ((num_read = read(fd, buffer, 255)) > 0) {
299 buffer[num_read] = '\0';
300 error << buffer;
302 } while (num_read == -1 && errno == EINTR);
304 // TODO(smcafee): Maybe just FAIL the test instead?
305 if (num_read == 0) {
306 GTEST_LOG_(FATAL, error);
307 } else {
308 GTEST_LOG_(FATAL,
309 Message() << "Error while reading death test internal: "
310 << strerror(errno) << " [" << errno << "]");
314 // Waits for the child in a death test to exit, returning its exit
315 // status, or 0 if no child process exists. As a side effect, sets the
316 // outcome data member.
317 int ForkingDeathTest::Wait() {
318 if (!forked_)
319 return 0;
321 // The read() here blocks until data is available (signifying the
322 // failure of the death test) or until the pipe is closed (signifying
323 // its success), so it's okay to call this in the parent before
324 // the child process has exited.
325 char flag;
326 ssize_t bytes_read;
328 do {
329 bytes_read = read(read_fd_, &flag, 1);
330 } while (bytes_read == -1 && errno == EINTR);
332 if (bytes_read == 0) {
333 outcome_ = DIED;
334 } else if (bytes_read == 1) {
335 switch (flag) {
336 case kDeathTestReturned:
337 outcome_ = RETURNED;
338 break;
339 case kDeathTestLived:
340 outcome_ = LIVED;
341 break;
342 case kDeathTestInternalError:
343 FailFromInternalError(read_fd_); // Does not return.
344 break;
345 default:
346 GTEST_LOG_(FATAL,
347 Message() << "Death test child process reported unexpected "
348 << "status byte (" << static_cast<unsigned int>(flag)
349 << ")");
351 } else {
352 GTEST_LOG_(FATAL,
353 Message() << "Read from death test child process failed: "
354 << strerror(errno));
357 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(read_fd_));
358 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_, 0));
359 return status_;
362 // Assesses the success or failure of a death test, using both private
363 // members which have previously been set, and one argument:
365 // Private data members:
366 // outcome: an enumeration describing how the death test
367 // concluded: DIED, LIVED, or RETURNED. The death test fails
368 // in the latter two cases
369 // status: the exit status of the child process, in the format
370 // specified by wait(2)
371 // regex: a regular expression object to be applied to
372 // the test's captured standard error output; the death test
373 // fails if it does not match
375 // Argument:
376 // status_ok: true if exit_status is acceptable in the context of
377 // this particular death test, which fails if it is false
379 // Returns true iff all of the above conditions are met. Otherwise, the
380 // first failing condition, in the order given above, is the one that is
381 // reported. Also sets the static variable last_death_test_message.
382 bool ForkingDeathTest::Passed(bool status_ok) {
383 if (!forked_)
384 return false;
386 #if GTEST_HAS_GLOBAL_STRING
387 const ::string error_message = GetCapturedStderr();
388 #else
389 const ::std::string error_message = GetCapturedStderr();
390 #endif // GTEST_HAS_GLOBAL_STRING
392 bool success = false;
393 Message buffer;
395 buffer << "Death test: " << statement_ << "\n";
396 switch (outcome_) {
397 case LIVED:
398 buffer << " Result: failed to die.\n"
399 << " Error msg: " << error_message;
400 break;
401 case RETURNED:
402 buffer << " Result: illegal return in test statement.\n"
403 << " Error msg: " << error_message;
404 break;
405 case DIED:
406 if (status_ok) {
407 if (RE::PartialMatch(error_message, *regex_)) {
408 success = true;
409 } else {
410 buffer << " Result: died but not with expected error.\n"
411 << " Expected: " << regex_->pattern() << "\n"
412 << "Actual msg: " << error_message;
414 } else {
415 buffer << " Result: died but not with expected exit code:\n"
416 << " " << ExitSummary(status_) << "\n";
418 break;
419 case IN_PROGRESS:
420 default:
421 GTEST_LOG_(FATAL,
422 "DeathTest::Passed somehow called before conclusion of test");
425 last_death_test_message = buffer.GetString();
426 return success;
429 // Signals that the death test code which should have exited, didn't.
430 // Should be called only in a death test child process.
431 // Writes a status byte to the child's status file desriptor, then
432 // calls _exit(1).
433 void ForkingDeathTest::Abort(AbortReason reason) {
434 // The parent process considers the death test to be a failure if
435 // it finds any data in our pipe. So, here we write a single flag byte
436 // to the pipe, then exit.
437 const char flag =
438 reason == TEST_DID_NOT_DIE ? kDeathTestLived : kDeathTestReturned;
439 GTEST_DEATH_TEST_CHECK_SYSCALL_(write(write_fd_, &flag, 1));
440 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(write_fd_));
441 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
444 // A concrete death test class that forks, then immediately runs the test
445 // in the child process.
446 class NoExecDeathTest : public ForkingDeathTest {
447 public:
448 NoExecDeathTest(const char* statement, const RE* regex) :
449 ForkingDeathTest(statement, regex) { }
450 virtual TestRole AssumeRole();
453 // The AssumeRole process for a fork-and-run death test. It implements a
454 // straightforward fork, with a simple pipe to transmit the status byte.
455 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
456 const size_t thread_count = GetThreadCount();
457 if (thread_count != 1) {
458 GTEST_LOG_(WARNING, DeathTestThreadWarning(thread_count));
461 int pipe_fd[2];
462 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
464 last_death_test_message = "";
465 CaptureStderr();
466 // When we fork the process below, the log file buffers are copied, but the
467 // file descriptors are shared. We flush all log files here so that closing
468 // the file descriptors in the child process doesn't throw off the
469 // synchronization between descriptors and buffers in the parent process.
470 // This is as close to the fork as possible to avoid a race condition in case
471 // there are multiple threads running before the death test, and another
472 // thread writes to the log file.
473 FlushInfoLog();
475 const pid_t child_pid = fork();
476 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
477 set_child_pid(child_pid);
478 if (child_pid == 0) {
479 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
480 set_write_fd(pipe_fd[1]);
481 // Redirects all logging to stderr in the child process to prevent
482 // concurrent writes to the log files. We capture stderr in the parent
483 // process and append the child process' output to a log.
484 LogToStderr();
485 return EXECUTE_TEST;
486 } else {
487 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
488 set_read_fd(pipe_fd[0]);
489 set_forked(true);
490 return OVERSEE_TEST;
494 // A concrete death test class that forks and re-executes the main
495 // program from the beginning, with command-line flags set that cause
496 // only this specific death test to be run.
497 class ExecDeathTest : public ForkingDeathTest {
498 public:
499 ExecDeathTest(const char* statement, const RE* regex,
500 const char* file, int line) :
501 ForkingDeathTest(statement, regex), file_(file), line_(line) { }
502 virtual TestRole AssumeRole();
503 private:
504 // The name of the file in which the death test is located.
505 const char* const file_;
506 // The line number on which the death test is located.
507 const int line_;
510 // Utility class for accumulating command-line arguments.
511 class Arguments {
512 public:
513 Arguments() {
514 args_.push_back(NULL);
516 ~Arguments() {
517 for (std::vector<char*>::iterator i = args_.begin();
518 i + 1 != args_.end();
519 ++i) {
520 free(*i);
523 void AddArgument(const char* argument) {
524 args_.insert(args_.end() - 1, strdup(argument));
527 template <typename Str>
528 void AddArguments(const ::std::vector<Str>& arguments) {
529 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
530 i != arguments.end();
531 ++i) {
532 args_.insert(args_.end() - 1, strdup(i->c_str()));
535 char* const* Argv() {
536 return &args_[0];
538 private:
539 std::vector<char*> args_;
542 // A struct that encompasses the arguments to the child process of a
543 // threadsafe-style death test process.
544 struct ExecDeathTestArgs {
545 char* const* argv; // Command-line arguments for the child's call to exec
546 int close_fd; // File descriptor to close; the read end of a pipe
549 // The main function for a threadsafe-style death test child process.
550 // This function is called in a clone()-ed process and thus must avoid
551 // any potentially unsafe operations like malloc or libc functions.
552 static int ExecDeathTestChildMain(void* child_arg) {
553 ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
554 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
556 // We need to execute the test program in the same environment where
557 // it was originally invoked. Therefore we change to the original
558 // working directory first.
559 const char* const original_dir =
560 UnitTest::GetInstance()->original_working_dir();
561 // We can safely call chdir() as it's a direct system call.
562 if (chdir(original_dir) != 0) {
563 DeathTestAbort("chdir(\"%s\") failed: %s",
564 original_dir, strerror(errno));
565 return EXIT_FAILURE;
568 // We can safely call execve() as it's a direct system call. We
569 // cannot use execvp() as it's a libc function and thus potentially
570 // unsafe. Since execve() doesn't search the PATH, the user must
571 // invoke the test program via a valid path that contains at least
572 // one path separator.
573 execve(args->argv[0], args->argv, environ);
574 DeathTestAbort("execve(%s, ...) in %s failed: %s",
575 args->argv[0], original_dir, strerror(errno));
576 return EXIT_FAILURE;
579 // Two utility routines that together determine the direction the stack
580 // grows.
581 // This could be accomplished more elegantly by a single recursive
582 // function, but we want to guard against the unlikely possibility of
583 // a smart compiler optimizing the recursion away.
584 static bool StackLowerThanAddress(const void* ptr) {
585 int dummy;
586 return &dummy < ptr;
589 static bool StackGrowsDown() {
590 int dummy;
591 return StackLowerThanAddress(&dummy);
594 // A threadsafe implementation of fork(2) for threadsafe-style death tests
595 // that uses clone(2). It dies with an error message if anything goes
596 // wrong.
597 static pid_t ExecDeathTestFork(char* const* argv, int close_fd) {
598 static const bool stack_grows_down = StackGrowsDown();
599 const size_t stack_size = getpagesize();
600 void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
601 MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
602 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
603 void* const stack_top =
604 static_cast<char*>(stack) + (stack_grows_down ? stack_size : 0);
605 ExecDeathTestArgs args = { argv, close_fd };
606 const pid_t child_pid = clone(&ExecDeathTestChildMain, stack_top,
607 SIGCHLD, &args);
608 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
609 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
610 return child_pid;
613 // The AssumeRole process for a fork-and-exec death test. It re-executes the
614 // main program from the beginning, setting the --gtest_filter
615 // and --gtest_internal_run_death_test flags to cause only the current
616 // death test to be re-run.
617 DeathTest::TestRole ExecDeathTest::AssumeRole() {
618 const UnitTestImpl* const impl = GetUnitTestImpl();
619 const InternalRunDeathTestFlag* const flag =
620 impl->internal_run_death_test_flag();
621 const TestInfo* const info = impl->current_test_info();
622 const int death_test_index = info->result()->death_test_count();
624 if (flag != NULL) {
625 set_write_fd(flag->status_fd);
626 return EXECUTE_TEST;
629 int pipe_fd[2];
630 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
631 // Clear the close-on-exec flag on the write end of the pipe, lest
632 // it be closed when the child process does an exec:
633 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
635 const String filter_flag =
636 String::Format("--%s%s=%s.%s",
637 GTEST_FLAG_PREFIX, kFilterFlag,
638 info->test_case_name(), info->name());
639 const String internal_flag =
640 String::Format("--%s%s=%s:%d:%d:%d",
641 GTEST_FLAG_PREFIX, kInternalRunDeathTestFlag, file_, line_,
642 death_test_index, pipe_fd[1]);
643 Arguments args;
644 args.AddArguments(GetArgvs());
645 args.AddArgument("--logtostderr");
646 args.AddArgument(filter_flag.c_str());
647 args.AddArgument(internal_flag.c_str());
649 last_death_test_message = "";
651 CaptureStderr();
652 // See the comment in NoExecDeathTest::AssumeRole for why the next line
653 // is necessary.
654 FlushInfoLog();
656 const pid_t child_pid = ExecDeathTestFork(args.Argv(), pipe_fd[0]);
657 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
658 set_child_pid(child_pid);
659 set_read_fd(pipe_fd[0]);
660 set_forked(true);
661 return OVERSEE_TEST;
664 // Creates a concrete DeathTest-derived class that depends on the
665 // --gtest_death_test_style flag, and sets the pointer pointed to
666 // by the "test" argument to its address. If the test should be
667 // skipped, sets that pointer to NULL. Returns true, unless the
668 // flag is set to an invalid value.
669 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
670 const char* file, int line,
671 DeathTest** test) {
672 UnitTestImpl* const impl = GetUnitTestImpl();
673 const InternalRunDeathTestFlag* const flag =
674 impl->internal_run_death_test_flag();
675 const int death_test_index = impl->current_test_info()
676 ->increment_death_test_count();
678 if (flag != NULL) {
679 if (death_test_index > flag->index) {
680 last_death_test_message = String::Format(
681 "Death test count (%d) somehow exceeded expected maximum (%d)",
682 death_test_index, flag->index);
683 return false;
686 if (!(flag->file == file && flag->line == line &&
687 flag->index == death_test_index)) {
688 *test = NULL;
689 return true;
693 if (GTEST_FLAG(death_test_style) == "threadsafe") {
694 *test = new ExecDeathTest(statement, regex, file, line);
695 } else if (GTEST_FLAG(death_test_style) == "fast") {
696 *test = new NoExecDeathTest(statement, regex);
697 } else {
698 last_death_test_message = String::Format(
699 "Unknown death test style \"%s\" encountered",
700 GTEST_FLAG(death_test_style).c_str());
701 return false;
704 return true;
707 // Splits a given string on a given delimiter, populating a given
708 // vector with the fields. GTEST_HAS_DEATH_TEST implies that we have
709 // ::std::string, so we can use it here.
710 static void SplitString(const ::std::string& str, char delimiter,
711 ::std::vector< ::std::string>* dest) {
712 ::std::vector< ::std::string> parsed;
713 ::std::string::size_type pos = 0;
714 while (true) {
715 const ::std::string::size_type colon = str.find(delimiter, pos);
716 if (colon == ::std::string::npos) {
717 parsed.push_back(str.substr(pos));
718 break;
719 } else {
720 parsed.push_back(str.substr(pos, colon - pos));
721 pos = colon + 1;
724 dest->swap(parsed);
727 // Attempts to parse a string into a positive integer. Returns true
728 // if that is possible. GTEST_HAS_DEATH_TEST implies that we have
729 // ::std::string, so we can use it here.
730 static bool ParsePositiveInt(const ::std::string& str, int* number) {
731 // Fail fast if the given string does not begin with a digit;
732 // this bypasses strtol's "optional leading whitespace and plus
733 // or minus sign" semantics, which are undesirable here.
734 if (str.empty() || !isdigit(str[0])) {
735 return false;
737 char* endptr;
738 const long parsed = strtol(str.c_str(), &endptr, 10); // NOLINT
739 if (*endptr == '\0' && parsed <= INT_MAX) {
740 *number = static_cast<int>(parsed);
741 return true;
742 } else {
743 return false;
747 // Returns a newly created InternalRunDeathTestFlag object with fields
748 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
749 // the flag is specified; otherwise returns NULL.
750 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
751 if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
753 InternalRunDeathTestFlag* const internal_run_death_test_flag =
754 new InternalRunDeathTestFlag;
755 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
756 // can use it here.
757 ::std::vector< ::std::string> fields;
758 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), ':', &fields);
759 if (fields.size() != 4
760 || !ParsePositiveInt(fields[1], &internal_run_death_test_flag->line)
761 || !ParsePositiveInt(fields[2], &internal_run_death_test_flag->index)
762 || !ParsePositiveInt(fields[3],
763 &internal_run_death_test_flag->status_fd)) {
764 DeathTestAbort("Bad --gtest_internal_run_death_test flag: %s",
765 GTEST_FLAG(internal_run_death_test).c_str());
767 internal_run_death_test_flag->file = fields[0].c_str();
768 return internal_run_death_test_flag;
771 } // namespace internal
773 #endif // GTEST_HAS_DEATH_TEST
775 } // namespace testing