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.
31 // This file implements death tests.
33 #include "gtest/gtest-death-test.h"
42 #include "gtest/internal/custom/gtest.h"
43 #include "gtest/internal/gtest-port.h"
45 #ifdef GTEST_HAS_DEATH_TEST
48 #include <crt_externs.h>
49 #endif // GTEST_OS_MAC
57 #endif // GTEST_OS_LINUX
61 #ifdef GTEST_OS_WINDOWS
66 #endif // GTEST_OS_WINDOWS
70 #endif // GTEST_OS_QNX
72 #ifdef GTEST_OS_FUCHSIA
73 #include <lib/fdio/fd.h>
74 #include <lib/fdio/io.h>
75 #include <lib/fdio/spawn.h>
76 #include <lib/zx/channel.h>
77 #include <lib/zx/port.h>
78 #include <lib/zx/process.h>
79 #include <lib/zx/socket.h>
80 #include <zircon/processargs.h>
81 #include <zircon/syscalls.h>
82 #include <zircon/syscalls/policy.h>
83 #include <zircon/syscalls/port.h>
84 #endif // GTEST_OS_FUCHSIA
86 #endif // GTEST_HAS_DEATH_TEST
88 #include "gtest/gtest-message.h"
89 #include "gtest/internal/gtest-string.h"
90 #include "src/gtest-internal-inl.h"
96 // The default death test style.
98 // This is defined in internal/gtest-port.h as "fast", but can be overridden by
99 // a definition in internal/custom/gtest-port.h. The recommended value, which is
100 // used internally at Google, is "threadsafe".
101 static const char kDefaultDeathTestStyle
[] = GTEST_DEFAULT_DEATH_TEST_STYLE
;
103 } // namespace testing
105 GTEST_DEFINE_string_(
107 testing::internal::StringFromGTestEnv("death_test_style",
108 testing::kDefaultDeathTestStyle
),
109 "Indicates how to run a death test in a forked child process: "
110 "\"threadsafe\" (child process re-executes the test binary "
111 "from the beginning, running only the specific death test) or "
112 "\"fast\" (child process runs the death test immediately "
117 testing::internal::BoolFromGTestEnv("death_test_use_fork", false),
118 "Instructs to use fork()/_exit() instead of clone() in death tests. "
119 "Ignored and always uses fork() on POSIX systems where clone() is not "
120 "implemented. Useful when running under valgrind or similar tools if "
121 "those do not support clone(). Valgrind 3.3.1 will just fail if "
122 "it sees an unsupported combination of clone() flags. "
123 "It is not recommended to use this flag w/o valgrind though it will "
124 "work in 99% of the cases. Once valgrind is fixed, this flag will "
125 "most likely be removed.");
127 GTEST_DEFINE_string_(
128 internal_run_death_test
, "",
129 "Indicates the file, line number, temporal index of "
130 "the single death test to run, and a file descriptor to "
131 "which a success code may be sent, all separated by "
132 "the '|' characters. This flag is specified if and only if the "
133 "current process is a sub-process launched for running a thread-safe "
134 "death test. FOR INTERNAL USE ONLY.");
138 #ifdef GTEST_HAS_DEATH_TEST
142 // Valid only for fast death tests. Indicates the code is running in the
143 // child process of a fast style death test.
144 #if !defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_FUCHSIA)
145 static bool g_in_fast_death_test_child
= false;
148 // Returns a Boolean value indicating whether the caller is currently
149 // executing in the context of the death test child process. Tools such as
150 // Valgrind heap checkers may need this to modify their behavior in death
151 // tests. IMPORTANT: This is an internal utility. Using it may break the
152 // implementation of death tests. User code MUST NOT use it.
153 bool InDeathTestChild() {
154 #if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_FUCHSIA)
156 // On Windows and Fuchsia, death tests are thread-safe regardless of the value
157 // of the death_test_style flag.
158 return !GTEST_FLAG_GET(internal_run_death_test
).empty();
162 if (GTEST_FLAG_GET(death_test_style
) == "threadsafe")
163 return !GTEST_FLAG_GET(internal_run_death_test
).empty();
165 return g_in_fast_death_test_child
;
169 } // namespace internal
171 // ExitedWithCode constructor.
172 ExitedWithCode::ExitedWithCode(int exit_code
) : exit_code_(exit_code
) {}
174 // ExitedWithCode function-call operator.
175 bool ExitedWithCode::operator()(int exit_status
) const {
176 #if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_FUCHSIA)
178 return exit_status
== exit_code_
;
182 return WIFEXITED(exit_status
) && WEXITSTATUS(exit_status
) == exit_code_
;
184 #endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
187 #if !defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_FUCHSIA)
188 // KilledBySignal constructor.
189 KilledBySignal::KilledBySignal(int signum
) : signum_(signum
) {}
191 // KilledBySignal function-call operator.
192 bool KilledBySignal::operator()(int exit_status
) const {
193 #if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
196 if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_
, exit_status
, &result
)) {
200 #endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
201 return WIFSIGNALED(exit_status
) && WTERMSIG(exit_status
) == signum_
;
203 #endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
207 // Utilities needed for death tests.
209 // Generates a textual description of a given exit code, in the format
210 // specified by wait(2).
211 static std::string
ExitSummary(int exit_code
) {
214 #if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_FUCHSIA)
216 m
<< "Exited with exit status " << exit_code
;
220 if (WIFEXITED(exit_code
)) {
221 m
<< "Exited with exit status " << WEXITSTATUS(exit_code
);
222 } else if (WIFSIGNALED(exit_code
)) {
223 m
<< "Terminated by signal " << WTERMSIG(exit_code
);
226 if (WCOREDUMP(exit_code
)) {
227 m
<< " (core dumped)";
230 #endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
232 return m
.GetString();
235 // Returns true if exit_status describes a process that was terminated
236 // by a signal, or exited normally with a nonzero exit code.
237 bool ExitedUnsuccessfully(int exit_status
) {
238 return !ExitedWithCode(0)(exit_status
);
241 #if !defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_FUCHSIA)
242 // Generates a textual failure message when a death test finds more than
243 // one thread running, or cannot determine the number of threads, prior
244 // to executing the given statement. It is the responsibility of the
245 // caller not to pass a thread_count of 1.
246 static std::string
DeathTestThreadWarning(size_t thread_count
) {
248 msg
<< "Death tests use fork(), which is unsafe particularly"
249 << " in a threaded context. For this test, " << GTEST_NAME_
<< " ";
250 if (thread_count
== 0) {
251 msg
<< "couldn't detect the number of threads.";
253 msg
<< "detected " << thread_count
<< " threads.";
256 "https://github.com/google/googletest/blob/main/docs/"
257 "advanced.md#death-tests-and-threads"
258 << " for more explanation and suggested solutions, especially if"
259 << " this is the last message you see before your test times out.";
260 return msg
.GetString();
262 #endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
264 // Flag characters for reporting a death test that did not die.
265 static const char kDeathTestLived
= 'L';
266 static const char kDeathTestReturned
= 'R';
267 static const char kDeathTestThrew
= 'T';
268 static const char kDeathTestInternalError
= 'I';
270 #ifdef GTEST_OS_FUCHSIA
272 // File descriptor used for the pipe in the child process.
273 static const int kFuchsiaReadPipeFd
= 3;
277 // An enumeration describing all of the possible ways that a death test can
278 // conclude. DIED means that the process died while executing the test
279 // code; LIVED means that process lived beyond the end of the test code;
280 // RETURNED means that the test statement attempted to execute a return
281 // statement, which is not allowed; THREW means that the test statement
282 // returned control by throwing an exception. IN_PROGRESS means the test
283 // has not yet concluded.
284 enum DeathTestOutcome
{ IN_PROGRESS
, DIED
, LIVED
, RETURNED
, THREW
};
286 // Routine for aborting the program which is safe to call from an
287 // exec-style death test child process, in which case the error
288 // message is propagated back to the parent process. Otherwise, the
289 // message is simply printed to stderr. In either case, the program
290 // then exits with status 1.
291 [[noreturn
]] static void DeathTestAbort(const std::string
& message
) {
292 // On a POSIX system, this function may be called from a threadsafe-style
293 // death test child process, which operates on a very small stack. Use
294 // the heap for any additional non-minuscule memory requirements.
295 const InternalRunDeathTestFlag
* const flag
=
296 GetUnitTestImpl()->internal_run_death_test_flag();
297 if (flag
!= nullptr) {
298 FILE* parent
= posix::FDOpen(flag
->write_fd(), "w");
299 fputc(kDeathTestInternalError
, parent
);
300 fprintf(parent
, "%s", message
.c_str());
304 fprintf(stderr
, "%s", message
.c_str());
310 // A replacement for CHECK that calls DeathTestAbort if the assertion
312 #define GTEST_DEATH_TEST_CHECK_(expression) \
314 if (!::testing::internal::IsTrue(expression)) { \
315 DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \
317 ::testing::internal::StreamableToString(__LINE__) + \
318 ": " + #expression); \
320 } while (::testing::internal::AlwaysFalse())
322 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
323 // evaluating any system call that fulfills two conditions: it must return
324 // -1 on failure, and set errno to EINTR when it is interrupted and
325 // should be tried again. The macro expands to a loop that repeatedly
326 // evaluates the expression as long as it evaluates to -1 and sets
327 // errno to EINTR. If the expression evaluates to -1 but errno is
328 // something other than EINTR, DeathTestAbort is called.
329 #define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
333 gtest_retval = (expression); \
334 } while (gtest_retval == -1 && errno == EINTR); \
335 if (gtest_retval == -1) { \
336 DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \
338 ::testing::internal::StreamableToString(__LINE__) + \
339 ": " + #expression + " != -1"); \
341 } while (::testing::internal::AlwaysFalse())
343 // Returns the message describing the last system error in errno.
344 std::string
GetLastErrnoDescription() {
345 return errno
== 0 ? "" : posix::StrError(errno
);
348 // This is called from a death test parent process to read a failure
349 // message from the death test child process and log it with the FATAL
350 // severity. On Windows, the message is read from a pipe handle. On other
351 // platforms, it is read from a file descriptor.
352 static void FailFromInternalError(int fd
) {
358 while ((num_read
= posix::Read(fd
, buffer
, 255)) > 0) {
359 buffer
[num_read
] = '\0';
362 } while (num_read
== -1 && errno
== EINTR
);
365 GTEST_LOG_(FATAL
) << error
.GetString();
367 const int last_error
= errno
;
368 GTEST_LOG_(FATAL
) << "Error while reading death test internal: "
369 << GetLastErrnoDescription() << " [" << last_error
<< "]";
373 // Death test constructor. Increments the running death test count
374 // for the current test.
375 DeathTest::DeathTest() {
376 TestInfo
* const info
= GetUnitTestImpl()->current_test_info();
377 if (info
== nullptr) {
379 "Cannot run a death test outside of a TEST or "
384 // Creates and returns a death test by dispatching to the current
385 // death test factory.
386 bool DeathTest::Create(const char* statement
,
387 Matcher
<const std::string
&> matcher
, const char* file
,
388 int line
, DeathTest
** test
) {
389 return GetUnitTestImpl()->death_test_factory()->Create(
390 statement
, std::move(matcher
), file
, line
, test
);
393 const char* DeathTest::LastMessage() {
394 return last_death_test_message_
.c_str();
397 void DeathTest::set_last_death_test_message(const std::string
& message
) {
398 last_death_test_message_
= message
;
401 std::string
DeathTest::last_death_test_message_
;
403 // Provides cross platform implementation for some death functionality.
404 class DeathTestImpl
: public DeathTest
{
406 DeathTestImpl(const char* a_statement
, Matcher
<const std::string
&> matcher
)
407 : statement_(a_statement
),
408 matcher_(std::move(matcher
)),
411 outcome_(IN_PROGRESS
),
415 // read_fd_ is expected to be closed and cleared by a derived class.
416 ~DeathTestImpl() override
{ GTEST_DEATH_TEST_CHECK_(read_fd_
== -1); }
418 void Abort(AbortReason reason
) override
;
419 bool Passed(bool status_ok
) override
;
421 const char* statement() const { return statement_
; }
422 bool spawned() const { return spawned_
; }
423 void set_spawned(bool is_spawned
) { spawned_
= is_spawned
; }
424 int status() const { return status_
; }
425 void set_status(int a_status
) { status_
= a_status
; }
426 DeathTestOutcome
outcome() const { return outcome_
; }
427 void set_outcome(DeathTestOutcome an_outcome
) { outcome_
= an_outcome
; }
428 int read_fd() const { return read_fd_
; }
429 void set_read_fd(int fd
) { read_fd_
= fd
; }
430 int write_fd() const { return write_fd_
; }
431 void set_write_fd(int fd
) { write_fd_
= fd
; }
433 // Called in the parent process only. Reads the result code of the death
434 // test child process via a pipe, interprets it to set the outcome_
435 // member, and closes read_fd_. Outputs diagnostics and terminates in
436 // case of unexpected codes.
437 void ReadAndInterpretStatusByte();
439 // Returns stderr output from the child process.
440 virtual std::string
GetErrorLogs();
443 // The textual content of the code this object is testing. This class
444 // doesn't own this string and should not attempt to delete it.
445 const char* const statement_
;
446 // A matcher that's expected to match the stderr output by the child process.
447 Matcher
<const std::string
&> matcher_
;
448 // True if the death test child process has been successfully spawned.
450 // The exit status of the child process.
452 // How the death test concluded.
453 DeathTestOutcome outcome_
;
454 // Descriptor to the read end of the pipe to the child process. It is
455 // always -1 in the child process. The child keeps its write end of the
456 // pipe in write_fd_.
458 // Descriptor to the child's write end of the pipe to the parent process.
459 // It is always -1 in the parent process. The parent keeps its end of the
464 // Called in the parent process only. Reads the result code of the death
465 // test child process via a pipe, interprets it to set the outcome_
466 // member, and closes read_fd_. Outputs diagnostics and terminates in
467 // case of unexpected codes.
468 void DeathTestImpl::ReadAndInterpretStatusByte() {
472 // The read() here blocks until data is available (signifying the
473 // failure of the death test) or until the pipe is closed (signifying
474 // its success), so it's okay to call this in the parent before
475 // the child process has exited.
477 bytes_read
= posix::Read(read_fd(), &flag
, 1);
478 } while (bytes_read
== -1 && errno
== EINTR
);
480 if (bytes_read
== 0) {
482 } else if (bytes_read
== 1) {
484 case kDeathTestReturned
:
485 set_outcome(RETURNED
);
487 case kDeathTestThrew
:
490 case kDeathTestLived
:
493 case kDeathTestInternalError
:
494 FailFromInternalError(read_fd()); // Does not return.
497 GTEST_LOG_(FATAL
) << "Death test child process reported "
498 << "unexpected status byte ("
499 << static_cast<unsigned int>(flag
) << ")";
502 GTEST_LOG_(FATAL
) << "Read from death test child process failed: "
503 << GetLastErrnoDescription();
505 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
509 std::string
DeathTestImpl::GetErrorLogs() { return GetCapturedStderr(); }
511 // Signals that the death test code which should have exited, didn't.
512 // Should be called only in a death test child process.
513 // Writes a status byte to the child's status file descriptor, then
515 void DeathTestImpl::Abort(AbortReason reason
) {
516 // The parent process considers the death test to be a failure if
517 // it finds any data in our pipe. So, here we write a single flag byte
518 // to the pipe, then exit.
519 const char status_ch
= reason
== TEST_DID_NOT_DIE
? kDeathTestLived
520 : reason
== TEST_THREW_EXCEPTION
? kDeathTestThrew
521 : kDeathTestReturned
;
523 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch
, 1));
524 // We are leaking the descriptor here because on some platforms (i.e.,
525 // when built as Windows DLL), destructors of global objects will still
526 // run after calling _exit(). On such systems, write_fd_ will be
527 // indirectly closed from the destructor of UnitTestImpl, causing double
528 // close if it is also closed here. On debug configurations, double close
529 // may assert. As there are no in-process buffers to flush here, we are
530 // relying on the OS to close the descriptor after the process terminates
531 // when the destructors are not run.
532 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
535 // Returns an indented copy of stderr output for a death test.
536 // This makes distinguishing death test output lines from regular log lines
538 static ::std::string
FormatDeathTestOutput(const ::std::string
& output
) {
540 for (size_t at
= 0;;) {
541 const size_t line_end
= output
.find('\n', at
);
543 if (line_end
== ::std::string::npos
) {
544 ret
+= output
.substr(at
);
547 ret
+= output
.substr(at
, line_end
+ 1 - at
);
553 // Assesses the success or failure of a death test, using both private
554 // members which have previously been set, and one argument:
556 // Private data members:
557 // outcome: An enumeration describing how the death test
558 // concluded: DIED, LIVED, THREW, or RETURNED. The death test
559 // fails in the latter three cases.
560 // status: The exit status of the child process. On *nix, it is in the
561 // in the format specified by wait(2). On Windows, this is the
562 // value supplied to the ExitProcess() API or a numeric code
563 // of the exception that terminated the program.
564 // matcher_: A matcher that's expected to match the stderr output by the child
568 // status_ok: true if exit_status is acceptable in the context of
569 // this particular death test, which fails if it is false
571 // Returns true if and only if all of the above conditions are met. Otherwise,
572 // the first failing condition, in the order given above, is the one that is
573 // reported. Also sets the last death test message string.
574 bool DeathTestImpl::Passed(bool status_ok
) {
575 if (!spawned()) return false;
577 const std::string error_message
= GetErrorLogs();
579 bool success
= false;
582 buffer
<< "Death test: " << statement() << "\n";
585 buffer
<< " Result: failed to die.\n"
587 << FormatDeathTestOutput(error_message
);
590 buffer
<< " Result: threw an exception.\n"
592 << FormatDeathTestOutput(error_message
);
595 buffer
<< " Result: illegal return in test statement.\n"
597 << FormatDeathTestOutput(error_message
);
601 if (matcher_
.Matches(error_message
)) {
604 std::ostringstream stream
;
605 matcher_
.DescribeTo(&stream
);
606 buffer
<< " Result: died but not with expected error.\n"
607 << " Expected: " << stream
.str() << "\n"
609 << FormatDeathTestOutput(error_message
);
612 buffer
<< " Result: died but not with expected exit code:\n"
613 << " " << ExitSummary(status()) << "\n"
615 << FormatDeathTestOutput(error_message
);
621 << "DeathTest::Passed somehow called before conclusion of test";
624 DeathTest::set_last_death_test_message(buffer
.GetString());
628 #ifndef GTEST_OS_WINDOWS
629 // Note: The return value points into args, so the return value's lifetime is
630 // bound to that of args.
631 static std::unique_ptr
<char*[]> CreateArgvFromArgs(
632 std::vector
<std::string
>& args
) {
633 auto result
= std::make_unique
<char*[]>(args
.size() + 1);
634 for (size_t i
= 0; i
< args
.size(); ++i
) {
635 result
[i
] = &args
[i
][0];
637 result
[args
.size()] = nullptr; // extra null terminator
642 #ifdef GTEST_OS_WINDOWS
643 // WindowsDeathTest implements death tests on Windows. Due to the
644 // specifics of starting new processes on Windows, death tests there are
645 // always threadsafe, and Google Test considers the
646 // --gtest_death_test_style=fast setting to be equivalent to
647 // --gtest_death_test_style=threadsafe there.
649 // A few implementation notes: Like the Linux version, the Windows
650 // implementation uses pipes for child-to-parent communication. But due to
651 // the specifics of pipes on Windows, some extra steps are required:
653 // 1. The parent creates a communication pipe and stores handles to both
655 // 2. The parent starts the child and provides it with the information
656 // necessary to acquire the handle to the write end of the pipe.
657 // 3. The child acquires the write end of the pipe and signals the parent
658 // using a Windows event.
659 // 4. Now the parent can release the write end of the pipe on its side. If
660 // this is done before step 3, the object's reference count goes down to
661 // 0 and it is destroyed, preventing the child from acquiring it. The
662 // parent now has to release it, or read operations on the read end of
663 // the pipe will not return when the child terminates.
664 // 5. The parent reads child's output through the pipe (outcome code and
665 // any possible error messages) from the pipe, and its stderr and then
666 // determines whether to fail the test.
668 // Note: to distinguish Win32 API calls from the local method and function
669 // calls, the former are explicitly resolved in the global namespace.
671 class WindowsDeathTest
: public DeathTestImpl
{
673 WindowsDeathTest(const char* a_statement
, Matcher
<const std::string
&> matcher
,
674 const char* file
, int line
)
675 : DeathTestImpl(a_statement
, std::move(matcher
)),
679 // All of these virtual functions are inherited from DeathTest.
681 virtual TestRole
AssumeRole();
684 // The name of the file in which the death test is located.
685 const char* const file_
;
686 // The line number on which the death test is located.
688 // Handle to the write end of the pipe to the child process.
689 AutoHandle write_handle_
;
690 // Child process handle.
691 AutoHandle child_handle_
;
692 // Event the child process uses to signal the parent that it has
693 // acquired the handle to the write end of the pipe. After seeing this
694 // event the parent can release its own handles to make sure its
695 // ReadFile() calls return when the child terminates.
696 AutoHandle event_handle_
;
699 // Waits for the child in a death test to exit, returning its exit
700 // status, or 0 if no child process exists. As a side effect, sets the
701 // outcome data member.
702 int WindowsDeathTest::Wait() {
703 if (!spawned()) return 0;
705 // Wait until the child either signals that it has acquired the write end
706 // of the pipe or it dies.
707 const HANDLE wait_handles
[2] = {child_handle_
.Get(), event_handle_
.Get()};
708 switch (::WaitForMultipleObjects(2, wait_handles
,
709 FALSE
, // Waits for any of the handles.
712 case WAIT_OBJECT_0
+ 1:
715 GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
718 // The child has acquired the write end of the pipe or exited.
719 // We release the handle on our side and continue.
720 write_handle_
.Reset();
721 event_handle_
.Reset();
723 ReadAndInterpretStatusByte();
725 // Waits for the child process to exit if it haven't already. This
726 // returns immediately if the child has already exited, regardless of
727 // whether previous calls to WaitForMultipleObjects synchronized on this
729 GTEST_DEATH_TEST_CHECK_(WAIT_OBJECT_0
==
730 ::WaitForSingleObject(child_handle_
.Get(), INFINITE
));
732 GTEST_DEATH_TEST_CHECK_(
733 ::GetExitCodeProcess(child_handle_
.Get(), &status_code
) != FALSE
);
734 child_handle_
.Reset();
735 set_status(static_cast<int>(status_code
));
739 // The AssumeRole process for a Windows death test. It creates a child
740 // process with the same executable as the current process to run the
741 // death test. The child process is given the --gtest_filter and
742 // --gtest_internal_run_death_test flags such that it knows to run the
743 // current death test only.
744 DeathTest::TestRole
WindowsDeathTest::AssumeRole() {
745 const UnitTestImpl
* const impl
= GetUnitTestImpl();
746 const InternalRunDeathTestFlag
* const flag
=
747 impl
->internal_run_death_test_flag();
748 const TestInfo
* const info
= impl
->current_test_info();
749 const int death_test_index
= info
->result()->death_test_count();
751 if (flag
!= nullptr) {
752 // ParseInternalRunDeathTestFlag() has performed all the necessary
754 set_write_fd(flag
->write_fd());
758 // WindowsDeathTest uses an anonymous pipe to communicate results of
760 SECURITY_ATTRIBUTES handles_are_inheritable
= {sizeof(SECURITY_ATTRIBUTES
),
762 HANDLE read_handle
, write_handle
;
763 GTEST_DEATH_TEST_CHECK_(::CreatePipe(&read_handle
, &write_handle
,
764 &handles_are_inheritable
,
765 0) // Default buffer size.
768 ::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle
), O_RDONLY
));
769 write_handle_
.Reset(write_handle
);
770 event_handle_
.Reset(::CreateEvent(
771 &handles_are_inheritable
,
772 TRUE
, // The event will automatically reset to non-signaled state.
773 FALSE
, // The initial state is non-signalled.
774 nullptr)); // The even is unnamed.
775 GTEST_DEATH_TEST_CHECK_(event_handle_
.Get() != nullptr);
776 const std::string filter_flag
= std::string("--") + GTEST_FLAG_PREFIX_
+
777 "filter=" + info
->test_suite_name() + "." +
779 const std::string internal_flag
=
780 std::string("--") + GTEST_FLAG_PREFIX_
+
781 "internal_run_death_test=" + file_
+ "|" + StreamableToString(line_
) +
782 "|" + StreamableToString(death_test_index
) + "|" +
783 StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
784 // size_t has the same width as pointers on both 32-bit and 64-bit
785 // Windows platforms.
786 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
787 "|" + StreamableToString(reinterpret_cast<size_t>(write_handle
)) + "|" +
788 StreamableToString(reinterpret_cast<size_t>(event_handle_
.Get()));
790 char executable_path
[_MAX_PATH
+ 1]; // NOLINT
791 GTEST_DEATH_TEST_CHECK_(_MAX_PATH
+ 1 != ::GetModuleFileNameA(nullptr,
795 std::string command_line
= std::string(::GetCommandLineA()) + " " +
796 filter_flag
+ " \"" + internal_flag
+ "\"";
798 DeathTest::set_last_death_test_message("");
801 // Flush the log buffers since the log streams are shared with the child.
804 // The child process will share the standard handles with the parent.
805 STARTUPINFOA startup_info
;
806 memset(&startup_info
, 0, sizeof(STARTUPINFO
));
807 startup_info
.dwFlags
= STARTF_USESTDHANDLES
;
808 startup_info
.hStdInput
= ::GetStdHandle(STD_INPUT_HANDLE
);
809 startup_info
.hStdOutput
= ::GetStdHandle(STD_OUTPUT_HANDLE
);
810 startup_info
.hStdError
= ::GetStdHandle(STD_ERROR_HANDLE
);
812 PROCESS_INFORMATION process_info
;
813 GTEST_DEATH_TEST_CHECK_(
815 executable_path
, const_cast<char*>(command_line
.c_str()),
816 nullptr, // Returned process handle is not inheritable.
817 nullptr, // Returned thread handle is not inheritable.
818 TRUE
, // Child inherits all inheritable handles (for write_handle_).
819 0x0, // Default creation flags.
820 nullptr, // Inherit the parent's environment.
821 UnitTest::GetInstance()->original_working_dir(), &startup_info
,
822 &process_info
) != FALSE
);
823 child_handle_
.Reset(process_info
.hProcess
);
824 ::CloseHandle(process_info
.hThread
);
829 #elif defined(GTEST_OS_FUCHSIA)
831 class FuchsiaDeathTest
: public DeathTestImpl
{
833 FuchsiaDeathTest(const char* a_statement
, Matcher
<const std::string
&> matcher
,
834 const char* file
, int line
)
835 : DeathTestImpl(a_statement
, std::move(matcher
)),
839 // All of these virtual functions are inherited from DeathTest.
841 TestRole
AssumeRole() override
;
842 std::string
GetErrorLogs() override
;
845 // The name of the file in which the death test is located.
846 const char* const file_
;
847 // The line number on which the death test is located.
849 // The stderr data captured by the child process.
850 std::string captured_stderr_
;
852 zx::process child_process_
;
853 zx::channel exception_channel_
;
854 zx::socket stderr_socket_
;
857 // Waits for the child in a death test to exit, returning its exit
858 // status, or 0 if no child process exists. As a side effect, sets the
859 // outcome data member.
860 int FuchsiaDeathTest::Wait() {
861 const int kProcessKey
= 0;
862 const int kSocketKey
= 1;
863 const int kExceptionKey
= 2;
865 if (!spawned()) return 0;
867 // Create a port to wait for socket/task/exception events.
868 zx_status_t status_zx
;
870 status_zx
= zx::port::create(0, &port
);
871 GTEST_DEATH_TEST_CHECK_(status_zx
== ZX_OK
);
873 // Register to wait for the child process to terminate.
875 child_process_
.wait_async(port
, kProcessKey
, ZX_PROCESS_TERMINATED
, 0);
876 GTEST_DEATH_TEST_CHECK_(status_zx
== ZX_OK
);
878 // Register to wait for the socket to be readable or closed.
879 status_zx
= stderr_socket_
.wait_async(
880 port
, kSocketKey
, ZX_SOCKET_READABLE
| ZX_SOCKET_PEER_CLOSED
, 0);
881 GTEST_DEATH_TEST_CHECK_(status_zx
== ZX_OK
);
883 // Register to wait for an exception.
884 status_zx
= exception_channel_
.wait_async(port
, kExceptionKey
,
885 ZX_CHANNEL_READABLE
, 0);
886 GTEST_DEATH_TEST_CHECK_(status_zx
== ZX_OK
);
888 bool process_terminated
= false;
889 bool socket_closed
= false;
891 zx_port_packet_t packet
= {};
892 status_zx
= port
.wait(zx::time::infinite(), &packet
);
893 GTEST_DEATH_TEST_CHECK_(status_zx
== ZX_OK
);
895 if (packet
.key
== kExceptionKey
) {
896 // Process encountered an exception. Kill it directly rather than
897 // letting other handlers process the event. We will get a kProcessKey
898 // event when the process actually terminates.
899 status_zx
= child_process_
.kill();
900 GTEST_DEATH_TEST_CHECK_(status_zx
== ZX_OK
);
901 } else if (packet
.key
== kProcessKey
) {
902 // Process terminated.
903 GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet
.type
));
904 GTEST_DEATH_TEST_CHECK_(packet
.signal
.observed
& ZX_PROCESS_TERMINATED
);
905 process_terminated
= true;
906 } else if (packet
.key
== kSocketKey
) {
907 GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet
.type
));
908 if (packet
.signal
.observed
& ZX_SOCKET_READABLE
) {
909 // Read data from the socket.
910 constexpr size_t kBufferSize
= 1024;
912 size_t old_length
= captured_stderr_
.length();
913 size_t bytes_read
= 0;
914 captured_stderr_
.resize(old_length
+ kBufferSize
);
916 stderr_socket_
.read(0, &captured_stderr_
.front() + old_length
,
917 kBufferSize
, &bytes_read
);
918 captured_stderr_
.resize(old_length
+ bytes_read
);
919 } while (status_zx
== ZX_OK
);
920 if (status_zx
== ZX_ERR_PEER_CLOSED
) {
921 socket_closed
= true;
923 GTEST_DEATH_TEST_CHECK_(status_zx
== ZX_ERR_SHOULD_WAIT
);
924 status_zx
= stderr_socket_
.wait_async(
925 port
, kSocketKey
, ZX_SOCKET_READABLE
| ZX_SOCKET_PEER_CLOSED
, 0);
926 GTEST_DEATH_TEST_CHECK_(status_zx
== ZX_OK
);
929 GTEST_DEATH_TEST_CHECK_(packet
.signal
.observed
& ZX_SOCKET_PEER_CLOSED
);
930 socket_closed
= true;
933 } while (!process_terminated
&& !socket_closed
);
935 ReadAndInterpretStatusByte();
937 zx_info_process_t buffer
;
938 status_zx
= child_process_
.get_info(ZX_INFO_PROCESS
, &buffer
, sizeof(buffer
),
940 GTEST_DEATH_TEST_CHECK_(status_zx
== ZX_OK
);
942 GTEST_DEATH_TEST_CHECK_(buffer
.flags
& ZX_INFO_PROCESS_FLAG_EXITED
);
943 set_status(static_cast<int>(buffer
.return_code
));
947 // The AssumeRole process for a Fuchsia death test. It creates a child
948 // process with the same executable as the current process to run the
949 // death test. The child process is given the --gtest_filter and
950 // --gtest_internal_run_death_test flags such that it knows to run the
951 // current death test only.
952 DeathTest::TestRole
FuchsiaDeathTest::AssumeRole() {
953 const UnitTestImpl
* const impl
= GetUnitTestImpl();
954 const InternalRunDeathTestFlag
* const flag
=
955 impl
->internal_run_death_test_flag();
956 const TestInfo
* const info
= impl
->current_test_info();
957 const int death_test_index
= info
->result()->death_test_count();
959 if (flag
!= nullptr) {
960 // ParseInternalRunDeathTestFlag() has performed all the necessary
962 set_write_fd(kFuchsiaReadPipeFd
);
966 // Flush the log buffers since the log streams are shared with the child.
969 // Build the child process command line.
970 const std::string filter_flag
= std::string("--") + GTEST_FLAG_PREFIX_
+
971 "filter=" + info
->test_suite_name() + "." +
973 const std::string internal_flag
= std::string("--") + GTEST_FLAG_PREFIX_
+
974 kInternalRunDeathTestFlag
+ "=" + file_
+
975 "|" + StreamableToString(line_
) + "|" +
976 StreamableToString(death_test_index
);
978 std::vector
<std::string
> args
= GetInjectableArgvs();
979 args
.push_back(filter_flag
);
980 args
.push_back(internal_flag
);
982 // Build the pipe for communication with the child.
984 zx_handle_t child_pipe_handle
;
986 status
= fdio_pipe_half(&child_pipe_fd
, &child_pipe_handle
);
987 GTEST_DEATH_TEST_CHECK_(status
== ZX_OK
);
988 set_read_fd(child_pipe_fd
);
990 // Set the pipe handle for the child.
991 fdio_spawn_action_t spawn_actions
[2] = {};
992 fdio_spawn_action_t
* add_handle_action
= &spawn_actions
[0];
993 add_handle_action
->action
= FDIO_SPAWN_ACTION_ADD_HANDLE
;
994 add_handle_action
->h
.id
= PA_HND(PA_FD
, kFuchsiaReadPipeFd
);
995 add_handle_action
->h
.handle
= child_pipe_handle
;
997 // Create a socket pair will be used to receive the child process' stderr.
998 zx::socket stderr_producer_socket
;
999 status
= zx::socket::create(0, &stderr_producer_socket
, &stderr_socket_
);
1000 GTEST_DEATH_TEST_CHECK_(status
>= 0);
1001 int stderr_producer_fd
= -1;
1003 fdio_fd_create(stderr_producer_socket
.release(), &stderr_producer_fd
);
1004 GTEST_DEATH_TEST_CHECK_(status
>= 0);
1006 // Make the stderr socket nonblocking.
1007 GTEST_DEATH_TEST_CHECK_(fcntl(stderr_producer_fd
, F_SETFL
, 0) == 0);
1009 fdio_spawn_action_t
* add_stderr_action
= &spawn_actions
[1];
1010 add_stderr_action
->action
= FDIO_SPAWN_ACTION_CLONE_FD
;
1011 add_stderr_action
->fd
.local_fd
= stderr_producer_fd
;
1012 add_stderr_action
->fd
.target_fd
= STDERR_FILENO
;
1014 // Create a child job.
1015 zx_handle_t child_job
= ZX_HANDLE_INVALID
;
1016 status
= zx_job_create(zx_job_default(), 0, &child_job
);
1017 GTEST_DEATH_TEST_CHECK_(status
== ZX_OK
);
1018 zx_policy_basic_t policy
;
1019 policy
.condition
= ZX_POL_NEW_ANY
;
1020 policy
.policy
= ZX_POL_ACTION_ALLOW
;
1021 status
= zx_job_set_policy(child_job
, ZX_JOB_POL_RELATIVE
, ZX_JOB_POL_BASIC
,
1023 GTEST_DEATH_TEST_CHECK_(status
== ZX_OK
);
1025 // Create an exception channel attached to the |child_job|, to allow
1026 // us to suppress the system default exception handler from firing.
1027 status
= zx_task_create_exception_channel(
1028 child_job
, 0, exception_channel_
.reset_and_get_address());
1029 GTEST_DEATH_TEST_CHECK_(status
== ZX_OK
);
1031 // Spawn the child process.
1032 // Note: The test component must have `fuchsia.process.Launcher` declared
1033 // in its manifest. (Fuchsia integration tests require creating a
1034 // "Fuchsia Test Component" which contains a "Fuchsia Component Manifest")
1035 // Launching processes is a privileged operation in Fuchsia, and the
1036 // declaration indicates that the ability is required for the component.
1037 std::unique_ptr
<char*[]> argv
= CreateArgvFromArgs(args
);
1038 status
= fdio_spawn_etc(child_job
, FDIO_SPAWN_CLONE_ALL
, argv
[0], argv
.get(),
1039 nullptr, 2, spawn_actions
,
1040 child_process_
.reset_and_get_address(), nullptr);
1041 GTEST_DEATH_TEST_CHECK_(status
== ZX_OK
);
1044 return OVERSEE_TEST
;
1047 std::string
FuchsiaDeathTest::GetErrorLogs() { return captured_stderr_
; }
1049 #else // We are neither on Windows, nor on Fuchsia.
1051 // ForkingDeathTest provides implementations for most of the abstract
1052 // methods of the DeathTest interface. Only the AssumeRole method is
1054 class ForkingDeathTest
: public DeathTestImpl
{
1056 ForkingDeathTest(const char* statement
, Matcher
<const std::string
&> matcher
);
1058 // All of these virtual functions are inherited from DeathTest.
1059 int Wait() override
;
1062 void set_child_pid(pid_t child_pid
) { child_pid_
= child_pid
; }
1065 // PID of child process during death test; 0 in the child process itself.
1069 // Constructs a ForkingDeathTest.
1070 ForkingDeathTest::ForkingDeathTest(const char* a_statement
,
1071 Matcher
<const std::string
&> matcher
)
1072 : DeathTestImpl(a_statement
, std::move(matcher
)), child_pid_(-1) {}
1074 // Waits for the child in a death test to exit, returning its exit
1075 // status, or 0 if no child process exists. As a side effect, sets the
1076 // outcome data member.
1077 int ForkingDeathTest::Wait() {
1078 if (!spawned()) return 0;
1080 ReadAndInterpretStatusByte();
1083 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_
, &status_value
, 0));
1084 set_status(status_value
);
1085 return status_value
;
1088 // A concrete death test class that forks, then immediately runs the test
1089 // in the child process.
1090 class NoExecDeathTest
: public ForkingDeathTest
{
1092 NoExecDeathTest(const char* a_statement
, Matcher
<const std::string
&> matcher
)
1093 : ForkingDeathTest(a_statement
, std::move(matcher
)) {}
1094 TestRole
AssumeRole() override
;
1097 // The AssumeRole process for a fork-and-run death test. It implements a
1098 // straightforward fork, with a simple pipe to transmit the status byte.
1099 DeathTest::TestRole
NoExecDeathTest::AssumeRole() {
1100 const size_t thread_count
= GetThreadCount();
1101 if (thread_count
!= 1) {
1102 GTEST_LOG_(WARNING
) << DeathTestThreadWarning(thread_count
);
1106 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd
) != -1);
1108 DeathTest::set_last_death_test_message("");
1110 // When we fork the process below, the log file buffers are copied, but the
1111 // file descriptors are shared. We flush all log files here so that closing
1112 // the file descriptors in the child process doesn't throw off the
1113 // synchronization between descriptors and buffers in the parent process.
1114 // This is as close to the fork as possible to avoid a race condition in case
1115 // there are multiple threads running before the death test, and another
1116 // thread writes to the log file.
1119 const pid_t child_pid
= fork();
1120 GTEST_DEATH_TEST_CHECK_(child_pid
!= -1);
1121 set_child_pid(child_pid
);
1122 if (child_pid
== 0) {
1123 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd
[0]));
1124 set_write_fd(pipe_fd
[1]);
1125 // Redirects all logging to stderr in the child process to prevent
1126 // concurrent writes to the log files. We capture stderr in the parent
1127 // process and append the child process' output to a log.
1129 // Event forwarding to the listeners of event listener API mush be shut
1130 // down in death test subprocesses.
1131 GetUnitTestImpl()->listeners()->SuppressEventForwarding(true);
1132 g_in_fast_death_test_child
= true;
1133 return EXECUTE_TEST
;
1135 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd
[1]));
1136 set_read_fd(pipe_fd
[0]);
1138 return OVERSEE_TEST
;
1142 // A concrete death test class that forks and re-executes the main
1143 // program from the beginning, with command-line flags set that cause
1144 // only this specific death test to be run.
1145 class ExecDeathTest
: public ForkingDeathTest
{
1147 ExecDeathTest(const char* a_statement
, Matcher
<const std::string
&> matcher
,
1148 const char* file
, int line
)
1149 : ForkingDeathTest(a_statement
, std::move(matcher
)),
1152 TestRole
AssumeRole() override
;
1155 static ::std::vector
<std::string
> GetArgvsForDeathTestChildProcess() {
1156 ::std::vector
<std::string
> args
= GetInjectableArgvs();
1157 #if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
1158 ::std::vector
<std::string
> extra_args
=
1159 GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
1160 args
.insert(args
.end(), extra_args
.begin(), extra_args
.end());
1161 #endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
1164 // The name of the file in which the death test is located.
1165 const char* const file_
;
1166 // The line number on which the death test is located.
1170 // A struct that encompasses the arguments to the child process of a
1171 // threadsafe-style death test process.
1172 struct ExecDeathTestArgs
{
1173 char* const* argv
; // Command-line arguments for the child's call to exec
1174 int close_fd
; // File descriptor to close; the read end of a pipe
1178 extern "C" char** environ
;
1179 #else // GTEST_OS_QNX
1180 // The main function for a threadsafe-style death test child process.
1181 // This function is called in a clone()-ed process and thus must avoid
1182 // any potentially unsafe operations like malloc or libc functions.
1183 static int ExecDeathTestChildMain(void* child_arg
) {
1184 ExecDeathTestArgs
* const args
= static_cast<ExecDeathTestArgs
*>(child_arg
);
1185 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args
->close_fd
));
1187 // We need to execute the test program in the same environment where
1188 // it was originally invoked. Therefore we change to the original
1189 // working directory first.
1190 const char* const original_dir
=
1191 UnitTest::GetInstance()->original_working_dir();
1192 // We can safely call chdir() as it's a direct system call.
1193 if (chdir(original_dir
) != 0) {
1194 DeathTestAbort(std::string("chdir(\"") + original_dir
+
1195 "\") failed: " + GetLastErrnoDescription());
1196 return EXIT_FAILURE
;
1199 // We can safely call execv() as it's almost a direct system call. We
1200 // cannot use execvp() as it's a libc function and thus potentially
1201 // unsafe. Since execv() doesn't search the PATH, the user must
1202 // invoke the test program via a valid path that contains at least
1203 // one path separator.
1204 execv(args
->argv
[0], args
->argv
);
1205 DeathTestAbort(std::string("execv(") + args
->argv
[0] + ", ...) in " +
1206 original_dir
+ " failed: " + GetLastErrnoDescription());
1207 return EXIT_FAILURE
;
1209 #endif // GTEST_OS_QNX
1212 // Two utility routines that together determine the direction the stack
1214 // This could be accomplished more elegantly by a single recursive
1215 // function, but we want to guard against the unlikely possibility of
1216 // a smart compiler optimizing the recursion away.
1218 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
1219 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
1221 static void StackLowerThanAddress(const void* ptr
,
1222 bool* result
) GTEST_NO_INLINE_
;
1223 // Make sure sanitizers do not tamper with the stack here.
1224 // Ideally, we want to use `__builtin_frame_address` instead of a local variable
1225 // address with sanitizer disabled, but it does not work when the
1226 // compiler optimizes the stack frame out, which happens on PowerPC targets.
1227 // HWAddressSanitizer add a random tag to the MSB of the local variable address,
1228 // making comparison result unpredictable.
1229 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
1230 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
1231 static void StackLowerThanAddress(const void* ptr
, bool* result
) {
1233 *result
= std::less
<const void*>()(&dummy
, ptr
);
1236 // Make sure AddressSanitizer does not tamper with the stack here.
1237 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
1238 GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
1239 static bool StackGrowsDown() {
1242 StackLowerThanAddress(&dummy
, &result
);
1245 #endif // GTEST_HAS_CLONE
1247 // Spawns a child process with the same executable as the current process in
1248 // a thread-safe manner and instructs it to run the death test. The
1249 // implementation uses fork(2) + exec. On systems where clone(2) is
1250 // available, it is used instead, being slightly more thread-safe. On QNX,
1251 // fork supports only single-threaded environments, so this function uses
1252 // spawn(2) there instead. The function dies with an error message if
1253 // anything goes wrong.
1254 static pid_t
ExecDeathTestSpawnChild(char* const* argv
, int close_fd
) {
1255 ExecDeathTestArgs args
= {argv
, close_fd
};
1256 pid_t child_pid
= -1;
1259 // Obtains the current directory and sets it to be closed in the child
1261 const int cwd_fd
= open(".", O_RDONLY
);
1262 GTEST_DEATH_TEST_CHECK_(cwd_fd
!= -1);
1263 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd
, F_SETFD
, FD_CLOEXEC
));
1264 // We need to execute the test program in the same environment where
1265 // it was originally invoked. Therefore we change to the original
1266 // working directory first.
1267 const char* const original_dir
=
1268 UnitTest::GetInstance()->original_working_dir();
1269 // We can safely call chdir() as it's a direct system call.
1270 if (chdir(original_dir
) != 0) {
1271 DeathTestAbort(std::string("chdir(\"") + original_dir
+
1272 "\") failed: " + GetLastErrnoDescription());
1273 return EXIT_FAILURE
;
1277 // Set close_fd to be closed after spawn.
1278 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags
= fcntl(close_fd
, F_GETFD
));
1279 GTEST_DEATH_TEST_CHECK_SYSCALL_(
1280 fcntl(close_fd
, F_SETFD
, fd_flags
| FD_CLOEXEC
));
1281 struct inheritance inherit
= {0};
1282 // spawn is a system call.
1283 child_pid
= spawn(args
.argv
[0], 0, nullptr, &inherit
, args
.argv
, environ
);
1284 // Restores the current working directory.
1285 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd
) != -1);
1286 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd
));
1288 #else // GTEST_OS_QNX
1289 #ifdef GTEST_OS_LINUX
1290 // When a SIGPROF signal is received while fork() or clone() are executing,
1291 // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
1292 // it after the call to fork()/clone() is complete.
1293 struct sigaction saved_sigprof_action
;
1294 struct sigaction ignore_sigprof_action
;
1295 memset(&ignore_sigprof_action
, 0, sizeof(ignore_sigprof_action
));
1296 sigemptyset(&ignore_sigprof_action
.sa_mask
);
1297 ignore_sigprof_action
.sa_handler
= SIG_IGN
;
1298 GTEST_DEATH_TEST_CHECK_SYSCALL_(
1299 sigaction(SIGPROF
, &ignore_sigprof_action
, &saved_sigprof_action
));
1300 #endif // GTEST_OS_LINUX
1303 const bool use_fork
= GTEST_FLAG_GET(death_test_use_fork
);
1306 static const bool stack_grows_down
= StackGrowsDown();
1307 const auto stack_size
= static_cast<size_t>(getpagesize() * 2);
1308 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
1309 void* const stack
= mmap(nullptr, stack_size
, PROT_READ
| PROT_WRITE
,
1310 MAP_ANON
| MAP_PRIVATE
, -1, 0);
1311 GTEST_DEATH_TEST_CHECK_(stack
!= MAP_FAILED
);
1313 // Maximum stack alignment in bytes: For a downward-growing stack, this
1314 // amount is subtracted from size of the stack space to get an address
1315 // that is within the stack space and is aligned on all systems we care
1316 // about. As far as I know there is no ABI with stack alignment greater
1317 // than 64. We assume stack and stack_size already have alignment of
1318 // kMaxStackAlignment.
1319 const size_t kMaxStackAlignment
= 64;
1320 void* const stack_top
=
1321 static_cast<char*>(stack
) +
1322 (stack_grows_down
? stack_size
- kMaxStackAlignment
: 0);
1323 GTEST_DEATH_TEST_CHECK_(
1324 static_cast<size_t>(stack_size
) > kMaxStackAlignment
&&
1325 reinterpret_cast<uintptr_t>(stack_top
) % kMaxStackAlignment
== 0);
1327 child_pid
= clone(&ExecDeathTestChildMain
, stack_top
, SIGCHLD
, &args
);
1329 GTEST_DEATH_TEST_CHECK_(munmap(stack
, stack_size
) != -1);
1332 const bool use_fork
= true;
1333 #endif // GTEST_HAS_CLONE
1335 if (use_fork
&& (child_pid
= fork()) == 0) {
1336 _exit(ExecDeathTestChildMain(&args
));
1338 #endif // GTEST_OS_QNX
1339 #ifdef GTEST_OS_LINUX
1340 GTEST_DEATH_TEST_CHECK_SYSCALL_(
1341 sigaction(SIGPROF
, &saved_sigprof_action
, nullptr));
1342 #endif // GTEST_OS_LINUX
1344 GTEST_DEATH_TEST_CHECK_(child_pid
!= -1);
1348 // The AssumeRole process for a fork-and-exec death test. It re-executes the
1349 // main program from the beginning, setting the --gtest_filter
1350 // and --gtest_internal_run_death_test flags to cause only the current
1351 // death test to be re-run.
1352 DeathTest::TestRole
ExecDeathTest::AssumeRole() {
1353 const UnitTestImpl
* const impl
= GetUnitTestImpl();
1354 const InternalRunDeathTestFlag
* const flag
=
1355 impl
->internal_run_death_test_flag();
1356 const TestInfo
* const info
= impl
->current_test_info();
1357 const int death_test_index
= info
->result()->death_test_count();
1359 if (flag
!= nullptr) {
1360 set_write_fd(flag
->write_fd());
1361 return EXECUTE_TEST
;
1365 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd
) != -1);
1366 // Clear the close-on-exec flag on the write end of the pipe, lest
1367 // it be closed when the child process does an exec:
1368 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd
[1], F_SETFD
, 0) != -1);
1370 const std::string filter_flag
= std::string("--") + GTEST_FLAG_PREFIX_
+
1371 "filter=" + info
->test_suite_name() + "." +
1373 const std::string internal_flag
= std::string("--") + GTEST_FLAG_PREFIX_
+
1374 "internal_run_death_test=" + file_
+ "|" +
1375 StreamableToString(line_
) + "|" +
1376 StreamableToString(death_test_index
) + "|" +
1377 StreamableToString(pipe_fd
[1]);
1378 std::vector
<std::string
> args
= GetArgvsForDeathTestChildProcess();
1379 args
.push_back(filter_flag
);
1380 args
.push_back(internal_flag
);
1382 DeathTest::set_last_death_test_message("");
1385 // See the comment in NoExecDeathTest::AssumeRole for why the next line
1389 std::unique_ptr
<char*[]> argv
= CreateArgvFromArgs(args
);
1390 const pid_t child_pid
= ExecDeathTestSpawnChild(argv
.get(), pipe_fd
[0]);
1391 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd
[1]));
1392 set_child_pid(child_pid
);
1393 set_read_fd(pipe_fd
[0]);
1395 return OVERSEE_TEST
;
1398 #endif // !GTEST_OS_WINDOWS
1400 // Creates a concrete DeathTest-derived class that depends on the
1401 // --gtest_death_test_style flag, and sets the pointer pointed to
1402 // by the "test" argument to its address. If the test should be
1403 // skipped, sets that pointer to NULL. Returns true, unless the
1404 // flag is set to an invalid value.
1405 bool DefaultDeathTestFactory::Create(const char* statement
,
1406 Matcher
<const std::string
&> matcher
,
1407 const char* file
, int line
,
1409 UnitTestImpl
* const impl
= GetUnitTestImpl();
1410 const InternalRunDeathTestFlag
* const flag
=
1411 impl
->internal_run_death_test_flag();
1412 const int death_test_index
=
1413 impl
->current_test_info()->increment_death_test_count();
1415 if (flag
!= nullptr) {
1416 if (death_test_index
> flag
->index()) {
1417 DeathTest::set_last_death_test_message(
1418 "Death test count (" + StreamableToString(death_test_index
) +
1419 ") somehow exceeded expected maximum (" +
1420 StreamableToString(flag
->index()) + ")");
1424 if (!(flag
->file() == file
&& flag
->line() == line
&&
1425 flag
->index() == death_test_index
)) {
1431 #ifdef GTEST_OS_WINDOWS
1433 if (GTEST_FLAG_GET(death_test_style
) == "threadsafe" ||
1434 GTEST_FLAG_GET(death_test_style
) == "fast") {
1435 *test
= new WindowsDeathTest(statement
, std::move(matcher
), file
, line
);
1438 #elif defined(GTEST_OS_FUCHSIA)
1440 if (GTEST_FLAG_GET(death_test_style
) == "threadsafe" ||
1441 GTEST_FLAG_GET(death_test_style
) == "fast") {
1442 *test
= new FuchsiaDeathTest(statement
, std::move(matcher
), file
, line
);
1447 if (GTEST_FLAG_GET(death_test_style
) == "threadsafe") {
1448 *test
= new ExecDeathTest(statement
, std::move(matcher
), file
, line
);
1449 } else if (GTEST_FLAG_GET(death_test_style
) == "fast") {
1450 *test
= new NoExecDeathTest(statement
, std::move(matcher
));
1453 #endif // GTEST_OS_WINDOWS
1455 else { // NOLINT - this is more readable than unbalanced brackets inside #if.
1456 DeathTest::set_last_death_test_message("Unknown death test style \"" +
1457 GTEST_FLAG_GET(death_test_style
) +
1465 #ifdef GTEST_OS_WINDOWS
1466 // Recreates the pipe and event handles from the provided parameters,
1467 // signals the event, and returns a file descriptor wrapped around the pipe
1468 // handle. This function is called in the child process only.
1469 static int GetStatusFileDescriptor(unsigned int parent_process_id
,
1470 size_t write_handle_as_size_t
,
1471 size_t event_handle_as_size_t
) {
1472 AutoHandle
parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE
,
1473 FALSE
, // Non-inheritable.
1474 parent_process_id
));
1475 if (parent_process_handle
.Get() == INVALID_HANDLE_VALUE
) {
1476 DeathTestAbort("Unable to open parent process " +
1477 StreamableToString(parent_process_id
));
1480 GTEST_CHECK_(sizeof(HANDLE
) <= sizeof(size_t));
1482 const HANDLE write_handle
= reinterpret_cast<HANDLE
>(write_handle_as_size_t
);
1483 HANDLE dup_write_handle
;
1485 // The newly initialized handle is accessible only in the parent
1486 // process. To obtain one accessible within the child, we need to use
1488 if (!::DuplicateHandle(parent_process_handle
.Get(), write_handle
,
1489 ::GetCurrentProcess(), &dup_write_handle
,
1490 0x0, // Requested privileges ignored since
1491 // DUPLICATE_SAME_ACCESS is used.
1492 FALSE
, // Request non-inheritable handler.
1493 DUPLICATE_SAME_ACCESS
)) {
1494 DeathTestAbort("Unable to duplicate the pipe handle " +
1495 StreamableToString(write_handle_as_size_t
) +
1496 " from the parent process " +
1497 StreamableToString(parent_process_id
));
1500 const HANDLE event_handle
= reinterpret_cast<HANDLE
>(event_handle_as_size_t
);
1501 HANDLE dup_event_handle
;
1503 if (!::DuplicateHandle(parent_process_handle
.Get(), event_handle
,
1504 ::GetCurrentProcess(), &dup_event_handle
, 0x0, FALSE
,
1505 DUPLICATE_SAME_ACCESS
)) {
1506 DeathTestAbort("Unable to duplicate the event handle " +
1507 StreamableToString(event_handle_as_size_t
) +
1508 " from the parent process " +
1509 StreamableToString(parent_process_id
));
1512 const int write_fd
=
1513 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle
), O_APPEND
);
1514 if (write_fd
== -1) {
1515 DeathTestAbort("Unable to convert pipe handle " +
1516 StreamableToString(write_handle_as_size_t
) +
1517 " to a file descriptor");
1520 // Signals the parent that the write end of the pipe has been acquired
1521 // so the parent can release its own write end.
1522 ::SetEvent(dup_event_handle
);
1526 #endif // GTEST_OS_WINDOWS
1528 // Returns a newly created InternalRunDeathTestFlag object with fields
1529 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
1530 // the flag is specified; otherwise returns NULL.
1531 InternalRunDeathTestFlag
* ParseInternalRunDeathTestFlag() {
1532 if (GTEST_FLAG_GET(internal_run_death_test
).empty()) return nullptr;
1534 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
1538 ::std::vector
< ::std::string
> fields
;
1539 SplitString(GTEST_FLAG_GET(internal_run_death_test
), '|', &fields
);
1542 #ifdef GTEST_OS_WINDOWS
1544 unsigned int parent_process_id
= 0;
1545 size_t write_handle_as_size_t
= 0;
1546 size_t event_handle_as_size_t
= 0;
1548 if (fields
.size() != 6 || !ParseNaturalNumber(fields
[1], &line
) ||
1549 !ParseNaturalNumber(fields
[2], &index
) ||
1550 !ParseNaturalNumber(fields
[3], &parent_process_id
) ||
1551 !ParseNaturalNumber(fields
[4], &write_handle_as_size_t
) ||
1552 !ParseNaturalNumber(fields
[5], &event_handle_as_size_t
)) {
1553 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
1554 GTEST_FLAG_GET(internal_run_death_test
));
1556 write_fd
= GetStatusFileDescriptor(parent_process_id
, write_handle_as_size_t
,
1557 event_handle_as_size_t
);
1559 #elif defined(GTEST_OS_FUCHSIA)
1561 if (fields
.size() != 3 || !ParseNaturalNumber(fields
[1], &line
) ||
1562 !ParseNaturalNumber(fields
[2], &index
)) {
1563 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
1564 GTEST_FLAG_GET(internal_run_death_test
));
1569 if (fields
.size() != 4 || !ParseNaturalNumber(fields
[1], &line
) ||
1570 !ParseNaturalNumber(fields
[2], &index
) ||
1571 !ParseNaturalNumber(fields
[3], &write_fd
)) {
1572 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
1573 GTEST_FLAG_GET(internal_run_death_test
));
1576 #endif // GTEST_OS_WINDOWS
1578 return new InternalRunDeathTestFlag(fields
[0], line
, index
, write_fd
);
1581 } // namespace internal
1583 #endif // GTEST_HAS_DEATH_TEST
1585 } // namespace testing