1 // Copyright 2005, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
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
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
51 #define GTEST_IMPLEMENTATION
52 #include "gtest/internal/gtest-internal-inl.h"
53 #undef GTEST_IMPLEMENTATION
59 // The default death test style.
60 static const char kDefaultDeathTestStyle
[] = "fast";
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 "
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_
;
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
) {
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
);
116 if (WCOREDUMP(exit_code
)) {
117 m
<< " (core dumped)";
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
) {
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.";
140 msg
<< "detected " << thread_count
<< " threads.";
141 return msg
.GetString();
144 // Static string containing a description of the outcome of the
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
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();
173 va_start(args
, format
);
176 FILE* parent
= fdopen(flag
->status_fd
, "w");
177 fputc(kDeathTestInternalError
, parent
);
178 vfprintf(parent
, format
, args
);
183 vfprintf(stderr
, format
, args
);
189 // A replacement for CHECK that calls DeathTestAbort if the assertion
191 #define GTEST_DEATH_TEST_CHECK_(expression) \
193 if (!(expression)) { \
194 DeathTestAbort("CHECK failed: File %s, line %d: %s", \
195 __FILE__, __LINE__, #expression); \
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) \
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); \
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();
223 DeathTestAbort("Cannot run a death test outside of a TEST or "
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
243 class ForkingDeathTest
: public DeathTest
{
245 ForkingDeathTest(const char* statement
, const RE
* regex
);
247 // All of these virtual functions are inherited from DeathTest.
249 virtual bool Passed(bool status_ok
);
250 virtual void Abort(AbortReason reason
);
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
; }
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.
265 // PID of child process during death test; 0 in the child process itself.
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.
272 // How the death test concluded.
273 DeathTestOutcome outcome_
;
276 // Constructs a ForkingDeathTest.
277 ForkingDeathTest::ForkingDeathTest(const char* statement
, const RE
* regex
)
279 statement_(statement
),
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
) {
298 while ((num_read
= read(fd
, buffer
, 255)) > 0) {
299 buffer
[num_read
] = '\0';
302 } while (num_read
== -1 && errno
== EINTR
);
304 // TODO(smcafee): Maybe just FAIL the test instead?
306 GTEST_LOG_(FATAL
, error
);
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() {
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.
329 bytes_read
= read(read_fd_
, &flag
, 1);
330 } while (bytes_read
== -1 && errno
== EINTR
);
332 if (bytes_read
== 0) {
334 } else if (bytes_read
== 1) {
336 case kDeathTestReturned
:
339 case kDeathTestLived
:
342 case kDeathTestInternalError
:
343 FailFromInternalError(read_fd_
); // Does not return.
347 Message() << "Death test child process reported unexpected "
348 << "status byte (" << static_cast<unsigned int>(flag
)
353 Message() << "Read from death test child process failed: "
357 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(read_fd_
));
358 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_
, &status_
, 0));
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
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
) {
386 #if GTEST_HAS_GLOBAL_STRING
387 const ::string error_message
= GetCapturedStderr();
389 const ::std::string error_message
= GetCapturedStderr();
390 #endif // GTEST_HAS_GLOBAL_STRING
392 bool success
= false;
395 buffer
<< "Death test: " << statement_
<< "\n";
398 buffer
<< " Result: failed to die.\n"
399 << " Error msg: " << error_message
;
402 buffer
<< " Result: illegal return in test statement.\n"
403 << " Error msg: " << error_message
;
407 if (RE::PartialMatch(error_message
, *regex_
)) {
410 buffer
<< " Result: died but not with expected error.\n"
411 << " Expected: " << regex_
->pattern() << "\n"
412 << "Actual msg: " << error_message
;
415 buffer
<< " Result: died but not with expected exit code:\n"
416 << " " << ExitSummary(status_
) << "\n";
422 "DeathTest::Passed somehow called before conclusion of test");
425 last_death_test_message
= buffer
.GetString();
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
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.
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
{
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
));
462 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd
) != -1);
464 last_death_test_message
= "";
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.
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.
487 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd
[1]));
488 set_read_fd(pipe_fd
[0]);
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
{
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();
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.
510 // Utility class for accumulating command-line arguments.
514 args_
.push_back(NULL
);
517 for (std::vector
<char*>::iterator i
= args_
.begin();
518 i
+ 1 != args_
.end();
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();
532 args_
.insert(args_
.end() - 1, strdup(i
->c_str()));
535 char* const* Argv() {
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
));
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
));
579 // Two utility routines that together determine the direction the stack
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
) {
589 static bool StackGrowsDown() {
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
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
,
608 GTEST_DEATH_TEST_CHECK_(child_pid
!= -1);
609 GTEST_DEATH_TEST_CHECK_(munmap(stack
, stack_size
) != -1);
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();
625 set_write_fd(flag
->status_fd
);
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]);
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
= "";
652 // See the comment in NoExecDeathTest::AssumeRole for why the next line
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]);
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
,
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();
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
);
686 if (!(flag
->file
== file
&& flag
->line
== line
&&
687 flag
->index
== death_test_index
)) {
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
);
698 last_death_test_message
= String::Format(
699 "Unknown death test style \"%s\" encountered",
700 GTEST_FLAG(death_test_style
).c_str());
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;
715 const ::std::string::size_type colon
= str
.find(delimiter
, pos
);
716 if (colon
== ::std::string::npos
) {
717 parsed
.push_back(str
.substr(pos
));
720 parsed
.push_back(str
.substr(pos
, colon
- pos
));
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])) {
738 const long parsed
= strtol(str
.c_str(), &endptr
, 10); // NOLINT
739 if (*endptr
== '\0' && parsed
<= INT_MAX
) {
740 *number
= static_cast<int>(parsed
);
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
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