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 // Suppress MSVC complaints about POSIX functions.
209 #pragma warning(push)
210 #pragma warning(disable: 4996)
212 FILE* parent = fdopen(flag->status_fd(), "w");
216 fputc(kDeathTestInternalError, parent);
217 fprintf(parent, "%s", message.c_str());
221 fprintf(stderr, "%s", message.c_str());
227 // A replacement for CHECK that calls DeathTestAbort if the assertion
229 #define GTEST_DEATH_TEST_CHECK_(expression) \
231 if (!(expression)) { \
232 DeathTestAbort(::testing::internal::String::Format(\
233 "CHECK failed: File %s, line %d: %s", \
234 __FILE__, __LINE__, #expression)); \
238 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
239 // evaluating any system call that fulfills two conditions: it must return
240 // -1 on failure, and set errno to EINTR when it is interrupted and
241 // should be tried again. The macro expands to a loop that repeatedly
242 // evaluates the expression as long as it evaluates to -1 and sets
243 // errno to EINTR. If the expression evaluates to -1 but errno is
244 // something other than EINTR, DeathTestAbort is called.
245 #define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
249 gtest_retval = (expression); \
250 } while (gtest_retval == -1 && errno == EINTR); \
251 if (gtest_retval == -1) { \
252 DeathTestAbort(::testing::internal::String::Format(\
253 "CHECK failed: File %s, line %d: %s != -1", \
254 __FILE__, __LINE__, #expression)); \
258 // Returns the message describing the last system error, regardless of the
260 String GetLastSystemErrorMessage() {
262 const DWORD error_num = ::GetLastError();
264 if (error_num == NULL)
270 // The caller does not provide a buffer. The function will allocate one.
271 FORMAT_MESSAGE_ALLOCATE_BUFFER |
272 // The function must look up an error message in its system error
274 FORMAT_MESSAGE_FROM_SYSTEM |
275 // Do not expand insert sequences in the message definition.
276 FORMAT_MESSAGE_IGNORE_INSERTS,
277 NULL, // Message source. Ignored in this call.
279 0x0, // Use system-default language.
280 reinterpret_cast<LPSTR>(&message_ptr),
281 0, // Buffer size. Ignored in this call.
282 NULL); // Message arguments. Ignored in this call.
284 const String message = message_ptr;
285 ::LocalFree(message_ptr);
288 return errno == 0 ? String("") : String(strerror(errno));
289 #endif // GTEST_OS_WINDOWS
292 // TODO(vladl@google.com): Move the definition of FailFromInternalError
295 static void FailFromInternalError(HANDLE handle);
297 static void FailFromInternalError(int fd);
298 #endif // GTEST_OS_WINDOWS
300 // Death test constructor. Increments the running death test count
301 // for the current test.
302 DeathTest::DeathTest() {
303 TestInfo* const info = GetUnitTestImpl()->current_test_info();
305 DeathTestAbort("Cannot run a death test outside of a TEST or "
310 // Creates and returns a death test by dispatching to the current
311 // death test factory.
312 bool DeathTest::Create(const char* statement, const RE* regex,
313 const char* file, int line, DeathTest** test) {
314 return GetUnitTestImpl()->death_test_factory()->Create(
315 statement, regex, file, line, test);
318 const char* DeathTest::LastMessage() {
319 return last_death_test_message_.c_str();
322 void DeathTest::set_last_death_test_message(const String& message) {
323 last_death_test_message_ = message;
326 String DeathTest::last_death_test_message_;
328 // Provides cross platform implementation for some death functionality.
329 // TODO(vladl@google.com): Merge this class with DeathTest in
330 // gtest-death-test-internal.h.
331 class DeathTestImpl : public DeathTest {
333 DeathTestImpl(const char* statement, const RE* regex)
334 : statement_(statement),
338 outcome_(IN_PROGRESS) {}
340 virtual bool Passed(bool status_ok);
342 const char* statement() const { return statement_; }
343 const RE* regex() const { return regex_; }
344 bool spawned() const { return spawned_; }
345 void set_spawned(bool spawned) { spawned_ = spawned; }
346 int status() const { return status_; }
347 void set_status(int status) { status_ = status; }
348 DeathTestOutcome outcome() const { return outcome_; }
349 void set_outcome(DeathTestOutcome outcome) { outcome_ = outcome; }
352 // The textual content of the code this object is testing. This class
353 // doesn't own this string and should not attempt to delete it.
354 const char* const statement_;
355 // The regular expression which test output must match. DeathTestImpl
356 // doesn't own this object and should not attempt to delete it.
357 const RE* const regex_;
358 // True if the death test child process has been successfully spawned.
360 // The exit status of the child process.
362 // How the death test concluded.
363 DeathTestOutcome outcome_;
366 // TODO(vladl@google.com): Move definition of DeathTestImpl::Passed() here.
369 // WindowsDeathTest implements death tests on Windows. Due to the
370 // specifics of starting new processes on Windows, death tests there are
371 // always threadsafe, and Google Test considers the
372 // --gtest_death_test_style=fast setting to be equivalent to
373 // --gtest_death_test_style=threadsafe there.
375 // A few implementation notes: Like the Linux version, the Windows
376 // implementation uses pipes for child-to-parent communication. But due to
377 // the specifics of pipes on Windows, some extra steps are required:
379 // 1. The parent creates a communication pipe and stores handles to both
381 // 2. The parent starts the child and provides it with the information
382 // necessary to acquire the handle to the write end of the pipe.
383 // 3. The child acquires the write end of the pipe and signals the parent
384 // using a Windows event.
385 // 4. Now the parent can release the write end of the pipe on its side. If
386 // this is done before step 3, the object's reference count goes down to
387 // 0 and it is destroyed, preventing the child from acquiring it. The
388 // parent now has to release it, or read operations on the read end of
389 // the pipe will not return when the child terminates.
390 // 5. The parent reads child's output through the pipe (outcome code and
391 // any possible error messages) from the pipe, and its stderr and then
392 // determines whether to fail the test.
394 // Note: to distinguish Win32 API calls from the local method and function
395 // calls, the former are explicitly resolved in the global namespace.
397 class WindowsDeathTest : public DeathTestImpl {
399 WindowsDeathTest(const char* statement,
403 : DeathTestImpl(statement, regex), file_(file), line_(line) {}
405 // All of these virtual functions are inherited from DeathTest.
407 virtual void Abort(AbortReason reason);
408 virtual TestRole AssumeRole();
411 // The name of the file in which the death test is located.
412 const char* const file_;
413 // The line number on which the death test is located.
415 // Handle to the read end of the pipe to the child process.
416 // The child keeps its write end of the pipe in the status_handle_
417 // field of its InternalRunDeathTestFlag class.
418 AutoHandle read_handle_;
419 // Handle to the write end of the pipe to the child process.
420 AutoHandle write_handle_;
421 // Child process handle.
422 AutoHandle child_handle_;
423 // Event the child process uses to signal the parent that it has
424 // acquired the handle to the write end of the pipe. After seeing this
425 // event the parent can release its own handles to make sure its
426 // ReadFile() calls return when the child terminates.
427 AutoHandle event_handle_;
430 // Waits for the child in a death test to exit, returning its exit
431 // status, or 0 if no child process exists. As a side effect, sets the
432 // outcome data member.
433 // TODO(vladl@google.com): Outcome classification logic is common with
434 // ForkingDeathTes::Wait(). Refactor it into a
436 int WindowsDeathTest::Wait() {
440 // Wait until the child either signals that it has acquired the write end
441 // of the pipe or it dies.
442 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
443 switch (::WaitForMultipleObjects(2,
445 FALSE, // Waits for any of the handles.
448 case WAIT_OBJECT_0 + 1:
451 GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
454 // The child has acquired the write end of the pipe or exited.
455 // We release the handle on our side and continue.
456 write_handle_.Reset();
457 event_handle_.Reset();
459 // ReadFile() blocks until data is available (signifying the
460 // failure of the death test) or until the pipe is closed (signifying
461 // its success), so it's okay to call this in the parent before or
462 // after the child process has exited.
465 GTEST_DEATH_TEST_CHECK_(::ReadFile(read_handle_.Get(),
470 ::GetLastError() == ERROR_BROKEN_PIPE);
472 if (bytes_read == 0) {
474 } else if (bytes_read == 1) {
476 case kDeathTestReturned:
477 set_outcome(RETURNED);
479 case kDeathTestLived:
482 case kDeathTestInternalError:
483 FailFromInternalError(read_handle_.Get()); // Does not return.
487 Message() << "Death test child process reported "
488 << " unexpected status byte ("
489 << static_cast<unsigned int>(flag) << ")");
493 Message() << "Read from death test child process failed: "
494 << GetLastSystemErrorMessage());
496 read_handle_.Reset(); // Done with reading.
498 // Waits for the child process to exit if it haven't already. This
499 // returns immediately if the child has already exited, regardless of
500 // whether previous calls to WaitForMultipleObjects synchronized on this
502 GTEST_DEATH_TEST_CHECK_(
503 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
506 GTEST_DEATH_TEST_CHECK_(::GetExitCodeProcess(child_handle_.Get(),
508 child_handle_.Reset();
509 set_status(static_cast<int>(status));
510 return this->status();
513 // TODO(vladl@google.com): define a cross-platform way to write to
514 // status_fd to be used both here and in ForkingDeathTest::Abort().
516 // Signals that the death test did not die as expected. This is called
517 // from the child process only.
518 void WindowsDeathTest::Abort(AbortReason reason) {
519 const InternalRunDeathTestFlag* const internal_flag =
520 GetUnitTestImpl()->internal_run_death_test_flag();
521 // The parent process considers the death test to be a failure if
522 // it finds any data in our pipe. So, here we write a single flag byte
523 // to the pipe, then exit.
524 const char status_ch =
525 reason == TEST_DID_NOT_DIE ? kDeathTestLived : kDeathTestReturned;
528 #pragma warning(push)
529 #pragma warning(disable: 4996)
531 GTEST_DEATH_TEST_CHECK_SYSCALL_(write(internal_flag->status_fd(),
537 // The write handle will be closed when the child terminates in _exit().
538 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
541 // The AssumeRole process for a Windows death test. It creates a child
542 // process with the same executable as the current process to run the
543 // death test. The child process is given the --gtest_filter and
544 // --gtest_internal_run_death_test flags such that it knows to run the
545 // current death test only.
546 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
547 const UnitTestImpl* const impl = GetUnitTestImpl();
548 const InternalRunDeathTestFlag* const flag =
549 impl->internal_run_death_test_flag();
550 const TestInfo* const info = impl->current_test_info();
551 const int death_test_index = info->result()->death_test_count();
554 // ParseInternalRunDeathTestFlag() has performed all the necessary
559 // WindowsDeathTest uses an anonymous pipe to communicate results of
561 SECURITY_ATTRIBUTES handles_are_inheritable = {
562 sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
563 HANDLE read_handle, write_handle;
564 GTEST_DEATH_TEST_CHECK_(::CreatePipe(&read_handle, &write_handle,
565 &handles_are_inheritable,
566 0)); // Default buffer size.
567 read_handle_.Reset(read_handle);
568 write_handle_.Reset(write_handle);
569 event_handle_.Reset(::CreateEvent(
570 &handles_are_inheritable,
571 TRUE, // The event will automatically reset to non-signaled state.
572 FALSE, // The initial state is non-signalled.
573 NULL)); // The even is unnamed.
574 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
575 const String filter_flag = String::Format("--%s%s=%s.%s",
576 GTEST_FLAG_PREFIX_, kFilterFlag,
577 info->test_case_name(),
579 const String internal_flag = String::Format(
580 "--%s%s=%s|%d|%d|%u|%Iu|%Iu",
582 kInternalRunDeathTestFlag,
585 static_cast<unsigned int>(::GetCurrentProcessId()),
586 // size_t has the same with as pointers on both 32-bit and 64-bit
587 // Windows platforms.
588 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
589 reinterpret_cast<size_t>(write_handle),
590 reinterpret_cast<size_t>(event_handle_.Get()));
592 char executable_path[_MAX_PATH + 1]; // NOLINT
593 GTEST_DEATH_TEST_CHECK_(
594 _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
598 String command_line = String::Format("%s %s \"%s\"",
601 internal_flag.c_str());
603 DeathTest::set_last_death_test_message("");
606 // Flush the log buffers since the log streams are shared with the child.
609 // The child process will share the standard handles with the parent.
610 STARTUPINFOA startup_info;
611 memset(&startup_info, 0, sizeof(STARTUPINFO));
612 startup_info.dwFlags = STARTF_USESTDHANDLES;
613 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
614 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
615 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
617 PROCESS_INFORMATION process_info;
618 GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
620 const_cast<char*>(command_line.c_str()),
621 NULL, // Retuned process handle is not inheritable.
622 NULL, // Retuned thread handle is not inheritable.
623 TRUE, // Child inherits all inheritable handles (for write_handle_).
624 0x0, // Default creation flags.
625 NULL, // Inherit the parent's environment.
626 UnitTest::GetInstance()->original_working_dir(),
629 child_handle_.Reset(process_info.hProcess);
630 ::CloseHandle(process_info.hThread);
634 #else // We are not on Windows.
636 // ForkingDeathTest provides implementations for most of the abstract
637 // methods of the DeathTest interface. Only the AssumeRole method is
639 class ForkingDeathTest : public DeathTestImpl {
641 ForkingDeathTest(const char* statement, const RE* regex);
643 // All of these virtual functions are inherited from DeathTest.
645 virtual void Abort(AbortReason reason);
648 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
649 void set_read_fd(int fd) { read_fd_ = fd; }
650 void set_write_fd(int fd) { write_fd_ = fd; }
653 // PID of child process during death test; 0 in the child process itself.
655 // File descriptors for communicating the death test's status byte.
656 int read_fd_; // Always -1 in the child process.
657 int write_fd_; // Always -1 in the parent process.
660 // Constructs a ForkingDeathTest.
661 ForkingDeathTest::ForkingDeathTest(const char* statement, const RE* regex)
662 : DeathTestImpl(statement, regex),
667 #endif // GTEST_OS_WINDOWS
669 // This is called from a death test parent process to read a failure
670 // message from the death test child process and log it with the FATAL
671 // severity. On Windows, the message is read from a pipe handle. On other
672 // platforms, it is read from a file descriptor.
673 // TODO(vladl@google.com): Re-factor the code to merge common parts after
674 // the reading code is abstracted.
676 static void FailFromInternalError(HANDLE handle) {
680 bool read_succeeded = true;
683 // ERROR_BROKEN_PIPE arises when the other end of the pipe has been
684 // closed. This is a normal condition for us.
686 read_succeeded = ::ReadFile(handle,
690 NULL) || ::GetLastError() == ERROR_BROKEN_PIPE;
691 buffer[bytes_read] = 0;
693 } while (read_succeeded && bytes_read > 0);
695 if (read_succeeded) {
696 GTEST_LOG_(FATAL, error);
698 const DWORD last_error = ::GetLastError();
699 const String message = GetLastSystemErrorMessage();
701 Message() << "Error while reading death test internal: "
702 << message << " [" << last_error << "]");
706 static void FailFromInternalError(int fd) {
712 while ((num_read = read(fd, buffer, 255)) > 0) {
713 buffer[num_read] = '\0';
716 } while (num_read == -1 && errno == EINTR);
719 GTEST_LOG_(FATAL, error);
721 const int last_error = errno;
722 const String message = GetLastSystemErrorMessage();
724 Message() << "Error while reading death test internal: "
725 << message << " [" << last_error << "]");
728 #endif // GTEST_OS_WINDOWS
730 #if !GTEST_OS_WINDOWS
731 // Waits for the child in a death test to exit, returning its exit
732 // status, or 0 if no child process exists. As a side effect, sets the
733 // outcome data member.
734 int ForkingDeathTest::Wait() {
738 // The read() here blocks until data is available (signifying the
739 // failure of the death test) or until the pipe is closed (signifying
740 // its success), so it's okay to call this in the parent before
741 // the child process has exited.
746 bytes_read = read(read_fd_, &flag, 1);
747 } while (bytes_read == -1 && errno == EINTR);
749 if (bytes_read == 0) {
751 } else if (bytes_read == 1) {
753 case kDeathTestReturned:
754 set_outcome(RETURNED);
756 case kDeathTestLived:
759 case kDeathTestInternalError:
760 FailFromInternalError(read_fd_); // Does not return.
764 Message() << "Death test child process reported unexpected "
765 << "status byte (" << static_cast<unsigned int>(flag)
769 const String error_message = GetLastSystemErrorMessage();
771 Message() << "Read from death test child process failed: "
775 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(read_fd_));
777 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status, 0));
781 #endif // !GTEST_OS_WINDOWS
783 // Assesses the success or failure of a death test, using both private
784 // members which have previously been set, and one argument:
786 // Private data members:
787 // outcome: An enumeration describing how the death test
788 // concluded: DIED, LIVED, or RETURNED. The death test fails
789 // in the latter two cases.
790 // status: The exit status of the child process. On *nix, it is in the
791 // in the format specified by wait(2). On Windows, this is the
792 // value supplied to the ExitProcess() API or a numeric code
793 // of the exception that terminated the program.
794 // regex: A regular expression object to be applied to
795 // the test's captured standard error output; the death test
796 // fails if it does not match.
799 // status_ok: true if exit_status is acceptable in the context of
800 // this particular death test, which fails if it is false
802 // Returns true iff all of the above conditions are met. Otherwise, the
803 // first failing condition, in the order given above, is the one that is
804 // reported. Also sets the last death test message string.
805 bool DeathTestImpl::Passed(bool status_ok) {
809 #if GTEST_HAS_GLOBAL_STRING
810 const ::string error_message = GetCapturedStderr();
812 const ::std::string error_message = GetCapturedStderr();
813 #endif // GTEST_HAS_GLOBAL_STRING
815 bool success = false;
818 buffer << "Death test: " << statement() << "\n";
821 buffer << " Result: failed to die.\n"
822 << " Error msg: " << error_message;
825 buffer << " Result: illegal return in test statement.\n"
826 << " Error msg: " << error_message;
830 if (RE::PartialMatch(error_message, *regex())) {
833 buffer << " Result: died but not with expected error.\n"
834 << " Expected: " << regex()->pattern() << "\n"
835 << "Actual msg: " << error_message;
838 buffer << " Result: died but not with expected exit code:\n"
839 << " " << ExitSummary(status()) << "\n";
845 "DeathTest::Passed somehow called before conclusion of test");
848 DeathTest::set_last_death_test_message(buffer.GetString());
852 #if !GTEST_OS_WINDOWS
853 // Signals that the death test code which should have exited, didn't.
854 // Should be called only in a death test child process.
855 // Writes a status byte to the child's status file descriptor, then
857 void ForkingDeathTest::Abort(AbortReason reason) {
858 // The parent process considers the death test to be a failure if
859 // it finds any data in our pipe. So, here we write a single flag byte
860 // to the pipe, then exit.
862 reason == TEST_DID_NOT_DIE ? kDeathTestLived : kDeathTestReturned;
863 GTEST_DEATH_TEST_CHECK_SYSCALL_(write(write_fd_, &flag, 1));
864 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(write_fd_));
865 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
868 // A concrete death test class that forks, then immediately runs the test
869 // in the child process.
870 class NoExecDeathTest : public ForkingDeathTest {
872 NoExecDeathTest(const char* statement, const RE* regex) :
873 ForkingDeathTest(statement, regex) { }
874 virtual TestRole AssumeRole();
877 // The AssumeRole process for a fork-and-run death test. It implements a
878 // straightforward fork, with a simple pipe to transmit the status byte.
879 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
880 const size_t thread_count = GetThreadCount();
881 if (thread_count != 1) {
882 GTEST_LOG_(WARNING, DeathTestThreadWarning(thread_count));
886 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
888 DeathTest::set_last_death_test_message("");
890 // When we fork the process below, the log file buffers are copied, but the
891 // file descriptors are shared. We flush all log files here so that closing
892 // the file descriptors in the child process doesn't throw off the
893 // synchronization between descriptors and buffers in the parent process.
894 // This is as close to the fork as possible to avoid a race condition in case
895 // there are multiple threads running before the death test, and another
896 // thread writes to the log file.
899 const pid_t child_pid = fork();
900 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
901 set_child_pid(child_pid);
902 if (child_pid == 0) {
903 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
904 set_write_fd(pipe_fd[1]);
905 // Redirects all logging to stderr in the child process to prevent
906 // concurrent writes to the log files. We capture stderr in the parent
907 // process and append the child process' output to a log.
911 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
912 set_read_fd(pipe_fd[0]);
918 // A concrete death test class that forks and re-executes the main
919 // program from the beginning, with command-line flags set that cause
920 // only this specific death test to be run.
921 class ExecDeathTest : public ForkingDeathTest {
923 ExecDeathTest(const char* statement, const RE* regex,
924 const char* file, int line) :
925 ForkingDeathTest(statement, regex), file_(file), line_(line) { }
926 virtual TestRole AssumeRole();
928 // The name of the file in which the death test is located.
929 const char* const file_;
930 // The line number on which the death test is located.
934 // Utility class for accumulating command-line arguments.
938 args_.push_back(NULL);
942 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
947 void AddArgument(const char* argument) {
948 args_.insert(args_.end() - 1, strdup(argument));
951 template <typename Str>
952 void AddArguments(const ::std::vector<Str>& arguments) {
953 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
954 i != arguments.end();
956 args_.insert(args_.end() - 1, strdup(i->c_str()));
959 char* const* Argv() {
963 std::vector<char*> args_;
966 // A struct that encompasses the arguments to the child process of a
967 // threadsafe-style death test process.
968 struct ExecDeathTestArgs {
969 char* const* argv; // Command-line arguments for the child's call to exec
970 int close_fd; // File descriptor to close; the read end of a pipe
974 inline char** GetEnviron() {
975 // When Google Test is built as a framework on MacOS X, the environ variable
976 // is unavailable. Apple's documentation (man environ) recommends using
977 // _NSGetEnviron() instead.
978 return *_NSGetEnviron();
981 extern "C" char** environ; // Some POSIX platforms expect you
982 // to declare environ. extern "C" makes
983 // it reside in the global namespace.
984 inline char** GetEnviron() {
987 #endif // GTEST_OS_MAC
989 // The main function for a threadsafe-style death test child process.
990 // This function is called in a clone()-ed process and thus must avoid
991 // any potentially unsafe operations like malloc or libc functions.
992 static int ExecDeathTestChildMain(void* child_arg) {
993 ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
994 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
996 // We need to execute the test program in the same environment where
997 // it was originally invoked. Therefore we change to the original
998 // working directory first.
999 const char* const original_dir =
1000 UnitTest::GetInstance()->original_working_dir();
1001 // We can safely call chdir() as it's a direct system call.
1002 if (chdir(original_dir) != 0) {
1003 DeathTestAbort(String::Format("chdir(\"%s\") failed: %s",
1005 GetLastSystemErrorMessage().c_str()));
1006 return EXIT_FAILURE;
1009 // We can safely call execve() as it's a direct system call. We
1010 // cannot use execvp() as it's a libc function and thus potentially
1011 // unsafe. Since execve() doesn't search the PATH, the user must
1012 // invoke the test program via a valid path that contains at least
1013 // one path separator.
1014 execve(args->argv[0], args->argv, GetEnviron());
1015 DeathTestAbort(String::Format("execve(%s, ...) in %s failed: %s",
1018 GetLastSystemErrorMessage().c_str()));
1019 return EXIT_FAILURE;
1022 // Two utility routines that together determine the direction the stack
1024 // This could be accomplished more elegantly by a single recursive
1025 // function, but we want to guard against the unlikely possibility of
1026 // a smart compiler optimizing the recursion away.
1027 bool StackLowerThanAddress(const void* ptr) {
1029 return &dummy < ptr;
1032 bool StackGrowsDown() {
1034 return StackLowerThanAddress(&dummy);
1037 // A threadsafe implementation of fork(2) for threadsafe-style death tests
1038 // that uses clone(2). It dies with an error message if anything goes
1040 static pid_t ExecDeathTestFork(char* const* argv, int close_fd) {
1041 ExecDeathTestArgs args = { argv, close_fd };
1045 const bool use_fork = GTEST_FLAG(death_test_use_fork);
1048 static const bool stack_grows_down = StackGrowsDown();
1049 const size_t stack_size = getpagesize();
1050 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
1051 void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
1052 MAP_ANON | MAP_PRIVATE, -1, 0);
1053 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
1054 void* const stack_top =
1055 static_cast<char*>(stack) + (stack_grows_down ? stack_size : 0);
1057 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
1059 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
1062 const bool use_fork = true;
1063 #endif // GTEST_HAS_CLONE
1065 if (use_fork && (child_pid = fork()) == 0) {
1066 ExecDeathTestChildMain(&args);
1070 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
1074 // The AssumeRole process for a fork-and-exec death test. It re-executes the
1075 // main program from the beginning, setting the --gtest_filter
1076 // and --gtest_internal_run_death_test flags to cause only the current
1077 // death test to be re-run.
1078 DeathTest::TestRole ExecDeathTest::AssumeRole() {
1079 const UnitTestImpl* const impl = GetUnitTestImpl();
1080 const InternalRunDeathTestFlag* const flag =
1081 impl->internal_run_death_test_flag();
1082 const TestInfo* const info = impl->current_test_info();
1083 const int death_test_index = info->result()->death_test_count();
1086 set_write_fd(flag->status_fd());
1087 return EXECUTE_TEST;
1091 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
1092 // Clear the close-on-exec flag on the write end of the pipe, lest
1093 // it be closed when the child process does an exec:
1094 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
1096 const String filter_flag =
1097 String::Format("--%s%s=%s.%s",
1098 GTEST_FLAG_PREFIX_, kFilterFlag,
1099 info->test_case_name(), info->name());
1100 const String internal_flag =
1101 String::Format("--%s%s=%s|%d|%d|%d",
1102 GTEST_FLAG_PREFIX_, kInternalRunDeathTestFlag,
1103 file_, line_, death_test_index, pipe_fd[1]);
1105 args.AddArguments(GetArgvs());
1106 args.AddArgument(filter_flag.c_str());
1107 args.AddArgument(internal_flag.c_str());
1109 DeathTest::set_last_death_test_message("");
1112 // See the comment in NoExecDeathTest::AssumeRole for why the next line
1116 const pid_t child_pid = ExecDeathTestFork(args.Argv(), pipe_fd[0]);
1117 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
1118 set_child_pid(child_pid);
1119 set_read_fd(pipe_fd[0]);
1121 return OVERSEE_TEST;
1124 #endif // !GTEST_OS_WINDOWS
1126 // Creates a concrete DeathTest-derived class that depends on the
1127 // --gtest_death_test_style flag, and sets the pointer pointed to
1128 // by the "test" argument to its address. If the test should be
1129 // skipped, sets that pointer to NULL. Returns true, unless the
1130 // flag is set to an invalid value.
1131 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
1132 const char* file, int line,
1134 UnitTestImpl* const impl = GetUnitTestImpl();
1135 const InternalRunDeathTestFlag* const flag =
1136 impl->internal_run_death_test_flag();
1137 const int death_test_index = impl->current_test_info()
1138 ->increment_death_test_count();
1141 if (death_test_index > flag->index()) {
1142 DeathTest::set_last_death_test_message(String::Format(
1143 "Death test count (%d) somehow exceeded expected maximum (%d)",
1144 death_test_index, flag->index()));
1148 if (!(flag->file() == file && flag->line() == line &&
1149 flag->index() == death_test_index)) {
1155 #if GTEST_OS_WINDOWS
1156 if (GTEST_FLAG(death_test_style) == "threadsafe" ||
1157 GTEST_FLAG(death_test_style) == "fast") {
1158 *test = new WindowsDeathTest(statement, regex, file, line);
1161 if (GTEST_FLAG(death_test_style) == "threadsafe") {
1162 *test = new ExecDeathTest(statement, regex, file, line);
1163 } else if (GTEST_FLAG(death_test_style) == "fast") {
1164 *test = new NoExecDeathTest(statement, regex);
1166 #endif // GTEST_OS_WINDOWS
1167 else { // NOLINT - this is more readable than unbalanced brackets inside #if.
1168 DeathTest::set_last_death_test_message(String::Format(
1169 "Unknown death test style \"%s\" encountered",
1170 GTEST_FLAG(death_test_style).c_str()));
1177 // Splits a given string on a given delimiter, populating a given
1178 // vector with the fields. GTEST_HAS_DEATH_TEST implies that we have
1179 // ::std::string, so we can use it here.
1180 // TODO(vladl@google.com): Get rid of std::vector to be able to build on
1181 // Visual C++ 7.1 with exceptions disabled.
1182 static void SplitString(const ::std::string& str, char delimiter,
1183 ::std::vector< ::std::string>* dest) {
1184 ::std::vector< ::std::string> parsed;
1185 ::std::string::size_type pos = 0;
1187 const ::std::string::size_type colon = str.find(delimiter, pos);
1188 if (colon == ::std::string::npos) {
1189 parsed.push_back(str.substr(pos));
1192 parsed.push_back(str.substr(pos, colon - pos));
1199 #if GTEST_OS_WINDOWS
1200 // Recreates the pipe and event handles from the provided parameters,
1201 // signals the event, and returns a file descriptor wrapped around the pipe
1202 // handle. This function is called in the child process only.
1203 int GetStatusFileDescriptor(unsigned int parent_process_id,
1204 size_t status_handle_as_size_t,
1205 size_t event_handle_as_size_t) {
1206 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
1207 FALSE, // Non-inheritable.
1208 parent_process_id));
1209 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
1210 DeathTestAbort(String::Format("Unable to open parent process %u",
1211 parent_process_id));
1214 // TODO(vladl@google.com): Replace the following check with a
1215 // compile-time assertion when available.
1216 GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
1218 const HANDLE status_handle =
1219 reinterpret_cast<HANDLE>(status_handle_as_size_t);
1220 HANDLE dup_status_handle;
1222 // The newly initialized handle is accessible only in in the parent
1223 // process. To obtain one accessible within the child, we need to use
1225 if (!::DuplicateHandle(parent_process_handle.Get(), status_handle,
1226 ::GetCurrentProcess(), &dup_status_handle,
1227 0x0, // Requested privileges ignored since
1228 // DUPLICATE_SAME_ACCESS is used.
1229 FALSE, // Request non-inheritable handler.
1230 DUPLICATE_SAME_ACCESS)) {
1231 DeathTestAbort(String::Format(
1232 "Unable to duplicate the pipe handle %Iu from the parent process %u",
1233 status_handle_as_size_t, parent_process_id));
1236 const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
1237 HANDLE dup_event_handle;
1239 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
1240 ::GetCurrentProcess(), &dup_event_handle,
1243 DUPLICATE_SAME_ACCESS)) {
1244 DeathTestAbort(String::Format(
1245 "Unable to duplicate the event handle %Iu from the parent process %u",
1246 event_handle_as_size_t, parent_process_id));
1249 const int status_fd =
1250 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_status_handle),
1252 if (status_fd == -1) {
1253 DeathTestAbort(String::Format(
1254 "Unable to convert pipe handle %Iu to a file descriptor",
1255 status_handle_as_size_t));
1258 // Signals the parent that the write end of the pipe has been acquired
1259 // so the parent can release its own write end.
1260 ::SetEvent(dup_event_handle);
1264 #endif // GTEST_OS_WINDOWS
1266 // Returns a newly created InternalRunDeathTestFlag object with fields
1267 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
1268 // the flag is specified; otherwise returns NULL.
1269 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
1270 if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
1272 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
1276 ::std::vector< ::std::string> fields;
1277 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
1280 #if GTEST_OS_WINDOWS
1281 unsigned int parent_process_id = 0;
1282 size_t status_handle_as_size_t = 0;
1283 size_t event_handle_as_size_t = 0;
1285 if (fields.size() != 6
1286 || !ParseNaturalNumber(fields[1], &line)
1287 || !ParseNaturalNumber(fields[2], &index)
1288 || !ParseNaturalNumber(fields[3], &parent_process_id)
1289 || !ParseNaturalNumber(fields[4], &status_handle_as_size_t)
1290 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
1291 DeathTestAbort(String::Format(
1292 "Bad --gtest_internal_run_death_test flag: %s",
1293 GTEST_FLAG(internal_run_death_test).c_str()));
1295 status_fd = GetStatusFileDescriptor(parent_process_id,
1296 status_handle_as_size_t,
1297 event_handle_as_size_t);
1299 if (fields.size() != 4
1300 || !ParseNaturalNumber(fields[1], &line)
1301 || !ParseNaturalNumber(fields[2], &index)
1302 || !ParseNaturalNumber(fields[3], &status_fd)) {
1303 DeathTestAbort(String::Format(
1304 "Bad --gtest_internal_run_death_test flag: %s",
1305 GTEST_FLAG(internal_run_death_test).c_str()));
1307 #endif // GTEST_OS_WINDOWS
1308 return new InternalRunDeathTestFlag(fields[0], line, index, status_fd);
1311 } // namespace internal
1313 #endif // GTEST_HAS_DEATH_TEST
1315 } // namespace testing