33#include "gtest/gtest-death-test.h"
38#include "gtest/internal/custom/gtest.h"
39#include "gtest/internal/gtest-port.h"
41#if GTEST_HAS_DEATH_TEST
44#include <crt_externs.h>
69#include <lib/fdio/fd.h>
70#include <lib/fdio/io.h>
71#include <lib/fdio/spawn.h>
72#include <lib/zx/channel.h>
73#include <lib/zx/port.h>
74#include <lib/zx/process.h>
75#include <lib/zx/socket.h>
76#include <zircon/processargs.h>
77#include <zircon/syscalls.h>
78#include <zircon/syscalls/policy.h>
79#include <zircon/syscalls/port.h>
84#include "gtest/gtest-message.h"
85#include "gtest/internal/gtest-string.h"
105 "Indicates how to run a death test in a forked child process: "
106 "\"threadsafe\" (child process re-executes the test binary "
107 "from the beginning, running only the specific death test) or "
108 "\"fast\" (child process runs the death test immediately "
114 "Instructs to use fork()/_exit() instead of clone() in death tests. "
115 "Ignored and always uses fork() on POSIX systems where clone() is not "
116 "implemented. Useful when running under valgrind or similar tools if "
117 "those do not support clone(). Valgrind 3.3.1 will just fail if "
118 "it sees an unsupported combination of clone() flags. "
119 "It is not recommended to use this flag w/o valgrind though it will "
120 "work in 99% of the cases. Once valgrind is fixed, this flag will "
121 "most likely be removed.");
124 internal_run_death_test,
"",
125 "Indicates the file, line number, temporal index of "
126 "the single death test to run, and a file descriptor to "
127 "which a success code may be sent, all separated by "
128 "the '|' characters. This flag is specified if and only if the "
129 "current process is a sub-process launched for running a thread-safe "
130 "death test. FOR INTERNAL USE ONLY.");
134#if GTEST_HAS_DEATH_TEST
140#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
141static bool g_in_fast_death_test_child =
false;
149bool InDeathTestChild() {
150#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
154 return !GTEST_FLAG_GET(internal_run_death_test).empty();
158 if (GTEST_FLAG_GET(death_test_style) ==
"threadsafe")
159 return !GTEST_FLAG_GET(internal_run_death_test).empty();
161 return g_in_fast_death_test_child;
168ExitedWithCode::ExitedWithCode(
int exit_code) : exit_code_(exit_code) {}
171bool ExitedWithCode::operator()(
int exit_status)
const {
172#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
174 return exit_status == exit_code_;
178 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
183#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
185KilledBySignal::KilledBySignal(
int signum) : signum_(signum) {}
188bool KilledBySignal::operator()(
int exit_status)
const {
189#if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
192 if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
197 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
207static std::string ExitSummary(
int exit_code) {
210#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
212 m <<
"Exited with exit status " << exit_code;
216 if (WIFEXITED(exit_code)) {
217 m <<
"Exited with exit status " << WEXITSTATUS(exit_code);
218 }
else if (WIFSIGNALED(exit_code)) {
219 m <<
"Terminated by signal " << WTERMSIG(exit_code);
222 if (WCOREDUMP(exit_code)) {
223 m <<
" (core dumped)";
228 return m.GetString();
233bool ExitedUnsuccessfully(
int exit_status) {
234 return !ExitedWithCode(0)(exit_status);
237#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
242static std::string DeathTestThreadWarning(
size_t thread_count) {
244 msg <<
"Death tests use fork(), which is unsafe particularly"
245 <<
" in a threaded context. For this test, " << GTEST_NAME_ <<
" ";
246 if (thread_count == 0) {
247 msg <<
"couldn't detect the number of threads.";
249 msg <<
"detected " << thread_count <<
" threads.";
252 "https://github.com/google/googletest/blob/master/docs/"
253 "advanced.md#death-tests-and-threads"
254 <<
" for more explanation and suggested solutions, especially if"
255 <<
" this is the last message you see before your test times out.";
256 return msg.GetString();
261static const char kDeathTestLived =
'L';
262static const char kDeathTestReturned =
'R';
263static const char kDeathTestThrew =
'T';
264static const char kDeathTestInternalError =
'I';
269static const int kFuchsiaReadPipeFd = 3;
280enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
287static void DeathTestAbort(
const std::string& message) {
291 const InternalRunDeathTestFlag*
const flag =
292 GetUnitTestImpl()->internal_run_death_test_flag();
293 if (flag !=
nullptr) {
294 FILE* parent = posix::FDOpen(flag->write_fd(),
"w");
295 fputc(kDeathTestInternalError, parent);
296 fprintf(parent,
"%s", message.c_str());
300 fprintf(stderr,
"%s", message.c_str());
308#define GTEST_DEATH_TEST_CHECK_(expression) \
310 if (!::testing::internal::IsTrue(expression)) { \
311 DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \
313 ::testing::internal::StreamableToString(__LINE__) + \
314 ": " + #expression); \
316 } while (::testing::internal::AlwaysFalse())
325#define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
329 gtest_retval = (expression); \
330 } while (gtest_retval == -1 && errno == EINTR); \
331 if (gtest_retval == -1) { \
332 DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \
334 ::testing::internal::StreamableToString(__LINE__) + \
335 ": " + #expression + " != -1"); \
337 } while (::testing::internal::AlwaysFalse())
340std::string GetLastErrnoDescription() {
341 return errno == 0 ?
"" : posix::StrError(errno);
348static void FailFromInternalError(
int fd) {
354 while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
355 buffer[num_read] =
'\0';
358 }
while (num_read == -1 && errno == EINTR);
361 GTEST_LOG_(FATAL) << error.GetString();
363 const int last_error = errno;
364 GTEST_LOG_(FATAL) <<
"Error while reading death test internal: "
365 << GetLastErrnoDescription() <<
" [" << last_error <<
"]";
371DeathTest::DeathTest() {
372 TestInfo*
const info = GetUnitTestImpl()->current_test_info();
373 if (info ==
nullptr) {
375 "Cannot run a death test outside of a TEST or "
382bool DeathTest::Create(
const char* statement,
383 Matcher<const std::string&> matcher,
const char* file,
384 int line, DeathTest** test) {
385 return GetUnitTestImpl()->death_test_factory()->Create(
386 statement, std::move(matcher), file, line, test);
389const char* DeathTest::LastMessage() {
390 return last_death_test_message_.c_str();
393void DeathTest::set_last_death_test_message(
const std::string& message) {
394 last_death_test_message_ = message;
397std::string DeathTest::last_death_test_message_;
400class DeathTestImpl :
public DeathTest {
402 DeathTestImpl(
const char* a_statement, Matcher<const std::string&> matcher)
403 : statement_(a_statement),
404 matcher_(std::move(matcher)),
407 outcome_(IN_PROGRESS),
412 ~DeathTestImpl()
override { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
414 void Abort(AbortReason reason)
override;
415 bool Passed(
bool status_ok)
override;
417 const char* statement()
const {
return statement_; }
418 bool spawned()
const {
return spawned_; }
419 void set_spawned(
bool is_spawned) { spawned_ = is_spawned; }
420 int status()
const {
return status_; }
421 void set_status(
int a_status) { status_ = a_status; }
422 DeathTestOutcome outcome()
const {
return outcome_; }
423 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
424 int read_fd()
const {
return read_fd_; }
425 void set_read_fd(
int fd) { read_fd_ = fd; }
426 int write_fd()
const {
return write_fd_; }
427 void set_write_fd(
int fd) { write_fd_ = fd; }
433 void ReadAndInterpretStatusByte();
436 virtual std::string GetErrorLogs();
441 const char*
const statement_;
443 Matcher<const std::string&> matcher_;
449 DeathTestOutcome outcome_;
464void DeathTestImpl::ReadAndInterpretStatusByte() {
473 bytes_read = posix::Read(read_fd(), &flag, 1);
474 }
while (bytes_read == -1 && errno == EINTR);
476 if (bytes_read == 0) {
478 }
else if (bytes_read == 1) {
480 case kDeathTestReturned:
481 set_outcome(RETURNED);
483 case kDeathTestThrew:
486 case kDeathTestLived:
489 case kDeathTestInternalError:
490 FailFromInternalError(read_fd());
493 GTEST_LOG_(FATAL) <<
"Death test child process reported "
494 <<
"unexpected status byte ("
495 <<
static_cast<unsigned int>(flag) <<
")";
498 GTEST_LOG_(FATAL) <<
"Read from death test child process failed: "
499 << GetLastErrnoDescription();
501 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
505std::string DeathTestImpl::GetErrorLogs() {
return GetCapturedStderr(); }
511void DeathTestImpl::Abort(AbortReason reason) {
515 const char status_ch = reason == TEST_DID_NOT_DIE ? kDeathTestLived
516 : reason == TEST_THREW_EXCEPTION ? kDeathTestThrew
517 : kDeathTestReturned;
519 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
534static ::std::string FormatDeathTestOutput(const ::std::string& output) {
536 for (
size_t at = 0;;) {
537 const size_t line_end = output.find(
'\n', at);
539 if (line_end == ::std::string::npos) {
540 ret += output.substr(at);
543 ret += output.substr(at, line_end + 1 - at);
570bool DeathTestImpl::Passed(
bool status_ok) {
571 if (!spawned())
return false;
573 const std::string error_message = GetErrorLogs();
575 bool success =
false;
578 buffer <<
"Death test: " << statement() <<
"\n";
581 buffer <<
" Result: failed to die.\n"
583 << FormatDeathTestOutput(error_message);
586 buffer <<
" Result: threw an exception.\n"
588 << FormatDeathTestOutput(error_message);
591 buffer <<
" Result: illegal return in test statement.\n"
593 << FormatDeathTestOutput(error_message);
597 if (matcher_.Matches(error_message)) {
600 std::ostringstream stream;
601 matcher_.DescribeTo(&stream);
602 buffer <<
" Result: died but not with expected error.\n"
603 <<
" Expected: " << stream.str() <<
"\n"
605 << FormatDeathTestOutput(error_message);
608 buffer <<
" Result: died but not with expected exit code:\n"
609 <<
" " << ExitSummary(status()) <<
"\n"
611 << FormatDeathTestOutput(error_message);
617 <<
"DeathTest::Passed somehow called before conclusion of test";
620 DeathTest::set_last_death_test_message(buffer.GetString());
653class WindowsDeathTest :
public DeathTestImpl {
655 WindowsDeathTest(
const char* a_statement, Matcher<const std::string&> matcher,
656 const char* file,
int line)
657 : DeathTestImpl(a_statement, std::move(matcher)),
663 virtual TestRole AssumeRole();
667 const char*
const file_;
671 AutoHandle write_handle_;
673 AutoHandle child_handle_;
678 AutoHandle event_handle_;
684int WindowsDeathTest::Wait() {
685 if (!spawned())
return 0;
689 const HANDLE wait_handles[2] = {child_handle_.Get(), event_handle_.Get()};
690 switch (::WaitForMultipleObjects(2, wait_handles,
694 case WAIT_OBJECT_0 + 1:
697 GTEST_DEATH_TEST_CHECK_(
false);
702 write_handle_.Reset();
703 event_handle_.Reset();
705 ReadAndInterpretStatusByte();
711 GTEST_DEATH_TEST_CHECK_(WAIT_OBJECT_0 ==
712 ::WaitForSingleObject(child_handle_.Get(), INFINITE));
714 GTEST_DEATH_TEST_CHECK_(
715 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
716 child_handle_.Reset();
717 set_status(
static_cast<int>(status_code));
726DeathTest::TestRole WindowsDeathTest::AssumeRole() {
727 const UnitTestImpl*
const impl = GetUnitTestImpl();
728 const InternalRunDeathTestFlag*
const flag =
729 impl->internal_run_death_test_flag();
730 const TestInfo*
const info = impl->current_test_info();
731 const int death_test_index = info->result()->death_test_count();
733 if (flag !=
nullptr) {
736 set_write_fd(flag->write_fd());
742 SECURITY_ATTRIBUTES handles_are_inheritable = {
sizeof(SECURITY_ATTRIBUTES),
744 HANDLE read_handle, write_handle;
745 GTEST_DEATH_TEST_CHECK_(::CreatePipe(&read_handle, &write_handle,
746 &handles_are_inheritable,
750 ::_open_osfhandle(
reinterpret_cast<intptr_t
>(read_handle), O_RDONLY));
751 write_handle_.Reset(write_handle);
752 event_handle_.Reset(::CreateEvent(
753 &handles_are_inheritable,
757 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() !=
nullptr);
758 const std::string filter_flag = std::string(
"--") + GTEST_FLAG_PREFIX_ +
759 "filter=" + info->test_suite_name() +
"." +
761 const std::string internal_flag =
762 std::string(
"--") + GTEST_FLAG_PREFIX_ +
763 "internal_run_death_test=" + file_ +
"|" + StreamableToString(line_) +
764 "|" + StreamableToString(death_test_index) +
"|" +
765 StreamableToString(
static_cast<unsigned int>(::GetCurrentProcessId())) +
769 "|" + StreamableToString(
reinterpret_cast<size_t>(write_handle)) +
"|" +
770 StreamableToString(
reinterpret_cast<size_t>(event_handle_.Get()));
772 char executable_path[_MAX_PATH + 1];
773 GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(
nullptr,
777 std::string command_line = std::string(::GetCommandLineA()) +
" " +
778 filter_flag +
" \"" + internal_flag +
"\"";
780 DeathTest::set_last_death_test_message(
"");
787 STARTUPINFOA startup_info;
788 memset(&startup_info, 0,
sizeof(STARTUPINFO));
789 startup_info.dwFlags = STARTF_USESTDHANDLES;
790 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
791 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
792 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
794 PROCESS_INFORMATION process_info;
795 GTEST_DEATH_TEST_CHECK_(
797 executable_path,
const_cast<char*
>(command_line.c_str()),
803 UnitTest::GetInstance()->original_working_dir(), &startup_info,
804 &process_info) != FALSE);
805 child_handle_.Reset(process_info.hProcess);
806 ::CloseHandle(process_info.hThread);
811#elif GTEST_OS_FUCHSIA
813class FuchsiaDeathTest :
public DeathTestImpl {
815 FuchsiaDeathTest(
const char* a_statement, Matcher<const std::string&> matcher,
816 const char* file,
int line)
817 : DeathTestImpl(a_statement, std::move(matcher)),
823 TestRole AssumeRole()
override;
824 std::string GetErrorLogs()
override;
828 const char*
const file_;
832 std::string captured_stderr_;
834 zx::process child_process_;
835 zx::channel exception_channel_;
836 zx::socket stderr_socket_;
842 Arguments() { args_.push_back(
nullptr); }
845 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
850 void AddArgument(
const char* argument) {
851 args_.insert(args_.end() - 1, posix::StrDup(argument));
854 template <
typename Str>
855 void AddArguments(const ::std::vector<Str>& arguments) {
856 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
857 i != arguments.end(); ++i) {
858 args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
861 char*
const* Argv() {
return &args_[0]; }
863 int size() {
return static_cast<int>(args_.size()) - 1; }
866 std::vector<char*> args_;
872int FuchsiaDeathTest::Wait() {
873 const int kProcessKey = 0;
874 const int kSocketKey = 1;
875 const int kExceptionKey = 2;
877 if (!spawned())
return 0;
880 zx_status_t status_zx;
882 status_zx = zx::port::create(0, &port);
883 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
887 child_process_.wait_async(port, kProcessKey, ZX_PROCESS_TERMINATED, 0);
888 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
891 status_zx = stderr_socket_.wait_async(
892 port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0);
893 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
896 status_zx = exception_channel_.wait_async(port, kExceptionKey,
897 ZX_CHANNEL_READABLE, 0);
898 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
900 bool process_terminated =
false;
901 bool socket_closed =
false;
903 zx_port_packet_t packet = {};
904 status_zx = port.wait(zx::time::infinite(), &packet);
905 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
907 if (packet.key == kExceptionKey) {
911 status_zx = child_process_.kill();
912 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
913 }
else if (packet.key == kProcessKey) {
915 GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));
916 GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED);
917 process_terminated =
true;
918 }
else if (packet.key == kSocketKey) {
919 GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));
920 if (packet.signal.observed & ZX_SOCKET_READABLE) {
922 constexpr size_t kBufferSize = 1024;
924 size_t old_length = captured_stderr_.length();
925 size_t bytes_read = 0;
926 captured_stderr_.resize(old_length + kBufferSize);
928 stderr_socket_.read(0, &captured_stderr_.front() + old_length,
929 kBufferSize, &bytes_read);
930 captured_stderr_.resize(old_length + bytes_read);
931 }
while (status_zx == ZX_OK);
932 if (status_zx == ZX_ERR_PEER_CLOSED) {
933 socket_closed =
true;
935 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_ERR_SHOULD_WAIT);
936 status_zx = stderr_socket_.wait_async(
937 port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0);
938 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
941 GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_SOCKET_PEER_CLOSED);
942 socket_closed =
true;
945 }
while (!process_terminated && !socket_closed);
947 ReadAndInterpretStatusByte();
949 zx_info_process_t buffer;
950 status_zx = child_process_.get_info(ZX_INFO_PROCESS, &buffer,
sizeof(buffer),
952 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
954 GTEST_DEATH_TEST_CHECK_(buffer.flags & ZX_INFO_PROCESS_FLAG_EXITED);
955 set_status(
static_cast<int>(buffer.return_code));
964DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
965 const UnitTestImpl*
const impl = GetUnitTestImpl();
966 const InternalRunDeathTestFlag*
const flag =
967 impl->internal_run_death_test_flag();
968 const TestInfo*
const info = impl->current_test_info();
969 const int death_test_index = info->result()->death_test_count();
971 if (flag !=
nullptr) {
974 set_write_fd(kFuchsiaReadPipeFd);
982 const std::string filter_flag = std::string(
"--") + GTEST_FLAG_PREFIX_ +
983 "filter=" + info->test_suite_name() +
"." +
985 const std::string internal_flag = std::string(
"--") + GTEST_FLAG_PREFIX_ +
986 kInternalRunDeathTestFlag +
"=" + file_ +
987 "|" + StreamableToString(line_) +
"|" +
988 StreamableToString(death_test_index);
990 args.AddArguments(GetInjectableArgvs());
991 args.AddArgument(filter_flag.c_str());
992 args.AddArgument(internal_flag.c_str());
996 zx_handle_t child_pipe_handle;
998 status = fdio_pipe_half(&child_pipe_fd, &child_pipe_handle);
999 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
1000 set_read_fd(child_pipe_fd);
1003 fdio_spawn_action_t spawn_actions[2] = {};
1004 fdio_spawn_action_t* add_handle_action = &spawn_actions[0];
1005 add_handle_action->action = FDIO_SPAWN_ACTION_ADD_HANDLE;
1006 add_handle_action->h.id = PA_HND(PA_FD, kFuchsiaReadPipeFd);
1007 add_handle_action->h.handle = child_pipe_handle;
1010 zx::socket stderr_producer_socket;
1011 status = zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);
1012 GTEST_DEATH_TEST_CHECK_(status >= 0);
1013 int stderr_producer_fd = -1;
1015 fdio_fd_create(stderr_producer_socket.release(), &stderr_producer_fd);
1016 GTEST_DEATH_TEST_CHECK_(status >= 0);
1019 GTEST_DEATH_TEST_CHECK_(fcntl(stderr_producer_fd, F_SETFL, 0) == 0);
1021 fdio_spawn_action_t* add_stderr_action = &spawn_actions[1];
1022 add_stderr_action->action = FDIO_SPAWN_ACTION_CLONE_FD;
1023 add_stderr_action->fd.local_fd = stderr_producer_fd;
1024 add_stderr_action->fd.target_fd = STDERR_FILENO;
1027 zx_handle_t child_job = ZX_HANDLE_INVALID;
1028 status = zx_job_create(zx_job_default(), 0, &child_job);
1029 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
1030 zx_policy_basic_t policy;
1031 policy.condition = ZX_POL_NEW_ANY;
1032 policy.policy = ZX_POL_ACTION_ALLOW;
1033 status = zx_job_set_policy(child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC,
1035 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
1039 status = zx_task_create_exception_channel(
1040 child_job, 0, exception_channel_.reset_and_get_address());
1041 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
1044 status = fdio_spawn_etc(child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0],
1045 args.Argv(),
nullptr, 2, spawn_actions,
1046 child_process_.reset_and_get_address(),
nullptr);
1047 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
1050 return OVERSEE_TEST;
1053std::string FuchsiaDeathTest::GetErrorLogs() {
return captured_stderr_; }
1060class ForkingDeathTest :
public DeathTestImpl {
1062 ForkingDeathTest(
const char* statement, Matcher<const std::string&> matcher);
1065 int Wait()
override;
1068 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
1076ForkingDeathTest::ForkingDeathTest(
const char* a_statement,
1077 Matcher<const std::string&> matcher)
1078 : DeathTestImpl(a_statement, std::move(matcher)), child_pid_(-1) {}
1083int ForkingDeathTest::Wait() {
1084 if (!spawned())
return 0;
1086 ReadAndInterpretStatusByte();
1089 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
1090 set_status(status_value);
1091 return status_value;
1096class NoExecDeathTest :
public ForkingDeathTest {
1098 NoExecDeathTest(
const char* a_statement, Matcher<const std::string&> matcher)
1099 : ForkingDeathTest(a_statement, std::move(matcher)) {}
1100 TestRole AssumeRole()
override;
1105DeathTest::TestRole NoExecDeathTest::AssumeRole() {
1107 if (thread_count != 1) {
1108 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
1112 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
1114 DeathTest::set_last_death_test_message(
"");
1125 const pid_t child_pid = fork();
1126 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
1127 set_child_pid(child_pid);
1128 if (child_pid == 0) {
1129 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
1130 set_write_fd(pipe_fd[1]);
1137 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
1138 g_in_fast_death_test_child =
true;
1139 return EXECUTE_TEST;
1141 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
1142 set_read_fd(pipe_fd[0]);
1144 return OVERSEE_TEST;
1151class ExecDeathTest :
public ForkingDeathTest {
1153 ExecDeathTest(
const char* a_statement, Matcher<const std::string&> matcher,
1154 const char* file,
int line)
1155 : ForkingDeathTest(a_statement, std::move(matcher)),
1158 TestRole AssumeRole()
override;
1161 static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {
1162 ::std::vector<std::string> args = GetInjectableArgvs();
1163#if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
1164 ::std::vector<std::string> extra_args =
1165 GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
1166 args.insert(args.end(), extra_args.begin(), extra_args.end());
1171 const char*
const file_;
1179 Arguments() { args_.push_back(
nullptr); }
1182 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
1187 void AddArgument(
const char* argument) {
1188 args_.insert(args_.end() - 1, posix::StrDup(argument));
1191 template <
typename Str>
1192 void AddArguments(const ::std::vector<Str>& arguments) {
1193 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
1194 i != arguments.end(); ++i) {
1195 args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
1198 char*
const* Argv() {
return &args_[0]; }
1201 std::vector<char*> args_;
1206struct ExecDeathTestArgs {
1212extern "C" char** environ;
1217static int ExecDeathTestChildMain(
void* child_arg) {
1218 ExecDeathTestArgs*
const args =
static_cast<ExecDeathTestArgs*
>(child_arg);
1219 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
1224 const char*
const original_dir =
1225 UnitTest::GetInstance()->original_working_dir();
1227 if (chdir(original_dir) != 0) {
1228 DeathTestAbort(std::string(
"chdir(\"") + original_dir +
1229 "\") failed: " + GetLastErrnoDescription());
1230 return EXIT_FAILURE;
1238 execv(args->argv[0], args->argv);
1239 DeathTestAbort(std::string(
"execv(") + args->argv[0] +
", ...) in " +
1240 original_dir +
" failed: " + GetLastErrnoDescription());
1241 return EXIT_FAILURE;
1255static void StackLowerThanAddress(
const void* ptr,
1256 bool* result) GTEST_NO_INLINE_;
1263GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
1264GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
1265static void StackLowerThanAddress(
const void* ptr,
bool* result) {
1267 *result = std::less<const void*>()(&dummy, ptr);
1271GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
1272GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
1273static bool StackGrowsDown() {
1276 StackLowerThanAddress(&dummy, &result);
1288static pid_t ExecDeathTestSpawnChild(
char*
const* argv,
int close_fd) {
1289 ExecDeathTestArgs args = {argv, close_fd};
1290 pid_t child_pid = -1;
1295 const int cwd_fd = open(
".", O_RDONLY);
1296 GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
1297 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
1301 const char*
const original_dir =
1302 UnitTest::GetInstance()->original_working_dir();
1304 if (chdir(original_dir) != 0) {
1305 DeathTestAbort(std::string(
"chdir(\"") + original_dir +
1306 "\") failed: " + GetLastErrnoDescription());
1307 return EXIT_FAILURE;
1312 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
1313 GTEST_DEATH_TEST_CHECK_SYSCALL_(
1314 fcntl(close_fd, F_SETFD, fd_flags | FD_CLOEXEC));
1315 struct inheritance inherit = {0};
1317 child_pid = spawn(args.argv[0], 0,
nullptr, &inherit, args.argv, environ);
1319 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
1320 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
1327 struct sigaction saved_sigprof_action;
1328 struct sigaction ignore_sigprof_action;
1329 memset(&ignore_sigprof_action, 0,
sizeof(ignore_sigprof_action));
1330 sigemptyset(&ignore_sigprof_action.sa_mask);
1331 ignore_sigprof_action.sa_handler = SIG_IGN;
1332 GTEST_DEATH_TEST_CHECK_SYSCALL_(
1333 sigaction(SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
1337 const bool use_fork = GTEST_FLAG_GET(death_test_use_fork);
1340 static const bool stack_grows_down = StackGrowsDown();
1341 const auto stack_size =
static_cast<size_t>(getpagesize() * 2);
1343 void*
const stack = mmap(
nullptr, stack_size, PROT_READ | PROT_WRITE,
1344 MAP_ANON | MAP_PRIVATE, -1, 0);
1345 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
1353 const size_t kMaxStackAlignment = 64;
1354 void*
const stack_top =
1355 static_cast<char*
>(stack) +
1356 (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
1357 GTEST_DEATH_TEST_CHECK_(
1358 static_cast<size_t>(stack_size) > kMaxStackAlignment &&
1359 reinterpret_cast<uintptr_t
>(stack_top) % kMaxStackAlignment == 0);
1361 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
1363 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
1366 const bool use_fork =
true;
1369 if (use_fork && (child_pid = fork()) == 0) {
1370 ExecDeathTestChildMain(&args);
1375 GTEST_DEATH_TEST_CHECK_SYSCALL_(
1376 sigaction(SIGPROF, &saved_sigprof_action,
nullptr));
1379 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
1387DeathTest::TestRole ExecDeathTest::AssumeRole() {
1388 const UnitTestImpl*
const impl = GetUnitTestImpl();
1389 const InternalRunDeathTestFlag*
const flag =
1390 impl->internal_run_death_test_flag();
1391 const TestInfo*
const info = impl->current_test_info();
1392 const int death_test_index = info->result()->death_test_count();
1394 if (flag !=
nullptr) {
1395 set_write_fd(flag->write_fd());
1396 return EXECUTE_TEST;
1400 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
1403 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
1405 const std::string filter_flag = std::string(
"--") + GTEST_FLAG_PREFIX_ +
1406 "filter=" + info->test_suite_name() +
"." +
1408 const std::string internal_flag = std::string(
"--") + GTEST_FLAG_PREFIX_ +
1409 "internal_run_death_test=" + file_ +
"|" +
1410 StreamableToString(line_) +
"|" +
1411 StreamableToString(death_test_index) +
"|" +
1412 StreamableToString(pipe_fd[1]);
1414 args.AddArguments(GetArgvsForDeathTestChildProcess());
1415 args.AddArgument(filter_flag.c_str());
1416 args.AddArgument(internal_flag.c_str());
1418 DeathTest::set_last_death_test_message(
"");
1425 const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
1426 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
1427 set_child_pid(child_pid);
1428 set_read_fd(pipe_fd[0]);
1430 return OVERSEE_TEST;
1440bool DefaultDeathTestFactory::Create(
const char* statement,
1441 Matcher<const std::string&> matcher,
1442 const char* file,
int line,
1444 UnitTestImpl*
const impl = GetUnitTestImpl();
1445 const InternalRunDeathTestFlag*
const flag =
1446 impl->internal_run_death_test_flag();
1447 const int death_test_index =
1448 impl->current_test_info()->increment_death_test_count();
1450 if (flag !=
nullptr) {
1451 if (death_test_index > flag->index()) {
1452 DeathTest::set_last_death_test_message(
1453 "Death test count (" + StreamableToString(death_test_index) +
1454 ") somehow exceeded expected maximum (" +
1455 StreamableToString(flag->index()) +
")");
1459 if (!(flag->file() == file && flag->line() == line &&
1460 flag->index() == death_test_index)) {
1468 if (GTEST_FLAG_GET(death_test_style) ==
"threadsafe" ||
1469 GTEST_FLAG_GET(death_test_style) ==
"fast") {
1470 *test =
new WindowsDeathTest(statement, std::move(matcher), file, line);
1473#elif GTEST_OS_FUCHSIA
1475 if (GTEST_FLAG_GET(death_test_style) ==
"threadsafe" ||
1476 GTEST_FLAG_GET(death_test_style) ==
"fast") {
1477 *test =
new FuchsiaDeathTest(statement, std::move(matcher), file, line);
1482 if (GTEST_FLAG_GET(death_test_style) ==
"threadsafe") {
1483 *test =
new ExecDeathTest(statement, std::move(matcher), file, line);
1484 }
else if (GTEST_FLAG_GET(death_test_style) ==
"fast") {
1485 *test =
new NoExecDeathTest(statement, std::move(matcher));
1491 DeathTest::set_last_death_test_message(
"Unknown death test style \"" +
1492 GTEST_FLAG_GET(death_test_style) +
1504static int GetStatusFileDescriptor(
unsigned int parent_process_id,
1505 size_t write_handle_as_size_t,
1506 size_t event_handle_as_size_t) {
1507 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
1509 parent_process_id));
1510 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
1511 DeathTestAbort(
"Unable to open parent process " +
1512 StreamableToString(parent_process_id));
1515 GTEST_CHECK_(
sizeof(HANDLE) <=
sizeof(
size_t));
1517 const HANDLE write_handle =
reinterpret_cast<HANDLE
>(write_handle_as_size_t);
1518 HANDLE dup_write_handle;
1523 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
1524 ::GetCurrentProcess(), &dup_write_handle,
1528 DUPLICATE_SAME_ACCESS)) {
1529 DeathTestAbort(
"Unable to duplicate the pipe handle " +
1530 StreamableToString(write_handle_as_size_t) +
1531 " from the parent process " +
1532 StreamableToString(parent_process_id));
1535 const HANDLE event_handle =
reinterpret_cast<HANDLE
>(event_handle_as_size_t);
1536 HANDLE dup_event_handle;
1538 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
1539 ::GetCurrentProcess(), &dup_event_handle, 0x0, FALSE,
1540 DUPLICATE_SAME_ACCESS)) {
1541 DeathTestAbort(
"Unable to duplicate the event handle " +
1542 StreamableToString(event_handle_as_size_t) +
1543 " from the parent process " +
1544 StreamableToString(parent_process_id));
1547 const int write_fd =
1548 ::_open_osfhandle(
reinterpret_cast<intptr_t
>(dup_write_handle), O_APPEND);
1549 if (write_fd == -1) {
1550 DeathTestAbort(
"Unable to convert pipe handle " +
1551 StreamableToString(write_handle_as_size_t) +
1552 " to a file descriptor");
1557 ::SetEvent(dup_event_handle);
1566InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
1567 if (GTEST_FLAG_GET(internal_run_death_test) ==
"")
return nullptr;
1573 ::std::vector< ::std::string> fields;
1574 SplitString(GTEST_FLAG_GET(internal_run_death_test),
'|', &fields);
1579 unsigned int parent_process_id = 0;
1580 size_t write_handle_as_size_t = 0;
1581 size_t event_handle_as_size_t = 0;
1583 if (fields.size() != 6 || !ParseNaturalNumber(fields[1], &line) ||
1584 !ParseNaturalNumber(fields[2], &index) ||
1585 !ParseNaturalNumber(fields[3], &parent_process_id) ||
1586 !ParseNaturalNumber(fields[4], &write_handle_as_size_t) ||
1587 !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
1588 DeathTestAbort(
"Bad --gtest_internal_run_death_test flag: " +
1589 GTEST_FLAG_GET(internal_run_death_test));
1591 write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t,
1592 event_handle_as_size_t);
1594#elif GTEST_OS_FUCHSIA
1596 if (fields.size() != 3 || !ParseNaturalNumber(fields[1], &line) ||
1597 !ParseNaturalNumber(fields[2], &index)) {
1598 DeathTestAbort(
"Bad --gtest_internal_run_death_test flag: " +
1599 GTEST_FLAG_GET(internal_run_death_test));
1604 if (fields.size() != 4 || !ParseNaturalNumber(fields[1], &line) ||
1605 !ParseNaturalNumber(fields[2], &index) ||
1606 !ParseNaturalNumber(fields[3], &write_fd)) {
1607 DeathTestAbort(
"Bad --gtest_internal_run_death_test flag: " +
1608 GTEST_FLAG_GET(internal_run_death_test));
1613 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
GTEST_DEFINE_bool_(death_test_use_fork, testing::internal::BoolFromGTestEnv("death_test_use_fork", false), "Instructs to use fork()/_exit() instead of clone() in death tests. " "Ignored and always uses fork() on POSIX systems where clone() is not " "implemented. Useful when running under valgrind or similar tools if " "those do not support clone(). Valgrind 3.3.1 will just fail if " "it sees an unsupported combination of clone() flags. " "It is not recommended to use this flag w/o valgrind though it will " "work in 99% of the cases. Once valgrind is fixed, this flag will " "most likely be removed.")
GTEST_DEFINE_string_(death_test_style, testing::internal::StringFromGTestEnv("death_test_style", testing::kDefaultDeathTestStyle), "Indicates how to run a death test in a forked child process: " "\"threadsafe\" (child process re-executes the test binary " "from the beginning, running only the specific death test) or " "\"fast\" (child process runs the death test immediately " "after forking).")
const char * StringFromGTestEnv(const char *flag, const char *default_value)
bool BoolFromGTestEnv(const char *flag, bool default_value)
void SplitString(const ::std::string &str, char delimiter, ::std::vector< ::std::string > *dest)
static const char kDefaultDeathTestStyle[]