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), vladl@google.com (Vlad Losev)
32 // This file implements death tests.
34 #include <gtest/gtest-death-test.h>
35 #include <gtest/internal/gtest-port.h>
37 #if GTEST_HAS_DEATH_TEST
40 #include <crt_externs.h>
41 #endif // GTEST_OS_MAC
53 #endif // GTEST_OS_WINDOWS
55 #endif // GTEST_HAS_DEATH_TEST
57 #include <gtest/gtest-message.h>
58 #include <gtest/internal/gtest-string.h>
60 // Indicates that this translation unit is part of Google Test's
61 // implementation. It must come before gtest-internal-inl.h is
62 // included, or there will be a compiler error. This trick is to
63 // prevent a user from accidentally including gtest-internal-inl.h in
65 #define GTEST_IMPLEMENTATION_ 1
66 #include "gtest/internal/gtest-internal-inl.h"
67 #undef GTEST_IMPLEMENTATION_
73 // The default death test style.
74 static const char kDefaultDeathTestStyle
[] = "fast";
78 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle
),
79 "Indicates how to run a death test in a forked child process: "
80 "\"threadsafe\" (child process re-executes the test binary "
81 "from the beginning, running only the specific death test) or "
82 "\"fast\" (child process runs the death test immediately "
87 internal::BoolFromGTestEnv("death_test_use_fork", false),
88 "Instructs to use fork()/_exit() instead of clone() in death tests. "
89 "Ignored and always uses fork() on POSIX systems where clone() is not "
90 "implemented. Useful when running under valgrind or similar tools if "
91 "those do not support clone(). Valgrind 3.3.1 will just fail if "
92 "it sees an unsupported combination of clone() flags. "
93 "It is not recommended to use this flag w/o valgrind though it will "
94 "work in 99% of the cases. Once valgrind is fixed, this flag will "
95 "most likely be removed.");
99 internal_run_death_test
, "",
100 "Indicates the file, line number, temporal index of "
101 "the single death test to run, and a file descriptor to "
102 "which a success code may be sent, all separated by "
103 "colons. This flag is specified if and only if the current "
104 "process is a sub-process launched for running a thread-safe "
105 "death test. FOR INTERNAL USE ONLY.");
106 } // namespace internal
108 #if GTEST_HAS_DEATH_TEST
110 // ExitedWithCode constructor.
111 ExitedWithCode::ExitedWithCode(int exit_code
) : exit_code_(exit_code
) {
114 // ExitedWithCode function-call operator.
115 bool ExitedWithCode::operator()(int exit_status
) const {
117 return exit_status
== exit_code_
;
119 return WIFEXITED(exit_status
) && WEXITSTATUS(exit_status
) == exit_code_
;
120 #endif // GTEST_OS_WINDOWS
123 #if !GTEST_OS_WINDOWS
124 // KilledBySignal constructor.
125 KilledBySignal::KilledBySignal(int signum
) : signum_(signum
) {
128 // KilledBySignal function-call operator.
129 bool KilledBySignal::operator()(int exit_status
) const {
130 return WIFSIGNALED(exit_status
) && WTERMSIG(exit_status
) == signum_
;
132 #endif // !GTEST_OS_WINDOWS
136 // Utilities needed for death tests.
138 // Generates a textual description of a given exit code, in the format
139 // specified by wait(2).
140 static String
ExitSummary(int exit_code
) {
143 m
<< "Exited with exit status " << exit_code
;
145 if (WIFEXITED(exit_code
)) {
146 m
<< "Exited with exit status " << WEXITSTATUS(exit_code
);
147 } else if (WIFSIGNALED(exit_code
)) {
148 m
<< "Terminated by signal " << WTERMSIG(exit_code
);
151 if (WCOREDUMP(exit_code
)) {
152 m
<< " (core dumped)";
155 #endif // GTEST_OS_WINDOWS
156 return m
.GetString();
159 // Returns true if exit_status describes a process that was terminated
160 // by a signal, or exited normally with a nonzero exit code.
161 bool ExitedUnsuccessfully(int exit_status
) {
162 return !ExitedWithCode(0)(exit_status
);
165 #if !GTEST_OS_WINDOWS
166 // Generates a textual failure message when a death test finds more than
167 // one thread running, or cannot determine the number of threads, prior
168 // to executing the given statement. It is the responsibility of the
169 // caller not to pass a thread_count of 1.
170 static String
DeathTestThreadWarning(size_t thread_count
) {
172 msg
<< "Death tests use fork(), which is unsafe particularly"
173 << " in a threaded context. For this test, " << GTEST_NAME_
<< " ";
174 if (thread_count
== 0)
175 msg
<< "couldn't detect the number of threads.";
177 msg
<< "detected " << thread_count
<< " threads.";
178 return msg
.GetString();
180 #endif // !GTEST_OS_WINDOWS
182 // Flag characters for reporting a death test that did not die.
183 static const char kDeathTestLived
= 'L';
184 static const char kDeathTestReturned
= 'R';
185 static const char kDeathTestInternalError
= 'I';
187 // An enumeration describing all of the possible ways that a death test
188 // can conclude. DIED means that the process died while executing the
189 // test code; LIVED means that process lived beyond the end of the test
190 // code; and RETURNED means that the test statement attempted a "return,"
191 // which is not allowed. IN_PROGRESS means the test has not yet
193 enum DeathTestOutcome
{ IN_PROGRESS
, DIED
, LIVED
, RETURNED
};
195 // Routine for aborting the program which is safe to call from an
196 // exec-style death test child process, in which case the error
197 // message is propagated back to the parent process. Otherwise, the
198 // message is simply printed to stderr. In either case, the program
199 // then exits with status 1.
200 void DeathTestAbort(const String
& message
) {
201 // On a POSIX system, this function may be called from a threadsafe-style
202 // death test child process, which operates on a very small stack. Use
203 // the heap for any additional non-minuscule memory requirements.
204 const InternalRunDeathTestFlag
* const flag
=
205 GetUnitTestImpl()->internal_run_death_test_flag();
207 FILE* parent
= posix::FDOpen(flag
->write_fd(), "w");
208 fputc(kDeathTestInternalError
, parent
);
209 fprintf(parent
, "%s", message
.c_str());
213 fprintf(stderr
, "%s", message
.c_str());
219 // A replacement for CHECK that calls DeathTestAbort if the assertion
221 #define GTEST_DEATH_TEST_CHECK_(expression) \
223 if (!::testing::internal::IsTrue(expression)) { \
224 DeathTestAbort(::testing::internal::String::Format( \
225 "CHECK failed: File %s, line %d: %s", \
226 __FILE__, __LINE__, #expression)); \
228 } while (::testing::internal::AlwaysFalse())
230 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
231 // evaluating any system call that fulfills two conditions: it must return
232 // -1 on failure, and set errno to EINTR when it is interrupted and
233 // should be tried again. The macro expands to a loop that repeatedly
234 // evaluates the expression as long as it evaluates to -1 and sets
235 // errno to EINTR. If the expression evaluates to -1 but errno is
236 // something other than EINTR, DeathTestAbort is called.
237 #define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
241 gtest_retval = (expression); \
242 } while (gtest_retval == -1 && errno == EINTR); \
243 if (gtest_retval == -1) { \
244 DeathTestAbort(::testing::internal::String::Format( \
245 "CHECK failed: File %s, line %d: %s != -1", \
246 __FILE__, __LINE__, #expression)); \
248 } while (::testing::internal::AlwaysFalse())
250 // Returns the message describing the last system error in errno.
251 String
GetLastErrnoDescription() {
252 return String(errno
== 0 ? "" : posix::StrError(errno
));
255 // This is called from a death test parent process to read a failure
256 // message from the death test child process and log it with the FATAL
257 // severity. On Windows, the message is read from a pipe handle. On other
258 // platforms, it is read from a file descriptor.
259 static void FailFromInternalError(int fd
) {
265 while ((num_read
= posix::Read(fd
, buffer
, 255)) > 0) {
266 buffer
[num_read
] = '\0';
269 } while (num_read
== -1 && errno
== EINTR
);
272 GTEST_LOG_(FATAL
) << error
.GetString();
274 const int last_error
= errno
;
275 GTEST_LOG_(FATAL
) << "Error while reading death test internal: "
276 << GetLastErrnoDescription() << " [" << last_error
<< "]";
280 // Death test constructor. Increments the running death test count
281 // for the current test.
282 DeathTest::DeathTest() {
283 TestInfo
* const info
= GetUnitTestImpl()->current_test_info();
285 DeathTestAbort("Cannot run a death test outside of a TEST or "
290 // Creates and returns a death test by dispatching to the current
291 // death test factory.
292 bool DeathTest::Create(const char* statement
, const RE
* regex
,
293 const char* file
, int line
, DeathTest
** test
) {
294 return GetUnitTestImpl()->death_test_factory()->Create(
295 statement
, regex
, file
, line
, test
);
298 const char* DeathTest::LastMessage() {
299 return last_death_test_message_
.c_str();
302 void DeathTest::set_last_death_test_message(const String
& message
) {
303 last_death_test_message_
= message
;
306 String
DeathTest::last_death_test_message_
;
308 // Provides cross platform implementation for some death functionality.
309 class DeathTestImpl
: public DeathTest
{
311 DeathTestImpl(const char* a_statement
, const RE
* a_regex
)
312 : statement_(a_statement
),
316 outcome_(IN_PROGRESS
),
320 // read_fd_ is expected to be closed and cleared by a derived class.
321 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_
== -1); }
323 void Abort(AbortReason reason
);
324 virtual bool Passed(bool status_ok
);
326 const char* statement() const { return statement_
; }
327 const RE
* regex() const { return regex_
; }
328 bool spawned() const { return spawned_
; }
329 void set_spawned(bool is_spawned
) { spawned_
= is_spawned
; }
330 int status() const { return status_
; }
331 void set_status(int a_status
) { status_
= a_status
; }
332 DeathTestOutcome
outcome() const { return outcome_
; }
333 void set_outcome(DeathTestOutcome an_outcome
) { outcome_
= an_outcome
; }
334 int read_fd() const { return read_fd_
; }
335 void set_read_fd(int fd
) { read_fd_
= fd
; }
336 int write_fd() const { return write_fd_
; }
337 void set_write_fd(int fd
) { write_fd_
= fd
; }
339 // Called in the parent process only. Reads the result code of the death
340 // test child process via a pipe, interprets it to set the outcome_
341 // member, and closes read_fd_. Outputs diagnostics and terminates in
342 // case of unexpected codes.
343 void ReadAndInterpretStatusByte();
346 // The textual content of the code this object is testing. This class
347 // doesn't own this string and should not attempt to delete it.
348 const char* const statement_
;
349 // The regular expression which test output must match. DeathTestImpl
350 // doesn't own this object and should not attempt to delete it.
351 const RE
* const regex_
;
352 // True if the death test child process has been successfully spawned.
354 // The exit status of the child process.
356 // How the death test concluded.
357 DeathTestOutcome outcome_
;
358 // Descriptor to the read end of the pipe to the child process. It is
359 // always -1 in the child process. The child keeps its write end of the
360 // pipe in write_fd_.
362 // Descriptor to the child's write end of the pipe to the parent process.
363 // It is always -1 in the parent process. The parent keeps its end of the
368 // Called in the parent process only. Reads the result code of the death
369 // test child process via a pipe, interprets it to set the outcome_
370 // member, and closes read_fd_. Outputs diagnostics and terminates in
371 // case of unexpected codes.
372 void DeathTestImpl::ReadAndInterpretStatusByte() {
376 // The read() here blocks until data is available (signifying the
377 // failure of the death test) or until the pipe is closed (signifying
378 // its success), so it's okay to call this in the parent before
379 // the child process has exited.
381 bytes_read
= posix::Read(read_fd(), &flag
, 1);
382 } while (bytes_read
== -1 && errno
== EINTR
);
384 if (bytes_read
== 0) {
386 } else if (bytes_read
== 1) {
388 case kDeathTestReturned
:
389 set_outcome(RETURNED
);
391 case kDeathTestLived
:
394 case kDeathTestInternalError
:
395 FailFromInternalError(read_fd()); // Does not return.
398 GTEST_LOG_(FATAL
) << "Death test child process reported "
399 << "unexpected status byte ("
400 << static_cast<unsigned int>(flag
) << ")";
403 GTEST_LOG_(FATAL
) << "Read from death test child process failed: "
404 << GetLastErrnoDescription();
406 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
410 // Signals that the death test code which should have exited, didn't.
411 // Should be called only in a death test child process.
412 // Writes a status byte to the child's status file descriptor, then
414 void DeathTestImpl::Abort(AbortReason reason
) {
415 // The parent process considers the death test to be a failure if
416 // it finds any data in our pipe. So, here we write a single flag byte
417 // to the pipe, then exit.
418 const char status_ch
=
419 reason
== TEST_DID_NOT_DIE
? kDeathTestLived
: kDeathTestReturned
;
420 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch
, 1));
421 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(write_fd()));
422 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
425 // Assesses the success or failure of a death test, using both private
426 // members which have previously been set, and one argument:
428 // Private data members:
429 // outcome: An enumeration describing how the death test
430 // concluded: DIED, LIVED, or RETURNED. The death test fails
431 // in the latter two cases.
432 // status: The exit status of the child process. On *nix, it is in the
433 // in the format specified by wait(2). On Windows, this is the
434 // value supplied to the ExitProcess() API or a numeric code
435 // of the exception that terminated the program.
436 // regex: A regular expression object to be applied to
437 // the test's captured standard error output; the death test
438 // fails if it does not match.
441 // status_ok: true if exit_status is acceptable in the context of
442 // this particular death test, which fails if it is false
444 // Returns true iff all of the above conditions are met. Otherwise, the
445 // first failing condition, in the order given above, is the one that is
446 // reported. Also sets the last death test message string.
447 bool DeathTestImpl::Passed(bool status_ok
) {
451 const String error_message
= GetCapturedStderr();
453 bool success
= false;
456 buffer
<< "Death test: " << statement() << "\n";
459 buffer
<< " Result: failed to die.\n"
460 << " Error msg: " << error_message
;
463 buffer
<< " Result: illegal return in test statement.\n"
464 << " Error msg: " << error_message
;
468 const bool matched
= RE::PartialMatch(error_message
.c_str(), *regex());
472 buffer
<< " Result: died but not with expected error.\n"
473 << " Expected: " << regex()->pattern() << "\n"
474 << "Actual msg: " << error_message
;
477 buffer
<< " Result: died but not with expected exit code:\n"
478 << " " << ExitSummary(status()) << "\n";
484 << "DeathTest::Passed somehow called before conclusion of test";
487 DeathTest::set_last_death_test_message(buffer
.GetString());
492 // WindowsDeathTest implements death tests on Windows. Due to the
493 // specifics of starting new processes on Windows, death tests there are
494 // always threadsafe, and Google Test considers the
495 // --gtest_death_test_style=fast setting to be equivalent to
496 // --gtest_death_test_style=threadsafe there.
498 // A few implementation notes: Like the Linux version, the Windows
499 // implementation uses pipes for child-to-parent communication. But due to
500 // the specifics of pipes on Windows, some extra steps are required:
502 // 1. The parent creates a communication pipe and stores handles to both
504 // 2. The parent starts the child and provides it with the information
505 // necessary to acquire the handle to the write end of the pipe.
506 // 3. The child acquires the write end of the pipe and signals the parent
507 // using a Windows event.
508 // 4. Now the parent can release the write end of the pipe on its side. If
509 // this is done before step 3, the object's reference count goes down to
510 // 0 and it is destroyed, preventing the child from acquiring it. The
511 // parent now has to release it, or read operations on the read end of
512 // the pipe will not return when the child terminates.
513 // 5. The parent reads child's output through the pipe (outcome code and
514 // any possible error messages) from the pipe, and its stderr and then
515 // determines whether to fail the test.
517 // Note: to distinguish Win32 API calls from the local method and function
518 // calls, the former are explicitly resolved in the global namespace.
520 class WindowsDeathTest
: public DeathTestImpl
{
522 WindowsDeathTest(const char* statement
,
526 : DeathTestImpl(statement
, regex
), file_(file
), line_(line
) {}
528 // All of these virtual functions are inherited from DeathTest.
530 virtual TestRole
AssumeRole();
533 // The name of the file in which the death test is located.
534 const char* const file_
;
535 // The line number on which the death test is located.
537 // Handle to the write end of the pipe to the child process.
538 AutoHandle write_handle_
;
539 // Child process handle.
540 AutoHandle child_handle_
;
541 // Event the child process uses to signal the parent that it has
542 // acquired the handle to the write end of the pipe. After seeing this
543 // event the parent can release its own handles to make sure its
544 // ReadFile() calls return when the child terminates.
545 AutoHandle event_handle_
;
548 // Waits for the child in a death test to exit, returning its exit
549 // status, or 0 if no child process exists. As a side effect, sets the
550 // outcome data member.
551 int WindowsDeathTest::Wait() {
555 // Wait until the child either signals that it has acquired the write end
556 // of the pipe or it dies.
557 const HANDLE wait_handles
[2] = { child_handle_
.Get(), event_handle_
.Get() };
558 switch (::WaitForMultipleObjects(2,
560 FALSE
, // Waits for any of the handles.
563 case WAIT_OBJECT_0
+ 1:
566 GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
569 // The child has acquired the write end of the pipe or exited.
570 // We release the handle on our side and continue.
571 write_handle_
.Reset();
572 event_handle_
.Reset();
574 ReadAndInterpretStatusByte();
576 // Waits for the child process to exit if it haven't already. This
577 // returns immediately if the child has already exited, regardless of
578 // whether previous calls to WaitForMultipleObjects synchronized on this
580 GTEST_DEATH_TEST_CHECK_(
581 WAIT_OBJECT_0
== ::WaitForSingleObject(child_handle_
.Get(),
584 GTEST_DEATH_TEST_CHECK_(::GetExitCodeProcess(child_handle_
.Get(), &status
)
586 child_handle_
.Reset();
587 set_status(static_cast<int>(status
));
588 return this->status();
591 // The AssumeRole process for a Windows death test. It creates a child
592 // process with the same executable as the current process to run the
593 // death test. The child process is given the --gtest_filter and
594 // --gtest_internal_run_death_test flags such that it knows to run the
595 // current death test only.
596 DeathTest::TestRole
WindowsDeathTest::AssumeRole() {
597 const UnitTestImpl
* const impl
= GetUnitTestImpl();
598 const InternalRunDeathTestFlag
* const flag
=
599 impl
->internal_run_death_test_flag();
600 const TestInfo
* const info
= impl
->current_test_info();
601 const int death_test_index
= info
->result()->death_test_count();
604 // ParseInternalRunDeathTestFlag() has performed all the necessary
606 set_write_fd(flag
->write_fd());
610 // WindowsDeathTest uses an anonymous pipe to communicate results of
612 SECURITY_ATTRIBUTES handles_are_inheritable
= {
613 sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
614 HANDLE read_handle
, write_handle
;
615 GTEST_DEATH_TEST_CHECK_(
616 ::CreatePipe(&read_handle
, &write_handle
, &handles_are_inheritable
,
617 0) // Default buffer size.
619 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle
),
621 write_handle_
.Reset(write_handle
);
622 event_handle_
.Reset(::CreateEvent(
623 &handles_are_inheritable
,
624 TRUE
, // The event will automatically reset to non-signaled state.
625 FALSE
, // The initial state is non-signalled.
626 NULL
)); // The even is unnamed.
627 GTEST_DEATH_TEST_CHECK_(event_handle_
.Get() != NULL
);
628 const String filter_flag
= String::Format("--%s%s=%s.%s",
629 GTEST_FLAG_PREFIX_
, kFilterFlag
,
630 info
->test_case_name(),
632 const String internal_flag
= String::Format(
633 "--%s%s=%s|%d|%d|%u|%Iu|%Iu",
635 kInternalRunDeathTestFlag
,
638 static_cast<unsigned int>(::GetCurrentProcessId()),
639 // size_t has the same with as pointers on both 32-bit and 64-bit
640 // Windows platforms.
641 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
642 reinterpret_cast<size_t>(write_handle
),
643 reinterpret_cast<size_t>(event_handle_
.Get()));
645 char executable_path
[_MAX_PATH
+ 1]; // NOLINT
646 GTEST_DEATH_TEST_CHECK_(
647 _MAX_PATH
+ 1 != ::GetModuleFileNameA(NULL
,
651 String command_line
= String::Format("%s %s \"%s\"",
654 internal_flag
.c_str());
656 DeathTest::set_last_death_test_message("");
659 // Flush the log buffers since the log streams are shared with the child.
662 // The child process will share the standard handles with the parent.
663 STARTUPINFOA startup_info
;
664 memset(&startup_info
, 0, sizeof(STARTUPINFO
));
665 startup_info
.dwFlags
= STARTF_USESTDHANDLES
;
666 startup_info
.hStdInput
= ::GetStdHandle(STD_INPUT_HANDLE
);
667 startup_info
.hStdOutput
= ::GetStdHandle(STD_OUTPUT_HANDLE
);
668 startup_info
.hStdError
= ::GetStdHandle(STD_ERROR_HANDLE
);
670 PROCESS_INFORMATION process_info
;
671 GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
673 const_cast<char*>(command_line
.c_str()),
674 NULL
, // Retuned process handle is not inheritable.
675 NULL
, // Retuned thread handle is not inheritable.
676 TRUE
, // Child inherits all inheritable handles (for write_handle_).
677 0x0, // Default creation flags.
678 NULL
, // Inherit the parent's environment.
679 UnitTest::GetInstance()->original_working_dir(),
681 &process_info
) != FALSE
);
682 child_handle_
.Reset(process_info
.hProcess
);
683 ::CloseHandle(process_info
.hThread
);
687 #else // We are not on Windows.
689 // ForkingDeathTest provides implementations for most of the abstract
690 // methods of the DeathTest interface. Only the AssumeRole method is
692 class ForkingDeathTest
: public DeathTestImpl
{
694 ForkingDeathTest(const char* statement
, const RE
* regex
);
696 // All of these virtual functions are inherited from DeathTest.
700 void set_child_pid(pid_t child_pid
) { child_pid_
= child_pid
; }
703 // PID of child process during death test; 0 in the child process itself.
707 // Constructs a ForkingDeathTest.
708 ForkingDeathTest::ForkingDeathTest(const char* a_statement
, const RE
* a_regex
)
709 : DeathTestImpl(a_statement
, a_regex
),
712 // Waits for the child in a death test to exit, returning its exit
713 // status, or 0 if no child process exists. As a side effect, sets the
714 // outcome data member.
715 int ForkingDeathTest::Wait() {
719 ReadAndInterpretStatusByte();
722 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_
, &status_value
, 0));
723 set_status(status_value
);
727 // A concrete death test class that forks, then immediately runs the test
728 // in the child process.
729 class NoExecDeathTest
: public ForkingDeathTest
{
731 NoExecDeathTest(const char* a_statement
, const RE
* a_regex
) :
732 ForkingDeathTest(a_statement
, a_regex
) { }
733 virtual TestRole
AssumeRole();
736 // The AssumeRole process for a fork-and-run death test. It implements a
737 // straightforward fork, with a simple pipe to transmit the status byte.
738 DeathTest::TestRole
NoExecDeathTest::AssumeRole() {
739 const size_t thread_count
= GetThreadCount();
740 if (thread_count
!= 1) {
741 GTEST_LOG_(WARNING
) << DeathTestThreadWarning(thread_count
);
745 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd
) != -1);
747 DeathTest::set_last_death_test_message("");
749 // When we fork the process below, the log file buffers are copied, but the
750 // file descriptors are shared. We flush all log files here so that closing
751 // the file descriptors in the child process doesn't throw off the
752 // synchronization between descriptors and buffers in the parent process.
753 // This is as close to the fork as possible to avoid a race condition in case
754 // there are multiple threads running before the death test, and another
755 // thread writes to the log file.
758 const pid_t child_pid
= fork();
759 GTEST_DEATH_TEST_CHECK_(child_pid
!= -1);
760 set_child_pid(child_pid
);
761 if (child_pid
== 0) {
762 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd
[0]));
763 set_write_fd(pipe_fd
[1]);
764 // Redirects all logging to stderr in the child process to prevent
765 // concurrent writes to the log files. We capture stderr in the parent
766 // process and append the child process' output to a log.
768 // Event forwarding to the listeners of event listener API mush be shut
769 // down in death test subprocesses.
770 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
773 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd
[1]));
774 set_read_fd(pipe_fd
[0]);
780 // A concrete death test class that forks and re-executes the main
781 // program from the beginning, with command-line flags set that cause
782 // only this specific death test to be run.
783 class ExecDeathTest
: public ForkingDeathTest
{
785 ExecDeathTest(const char* a_statement
, const RE
* a_regex
,
786 const char* file
, int line
) :
787 ForkingDeathTest(a_statement
, a_regex
), file_(file
), line_(line
) { }
788 virtual TestRole
AssumeRole();
790 // The name of the file in which the death test is located.
791 const char* const file_
;
792 // The line number on which the death test is located.
796 // Utility class for accumulating command-line arguments.
800 args_
.push_back(NULL
);
804 for (std::vector
<char*>::iterator i
= args_
.begin(); i
!= args_
.end();
809 void AddArgument(const char* argument
) {
810 args_
.insert(args_
.end() - 1, posix::StrDup(argument
));
813 template <typename Str
>
814 void AddArguments(const ::std::vector
<Str
>& arguments
) {
815 for (typename ::std::vector
<Str
>::const_iterator i
= arguments
.begin();
816 i
!= arguments
.end();
818 args_
.insert(args_
.end() - 1, posix::StrDup(i
->c_str()));
821 char* const* Argv() {
825 std::vector
<char*> args_
;
828 // A struct that encompasses the arguments to the child process of a
829 // threadsafe-style death test process.
830 struct ExecDeathTestArgs
{
831 char* const* argv
; // Command-line arguments for the child's call to exec
832 int close_fd
; // File descriptor to close; the read end of a pipe
836 inline char** GetEnviron() {
837 // When Google Test is built as a framework on MacOS X, the environ variable
838 // is unavailable. Apple's documentation (man environ) recommends using
839 // _NSGetEnviron() instead.
840 return *_NSGetEnviron();
843 // Some POSIX platforms expect you to declare environ. extern "C" makes
844 // it reside in the global namespace.
845 extern "C" char** environ
;
846 inline char** GetEnviron() { return environ
; }
847 #endif // GTEST_OS_MAC
849 // The main function for a threadsafe-style death test child process.
850 // This function is called in a clone()-ed process and thus must avoid
851 // any potentially unsafe operations like malloc or libc functions.
852 static int ExecDeathTestChildMain(void* child_arg
) {
853 ExecDeathTestArgs
* const args
= static_cast<ExecDeathTestArgs
*>(child_arg
);
854 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args
->close_fd
));
856 // We need to execute the test program in the same environment where
857 // it was originally invoked. Therefore we change to the original
858 // working directory first.
859 const char* const original_dir
=
860 UnitTest::GetInstance()->original_working_dir();
861 // We can safely call chdir() as it's a direct system call.
862 if (chdir(original_dir
) != 0) {
863 DeathTestAbort(String::Format("chdir(\"%s\") failed: %s",
865 GetLastErrnoDescription().c_str()));
869 // We can safely call execve() as it's a direct system call. We
870 // cannot use execvp() as it's a libc function and thus potentially
871 // unsafe. Since execve() doesn't search the PATH, the user must
872 // invoke the test program via a valid path that contains at least
873 // one path separator.
874 execve(args
->argv
[0], args
->argv
, GetEnviron());
875 DeathTestAbort(String::Format("execve(%s, ...) in %s failed: %s",
878 GetLastErrnoDescription().c_str()));
882 // Two utility routines that together determine the direction the stack
884 // This could be accomplished more elegantly by a single recursive
885 // function, but we want to guard against the unlikely possibility of
886 // a smart compiler optimizing the recursion away.
887 bool StackLowerThanAddress(const void* ptr
) {
892 bool StackGrowsDown() {
894 return StackLowerThanAddress(&dummy
);
897 // A threadsafe implementation of fork(2) for threadsafe-style death tests
898 // that uses clone(2). It dies with an error message if anything goes
900 static pid_t
ExecDeathTestFork(char* const* argv
, int close_fd
) {
901 ExecDeathTestArgs args
= { argv
, close_fd
};
902 pid_t child_pid
= -1;
905 const bool use_fork
= GTEST_FLAG(death_test_use_fork
);
908 static const bool stack_grows_down
= StackGrowsDown();
909 const size_t stack_size
= getpagesize();
910 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
911 void* const stack
= mmap(NULL
, stack_size
, PROT_READ
| PROT_WRITE
,
912 MAP_ANON
| MAP_PRIVATE
, -1, 0);
913 GTEST_DEATH_TEST_CHECK_(stack
!= MAP_FAILED
);
914 void* const stack_top
=
915 static_cast<char*>(stack
) + (stack_grows_down
? stack_size
: 0);
917 child_pid
= clone(&ExecDeathTestChildMain
, stack_top
, SIGCHLD
, &args
);
919 GTEST_DEATH_TEST_CHECK_(munmap(stack
, stack_size
) != -1);
922 const bool use_fork
= true;
923 #endif // GTEST_HAS_CLONE
925 if (use_fork
&& (child_pid
= fork()) == 0) {
926 ExecDeathTestChildMain(&args
);
930 GTEST_DEATH_TEST_CHECK_(child_pid
!= -1);
934 // The AssumeRole process for a fork-and-exec death test. It re-executes the
935 // main program from the beginning, setting the --gtest_filter
936 // and --gtest_internal_run_death_test flags to cause only the current
937 // death test to be re-run.
938 DeathTest::TestRole
ExecDeathTest::AssumeRole() {
939 const UnitTestImpl
* const impl
= GetUnitTestImpl();
940 const InternalRunDeathTestFlag
* const flag
=
941 impl
->internal_run_death_test_flag();
942 const TestInfo
* const info
= impl
->current_test_info();
943 const int death_test_index
= info
->result()->death_test_count();
946 set_write_fd(flag
->write_fd());
951 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd
) != -1);
952 // Clear the close-on-exec flag on the write end of the pipe, lest
953 // it be closed when the child process does an exec:
954 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd
[1], F_SETFD
, 0) != -1);
956 const String filter_flag
=
957 String::Format("--%s%s=%s.%s",
958 GTEST_FLAG_PREFIX_
, kFilterFlag
,
959 info
->test_case_name(), info
->name());
960 const String internal_flag
=
961 String::Format("--%s%s=%s|%d|%d|%d",
962 GTEST_FLAG_PREFIX_
, kInternalRunDeathTestFlag
,
963 file_
, line_
, death_test_index
, pipe_fd
[1]);
965 args
.AddArguments(GetArgvs());
966 args
.AddArgument(filter_flag
.c_str());
967 args
.AddArgument(internal_flag
.c_str());
969 DeathTest::set_last_death_test_message("");
972 // See the comment in NoExecDeathTest::AssumeRole for why the next line
976 const pid_t child_pid
= ExecDeathTestFork(args
.Argv(), pipe_fd
[0]);
977 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd
[1]));
978 set_child_pid(child_pid
);
979 set_read_fd(pipe_fd
[0]);
984 #endif // !GTEST_OS_WINDOWS
986 // Creates a concrete DeathTest-derived class that depends on the
987 // --gtest_death_test_style flag, and sets the pointer pointed to
988 // by the "test" argument to its address. If the test should be
989 // skipped, sets that pointer to NULL. Returns true, unless the
990 // flag is set to an invalid value.
991 bool DefaultDeathTestFactory::Create(const char* statement
, const RE
* regex
,
992 const char* file
, int line
,
994 UnitTestImpl
* const impl
= GetUnitTestImpl();
995 const InternalRunDeathTestFlag
* const flag
=
996 impl
->internal_run_death_test_flag();
997 const int death_test_index
= impl
->current_test_info()
998 ->increment_death_test_count();
1001 if (death_test_index
> flag
->index()) {
1002 DeathTest::set_last_death_test_message(String::Format(
1003 "Death test count (%d) somehow exceeded expected maximum (%d)",
1004 death_test_index
, flag
->index()));
1008 if (!(flag
->file() == file
&& flag
->line() == line
&&
1009 flag
->index() == death_test_index
)) {
1015 #if GTEST_OS_WINDOWS
1016 if (GTEST_FLAG(death_test_style
) == "threadsafe" ||
1017 GTEST_FLAG(death_test_style
) == "fast") {
1018 *test
= new WindowsDeathTest(statement
, regex
, file
, line
);
1021 if (GTEST_FLAG(death_test_style
) == "threadsafe") {
1022 *test
= new ExecDeathTest(statement
, regex
, file
, line
);
1023 } else if (GTEST_FLAG(death_test_style
) == "fast") {
1024 *test
= new NoExecDeathTest(statement
, regex
);
1026 #endif // GTEST_OS_WINDOWS
1027 else { // NOLINT - this is more readable than unbalanced brackets inside #if.
1028 DeathTest::set_last_death_test_message(String::Format(
1029 "Unknown death test style \"%s\" encountered",
1030 GTEST_FLAG(death_test_style
).c_str()));
1037 // Splits a given string on a given delimiter, populating a given
1038 // vector with the fields. GTEST_HAS_DEATH_TEST implies that we have
1039 // ::std::string, so we can use it here.
1040 static void SplitString(const ::std::string
& str
, char delimiter
,
1041 ::std::vector
< ::std::string
>* dest
) {
1042 ::std::vector
< ::std::string
> parsed
;
1043 ::std::string::size_type pos
= 0;
1044 while (::testing::internal::AlwaysTrue()) {
1045 const ::std::string::size_type colon
= str
.find(delimiter
, pos
);
1046 if (colon
== ::std::string::npos
) {
1047 parsed
.push_back(str
.substr(pos
));
1050 parsed
.push_back(str
.substr(pos
, colon
- pos
));
1057 #if GTEST_OS_WINDOWS
1058 // Recreates the pipe and event handles from the provided parameters,
1059 // signals the event, and returns a file descriptor wrapped around the pipe
1060 // handle. This function is called in the child process only.
1061 int GetStatusFileDescriptor(unsigned int parent_process_id
,
1062 size_t write_handle_as_size_t
,
1063 size_t event_handle_as_size_t
) {
1064 AutoHandle
parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE
,
1065 FALSE
, // Non-inheritable.
1066 parent_process_id
));
1067 if (parent_process_handle
.Get() == INVALID_HANDLE_VALUE
) {
1068 DeathTestAbort(String::Format("Unable to open parent process %u",
1069 parent_process_id
));
1072 // TODO(vladl@google.com): Replace the following check with a
1073 // compile-time assertion when available.
1074 GTEST_CHECK_(sizeof(HANDLE
) <= sizeof(size_t));
1076 const HANDLE write_handle
=
1077 reinterpret_cast<HANDLE
>(write_handle_as_size_t
);
1078 HANDLE dup_write_handle
;
1080 // The newly initialized handle is accessible only in in the parent
1081 // process. To obtain one accessible within the child, we need to use
1083 if (!::DuplicateHandle(parent_process_handle
.Get(), write_handle
,
1084 ::GetCurrentProcess(), &dup_write_handle
,
1085 0x0, // Requested privileges ignored since
1086 // DUPLICATE_SAME_ACCESS is used.
1087 FALSE
, // Request non-inheritable handler.
1088 DUPLICATE_SAME_ACCESS
)) {
1089 DeathTestAbort(String::Format(
1090 "Unable to duplicate the pipe handle %Iu from the parent process %u",
1091 write_handle_as_size_t
, parent_process_id
));
1094 const HANDLE event_handle
= reinterpret_cast<HANDLE
>(event_handle_as_size_t
);
1095 HANDLE dup_event_handle
;
1097 if (!::DuplicateHandle(parent_process_handle
.Get(), event_handle
,
1098 ::GetCurrentProcess(), &dup_event_handle
,
1101 DUPLICATE_SAME_ACCESS
)) {
1102 DeathTestAbort(String::Format(
1103 "Unable to duplicate the event handle %Iu from the parent process %u",
1104 event_handle_as_size_t
, parent_process_id
));
1107 const int write_fd
=
1108 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle
), O_APPEND
);
1109 if (write_fd
== -1) {
1110 DeathTestAbort(String::Format(
1111 "Unable to convert pipe handle %Iu to a file descriptor",
1112 write_handle_as_size_t
));
1115 // Signals the parent that the write end of the pipe has been acquired
1116 // so the parent can release its own write end.
1117 ::SetEvent(dup_event_handle
);
1121 #endif // GTEST_OS_WINDOWS
1123 // Returns a newly created InternalRunDeathTestFlag object with fields
1124 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
1125 // the flag is specified; otherwise returns NULL.
1126 InternalRunDeathTestFlag
* ParseInternalRunDeathTestFlag() {
1127 if (GTEST_FLAG(internal_run_death_test
) == "") return NULL
;
1129 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
1133 ::std::vector
< ::std::string
> fields
;
1134 SplitString(GTEST_FLAG(internal_run_death_test
).c_str(), '|', &fields
);
1137 #if GTEST_OS_WINDOWS
1138 unsigned int parent_process_id
= 0;
1139 size_t write_handle_as_size_t
= 0;
1140 size_t event_handle_as_size_t
= 0;
1142 if (fields
.size() != 6
1143 || !ParseNaturalNumber(fields
[1], &line
)
1144 || !ParseNaturalNumber(fields
[2], &index
)
1145 || !ParseNaturalNumber(fields
[3], &parent_process_id
)
1146 || !ParseNaturalNumber(fields
[4], &write_handle_as_size_t
)
1147 || !ParseNaturalNumber(fields
[5], &event_handle_as_size_t
)) {
1148 DeathTestAbort(String::Format(
1149 "Bad --gtest_internal_run_death_test flag: %s",
1150 GTEST_FLAG(internal_run_death_test
).c_str()));
1152 write_fd
= GetStatusFileDescriptor(parent_process_id
,
1153 write_handle_as_size_t
,
1154 event_handle_as_size_t
);
1156 if (fields
.size() != 4
1157 || !ParseNaturalNumber(fields
[1], &line
)
1158 || !ParseNaturalNumber(fields
[2], &index
)
1159 || !ParseNaturalNumber(fields
[3], &write_fd
)) {
1160 DeathTestAbort(String::Format(
1161 "Bad --gtest_internal_run_death_test flag: %s",
1162 GTEST_FLAG(internal_run_death_test
).c_str()));
1164 #endif // GTEST_OS_WINDOWS
1165 return new InternalRunDeathTestFlag(fields
[0], line
, index
, write_fd
);
1168 } // namespace internal
1170 #endif // GTEST_HAS_DEATH_TEST
1172 } // namespace testing