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"
36 #include "gtest/internal/custom/gtest.h"
38 #if GTEST_HAS_DEATH_TEST
41 # include <crt_externs.h>
42 # endif // GTEST_OS_MAC
50 # endif // GTEST_OS_LINUX
57 # include <sys/mman.h>
58 # include <sys/wait.h>
59 # endif // GTEST_OS_WINDOWS
63 # endif // GTEST_OS_QNX
66 # include <lib/fdio/io.h>
67 # include <lib/fdio/spawn.h>
68 # include <zircon/processargs.h>
69 # include <zircon/syscalls.h>
70 # endif // GTEST_OS_FUCHSIA
72 #endif // GTEST_HAS_DEATH_TEST
74 #include "gtest/gtest-message.h"
75 #include "gtest/internal/gtest-string.h"
76 #include "src/gtest-internal-inl.h"
82 // The default death test style.
84 // This is defined in internal/gtest-port.h as "fast", but can be overridden by
85 // a definition in internal/custom/gtest-port.h. The recommended value, which is
86 // used internally at Google, is "threadsafe".
87 static const char kDefaultDeathTestStyle
[] = GTEST_DEFAULT_DEATH_TEST_STYLE
;
91 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle
),
92 "Indicates how to run a death test in a forked child process: "
93 "\"threadsafe\" (child process re-executes the test binary "
94 "from the beginning, running only the specific death test) or "
95 "\"fast\" (child process runs the death test immediately "
100 internal::BoolFromGTestEnv("death_test_use_fork", false),
101 "Instructs to use fork()/_exit() instead of clone() in death tests. "
102 "Ignored and always uses fork() on POSIX systems where clone() is not "
103 "implemented. Useful when running under valgrind or similar tools if "
104 "those do not support clone(). Valgrind 3.3.1 will just fail if "
105 "it sees an unsupported combination of clone() flags. "
106 "It is not recommended to use this flag w/o valgrind though it will "
107 "work in 99% of the cases. Once valgrind is fixed, this flag will "
108 "most likely be removed.");
111 GTEST_DEFINE_string_(
112 internal_run_death_test
, "",
113 "Indicates the file, line number, temporal index of "
114 "the single death test to run, and a file descriptor to "
115 "which a success code may be sent, all separated by "
116 "the '|' characters. This flag is specified if and only if the current "
117 "process is a sub-process launched for running a thread-safe "
118 "death test. FOR INTERNAL USE ONLY.");
119 } // namespace internal
121 #if GTEST_HAS_DEATH_TEST
125 // Valid only for fast death tests. Indicates the code is running in the
126 // child process of a fast style death test.
127 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
128 static bool g_in_fast_death_test_child
= false;
131 // Returns a Boolean value indicating whether the caller is currently
132 // executing in the context of the death test child process. Tools such as
133 // Valgrind heap checkers may need this to modify their behavior in death
134 // tests. IMPORTANT: This is an internal utility. Using it may break the
135 // implementation of death tests. User code MUST NOT use it.
136 bool InDeathTestChild() {
137 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
139 // On Windows and Fuchsia, death tests are thread-safe regardless of the value
140 // of the death_test_style flag.
141 return !GTEST_FLAG(internal_run_death_test
).empty();
145 if (GTEST_FLAG(death_test_style
) == "threadsafe")
146 return !GTEST_FLAG(internal_run_death_test
).empty();
148 return g_in_fast_death_test_child
;
152 } // namespace internal
154 // ExitedWithCode constructor.
155 ExitedWithCode::ExitedWithCode(int exit_code
) : exit_code_(exit_code
) {
158 // ExitedWithCode function-call operator.
159 bool ExitedWithCode::operator()(int exit_status
) const {
160 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
162 return exit_status
== exit_code_
;
166 return WIFEXITED(exit_status
) && WEXITSTATUS(exit_status
) == exit_code_
;
168 # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
171 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
172 // KilledBySignal constructor.
173 KilledBySignal::KilledBySignal(int signum
) : signum_(signum
) {
176 // KilledBySignal function-call operator.
177 bool KilledBySignal::operator()(int exit_status
) const {
178 # if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
181 if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_
, exit_status
, &result
)) {
185 # endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
186 return WIFSIGNALED(exit_status
) && WTERMSIG(exit_status
) == signum_
;
188 # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
192 // Utilities needed for death tests.
194 // Generates a textual description of a given exit code, in the format
195 // specified by wait(2).
196 static std::string
ExitSummary(int exit_code
) {
199 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
201 m
<< "Exited with exit status " << exit_code
;
205 if (WIFEXITED(exit_code
)) {
206 m
<< "Exited with exit status " << WEXITSTATUS(exit_code
);
207 } else if (WIFSIGNALED(exit_code
)) {
208 m
<< "Terminated by signal " << WTERMSIG(exit_code
);
211 if (WCOREDUMP(exit_code
)) {
212 m
<< " (core dumped)";
215 # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
217 return m
.GetString();
220 // Returns true if exit_status describes a process that was terminated
221 // by a signal, or exited normally with a nonzero exit code.
222 bool ExitedUnsuccessfully(int exit_status
) {
223 return !ExitedWithCode(0)(exit_status
);
226 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
227 // Generates a textual failure message when a death test finds more than
228 // one thread running, or cannot determine the number of threads, prior
229 // to executing the given statement. It is the responsibility of the
230 // caller not to pass a thread_count of 1.
231 static std::string
DeathTestThreadWarning(size_t thread_count
) {
233 msg
<< "Death tests use fork(), which is unsafe particularly"
234 << " in a threaded context. For this test, " << GTEST_NAME_
<< " ";
235 if (thread_count
== 0)
236 msg
<< "couldn't detect the number of threads.";
238 msg
<< "detected " << thread_count
<< " threads.";
239 return msg
.GetString();
241 # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
243 // Flag characters for reporting a death test that did not die.
244 static const char kDeathTestLived
= 'L';
245 static const char kDeathTestReturned
= 'R';
246 static const char kDeathTestThrew
= 'T';
247 static const char kDeathTestInternalError
= 'I';
251 // File descriptor used for the pipe in the child process.
252 static const int kFuchsiaReadPipeFd
= 3;
256 // An enumeration describing all of the possible ways that a death test can
257 // conclude. DIED means that the process died while executing the test
258 // code; LIVED means that process lived beyond the end of the test code;
259 // RETURNED means that the test statement attempted to execute a return
260 // statement, which is not allowed; THREW means that the test statement
261 // returned control by throwing an exception. IN_PROGRESS means the test
262 // has not yet concluded.
263 // TODO(vladl@google.com): Unify names and possibly values for
264 // AbortReason, DeathTestOutcome, and flag characters above.
265 enum DeathTestOutcome
{ IN_PROGRESS
, DIED
, LIVED
, RETURNED
, THREW
};
267 // Routine for aborting the program which is safe to call from an
268 // exec-style death test child process, in which case the error
269 // message is propagated back to the parent process. Otherwise, the
270 // message is simply printed to stderr. In either case, the program
271 // then exits with status 1.
272 static void DeathTestAbort(const std::string
& message
) {
273 // On a POSIX system, this function may be called from a threadsafe-style
274 // death test child process, which operates on a very small stack. Use
275 // the heap for any additional non-minuscule memory requirements.
276 const InternalRunDeathTestFlag
* const flag
=
277 GetUnitTestImpl()->internal_run_death_test_flag();
279 FILE* parent
= posix::FDOpen(flag
->write_fd(), "w");
280 fputc(kDeathTestInternalError
, parent
);
281 fprintf(parent
, "%s", message
.c_str());
285 fprintf(stderr
, "%s", message
.c_str());
291 // A replacement for CHECK that calls DeathTestAbort if the assertion
293 # define GTEST_DEATH_TEST_CHECK_(expression) \
295 if (!::testing::internal::IsTrue(expression)) { \
297 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
298 + ::testing::internal::StreamableToString(__LINE__) + ": " \
301 } while (::testing::internal::AlwaysFalse())
303 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
304 // evaluating any system call that fulfills two conditions: it must return
305 // -1 on failure, and set errno to EINTR when it is interrupted and
306 // should be tried again. The macro expands to a loop that repeatedly
307 // evaluates the expression as long as it evaluates to -1 and sets
308 // errno to EINTR. If the expression evaluates to -1 but errno is
309 // something other than EINTR, DeathTestAbort is called.
310 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
314 gtest_retval = (expression); \
315 } while (gtest_retval == -1 && errno == EINTR); \
316 if (gtest_retval == -1) { \
318 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
319 + ::testing::internal::StreamableToString(__LINE__) + ": " \
320 + #expression + " != -1"); \
322 } while (::testing::internal::AlwaysFalse())
324 // Returns the message describing the last system error in errno.
325 std::string
GetLastErrnoDescription() {
326 return errno
== 0 ? "" : posix::StrError(errno
);
329 // This is called from a death test parent process to read a failure
330 // message from the death test child process and log it with the FATAL
331 // severity. On Windows, the message is read from a pipe handle. On other
332 // platforms, it is read from a file descriptor.
333 static void FailFromInternalError(int fd
) {
339 while ((num_read
= posix::Read(fd
, buffer
, 255)) > 0) {
340 buffer
[num_read
] = '\0';
343 } while (num_read
== -1 && errno
== EINTR
);
346 GTEST_LOG_(FATAL
) << error
.GetString();
348 const int last_error
= errno
;
349 GTEST_LOG_(FATAL
) << "Error while reading death test internal: "
350 << GetLastErrnoDescription() << " [" << last_error
<< "]";
354 // Death test constructor. Increments the running death test count
355 // for the current test.
356 DeathTest::DeathTest() {
357 TestInfo
* const info
= GetUnitTestImpl()->current_test_info();
359 DeathTestAbort("Cannot run a death test outside of a TEST or "
364 // Creates and returns a death test by dispatching to the current
365 // death test factory.
366 bool DeathTest::Create(const char* statement
, const RE
* regex
,
367 const char* file
, int line
, DeathTest
** test
) {
368 return GetUnitTestImpl()->death_test_factory()->Create(
369 statement
, regex
, file
, line
, test
);
372 const char* DeathTest::LastMessage() {
373 return last_death_test_message_
.c_str();
376 void DeathTest::set_last_death_test_message(const std::string
& message
) {
377 last_death_test_message_
= message
;
380 std::string
DeathTest::last_death_test_message_
;
382 // Provides cross platform implementation for some death functionality.
383 class DeathTestImpl
: public DeathTest
{
385 DeathTestImpl(const char* a_statement
, const RE
* a_regex
)
386 : statement_(a_statement
),
390 outcome_(IN_PROGRESS
),
394 // read_fd_ is expected to be closed and cleared by a derived class.
395 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_
== -1); }
397 void Abort(AbortReason reason
);
398 virtual bool Passed(bool status_ok
);
400 const char* statement() const { return statement_
; }
401 const RE
* regex() const { return regex_
; }
402 bool spawned() const { return spawned_
; }
403 void set_spawned(bool is_spawned
) { spawned_
= is_spawned
; }
404 int status() const { return status_
; }
405 void set_status(int a_status
) { status_
= a_status
; }
406 DeathTestOutcome
outcome() const { return outcome_
; }
407 void set_outcome(DeathTestOutcome an_outcome
) { outcome_
= an_outcome
; }
408 int read_fd() const { return read_fd_
; }
409 void set_read_fd(int fd
) { read_fd_
= fd
; }
410 int write_fd() const { return write_fd_
; }
411 void set_write_fd(int fd
) { write_fd_
= fd
; }
413 // Called in the parent process only. Reads the result code of the death
414 // test child process via a pipe, interprets it to set the outcome_
415 // member, and closes read_fd_. Outputs diagnostics and terminates in
416 // case of unexpected codes.
417 void ReadAndInterpretStatusByte();
420 // The textual content of the code this object is testing. This class
421 // doesn't own this string and should not attempt to delete it.
422 const char* const statement_
;
423 // The regular expression which test output must match. DeathTestImpl
424 // doesn't own this object and should not attempt to delete it.
425 const RE
* const regex_
;
426 // True if the death test child process has been successfully spawned.
428 // The exit status of the child process.
430 // How the death test concluded.
431 DeathTestOutcome outcome_
;
432 // Descriptor to the read end of the pipe to the child process. It is
433 // always -1 in the child process. The child keeps its write end of the
434 // pipe in write_fd_.
436 // Descriptor to the child's write end of the pipe to the parent process.
437 // It is always -1 in the parent process. The parent keeps its end of the
442 // Called in the parent process only. Reads the result code of the death
443 // test child process via a pipe, interprets it to set the outcome_
444 // member, and closes read_fd_. Outputs diagnostics and terminates in
445 // case of unexpected codes.
446 void DeathTestImpl::ReadAndInterpretStatusByte() {
450 // The read() here blocks until data is available (signifying the
451 // failure of the death test) or until the pipe is closed (signifying
452 // its success), so it's okay to call this in the parent before
453 // the child process has exited.
455 bytes_read
= posix::Read(read_fd(), &flag
, 1);
456 } while (bytes_read
== -1 && errno
== EINTR
);
458 if (bytes_read
== 0) {
460 } else if (bytes_read
== 1) {
462 case kDeathTestReturned
:
463 set_outcome(RETURNED
);
465 case kDeathTestThrew
:
468 case kDeathTestLived
:
471 case kDeathTestInternalError
:
472 FailFromInternalError(read_fd()); // Does not return.
475 GTEST_LOG_(FATAL
) << "Death test child process reported "
476 << "unexpected status byte ("
477 << static_cast<unsigned int>(flag
) << ")";
480 GTEST_LOG_(FATAL
) << "Read from death test child process failed: "
481 << GetLastErrnoDescription();
483 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
487 // Signals that the death test code which should have exited, didn't.
488 // Should be called only in a death test child process.
489 // Writes a status byte to the child's status file descriptor, then
491 void DeathTestImpl::Abort(AbortReason reason
) {
492 // The parent process considers the death test to be a failure if
493 // it finds any data in our pipe. So, here we write a single flag byte
494 // to the pipe, then exit.
495 const char status_ch
=
496 reason
== TEST_DID_NOT_DIE
? kDeathTestLived
:
497 reason
== TEST_THREW_EXCEPTION
? kDeathTestThrew
: kDeathTestReturned
;
499 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch
, 1));
500 // We are leaking the descriptor here because on some platforms (i.e.,
501 // when built as Windows DLL), destructors of global objects will still
502 // run after calling _exit(). On such systems, write_fd_ will be
503 // indirectly closed from the destructor of UnitTestImpl, causing double
504 // close if it is also closed here. On debug configurations, double close
505 // may assert. As there are no in-process buffers to flush here, we are
506 // relying on the OS to close the descriptor after the process terminates
507 // when the destructors are not run.
508 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
511 // Returns an indented copy of stderr output for a death test.
512 // This makes distinguishing death test output lines from regular log lines
514 static ::std::string
FormatDeathTestOutput(const ::std::string
& output
) {
516 for (size_t at
= 0; ; ) {
517 const size_t line_end
= output
.find('\n', at
);
519 if (line_end
== ::std::string::npos
) {
520 ret
+= output
.substr(at
);
523 ret
+= output
.substr(at
, line_end
+ 1 - at
);
529 // Assesses the success or failure of a death test, using both private
530 // members which have previously been set, and one argument:
532 // Private data members:
533 // outcome: An enumeration describing how the death test
534 // concluded: DIED, LIVED, THREW, or RETURNED. The death test
535 // fails in the latter three cases.
536 // status: The exit status of the child process. On *nix, it is in the
537 // in the format specified by wait(2). On Windows, this is the
538 // value supplied to the ExitProcess() API or a numeric code
539 // of the exception that terminated the program.
540 // regex: A regular expression object to be applied to
541 // the test's captured standard error output; the death test
542 // fails if it does not match.
545 // status_ok: true if exit_status is acceptable in the context of
546 // this particular death test, which fails if it is false
548 // Returns true iff all of the above conditions are met. Otherwise, the
549 // first failing condition, in the order given above, is the one that is
550 // reported. Also sets the last death test message string.
551 bool DeathTestImpl::Passed(bool status_ok
) {
555 const std::string error_message
= GetCapturedStderr();
557 bool success
= false;
560 buffer
<< "Death test: " << statement() << "\n";
563 buffer
<< " Result: failed to die.\n"
564 << " Error msg:\n" << FormatDeathTestOutput(error_message
);
567 buffer
<< " Result: threw an exception.\n"
568 << " Error msg:\n" << FormatDeathTestOutput(error_message
);
571 buffer
<< " Result: illegal return in test statement.\n"
572 << " Error msg:\n" << FormatDeathTestOutput(error_message
);
577 // PCRE regexes support embedded NULs.
578 // GTEST_USES_PCRE is defined only in google3 mode
579 const bool matched
= RE::PartialMatch(error_message
, *regex());
581 const bool matched
= RE::PartialMatch(error_message
.c_str(), *regex());
582 # endif // GTEST_USES_PCRE
586 buffer
<< " Result: died but not with expected error.\n"
587 << " Expected: " << regex()->pattern() << "\n"
588 << "Actual msg:\n" << FormatDeathTestOutput(error_message
);
591 buffer
<< " Result: died but not with expected exit code:\n"
592 << " " << ExitSummary(status()) << "\n"
593 << "Actual msg:\n" << FormatDeathTestOutput(error_message
);
599 << "DeathTest::Passed somehow called before conclusion of test";
602 DeathTest::set_last_death_test_message(buffer
.GetString());
606 # if GTEST_OS_WINDOWS
607 // WindowsDeathTest implements death tests on Windows. Due to the
608 // specifics of starting new processes on Windows, death tests there are
609 // always threadsafe, and Google Test considers the
610 // --gtest_death_test_style=fast setting to be equivalent to
611 // --gtest_death_test_style=threadsafe there.
613 // A few implementation notes: Like the Linux version, the Windows
614 // implementation uses pipes for child-to-parent communication. But due to
615 // the specifics of pipes on Windows, some extra steps are required:
617 // 1. The parent creates a communication pipe and stores handles to both
619 // 2. The parent starts the child and provides it with the information
620 // necessary to acquire the handle to the write end of the pipe.
621 // 3. The child acquires the write end of the pipe and signals the parent
622 // using a Windows event.
623 // 4. Now the parent can release the write end of the pipe on its side. If
624 // this is done before step 3, the object's reference count goes down to
625 // 0 and it is destroyed, preventing the child from acquiring it. The
626 // parent now has to release it, or read operations on the read end of
627 // the pipe will not return when the child terminates.
628 // 5. The parent reads child's output through the pipe (outcome code and
629 // any possible error messages) from the pipe, and its stderr and then
630 // determines whether to fail the test.
632 // Note: to distinguish Win32 API calls from the local method and function
633 // calls, the former are explicitly resolved in the global namespace.
635 class WindowsDeathTest
: public DeathTestImpl
{
637 WindowsDeathTest(const char* a_statement
,
641 : DeathTestImpl(a_statement
, a_regex
), file_(file
), line_(line
) {}
643 // All of these virtual functions are inherited from DeathTest.
645 virtual TestRole
AssumeRole();
648 // The name of the file in which the death test is located.
649 const char* const file_
;
650 // The line number on which the death test is located.
652 // Handle to the write end of the pipe to the child process.
653 AutoHandle write_handle_
;
654 // Child process handle.
655 AutoHandle child_handle_
;
656 // Event the child process uses to signal the parent that it has
657 // acquired the handle to the write end of the pipe. After seeing this
658 // event the parent can release its own handles to make sure its
659 // ReadFile() calls return when the child terminates.
660 AutoHandle event_handle_
;
663 // Waits for the child in a death test to exit, returning its exit
664 // status, or 0 if no child process exists. As a side effect, sets the
665 // outcome data member.
666 int WindowsDeathTest::Wait() {
670 // Wait until the child either signals that it has acquired the write end
671 // of the pipe or it dies.
672 const HANDLE wait_handles
[2] = { child_handle_
.Get(), event_handle_
.Get() };
673 switch (::WaitForMultipleObjects(2,
675 FALSE
, // Waits for any of the handles.
678 case WAIT_OBJECT_0
+ 1:
681 GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
684 // The child has acquired the write end of the pipe or exited.
685 // We release the handle on our side and continue.
686 write_handle_
.Reset();
687 event_handle_
.Reset();
689 ReadAndInterpretStatusByte();
691 // Waits for the child process to exit if it haven't already. This
692 // returns immediately if the child has already exited, regardless of
693 // whether previous calls to WaitForMultipleObjects synchronized on this
695 GTEST_DEATH_TEST_CHECK_(
696 WAIT_OBJECT_0
== ::WaitForSingleObject(child_handle_
.Get(),
699 GTEST_DEATH_TEST_CHECK_(
700 ::GetExitCodeProcess(child_handle_
.Get(), &status_code
) != FALSE
);
701 child_handle_
.Reset();
702 set_status(static_cast<int>(status_code
));
706 // The AssumeRole process for a Windows death test. It creates a child
707 // process with the same executable as the current process to run the
708 // death test. The child process is given the --gtest_filter and
709 // --gtest_internal_run_death_test flags such that it knows to run the
710 // current death test only.
711 DeathTest::TestRole
WindowsDeathTest::AssumeRole() {
712 const UnitTestImpl
* const impl
= GetUnitTestImpl();
713 const InternalRunDeathTestFlag
* const flag
=
714 impl
->internal_run_death_test_flag();
715 const TestInfo
* const info
= impl
->current_test_info();
716 const int death_test_index
= info
->result()->death_test_count();
719 // ParseInternalRunDeathTestFlag() has performed all the necessary
721 set_write_fd(flag
->write_fd());
725 // WindowsDeathTest uses an anonymous pipe to communicate results of
727 SECURITY_ATTRIBUTES handles_are_inheritable
= {
728 sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
729 HANDLE read_handle
, write_handle
;
730 GTEST_DEATH_TEST_CHECK_(
731 ::CreatePipe(&read_handle
, &write_handle
, &handles_are_inheritable
,
732 0) // Default buffer size.
734 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle
),
736 write_handle_
.Reset(write_handle
);
737 event_handle_
.Reset(::CreateEvent(
738 &handles_are_inheritable
,
739 TRUE
, // The event will automatically reset to non-signaled state.
740 FALSE
, // The initial state is non-signalled.
741 NULL
)); // The even is unnamed.
742 GTEST_DEATH_TEST_CHECK_(event_handle_
.Get() != NULL
);
743 const std::string filter_flag
=
744 std::string("--") + GTEST_FLAG_PREFIX_
+ kFilterFlag
+ "=" +
745 info
->test_case_name() + "." + info
->name();
746 const std::string internal_flag
=
747 std::string("--") + GTEST_FLAG_PREFIX_
+ kInternalRunDeathTestFlag
+
748 "=" + file_
+ "|" + StreamableToString(line_
) + "|" +
749 StreamableToString(death_test_index
) + "|" +
750 StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
751 // size_t has the same width as pointers on both 32-bit and 64-bit
752 // Windows platforms.
753 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
754 "|" + StreamableToString(reinterpret_cast<size_t>(write_handle
)) +
755 "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_
.Get()));
757 char executable_path
[_MAX_PATH
+ 1]; // NOLINT
758 GTEST_DEATH_TEST_CHECK_(
759 _MAX_PATH
+ 1 != ::GetModuleFileNameA(NULL
,
763 std::string command_line
=
764 std::string(::GetCommandLineA()) + " " + filter_flag
+ " \"" +
765 internal_flag
+ "\"";
767 DeathTest::set_last_death_test_message("");
770 // Flush the log buffers since the log streams are shared with the child.
773 // The child process will share the standard handles with the parent.
774 STARTUPINFOA startup_info
;
775 memset(&startup_info
, 0, sizeof(STARTUPINFO
));
776 startup_info
.dwFlags
= STARTF_USESTDHANDLES
;
777 startup_info
.hStdInput
= ::GetStdHandle(STD_INPUT_HANDLE
);
778 startup_info
.hStdOutput
= ::GetStdHandle(STD_OUTPUT_HANDLE
);
779 startup_info
.hStdError
= ::GetStdHandle(STD_ERROR_HANDLE
);
781 PROCESS_INFORMATION process_info
;
782 GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
784 const_cast<char*>(command_line
.c_str()),
785 NULL
, // Retuned process handle is not inheritable.
786 NULL
, // Retuned thread handle is not inheritable.
787 TRUE
, // Child inherits all inheritable handles (for write_handle_).
788 0x0, // Default creation flags.
789 NULL
, // Inherit the parent's environment.
790 UnitTest::GetInstance()->original_working_dir(),
792 &process_info
) != FALSE
);
793 child_handle_
.Reset(process_info
.hProcess
);
794 ::CloseHandle(process_info
.hThread
);
799 # elif GTEST_OS_FUCHSIA
801 class FuchsiaDeathTest
: public DeathTestImpl
{
803 FuchsiaDeathTest(const char* a_statement
,
807 : DeathTestImpl(a_statement
, a_regex
), file_(file
), line_(line
) {}
809 // All of these virtual functions are inherited from DeathTest.
811 virtual TestRole
AssumeRole();
814 // The name of the file in which the death test is located.
815 const char* const file_
;
816 // The line number on which the death test is located.
819 zx_handle_t child_process_
;
822 // Utility class for accumulating command-line arguments.
826 args_
.push_back(NULL
);
830 for (std::vector
<char*>::iterator i
= args_
.begin(); i
!= args_
.end();
835 void AddArgument(const char* argument
) {
836 args_
.insert(args_
.end() - 1, posix::StrDup(argument
));
839 template <typename Str
>
840 void AddArguments(const ::std::vector
<Str
>& arguments
) {
841 for (typename ::std::vector
<Str
>::const_iterator i
= arguments
.begin();
842 i
!= arguments
.end();
844 args_
.insert(args_
.end() - 1, posix::StrDup(i
->c_str()));
847 char* const* Argv() {
852 return args_
.size() - 1;
856 std::vector
<char*> args_
;
859 // Waits for the child in a death test to exit, returning its exit
860 // status, or 0 if no child process exists. As a side effect, sets the
861 // outcome data member.
862 int FuchsiaDeathTest::Wait() {
866 // Wait for child process to terminate.
867 zx_status_t status_zx
;
868 zx_signals_t signals
;
869 status_zx
= zx_object_wait_one(
871 ZX_PROCESS_TERMINATED
,
874 GTEST_DEATH_TEST_CHECK_(status_zx
== ZX_OK
);
876 ReadAndInterpretStatusByte();
878 zx_info_process_t buffer
;
879 status_zx
= zx_object_get_info(
886 GTEST_DEATH_TEST_CHECK_(status_zx
== ZX_OK
);
888 GTEST_DEATH_TEST_CHECK_(buffer
.exited
);
889 set_status(buffer
.return_code
);
893 // The AssumeRole process for a Fuchsia death test. It creates a child
894 // process with the same executable as the current process to run the
895 // death test. The child process is given the --gtest_filter and
896 // --gtest_internal_run_death_test flags such that it knows to run the
897 // current death test only.
898 DeathTest::TestRole
FuchsiaDeathTest::AssumeRole() {
899 const UnitTestImpl
* const impl
= GetUnitTestImpl();
900 const InternalRunDeathTestFlag
* const flag
=
901 impl
->internal_run_death_test_flag();
902 const TestInfo
* const info
= impl
->current_test_info();
903 const int death_test_index
= info
->result()->death_test_count();
906 // ParseInternalRunDeathTestFlag() has performed all the necessary
908 set_write_fd(kFuchsiaReadPipeFd
);
913 // Flush the log buffers since the log streams are shared with the child.
916 // Build the child process command line.
917 const std::string filter_flag
=
918 std::string("--") + GTEST_FLAG_PREFIX_
+ kFilterFlag
+ "="
919 + info
->test_case_name() + "." + info
->name();
920 const std::string internal_flag
=
921 std::string("--") + GTEST_FLAG_PREFIX_
+ kInternalRunDeathTestFlag
+ "="
923 + StreamableToString(line_
) + "|"
924 + StreamableToString(death_test_index
);
926 args
.AddArguments(GetInjectableArgvs());
927 args
.AddArgument(filter_flag
.c_str());
928 args
.AddArgument(internal_flag
.c_str());
930 // Build the pipe for communication with the child.
932 zx_handle_t child_pipe_handle
;
934 status
= fdio_pipe_half(&child_pipe_handle
, &type
);
935 GTEST_DEATH_TEST_CHECK_(status
>= 0);
938 // Set the pipe handle for the child.
939 fdio_spawn_action_t add_handle_action
= {
940 .action
= FDIO_SPAWN_ACTION_ADD_HANDLE
,
942 .id
= PA_HND(type
, kFuchsiaReadPipeFd
),
943 .handle
= child_pipe_handle
947 // Spawn the child process.
948 status
= fdio_spawn_etc(ZX_HANDLE_INVALID
, FDIO_SPAWN_CLONE_ALL
,
949 args
.Argv()[0], args
.Argv(), nullptr, 1,
950 &add_handle_action
, &child_process_
, nullptr);
951 GTEST_DEATH_TEST_CHECK_(status
== ZX_OK
);
957 #else // We are neither on Windows, nor on Fuchsia.
959 // ForkingDeathTest provides implementations for most of the abstract
960 // methods of the DeathTest interface. Only the AssumeRole method is
962 class ForkingDeathTest
: public DeathTestImpl
{
964 ForkingDeathTest(const char* statement
, const RE
* regex
);
966 // All of these virtual functions are inherited from DeathTest.
970 void set_child_pid(pid_t child_pid
) { child_pid_
= child_pid
; }
973 // PID of child process during death test; 0 in the child process itself.
977 // Constructs a ForkingDeathTest.
978 ForkingDeathTest::ForkingDeathTest(const char* a_statement
, const RE
* a_regex
)
979 : DeathTestImpl(a_statement
, a_regex
),
982 // Waits for the child in a death test to exit, returning its exit
983 // status, or 0 if no child process exists. As a side effect, sets the
984 // outcome data member.
985 int ForkingDeathTest::Wait() {
989 ReadAndInterpretStatusByte();
992 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_
, &status_value
, 0));
993 set_status(status_value
);
997 // A concrete death test class that forks, then immediately runs the test
998 // in the child process.
999 class NoExecDeathTest
: public ForkingDeathTest
{
1001 NoExecDeathTest(const char* a_statement
, const RE
* a_regex
) :
1002 ForkingDeathTest(a_statement
, a_regex
) { }
1003 virtual TestRole
AssumeRole();
1006 // The AssumeRole process for a fork-and-run death test. It implements a
1007 // straightforward fork, with a simple pipe to transmit the status byte.
1008 DeathTest::TestRole
NoExecDeathTest::AssumeRole() {
1009 const size_t thread_count
= GetThreadCount();
1010 if (thread_count
!= 1) {
1011 GTEST_LOG_(WARNING
) << DeathTestThreadWarning(thread_count
);
1015 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd
) != -1);
1017 DeathTest::set_last_death_test_message("");
1019 // When we fork the process below, the log file buffers are copied, but the
1020 // file descriptors are shared. We flush all log files here so that closing
1021 // the file descriptors in the child process doesn't throw off the
1022 // synchronization between descriptors and buffers in the parent process.
1023 // This is as close to the fork as possible to avoid a race condition in case
1024 // there are multiple threads running before the death test, and another
1025 // thread writes to the log file.
1028 const pid_t child_pid
= fork();
1029 GTEST_DEATH_TEST_CHECK_(child_pid
!= -1);
1030 set_child_pid(child_pid
);
1031 if (child_pid
== 0) {
1032 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd
[0]));
1033 set_write_fd(pipe_fd
[1]);
1034 // Redirects all logging to stderr in the child process to prevent
1035 // concurrent writes to the log files. We capture stderr in the parent
1036 // process and append the child process' output to a log.
1038 // Event forwarding to the listeners of event listener API mush be shut
1039 // down in death test subprocesses.
1040 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
1041 g_in_fast_death_test_child
= true;
1042 return EXECUTE_TEST
;
1044 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd
[1]));
1045 set_read_fd(pipe_fd
[0]);
1047 return OVERSEE_TEST
;
1051 // A concrete death test class that forks and re-executes the main
1052 // program from the beginning, with command-line flags set that cause
1053 // only this specific death test to be run.
1054 class ExecDeathTest
: public ForkingDeathTest
{
1056 ExecDeathTest(const char* a_statement
, const RE
* a_regex
,
1057 const char* file
, int line
) :
1058 ForkingDeathTest(a_statement
, a_regex
), file_(file
), line_(line
) { }
1059 virtual TestRole
AssumeRole();
1061 static ::std::vector
<std::string
> GetArgvsForDeathTestChildProcess() {
1062 ::std::vector
<std::string
> args
= GetInjectableArgvs();
1063 # if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
1064 ::std::vector
<std::string
> extra_args
=
1065 GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
1066 args
.insert(args
.end(), extra_args
.begin(), extra_args
.end());
1067 # endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
1070 // The name of the file in which the death test is located.
1071 const char* const file_
;
1072 // The line number on which the death test is located.
1076 // Utility class for accumulating command-line arguments.
1080 args_
.push_back(NULL
);
1084 for (std::vector
<char*>::iterator i
= args_
.begin(); i
!= args_
.end();
1089 void AddArgument(const char* argument
) {
1090 args_
.insert(args_
.end() - 1, posix::StrDup(argument
));
1093 template <typename Str
>
1094 void AddArguments(const ::std::vector
<Str
>& arguments
) {
1095 for (typename ::std::vector
<Str
>::const_iterator i
= arguments
.begin();
1096 i
!= arguments
.end();
1098 args_
.insert(args_
.end() - 1, posix::StrDup(i
->c_str()));
1101 char* const* Argv() {
1106 std::vector
<char*> args_
;
1109 // A struct that encompasses the arguments to the child process of a
1110 // threadsafe-style death test process.
1111 struct ExecDeathTestArgs
{
1112 char* const* argv
; // Command-line arguments for the child's call to exec
1113 int close_fd
; // File descriptor to close; the read end of a pipe
1117 inline char** GetEnviron() {
1118 // When Google Test is built as a framework on MacOS X, the environ variable
1119 // is unavailable. Apple's documentation (man environ) recommends using
1120 // _NSGetEnviron() instead.
1121 return *_NSGetEnviron();
1124 // Some POSIX platforms expect you to declare environ. extern "C" makes
1125 // it reside in the global namespace.
1126 extern "C" char** environ
;
1127 inline char** GetEnviron() { return environ
; }
1128 # endif // GTEST_OS_MAC
1131 // The main function for a threadsafe-style death test child process.
1132 // This function is called in a clone()-ed process and thus must avoid
1133 // any potentially unsafe operations like malloc or libc functions.
1134 static int ExecDeathTestChildMain(void* child_arg
) {
1135 ExecDeathTestArgs
* const args
= static_cast<ExecDeathTestArgs
*>(child_arg
);
1136 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args
->close_fd
));
1138 // We need to execute the test program in the same environment where
1139 // it was originally invoked. Therefore we change to the original
1140 // working directory first.
1141 const char* const original_dir
=
1142 UnitTest::GetInstance()->original_working_dir();
1143 // We can safely call chdir() as it's a direct system call.
1144 if (chdir(original_dir
) != 0) {
1145 DeathTestAbort(std::string("chdir(\"") + original_dir
+ "\") failed: " +
1146 GetLastErrnoDescription());
1147 return EXIT_FAILURE
;
1150 // We can safely call execve() as it's a direct system call. We
1151 // cannot use execvp() as it's a libc function and thus potentially
1152 // unsafe. Since execve() doesn't search the PATH, the user must
1153 // invoke the test program via a valid path that contains at least
1154 // one path separator.
1155 execve(args
->argv
[0], args
->argv
, GetEnviron());
1156 DeathTestAbort(std::string("execve(") + args
->argv
[0] + ", ...) in " +
1157 original_dir
+ " failed: " +
1158 GetLastErrnoDescription());
1159 return EXIT_FAILURE
;
1161 # endif // !GTEST_OS_QNX
1163 # if GTEST_HAS_CLONE
1164 // Two utility routines that together determine the direction the stack
1166 // This could be accomplished more elegantly by a single recursive
1167 // function, but we want to guard against the unlikely possibility of
1168 // a smart compiler optimizing the recursion away.
1170 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
1171 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
1173 static void StackLowerThanAddress(const void* ptr
,
1174 bool* result
) GTEST_NO_INLINE_
;
1175 static void StackLowerThanAddress(const void* ptr
, bool* result
) {
1177 *result
= (&dummy
< ptr
);
1180 // Make sure AddressSanitizer does not tamper with the stack here.
1181 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
1182 static bool StackGrowsDown() {
1185 StackLowerThanAddress(&dummy
, &result
);
1188 # endif // GTEST_HAS_CLONE
1190 // Spawns a child process with the same executable as the current process in
1191 // a thread-safe manner and instructs it to run the death test. The
1192 // implementation uses fork(2) + exec. On systems where clone(2) is
1193 // available, it is used instead, being slightly more thread-safe. On QNX,
1194 // fork supports only single-threaded environments, so this function uses
1195 // spawn(2) there instead. The function dies with an error message if
1196 // anything goes wrong.
1197 static pid_t
ExecDeathTestSpawnChild(char* const* argv
, int close_fd
) {
1198 ExecDeathTestArgs args
= { argv
, close_fd
};
1199 pid_t child_pid
= -1;
1202 // Obtains the current directory and sets it to be closed in the child
1204 const int cwd_fd
= open(".", O_RDONLY
);
1205 GTEST_DEATH_TEST_CHECK_(cwd_fd
!= -1);
1206 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd
, F_SETFD
, FD_CLOEXEC
));
1207 // We need to execute the test program in the same environment where
1208 // it was originally invoked. Therefore we change to the original
1209 // working directory first.
1210 const char* const original_dir
=
1211 UnitTest::GetInstance()->original_working_dir();
1212 // We can safely call chdir() as it's a direct system call.
1213 if (chdir(original_dir
) != 0) {
1214 DeathTestAbort(std::string("chdir(\"") + original_dir
+ "\") failed: " +
1215 GetLastErrnoDescription());
1216 return EXIT_FAILURE
;
1220 // Set close_fd to be closed after spawn.
1221 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags
= fcntl(close_fd
, F_GETFD
));
1222 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd
, F_SETFD
,
1223 fd_flags
| FD_CLOEXEC
));
1224 struct inheritance inherit
= {0};
1225 // spawn is a system call.
1226 child_pid
= spawn(args
.argv
[0], 0, NULL
, &inherit
, args
.argv
, GetEnviron());
1227 // Restores the current working directory.
1228 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd
) != -1);
1229 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd
));
1231 # else // GTEST_OS_QNX
1233 // When a SIGPROF signal is received while fork() or clone() are executing,
1234 // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
1235 // it after the call to fork()/clone() is complete.
1236 struct sigaction saved_sigprof_action
;
1237 struct sigaction ignore_sigprof_action
;
1238 memset(&ignore_sigprof_action
, 0, sizeof(ignore_sigprof_action
));
1239 sigemptyset(&ignore_sigprof_action
.sa_mask
);
1240 ignore_sigprof_action
.sa_handler
= SIG_IGN
;
1241 GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
1242 SIGPROF
, &ignore_sigprof_action
, &saved_sigprof_action
));
1243 # endif // GTEST_OS_LINUX
1245 # if GTEST_HAS_CLONE
1246 const bool use_fork
= GTEST_FLAG(death_test_use_fork
);
1249 static const bool stack_grows_down
= StackGrowsDown();
1250 const size_t stack_size
= getpagesize();
1251 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
1252 void* const stack
= mmap(NULL
, stack_size
, PROT_READ
| PROT_WRITE
,
1253 MAP_ANON
| MAP_PRIVATE
, -1, 0);
1254 GTEST_DEATH_TEST_CHECK_(stack
!= MAP_FAILED
);
1256 // Maximum stack alignment in bytes: For a downward-growing stack, this
1257 // amount is subtracted from size of the stack space to get an address
1258 // that is within the stack space and is aligned on all systems we care
1259 // about. As far as I know there is no ABI with stack alignment greater
1260 // than 64. We assume stack and stack_size already have alignment of
1261 // kMaxStackAlignment.
1262 const size_t kMaxStackAlignment
= 64;
1263 void* const stack_top
=
1264 static_cast<char*>(stack
) +
1265 (stack_grows_down
? stack_size
- kMaxStackAlignment
: 0);
1266 GTEST_DEATH_TEST_CHECK_(stack_size
> kMaxStackAlignment
&&
1267 reinterpret_cast<intptr_t>(stack_top
) % kMaxStackAlignment
== 0);
1269 child_pid
= clone(&ExecDeathTestChildMain
, stack_top
, SIGCHLD
, &args
);
1271 GTEST_DEATH_TEST_CHECK_(munmap(stack
, stack_size
) != -1);
1274 const bool use_fork
= true;
1275 # endif // GTEST_HAS_CLONE
1277 if (use_fork
&& (child_pid
= fork()) == 0) {
1278 ExecDeathTestChildMain(&args
);
1281 # endif // GTEST_OS_QNX
1283 GTEST_DEATH_TEST_CHECK_SYSCALL_(
1284 sigaction(SIGPROF
, &saved_sigprof_action
, NULL
));
1285 # endif // GTEST_OS_LINUX
1287 GTEST_DEATH_TEST_CHECK_(child_pid
!= -1);
1291 // The AssumeRole process for a fork-and-exec death test. It re-executes the
1292 // main program from the beginning, setting the --gtest_filter
1293 // and --gtest_internal_run_death_test flags to cause only the current
1294 // death test to be re-run.
1295 DeathTest::TestRole
ExecDeathTest::AssumeRole() {
1296 const UnitTestImpl
* const impl
= GetUnitTestImpl();
1297 const InternalRunDeathTestFlag
* const flag
=
1298 impl
->internal_run_death_test_flag();
1299 const TestInfo
* const info
= impl
->current_test_info();
1300 const int death_test_index
= info
->result()->death_test_count();
1303 set_write_fd(flag
->write_fd());
1304 return EXECUTE_TEST
;
1308 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd
) != -1);
1309 // Clear the close-on-exec flag on the write end of the pipe, lest
1310 // it be closed when the child process does an exec:
1311 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd
[1], F_SETFD
, 0) != -1);
1313 const std::string filter_flag
=
1314 std::string("--") + GTEST_FLAG_PREFIX_
+ kFilterFlag
+ "="
1315 + info
->test_case_name() + "." + info
->name();
1316 const std::string internal_flag
=
1317 std::string("--") + GTEST_FLAG_PREFIX_
+ kInternalRunDeathTestFlag
+ "="
1318 + file_
+ "|" + StreamableToString(line_
) + "|"
1319 + StreamableToString(death_test_index
) + "|"
1320 + StreamableToString(pipe_fd
[1]);
1322 args
.AddArguments(GetArgvsForDeathTestChildProcess());
1323 args
.AddArgument(filter_flag
.c_str());
1324 args
.AddArgument(internal_flag
.c_str());
1326 DeathTest::set_last_death_test_message("");
1329 // See the comment in NoExecDeathTest::AssumeRole for why the next line
1333 const pid_t child_pid
= ExecDeathTestSpawnChild(args
.Argv(), pipe_fd
[0]);
1334 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd
[1]));
1335 set_child_pid(child_pid
);
1336 set_read_fd(pipe_fd
[0]);
1338 return OVERSEE_TEST
;
1341 # endif // !GTEST_OS_WINDOWS
1343 // Creates a concrete DeathTest-derived class that depends on the
1344 // --gtest_death_test_style flag, and sets the pointer pointed to
1345 // by the "test" argument to its address. If the test should be
1346 // skipped, sets that pointer to NULL. Returns true, unless the
1347 // flag is set to an invalid value.
1348 bool DefaultDeathTestFactory::Create(const char* statement
, const RE
* regex
,
1349 const char* file
, int line
,
1351 UnitTestImpl
* const impl
= GetUnitTestImpl();
1352 const InternalRunDeathTestFlag
* const flag
=
1353 impl
->internal_run_death_test_flag();
1354 const int death_test_index
= impl
->current_test_info()
1355 ->increment_death_test_count();
1358 if (death_test_index
> flag
->index()) {
1359 DeathTest::set_last_death_test_message(
1360 "Death test count (" + StreamableToString(death_test_index
)
1361 + ") somehow exceeded expected maximum ("
1362 + StreamableToString(flag
->index()) + ")");
1366 if (!(flag
->file() == file
&& flag
->line() == line
&&
1367 flag
->index() == death_test_index
)) {
1373 # if GTEST_OS_WINDOWS
1375 if (GTEST_FLAG(death_test_style
) == "threadsafe" ||
1376 GTEST_FLAG(death_test_style
) == "fast") {
1377 *test
= new WindowsDeathTest(statement
, regex
, file
, line
);
1380 # elif GTEST_OS_FUCHSIA
1382 if (GTEST_FLAG(death_test_style
) == "threadsafe" ||
1383 GTEST_FLAG(death_test_style
) == "fast") {
1384 *test
= new FuchsiaDeathTest(statement
, regex
, file
, line
);
1389 if (GTEST_FLAG(death_test_style
) == "threadsafe") {
1390 *test
= new ExecDeathTest(statement
, regex
, file
, line
);
1391 } else if (GTEST_FLAG(death_test_style
) == "fast") {
1392 *test
= new NoExecDeathTest(statement
, regex
);
1395 # endif // GTEST_OS_WINDOWS
1397 else { // NOLINT - this is more readable than unbalanced brackets inside #if.
1398 DeathTest::set_last_death_test_message(
1399 "Unknown death test style \"" + GTEST_FLAG(death_test_style
)
1400 + "\" encountered");
1407 # if GTEST_OS_WINDOWS
1408 // Recreates the pipe and event handles from the provided parameters,
1409 // signals the event, and returns a file descriptor wrapped around the pipe
1410 // handle. This function is called in the child process only.
1411 static int GetStatusFileDescriptor(unsigned int parent_process_id
,
1412 size_t write_handle_as_size_t
,
1413 size_t event_handle_as_size_t
) {
1414 AutoHandle
parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE
,
1415 FALSE
, // Non-inheritable.
1416 parent_process_id
));
1417 if (parent_process_handle
.Get() == INVALID_HANDLE_VALUE
) {
1418 DeathTestAbort("Unable to open parent process " +
1419 StreamableToString(parent_process_id
));
1422 // TODO(vladl@google.com): Replace the following check with a
1423 // compile-time assertion when available.
1424 GTEST_CHECK_(sizeof(HANDLE
) <= sizeof(size_t));
1426 const HANDLE write_handle
=
1427 reinterpret_cast<HANDLE
>(write_handle_as_size_t
);
1428 HANDLE dup_write_handle
;
1430 // The newly initialized handle is accessible only in the parent
1431 // process. To obtain one accessible within the child, we need to use
1433 if (!::DuplicateHandle(parent_process_handle
.Get(), write_handle
,
1434 ::GetCurrentProcess(), &dup_write_handle
,
1435 0x0, // Requested privileges ignored since
1436 // DUPLICATE_SAME_ACCESS is used.
1437 FALSE
, // Request non-inheritable handler.
1438 DUPLICATE_SAME_ACCESS
)) {
1439 DeathTestAbort("Unable to duplicate the pipe handle " +
1440 StreamableToString(write_handle_as_size_t
) +
1441 " from the parent process " +
1442 StreamableToString(parent_process_id
));
1445 const HANDLE event_handle
= reinterpret_cast<HANDLE
>(event_handle_as_size_t
);
1446 HANDLE dup_event_handle
;
1448 if (!::DuplicateHandle(parent_process_handle
.Get(), event_handle
,
1449 ::GetCurrentProcess(), &dup_event_handle
,
1452 DUPLICATE_SAME_ACCESS
)) {
1453 DeathTestAbort("Unable to duplicate the event handle " +
1454 StreamableToString(event_handle_as_size_t
) +
1455 " from the parent process " +
1456 StreamableToString(parent_process_id
));
1459 const int write_fd
=
1460 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle
), O_APPEND
);
1461 if (write_fd
== -1) {
1462 DeathTestAbort("Unable to convert pipe handle " +
1463 StreamableToString(write_handle_as_size_t
) +
1464 " to a file descriptor");
1467 // Signals the parent that the write end of the pipe has been acquired
1468 // so the parent can release its own write end.
1469 ::SetEvent(dup_event_handle
);
1473 # endif // GTEST_OS_WINDOWS
1475 // Returns a newly created InternalRunDeathTestFlag object with fields
1476 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
1477 // the flag is specified; otherwise returns NULL.
1478 InternalRunDeathTestFlag
* ParseInternalRunDeathTestFlag() {
1479 if (GTEST_FLAG(internal_run_death_test
) == "") return NULL
;
1481 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
1485 ::std::vector
< ::std::string
> fields
;
1486 SplitString(GTEST_FLAG(internal_run_death_test
).c_str(), '|', &fields
);
1489 # if GTEST_OS_WINDOWS
1491 unsigned int parent_process_id
= 0;
1492 size_t write_handle_as_size_t
= 0;
1493 size_t event_handle_as_size_t
= 0;
1495 if (fields
.size() != 6
1496 || !ParseNaturalNumber(fields
[1], &line
)
1497 || !ParseNaturalNumber(fields
[2], &index
)
1498 || !ParseNaturalNumber(fields
[3], &parent_process_id
)
1499 || !ParseNaturalNumber(fields
[4], &write_handle_as_size_t
)
1500 || !ParseNaturalNumber(fields
[5], &event_handle_as_size_t
)) {
1501 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
1502 GTEST_FLAG(internal_run_death_test
));
1504 write_fd
= GetStatusFileDescriptor(parent_process_id
,
1505 write_handle_as_size_t
,
1506 event_handle_as_size_t
);
1508 # elif GTEST_OS_FUCHSIA
1510 if (fields
.size() != 3
1511 || !ParseNaturalNumber(fields
[1], &line
)
1512 || !ParseNaturalNumber(fields
[2], &index
)) {
1513 DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
1514 + GTEST_FLAG(internal_run_death_test
));
1519 if (fields
.size() != 4
1520 || !ParseNaturalNumber(fields
[1], &line
)
1521 || !ParseNaturalNumber(fields
[2], &index
)
1522 || !ParseNaturalNumber(fields
[3], &write_fd
)) {
1523 DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
1524 + GTEST_FLAG(internal_run_death_test
));
1527 # endif // GTEST_OS_WINDOWS
1529 return new InternalRunDeathTestFlag(fields
[0], line
, index
, write_fd
);
1532 } // namespace internal
1534 #endif // GTEST_HAS_DEATH_TEST
1536 } // namespace testing