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
49 # endif // GTEST_OS_LINUX
56 # include <sys/mman.h>
57 # include <sys/wait.h>
58 # endif // GTEST_OS_WINDOWS
62 # endif // GTEST_OS_QNX
64 #endif // GTEST_HAS_DEATH_TEST
66 #include "gtest/gtest-message.h"
67 #include "gtest/internal/gtest-string.h"
69 // Indicates that this translation unit is part of Google Test's
70 // implementation. It must come before gtest-internal-inl.h is
71 // included, or there will be a compiler error. This trick is to
72 // prevent a user from accidentally including gtest-internal-inl.h in
74 #define GTEST_IMPLEMENTATION_ 1
75 #include "src/gtest-internal-inl.h"
76 #undef GTEST_IMPLEMENTATION_
82 // The default death test style.
83 static const char kDefaultDeathTestStyle[] = "fast";
87 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
88 "Indicates how to run a death test in a forked child process: "
89 "\"threadsafe\" (child process re-executes the test binary "
90 "from the beginning, running only the specific death test) or "
91 "\"fast\" (child process runs the death test immediately "
96 internal::BoolFromGTestEnv("death_test_use_fork", false),
97 "Instructs to use fork()/_exit() instead of clone() in death tests. "
98 "Ignored and always uses fork() on POSIX systems where clone() is not "
99 "implemented. Useful when running under valgrind or similar tools if "
100 "those do not support clone(). Valgrind 3.3.1 will just fail if "
101 "it sees an unsupported combination of clone() flags. "
102 "It is not recommended to use this flag w/o valgrind though it will "
103 "work in 99% of the cases. Once valgrind is fixed, this flag will "
104 "most likely be removed.");
107 GTEST_DEFINE_string_(
108 internal_run_death_test, "",
109 "Indicates the file, line number, temporal index of "
110 "the single death test to run, and a file descriptor to "
111 "which a success code may be sent, all separated by "
112 "the '|' characters. This flag is specified if and only if the current "
113 "process is a sub-process launched for running a thread-safe "
114 "death test. FOR INTERNAL USE ONLY.");
115 } // namespace internal
117 #if GTEST_HAS_DEATH_TEST
121 // Valid only for fast death tests. Indicates the code is running in the
122 // child process of a fast style death test.
123 static bool g_in_fast_death_test_child = false;
125 // Returns a Boolean value indicating whether the caller is currently
126 // executing in the context of the death test child process. Tools such as
127 // Valgrind heap checkers may need this to modify their behavior in death
128 // tests. IMPORTANT: This is an internal utility. Using it may break the
129 // implementation of death tests. User code MUST NOT use it.
130 bool InDeathTestChild() {
131 # if GTEST_OS_WINDOWS
133 // On Windows, death tests are thread-safe regardless of the value of the
134 // death_test_style flag.
135 return !GTEST_FLAG(internal_run_death_test).empty();
139 if (GTEST_FLAG(death_test_style) == "threadsafe")
140 return !GTEST_FLAG(internal_run_death_test).empty();
142 return g_in_fast_death_test_child;
146 } // namespace internal
148 // ExitedWithCode constructor.
149 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
152 // ExitedWithCode function-call operator.
153 bool ExitedWithCode::operator()(int exit_status) const {
154 # if GTEST_OS_WINDOWS
156 return exit_status == exit_code_;
160 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
162 # endif // GTEST_OS_WINDOWS
165 # if !GTEST_OS_WINDOWS
166 // KilledBySignal constructor.
167 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
170 // KilledBySignal function-call operator.
171 bool KilledBySignal::operator()(int exit_status) const {
172 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
174 # endif // !GTEST_OS_WINDOWS
178 // Utilities needed for death tests.
180 // Generates a textual description of a given exit code, in the format
181 // specified by wait(2).
182 static std::string ExitSummary(int exit_code) {
185 # if GTEST_OS_WINDOWS
187 m << "Exited with exit status " << exit_code;
191 if (WIFEXITED(exit_code)) {
192 m << "Exited with exit status " << WEXITSTATUS(exit_code);
193 } else if (WIFSIGNALED(exit_code)) {
194 m << "Terminated by signal " << WTERMSIG(exit_code);
197 if (WCOREDUMP(exit_code)) {
198 m << " (core dumped)";
201 # endif // GTEST_OS_WINDOWS
203 return m.GetString();
206 // Returns true if exit_status describes a process that was terminated
207 // by a signal, or exited normally with a nonzero exit code.
208 bool ExitedUnsuccessfully(int exit_status) {
209 return !ExitedWithCode(0)(exit_status);
212 # if !GTEST_OS_WINDOWS
213 // Generates a textual failure message when a death test finds more than
214 // one thread running, or cannot determine the number of threads, prior
215 // to executing the given statement. It is the responsibility of the
216 // caller not to pass a thread_count of 1.
217 static std::string DeathTestThreadWarning(size_t thread_count) {
219 msg << "Death tests use fork(), which is unsafe particularly"
220 << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
221 if (thread_count == 0)
222 msg << "couldn't detect the number of threads.";
224 msg << "detected " << thread_count << " threads.";
225 return msg.GetString();
227 # endif // !GTEST_OS_WINDOWS
229 // Flag characters for reporting a death test that did not die.
230 static const char kDeathTestLived = 'L';
231 static const char kDeathTestReturned = 'R';
232 static const char kDeathTestThrew = 'T';
233 static const char kDeathTestInternalError = 'I';
235 // An enumeration describing all of the possible ways that a death test can
236 // conclude. DIED means that the process died while executing the test
237 // code; LIVED means that process lived beyond the end of the test code;
238 // RETURNED means that the test statement attempted to execute a return
239 // statement, which is not allowed; THREW means that the test statement
240 // returned control by throwing an exception. IN_PROGRESS means the test
241 // has not yet concluded.
242 // TODO(vladl@google.com): Unify names and possibly values for
243 // AbortReason, DeathTestOutcome, and flag characters above.
244 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
246 // Routine for aborting the program which is safe to call from an
247 // exec-style death test child process, in which case the error
248 // message is propagated back to the parent process. Otherwise, the
249 // message is simply printed to stderr. In either case, the program
250 // then exits with status 1.
251 void DeathTestAbort(const std::string& message) {
252 // On a POSIX system, this function may be called from a threadsafe-style
253 // death test child process, which operates on a very small stack. Use
254 // the heap for any additional non-minuscule memory requirements.
255 const InternalRunDeathTestFlag* const flag =
256 GetUnitTestImpl()->internal_run_death_test_flag();
258 FILE* parent = posix::FDOpen(flag->write_fd(), "w");
259 fputc(kDeathTestInternalError, parent);
260 fprintf(parent, "%s", message.c_str());
264 fprintf(stderr, "%s", message.c_str());
270 // A replacement for CHECK that calls DeathTestAbort if the assertion
272 # define GTEST_DEATH_TEST_CHECK_(expression) \
274 if (!::testing::internal::IsTrue(expression)) { \
275 DeathTestAbort(::testing::internal::String::Format( \
276 "CHECK failed: File %s, line %d: %s", \
277 __FILE__, __LINE__, #expression)); \
279 } while (::testing::internal::AlwaysFalse())
281 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
282 // evaluating any system call that fulfills two conditions: it must return
283 // -1 on failure, and set errno to EINTR when it is interrupted and
284 // should be tried again. The macro expands to a loop that repeatedly
285 // evaluates the expression as long as it evaluates to -1 and sets
286 // errno to EINTR. If the expression evaluates to -1 but errno is
287 // something other than EINTR, DeathTestAbort is called.
288 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
292 gtest_retval = (expression); \
293 } while (gtest_retval == -1 && errno == EINTR); \
294 if (gtest_retval == -1) { \
295 DeathTestAbort(::testing::internal::String::Format( \
296 "CHECK failed: File %s, line %d: %s != -1", \
297 __FILE__, __LINE__, #expression)); \
299 } while (::testing::internal::AlwaysFalse())
301 // Returns the message describing the last system error in errno.
302 std::string GetLastErrnoDescription() {
303 return errno == 0 ? "" : posix::StrError(errno);
306 // This is called from a death test parent process to read a failure
307 // message from the death test child process and log it with the FATAL
308 // severity. On Windows, the message is read from a pipe handle. On other
309 // platforms, it is read from a file descriptor.
310 static void FailFromInternalError(int fd) {
316 while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
317 buffer[num_read] = '\0';
320 } while (num_read == -1 && errno == EINTR);
323 GTEST_LOG_(FATAL) << error.GetString();
325 const int last_error = errno;
326 GTEST_LOG_(FATAL) << "Error while reading death test internal: "
327 << GetLastErrnoDescription() << " [" << last_error << "]";
331 // Death test constructor. Increments the running death test count
332 // for the current test.
333 DeathTest::DeathTest() {
334 TestInfo* const info = GetUnitTestImpl()->current_test_info();
336 DeathTestAbort("Cannot run a death test outside of a TEST or "
341 // Creates and returns a death test by dispatching to the current
342 // death test factory.
343 bool DeathTest::Create(const char* statement, const RE* regex,
344 const char* file, int line, DeathTest** test) {
345 return GetUnitTestImpl()->death_test_factory()->Create(
346 statement, regex, file, line, test);
349 const char* DeathTest::LastMessage() {
350 return last_death_test_message_.c_str();
353 void DeathTest::set_last_death_test_message(const std::string& message) {
354 last_death_test_message_ = message;
357 std::string DeathTest::last_death_test_message_;
359 // Provides cross platform implementation for some death functionality.
360 class DeathTestImpl : public DeathTest {
362 DeathTestImpl(const char* a_statement, const RE* a_regex)
363 : statement_(a_statement),
367 outcome_(IN_PROGRESS),
371 // read_fd_ is expected to be closed and cleared by a derived class.
372 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
374 void Abort(AbortReason reason);
375 virtual bool Passed(bool status_ok);
377 const char* statement() const { return statement_; }
378 const RE* regex() const { return regex_; }
379 bool spawned() const { return spawned_; }
380 void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
381 int status() const { return status_; }
382 void set_status(int a_status) { status_ = a_status; }
383 DeathTestOutcome outcome() const { return outcome_; }
384 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
385 int read_fd() const { return read_fd_; }
386 void set_read_fd(int fd) { read_fd_ = fd; }
387 int write_fd() const { return write_fd_; }
388 void set_write_fd(int fd) { write_fd_ = fd; }
390 // Called in the parent process only. Reads the result code of the death
391 // test child process via a pipe, interprets it to set the outcome_
392 // member, and closes read_fd_. Outputs diagnostics and terminates in
393 // case of unexpected codes.
394 void ReadAndInterpretStatusByte();
397 // The textual content of the code this object is testing. This class
398 // doesn't own this string and should not attempt to delete it.
399 const char* const statement_;
400 // The regular expression which test output must match. DeathTestImpl
401 // doesn't own this object and should not attempt to delete it.
402 const RE* const regex_;
403 // True if the death test child process has been successfully spawned.
405 // The exit status of the child process.
407 // How the death test concluded.
408 DeathTestOutcome outcome_;
409 // Descriptor to the read end of the pipe to the child process. It is
410 // always -1 in the child process. The child keeps its write end of the
411 // pipe in write_fd_.
413 // Descriptor to the child's write end of the pipe to the parent process.
414 // It is always -1 in the parent process. The parent keeps its end of the
419 // Called in the parent process only. Reads the result code of the death
420 // test child process via a pipe, interprets it to set the outcome_
421 // member, and closes read_fd_. Outputs diagnostics and terminates in
422 // case of unexpected codes.
423 void DeathTestImpl::ReadAndInterpretStatusByte() {
427 // The read() here blocks until data is available (signifying the
428 // failure of the death test) or until the pipe is closed (signifying
429 // its success), so it's okay to call this in the parent before
430 // the child process has exited.
432 bytes_read = posix::Read(read_fd(), &flag, 1);
433 } while (bytes_read == -1 && errno == EINTR);
435 if (bytes_read == 0) {
437 } else if (bytes_read == 1) {
439 case kDeathTestReturned:
440 set_outcome(RETURNED);
442 case kDeathTestThrew:
445 case kDeathTestLived:
448 case kDeathTestInternalError:
449 FailFromInternalError(read_fd()); // Does not return.
452 GTEST_LOG_(FATAL) << "Death test child process reported "
453 << "unexpected status byte ("
454 << static_cast<unsigned int>(flag) << ")";
457 GTEST_LOG_(FATAL) << "Read from death test child process failed: "
458 << GetLastErrnoDescription();
460 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
464 // Signals that the death test code which should have exited, didn't.
465 // Should be called only in a death test child process.
466 // Writes a status byte to the child's status file descriptor, then
468 void DeathTestImpl::Abort(AbortReason reason) {
469 // The parent process considers the death test to be a failure if
470 // it finds any data in our pipe. So, here we write a single flag byte
471 // to the pipe, then exit.
472 const char status_ch =
473 reason == TEST_DID_NOT_DIE ? kDeathTestLived :
474 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
476 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
477 // We are leaking the descriptor here because on some platforms (i.e.,
478 // when built as Windows DLL), destructors of global objects will still
479 // run after calling _exit(). On such systems, write_fd_ will be
480 // indirectly closed from the destructor of UnitTestImpl, causing double
481 // close if it is also closed here. On debug configurations, double close
482 // may assert. As there are no in-process buffers to flush here, we are
483 // relying on the OS to close the descriptor after the process terminates
484 // when the destructors are not run.
485 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
488 // Returns an indented copy of stderr output for a death test.
489 // This makes distinguishing death test output lines from regular log lines
491 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
493 for (size_t at = 0; ; ) {
494 const size_t line_end = output.find('\n', at);
496 if (line_end == ::std::string::npos) {
497 ret += output.substr(at);
500 ret += output.substr(at, line_end + 1 - at);
506 // Assesses the success or failure of a death test, using both private
507 // members which have previously been set, and one argument:
509 // Private data members:
510 // outcome: An enumeration describing how the death test
511 // concluded: DIED, LIVED, THREW, or RETURNED. The death test
512 // fails in the latter three cases.
513 // status: The exit status of the child process. On *nix, it is in the
514 // in the format specified by wait(2). On Windows, this is the
515 // value supplied to the ExitProcess() API or a numeric code
516 // of the exception that terminated the program.
517 // regex: A regular expression object to be applied to
518 // the test's captured standard error output; the death test
519 // fails if it does not match.
522 // status_ok: true if exit_status is acceptable in the context of
523 // this particular death test, which fails if it is false
525 // Returns true iff all of the above conditions are met. Otherwise, the
526 // first failing condition, in the order given above, is the one that is
527 // reported. Also sets the last death test message string.
528 bool DeathTestImpl::Passed(bool status_ok) {
532 const std::string error_message = GetCapturedStderr();
534 bool success = false;
537 buffer << "Death test: " << statement() << "\n";
540 buffer << " Result: failed to die.\n"
541 << " Error msg:\n" << FormatDeathTestOutput(error_message);
544 buffer << " Result: threw an exception.\n"
545 << " Error msg:\n" << FormatDeathTestOutput(error_message);
548 buffer << " Result: illegal return in test statement.\n"
549 << " Error msg:\n" << FormatDeathTestOutput(error_message);
553 const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
557 buffer << " Result: died but not with expected error.\n"
558 << " Expected: " << regex()->pattern() << "\n"
559 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
562 buffer << " Result: died but not with expected exit code:\n"
563 << " " << ExitSummary(status()) << "\n"
564 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
570 << "DeathTest::Passed somehow called before conclusion of test";
573 DeathTest::set_last_death_test_message(buffer.GetString());
577 # if GTEST_OS_WINDOWS
578 // WindowsDeathTest implements death tests on Windows. Due to the
579 // specifics of starting new processes on Windows, death tests there are
580 // always threadsafe, and Google Test considers the
581 // --gtest_death_test_style=fast setting to be equivalent to
582 // --gtest_death_test_style=threadsafe there.
584 // A few implementation notes: Like the Linux version, the Windows
585 // implementation uses pipes for child-to-parent communication. But due to
586 // the specifics of pipes on Windows, some extra steps are required:
588 // 1. The parent creates a communication pipe and stores handles to both
590 // 2. The parent starts the child and provides it with the information
591 // necessary to acquire the handle to the write end of the pipe.
592 // 3. The child acquires the write end of the pipe and signals the parent
593 // using a Windows event.
594 // 4. Now the parent can release the write end of the pipe on its side. If
595 // this is done before step 3, the object's reference count goes down to
596 // 0 and it is destroyed, preventing the child from acquiring it. The
597 // parent now has to release it, or read operations on the read end of
598 // the pipe will not return when the child terminates.
599 // 5. The parent reads child's output through the pipe (outcome code and
600 // any possible error messages) from the pipe, and its stderr and then
601 // determines whether to fail the test.
603 // Note: to distinguish Win32 API calls from the local method and function
604 // calls, the former are explicitly resolved in the global namespace.
606 class WindowsDeathTest : public DeathTestImpl {
608 WindowsDeathTest(const char* a_statement,
612 : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
614 // All of these virtual functions are inherited from DeathTest.
616 virtual TestRole AssumeRole();
619 // The name of the file in which the death test is located.
620 const char* const file_;
621 // The line number on which the death test is located.
623 // Handle to the write end of the pipe to the child process.
624 AutoHandle write_handle_;
625 // Child process handle.
626 AutoHandle child_handle_;
627 // Event the child process uses to signal the parent that it has
628 // acquired the handle to the write end of the pipe. After seeing this
629 // event the parent can release its own handles to make sure its
630 // ReadFile() calls return when the child terminates.
631 AutoHandle event_handle_;
634 // Waits for the child in a death test to exit, returning its exit
635 // status, or 0 if no child process exists. As a side effect, sets the
636 // outcome data member.
637 int WindowsDeathTest::Wait() {
641 // Wait until the child either signals that it has acquired the write end
642 // of the pipe or it dies.
643 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
644 switch (::WaitForMultipleObjects(2,
646 FALSE, // Waits for any of the handles.
649 case WAIT_OBJECT_0 + 1:
652 GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
655 // The child has acquired the write end of the pipe or exited.
656 // We release the handle on our side and continue.
657 write_handle_.Reset();
658 event_handle_.Reset();
660 ReadAndInterpretStatusByte();
662 // Waits for the child process to exit if it haven't already. This
663 // returns immediately if the child has already exited, regardless of
664 // whether previous calls to WaitForMultipleObjects synchronized on this
666 GTEST_DEATH_TEST_CHECK_(
667 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
670 GTEST_DEATH_TEST_CHECK_(
671 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
672 child_handle_.Reset();
673 set_status(static_cast<int>(status_code));
677 // The AssumeRole process for a Windows death test. It creates a child
678 // process with the same executable as the current process to run the
679 // death test. The child process is given the --gtest_filter and
680 // --gtest_internal_run_death_test flags such that it knows to run the
681 // current death test only.
682 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
683 const UnitTestImpl* const impl = GetUnitTestImpl();
684 const InternalRunDeathTestFlag* const flag =
685 impl->internal_run_death_test_flag();
686 const TestInfo* const info = impl->current_test_info();
687 const int death_test_index = info->result()->death_test_count();
690 // ParseInternalRunDeathTestFlag() has performed all the necessary
692 set_write_fd(flag->write_fd());
696 // WindowsDeathTest uses an anonymous pipe to communicate results of
698 SECURITY_ATTRIBUTES handles_are_inheritable = {
699 sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
700 HANDLE read_handle, write_handle;
701 GTEST_DEATH_TEST_CHECK_(
702 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
703 0) // Default buffer size.
705 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
707 write_handle_.Reset(write_handle);
708 event_handle_.Reset(::CreateEvent(
709 &handles_are_inheritable,
710 TRUE, // The event will automatically reset to non-signaled state.
711 FALSE, // The initial state is non-signalled.
712 NULL)); // The even is unnamed.
713 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
714 const std::string filter_flag =
715 std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
716 info->test_case_name() + "." + info->name();
717 const std::string internal_flag =
718 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
719 "=" + file_ + "|" + String::Format("%d|%d|%u|%Iu|%Iu", line_,
721 static_cast<unsigned int>(::GetCurrentProcessId()),
722 // size_t has the same with as pointers on both 32-bit and 64-bit
723 // Windows platforms.
724 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
725 reinterpret_cast<size_t>(write_handle),
726 reinterpret_cast<size_t>(event_handle_.Get()));
728 char executable_path[_MAX_PATH + 1]; // NOLINT
729 GTEST_DEATH_TEST_CHECK_(
730 _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
734 std::string command_line =
735 std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
736 internal_flag + "\"";
738 DeathTest::set_last_death_test_message("");
741 // Flush the log buffers since the log streams are shared with the child.
744 // The child process will share the standard handles with the parent.
745 STARTUPINFOA startup_info;
746 memset(&startup_info, 0, sizeof(STARTUPINFO));
747 startup_info.dwFlags = STARTF_USESTDHANDLES;
748 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
749 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
750 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
752 PROCESS_INFORMATION process_info;
753 GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
755 const_cast<char*>(command_line.c_str()),
756 NULL, // Retuned process handle is not inheritable.
757 NULL, // Retuned thread handle is not inheritable.
758 TRUE, // Child inherits all inheritable handles (for write_handle_).
759 0x0, // Default creation flags.
760 NULL, // Inherit the parent's environment.
761 UnitTest::GetInstance()->original_working_dir(),
763 &process_info) != FALSE);
764 child_handle_.Reset(process_info.hProcess);
765 ::CloseHandle(process_info.hThread);
769 # else // We are not on Windows.
771 // ForkingDeathTest provides implementations for most of the abstract
772 // methods of the DeathTest interface. Only the AssumeRole method is
774 class ForkingDeathTest : public DeathTestImpl {
776 ForkingDeathTest(const char* statement, const RE* regex);
778 // All of these virtual functions are inherited from DeathTest.
782 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
785 // PID of child process during death test; 0 in the child process itself.
789 // Constructs a ForkingDeathTest.
790 ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
791 : DeathTestImpl(a_statement, a_regex),
794 // Waits for the child in a death test to exit, returning its exit
795 // status, or 0 if no child process exists. As a side effect, sets the
796 // outcome data member.
797 int ForkingDeathTest::Wait() {
801 ReadAndInterpretStatusByte();
804 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
805 set_status(status_value);
809 // A concrete death test class that forks, then immediately runs the test
810 // in the child process.
811 class NoExecDeathTest : public ForkingDeathTest {
813 NoExecDeathTest(const char* a_statement, const RE* a_regex) :
814 ForkingDeathTest(a_statement, a_regex) { }
815 virtual TestRole AssumeRole();
818 // The AssumeRole process for a fork-and-run death test. It implements a
819 // straightforward fork, with a simple pipe to transmit the status byte.
820 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
821 const size_t thread_count = GetThreadCount();
822 if (thread_count != 1) {
823 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
827 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
829 DeathTest::set_last_death_test_message("");
831 // When we fork the process below, the log file buffers are copied, but the
832 // file descriptors are shared. We flush all log files here so that closing
833 // the file descriptors in the child process doesn't throw off the
834 // synchronization between descriptors and buffers in the parent process.
835 // This is as close to the fork as possible to avoid a race condition in case
836 // there are multiple threads running before the death test, and another
837 // thread writes to the log file.
840 const pid_t child_pid = fork();
841 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
842 set_child_pid(child_pid);
843 if (child_pid == 0) {
844 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
845 set_write_fd(pipe_fd[1]);
846 // Redirects all logging to stderr in the child process to prevent
847 // concurrent writes to the log files. We capture stderr in the parent
848 // process and append the child process' output to a log.
850 // Event forwarding to the listeners of event listener API mush be shut
851 // down in death test subprocesses.
852 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
853 g_in_fast_death_test_child = true;
856 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
857 set_read_fd(pipe_fd[0]);
863 // A concrete death test class that forks and re-executes the main
864 // program from the beginning, with command-line flags set that cause
865 // only this specific death test to be run.
866 class ExecDeathTest : public ForkingDeathTest {
868 ExecDeathTest(const char* a_statement, const RE* a_regex,
869 const char* file, int line) :
870 ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
871 virtual TestRole AssumeRole();
873 static ::std::vector<testing::internal::string>
874 GetArgvsForDeathTestChildProcess() {
875 ::std::vector<testing::internal::string> args = GetInjectableArgvs();
878 // The name of the file in which the death test is located.
879 const char* const file_;
880 // The line number on which the death test is located.
884 // Utility class for accumulating command-line arguments.
888 args_.push_back(NULL);
892 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
897 void AddArgument(const char* argument) {
898 args_.insert(args_.end() - 1, posix::StrDup(argument));
901 template <typename Str>
902 void AddArguments(const ::std::vector<Str>& arguments) {
903 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
904 i != arguments.end();
906 args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
909 char* const* Argv() {
914 std::vector<char*> args_;
917 // A struct that encompasses the arguments to the child process of a
918 // threadsafe-style death test process.
919 struct ExecDeathTestArgs {
920 char* const* argv; // Command-line arguments for the child's call to exec
921 int close_fd; // File descriptor to close; the read end of a pipe
925 inline char** GetEnviron() {
926 // When Google Test is built as a framework on MacOS X, the environ variable
927 // is unavailable. Apple's documentation (man environ) recommends using
928 // _NSGetEnviron() instead.
929 return *_NSGetEnviron();
932 // Some POSIX platforms expect you to declare environ. extern "C" makes
933 // it reside in the global namespace.
934 extern "C" char** environ;
935 inline char** GetEnviron() { return environ; }
936 # endif // GTEST_OS_MAC
939 // The main function for a threadsafe-style death test child process.
940 // This function is called in a clone()-ed process and thus must avoid
941 // any potentially unsafe operations like malloc or libc functions.
942 static int ExecDeathTestChildMain(void* child_arg) {
943 ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
944 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
946 // We need to execute the test program in the same environment where
947 // it was originally invoked. Therefore we change to the original
948 // working directory first.
949 const char* const original_dir =
950 UnitTest::GetInstance()->original_working_dir();
951 // We can safely call chdir() as it's a direct system call.
952 if (chdir(original_dir) != 0) {
953 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
954 GetLastErrnoDescription());
958 // We can safely call execve() as it's a direct system call. We
959 // cannot use execvp() as it's a libc function and thus potentially
960 // unsafe. Since execve() doesn't search the PATH, the user must
961 // invoke the test program via a valid path that contains at least
962 // one path separator.
963 execve(args->argv[0], args->argv, GetEnviron());
964 DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
965 original_dir + " failed: " +
966 GetLastErrnoDescription());
969 # endif // !GTEST_OS_QNX
971 // Two utility routines that together determine the direction the stack
973 // This could be accomplished more elegantly by a single recursive
974 // function, but we want to guard against the unlikely possibility of
975 // a smart compiler optimizing the recursion away.
977 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
978 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
980 void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;
981 void StackLowerThanAddress(const void* ptr, bool* result) {
983 *result = (&dummy < ptr);
986 bool StackGrowsDown() {
989 StackLowerThanAddress(&dummy, &result);
993 // Spawns a child process with the same executable as the current process in
994 // a thread-safe manner and instructs it to run the death test. The
995 // implementation uses fork(2) + exec. On systems where clone(2) is
996 // available, it is used instead, being slightly more thread-safe. On QNX,
997 // fork supports only single-threaded environments, so this function uses
998 // spawn(2) there instead. The function dies with an error message if
999 // anything goes wrong.
1000 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
1001 ExecDeathTestArgs args = { argv, close_fd };
1002 pid_t child_pid = -1;
1005 // Obtains the current directory and sets it to be closed in the child
1007 const int cwd_fd = open(".", O_RDONLY);
1008 GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
1009 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
1010 // We need to execute the test program in the same environment where
1011 // it was originally invoked. Therefore we change to the original
1012 // working directory first.
1013 const char* const original_dir =
1014 UnitTest::GetInstance()->original_working_dir();
1015 // We can safely call chdir() as it's a direct system call.
1016 if (chdir(original_dir) != 0) {
1017 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
1018 GetLastErrnoDescription());
1019 return EXIT_FAILURE;
1023 // Set close_fd to be closed after spawn.
1024 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
1025 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
1026 fd_flags | FD_CLOEXEC));
1027 struct inheritance inherit = {0};
1028 // spawn is a system call.
1029 child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
1030 // Restores the current working directory.
1031 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
1032 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
1034 # else // GTEST_OS_QNX
1036 // When a SIGPROF signal is received while fork() or clone() are executing,
1037 // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
1038 // it after the call to fork()/clone() is complete.
1039 struct sigaction saved_sigprof_action;
1040 struct sigaction ignore_sigprof_action;
1041 memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
1042 sigemptyset(&ignore_sigprof_action.sa_mask);
1043 ignore_sigprof_action.sa_handler = SIG_IGN;
1044 GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
1045 SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
1046 # endif // GTEST_OS_LINUX
1048 # if GTEST_HAS_CLONE
1049 const bool use_fork = GTEST_FLAG(death_test_use_fork);
1052 static const bool stack_grows_down = StackGrowsDown();
1053 const size_t stack_size = getpagesize();
1054 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
1055 void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
1056 MAP_ANON | MAP_PRIVATE, -1, 0);
1057 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
1059 // Maximum stack alignment in bytes: For a downward-growing stack, this
1060 // amount is subtracted from size of the stack space to get an address
1061 // that is within the stack space and is aligned on all systems we care
1062 // about. As far as I know there is no ABI with stack alignment greater
1063 // than 64. We assume stack and stack_size already have alignment of
1064 // kMaxStackAlignment.
1065 const size_t kMaxStackAlignment = 64;
1066 void* const stack_top =
1067 static_cast<char*>(stack) +
1068 (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
1069 GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
1070 reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
1072 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
1074 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
1077 const bool use_fork = true;
1078 # endif // GTEST_HAS_CLONE
1080 if (use_fork && (child_pid = fork()) == 0) {
1081 ExecDeathTestChildMain(&args);
1084 # endif // GTEST_OS_QNX
1086 GTEST_DEATH_TEST_CHECK_SYSCALL_(
1087 sigaction(SIGPROF, &saved_sigprof_action, NULL));
1088 # endif // GTEST_OS_LINUX
1090 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
1094 // The AssumeRole process for a fork-and-exec death test. It re-executes the
1095 // main program from the beginning, setting the --gtest_filter
1096 // and --gtest_internal_run_death_test flags to cause only the current
1097 // death test to be re-run.
1098 DeathTest::TestRole ExecDeathTest::AssumeRole() {
1099 const UnitTestImpl* const impl = GetUnitTestImpl();
1100 const InternalRunDeathTestFlag* const flag =
1101 impl->internal_run_death_test_flag();
1102 const TestInfo* const info = impl->current_test_info();
1103 const int death_test_index = info->result()->death_test_count();
1106 set_write_fd(flag->write_fd());
1107 return EXECUTE_TEST;
1111 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
1112 // Clear the close-on-exec flag on the write end of the pipe, lest
1113 // it be closed when the child process does an exec:
1114 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
1116 const std::string filter_flag =
1117 String::Format("--%s%s=%s.%s",
1118 GTEST_FLAG_PREFIX_, kFilterFlag,
1119 info->test_case_name(), info->name());
1120 const std::string internal_flag =
1121 String::Format("--%s%s=%s|%d|%d|%d",
1122 GTEST_FLAG_PREFIX_, kInternalRunDeathTestFlag,
1123 file_, line_, death_test_index, pipe_fd[1]);
1125 args.AddArguments(GetArgvsForDeathTestChildProcess());
1126 args.AddArgument(filter_flag.c_str());
1127 args.AddArgument(internal_flag.c_str());
1129 DeathTest::set_last_death_test_message("");
1132 // See the comment in NoExecDeathTest::AssumeRole for why the next line
1136 const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
1137 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
1138 set_child_pid(child_pid);
1139 set_read_fd(pipe_fd[0]);
1141 return OVERSEE_TEST;
1144 # endif // !GTEST_OS_WINDOWS
1146 // Creates a concrete DeathTest-derived class that depends on the
1147 // --gtest_death_test_style flag, and sets the pointer pointed to
1148 // by the "test" argument to its address. If the test should be
1149 // skipped, sets that pointer to NULL. Returns true, unless the
1150 // flag is set to an invalid value.
1151 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
1152 const char* file, int line,
1154 UnitTestImpl* const impl = GetUnitTestImpl();
1155 const InternalRunDeathTestFlag* const flag =
1156 impl->internal_run_death_test_flag();
1157 const int death_test_index = impl->current_test_info()
1158 ->increment_death_test_count();
1161 if (death_test_index > flag->index()) {
1162 DeathTest::set_last_death_test_message(String::Format(
1163 "Death test count (%d) somehow exceeded expected maximum (%d)",
1164 death_test_index, flag->index()));
1168 if (!(flag->file() == file && flag->line() == line &&
1169 flag->index() == death_test_index)) {
1175 # if GTEST_OS_WINDOWS
1177 if (GTEST_FLAG(death_test_style) == "threadsafe" ||
1178 GTEST_FLAG(death_test_style) == "fast") {
1179 *test = new WindowsDeathTest(statement, regex, file, line);
1184 if (GTEST_FLAG(death_test_style) == "threadsafe") {
1185 *test = new ExecDeathTest(statement, regex, file, line);
1186 } else if (GTEST_FLAG(death_test_style) == "fast") {
1187 *test = new NoExecDeathTest(statement, regex);
1190 # endif // GTEST_OS_WINDOWS
1192 else { // NOLINT - this is more readable than unbalanced brackets inside #if.
1193 DeathTest::set_last_death_test_message(String::Format(
1194 "Unknown death test style \"%s\" encountered",
1195 GTEST_FLAG(death_test_style).c_str()));
1202 // Splits a given string on a given delimiter, populating a given
1203 // vector with the fields. GTEST_HAS_DEATH_TEST implies that we have
1204 // ::std::string, so we can use it here.
1205 static void SplitString(const ::std::string& str, char delimiter,
1206 ::std::vector< ::std::string>* dest) {
1207 ::std::vector< ::std::string> parsed;
1208 ::std::string::size_type pos = 0;
1209 while (::testing::internal::AlwaysTrue()) {
1210 const ::std::string::size_type colon = str.find(delimiter, pos);
1211 if (colon == ::std::string::npos) {
1212 parsed.push_back(str.substr(pos));
1215 parsed.push_back(str.substr(pos, colon - pos));
1222 # if GTEST_OS_WINDOWS
1223 // Recreates the pipe and event handles from the provided parameters,
1224 // signals the event, and returns a file descriptor wrapped around the pipe
1225 // handle. This function is called in the child process only.
1226 int GetStatusFileDescriptor(unsigned int parent_process_id,
1227 size_t write_handle_as_size_t,
1228 size_t event_handle_as_size_t) {
1229 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
1230 FALSE, // Non-inheritable.
1231 parent_process_id));
1232 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
1233 DeathTestAbort(String::Format("Unable to open parent process %u",
1234 parent_process_id));
1237 // TODO(vladl@google.com): Replace the following check with a
1238 // compile-time assertion when available.
1239 GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
1241 const HANDLE write_handle =
1242 reinterpret_cast<HANDLE>(write_handle_as_size_t);
1243 HANDLE dup_write_handle;
1245 // The newly initialized handle is accessible only in in the parent
1246 // process. To obtain one accessible within the child, we need to use
1248 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
1249 ::GetCurrentProcess(), &dup_write_handle,
1250 0x0, // Requested privileges ignored since
1251 // DUPLICATE_SAME_ACCESS is used.
1252 FALSE, // Request non-inheritable handler.
1253 DUPLICATE_SAME_ACCESS)) {
1254 DeathTestAbort(String::Format(
1255 "Unable to duplicate the pipe handle %Iu from the parent process %u",
1256 write_handle_as_size_t, parent_process_id));
1259 const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
1260 HANDLE dup_event_handle;
1262 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
1263 ::GetCurrentProcess(), &dup_event_handle,
1266 DUPLICATE_SAME_ACCESS)) {
1267 DeathTestAbort(String::Format(
1268 "Unable to duplicate the event handle %Iu from the parent process %u",
1269 event_handle_as_size_t, parent_process_id));
1272 const int write_fd =
1273 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
1274 if (write_fd == -1) {
1275 DeathTestAbort(String::Format(
1276 "Unable to convert pipe handle %Iu to a file descriptor",
1277 write_handle_as_size_t));
1280 // Signals the parent that the write end of the pipe has been acquired
1281 // so the parent can release its own write end.
1282 ::SetEvent(dup_event_handle);
1286 # endif // GTEST_OS_WINDOWS
1288 // Returns a newly created InternalRunDeathTestFlag object with fields
1289 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
1290 // the flag is specified; otherwise returns NULL.
1291 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
1292 if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
1294 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
1298 ::std::vector< ::std::string> fields;
1299 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
1302 # if GTEST_OS_WINDOWS
1304 unsigned int parent_process_id = 0;
1305 size_t write_handle_as_size_t = 0;
1306 size_t event_handle_as_size_t = 0;
1308 if (fields.size() != 6
1309 || !ParseNaturalNumber(fields[1], &line)
1310 || !ParseNaturalNumber(fields[2], &index)
1311 || !ParseNaturalNumber(fields[3], &parent_process_id)
1312 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
1313 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
1314 DeathTestAbort(String::Format(
1315 "Bad --gtest_internal_run_death_test flag: %s",
1316 GTEST_FLAG(internal_run_death_test).c_str()));
1318 write_fd = GetStatusFileDescriptor(parent_process_id,
1319 write_handle_as_size_t,
1320 event_handle_as_size_t);
1323 if (fields.size() != 4
1324 || !ParseNaturalNumber(fields[1], &line)
1325 || !ParseNaturalNumber(fields[2], &index)
1326 || !ParseNaturalNumber(fields[3], &write_fd)) {
1327 DeathTestAbort(String::Format(
1328 "Bad --gtest_internal_run_death_test flag: %s",
1329 GTEST_FLAG(internal_run_death_test).c_str()));
1332 # endif // GTEST_OS_WINDOWS
1334 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
1337 } // namespace internal
1339 #endif // GTEST_HAS_DEATH_TEST
1341 } // namespace testing