40 #if GTEST_HAS_DEATH_TEST
43 # include <crt_externs.h>
44 # endif // GTEST_OS_MAC
52 # endif // GTEST_OS_LINUX
59 # include <sys/mman.h>
60 # include <sys/wait.h>
61 # endif // GTEST_OS_WINDOWS
65 # endif // GTEST_OS_QNX
68 # include <lib/fdio/fd.h>
69 # include <lib/fdio/io.h>
70 # include <lib/fdio/spawn.h>
71 # include <lib/zx/channel.h>
72 # include <lib/zx/port.h>
73 # include <lib/zx/process.h>
74 # include <lib/zx/socket.h>
75 # include <zircon/processargs.h>
76 # include <zircon/syscalls.h>
77 # include <zircon/syscalls/policy.h>
78 # include <zircon/syscalls/port.h>
79 # endif // GTEST_OS_FUCHSIA
81 #endif // GTEST_HAS_DEATH_TEST
101 "Indicates how to run a death test in a forked child process: "
102 "\"threadsafe\" (child process re-executes the test binary "
103 "from the beginning, running only the specific death test) or "
104 "\"fast\" (child process runs the death test immediately "
110 "Instructs to use fork()/_exit() instead of clone() in death tests. "
111 "Ignored and always uses fork() on POSIX systems where clone() is not "
112 "implemented. Useful when running under valgrind or similar tools if "
113 "those do not support clone(). Valgrind 3.3.1 will just fail if "
114 "it sees an unsupported combination of clone() flags. "
115 "It is not recommended to use this flag w/o valgrind though it will "
116 "work in 99% of the cases. Once valgrind is fixed, this flag will "
117 "most likely be removed.");
121 internal_run_death_test,
"",
122 "Indicates the file, line number, temporal index of "
123 "the single death test to run, and a file descriptor to "
124 "which a success code may be sent, all separated by "
125 "the '|' characters. This flag is specified if and only if the "
126 "current process is a sub-process launched for running a thread-safe "
127 "death test. FOR INTERNAL USE ONLY.");
130 #if GTEST_HAS_DEATH_TEST
136 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
137 static bool g_in_fast_death_test_child =
false;
145 bool InDeathTestChild() {
146 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
150 return !
GTEST_FLAG(internal_run_death_test).empty();
154 if (
GTEST_FLAG(death_test_style) ==
"threadsafe")
155 return !
GTEST_FLAG(internal_run_death_test).empty();
157 return g_in_fast_death_test_child;
164 ExitedWithCode::ExitedWithCode(
int exit_code) : exit_code_(exit_code) {
168 bool ExitedWithCode::operator()(
int exit_status)
const {
169 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
171 return exit_status == exit_code_;
175 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
177 # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
180 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
182 KilledBySignal::KilledBySignal(
int signum) : signum_(signum) {
186 bool KilledBySignal::operator()(
int exit_status)
const {
187 # if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
190 if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
194 # endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
195 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
197 # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
205 static std::string ExitSummary(
int exit_code) {
208 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
210 m <<
"Exited with exit status " << exit_code;
214 if (WIFEXITED(exit_code)) {
215 m <<
"Exited with exit status " << WEXITSTATUS(exit_code);
216 }
else if (WIFSIGNALED(exit_code)) {
217 m <<
"Terminated by signal " << WTERMSIG(exit_code);
220 if (WCOREDUMP(exit_code)) {
221 m <<
" (core dumped)";
224 # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
226 return m.GetString();
231 bool ExitedUnsuccessfully(
int exit_status) {
232 return !ExitedWithCode(0)(exit_status);
235 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
240 static std::string DeathTestThreadWarning(
size_t thread_count) {
242 msg <<
"Death tests use fork(), which is unsafe particularly"
243 <<
" in a threaded context. For this test, " <<
GTEST_NAME_ <<
" ";
244 if (thread_count == 0) {
245 msg <<
"couldn't detect the number of threads.";
247 msg <<
"detected " << thread_count <<
" threads.";
250 "https://github.com/google/googletest/blob/master/googletest/docs/"
251 "advanced.md#death-tests-and-threads"
252 <<
" for more explanation and suggested solutions, especially if"
253 <<
" this is the last message you see before your test times out.";
254 return msg.GetString();
256 # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
259 static const char kDeathTestLived =
'L';
260 static const char kDeathTestReturned =
'R';
261 static const char kDeathTestThrew =
'T';
262 static const char kDeathTestInternalError =
'I';
267 static const int kFuchsiaReadPipeFd = 3;
278 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
285 static void DeathTestAbort(
const std::string& message) {
289 const InternalRunDeathTestFlag*
const flag =
290 GetUnitTestImpl()->internal_run_death_test_flag();
291 if (flag !=
nullptr) {
293 fputc(kDeathTestInternalError, parent);
294 fprintf(parent,
"%s", message.c_str());
298 fprintf(stderr,
"%s", message.c_str());
306 # define GTEST_DEATH_TEST_CHECK_(expression) \
308 if (!::testing::internal::IsTrue(expression)) { \
310 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
311 + ::testing::internal::StreamableToString(__LINE__) + ": " \
314 } while (::testing::internal::AlwaysFalse())
323 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
327 gtest_retval = (expression); \
328 } while (gtest_retval == -1 && errno == EINTR); \
329 if (gtest_retval == -1) { \
331 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
332 + ::testing::internal::StreamableToString(__LINE__) + ": " \
333 + #expression + " != -1"); \
335 } while (::testing::internal::AlwaysFalse())
338 std::string GetLastErrnoDescription() {
346 static void FailFromInternalError(
int fd) {
352 while ((num_read =
posix::Read(fd, buffer, 255)) > 0) {
353 buffer[num_read] =
'\0';
356 }
while (num_read == -1 && errno == EINTR);
361 const int last_error = errno;
362 GTEST_LOG_(FATAL) <<
"Error while reading death test internal: "
363 << GetLastErrnoDescription() <<
" [" << last_error <<
"]";
369 DeathTest::DeathTest() {
370 TestInfo*
const info = GetUnitTestImpl()->current_test_info();
371 if (info ==
nullptr) {
372 DeathTestAbort(
"Cannot run a death test outside of a TEST or "
379 bool DeathTest::Create(
const char* statement,
380 Matcher<const std::string&> matcher,
const char* file,
381 int line, DeathTest** test) {
382 return GetUnitTestImpl()->death_test_factory()->Create(
383 statement, std::move(matcher), file, line, test);
386 const char* DeathTest::LastMessage() {
387 return last_death_test_message_.c_str();
390 void DeathTest::set_last_death_test_message(
const std::string& message) {
391 last_death_test_message_ = message;
394 std::string DeathTest::last_death_test_message_;
397 class DeathTestImpl :
public DeathTest {
399 DeathTestImpl(
const char* a_statement, Matcher<const std::string&> matcher)
400 : statement_(a_statement),
401 matcher_(std::move(matcher)),
404 outcome_(IN_PROGRESS),
409 ~DeathTestImpl()
override { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
411 void Abort(AbortReason reason)
override;
412 bool Passed(
bool status_ok)
override;
414 const char* statement()
const {
return statement_; }
415 bool spawned()
const {
return spawned_; }
416 void set_spawned(
bool is_spawned) { spawned_ = is_spawned; }
417 int status()
const {
return status_; }
418 void set_status(
int a_status) { status_ = a_status; }
419 DeathTestOutcome outcome()
const {
return outcome_; }
420 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
421 int read_fd()
const {
return read_fd_; }
422 void set_read_fd(
int fd) { read_fd_ = fd; }
423 int write_fd()
const {
return write_fd_; }
424 void set_write_fd(
int fd) { write_fd_ = fd; }
430 void ReadAndInterpretStatusByte();
433 virtual std::string GetErrorLogs();
438 const char*
const statement_;
440 Matcher<const std::string&> matcher_;
446 DeathTestOutcome outcome_;
461 void DeathTestImpl::ReadAndInterpretStatusByte() {
471 }
while (bytes_read == -1 && errno == EINTR);
473 if (bytes_read == 0) {
475 }
else if (bytes_read == 1) {
477 case kDeathTestReturned:
478 set_outcome(RETURNED);
480 case kDeathTestThrew:
483 case kDeathTestLived:
486 case kDeathTestInternalError:
487 FailFromInternalError(read_fd());
490 GTEST_LOG_(FATAL) <<
"Death test child process reported "
491 <<
"unexpected status byte ("
492 <<
static_cast<unsigned int>(flag) <<
")";
495 GTEST_LOG_(FATAL) <<
"Read from death test child process failed: "
496 << GetLastErrnoDescription();
498 GTEST_DEATH_TEST_CHECK_SYSCALL_(
posix::Close(read_fd()));
502 std::string DeathTestImpl::GetErrorLogs() {
514 const char status_ch =
515 reason == TEST_DID_NOT_DIE ? kDeathTestLived :
516 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
518 GTEST_DEATH_TEST_CHECK_SYSCALL_(
posix::Write(write_fd(), &status_ch, 1));
533 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
535 for (
size_t at = 0; ; ) {
536 const size_t line_end = output.find(
'\n', at);
538 if (line_end == ::std::string::npos) {
539 ret += output.substr(at);
542 ret += output.substr(at, line_end + 1 - at);
569 bool DeathTestImpl::Passed(
bool status_ok) {
573 const std::string error_message = GetErrorLogs();
575 bool success =
false;
578 buffer <<
"Death test: " << statement() <<
"\n";
581 buffer <<
" Result: failed to die.\n"
582 <<
" Error msg:\n" << FormatDeathTestOutput(error_message);
585 buffer <<
" Result: threw an exception.\n"
586 <<
" Error msg:\n" << FormatDeathTestOutput(error_message);
589 buffer <<
" Result: illegal return in test statement.\n"
590 <<
" Error msg:\n" << FormatDeathTestOutput(error_message);
594 if (matcher_.Matches(error_message)) {
597 std::ostringstream stream;
598 matcher_.DescribeTo(&stream);
599 buffer <<
" Result: died but not with expected error.\n"
600 <<
" Expected: " << stream.str() <<
"\n"
602 << FormatDeathTestOutput(error_message);
605 buffer <<
" Result: died but not with expected exit code:\n"
606 <<
" " << ExitSummary(status()) <<
"\n"
607 <<
"Actual msg:\n" << FormatDeathTestOutput(error_message);
613 <<
"DeathTest::Passed somehow called before conclusion of test";
616 DeathTest::set_last_death_test_message(buffer.GetString());
620 # if GTEST_OS_WINDOWS
649 class WindowsDeathTest :
public DeathTestImpl {
651 WindowsDeathTest(
const char* a_statement, Matcher<const std::string&> matcher,
652 const char* file,
int line)
653 : DeathTestImpl(a_statement, std::move(matcher)),
659 virtual TestRole AssumeRole();
663 const char*
const file_;
667 AutoHandle write_handle_;
669 AutoHandle child_handle_;
674 AutoHandle event_handle_;
680 int WindowsDeathTest::Wait() {
686 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
687 switch (::WaitForMultipleObjects(2,
692 case WAIT_OBJECT_0 + 1:
695 GTEST_DEATH_TEST_CHECK_(
false);
700 write_handle_.Reset();
701 event_handle_.Reset();
703 ReadAndInterpretStatusByte();
709 GTEST_DEATH_TEST_CHECK_(
710 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
713 GTEST_DEATH_TEST_CHECK_(
714 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
715 child_handle_.Reset();
716 set_status(static_cast<int>(status_code));
725 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
726 const UnitTestImpl*
const impl = GetUnitTestImpl();
727 const InternalRunDeathTestFlag*
const flag =
728 impl->internal_run_death_test_flag();
729 const TestInfo*
const info = impl->current_test_info();
730 const int death_test_index = info->result()->death_test_count();
732 if (flag !=
nullptr) {
735 set_write_fd(flag->write_fd());
741 SECURITY_ATTRIBUTES handles_are_inheritable = {
sizeof(SECURITY_ATTRIBUTES),
743 HANDLE read_handle, write_handle;
744 GTEST_DEATH_TEST_CHECK_(
745 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
748 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
750 write_handle_.Reset(write_handle);
751 event_handle_.Reset(::CreateEvent(
752 &handles_are_inheritable,
756 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() !=
nullptr);
758 kFilterFlag +
"=" + info->test_suite_name() +
760 const std::string internal_flag =
771 char executable_path[_MAX_PATH + 1];
772 GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(
nullptr,
776 std::string command_line =
777 std::string(::GetCommandLineA()) +
" " + filter_flag +
" \"" +
778 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
813 class 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) {
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();
862 char*
const* Argv() {
867 return args_.size() - 1;
871 std::vector<char*> args_;
877 int FuchsiaDeathTest::Wait() {
878 const int kProcessKey = 0;
879 const int kSocketKey = 1;
880 const int kExceptionKey = 2;
886 zx_status_t status_zx;
888 status_zx = zx::port::create(0, &port);
889 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
892 status_zx = child_process_.wait_async(
893 port, kProcessKey, ZX_PROCESS_TERMINATED, ZX_WAIT_ASYNC_ONCE);
894 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
897 status_zx = stderr_socket_.wait_async(
898 port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED,
900 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
903 status_zx = exception_channel_.wait_async(
904 port, kExceptionKey, ZX_CHANNEL_READABLE, ZX_WAIT_ASYNC_ONCE);
905 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
907 bool process_terminated =
false;
908 bool socket_closed =
false;
910 zx_port_packet_t packet = {};
911 status_zx = port.wait(zx::time::infinite(), &packet);
912 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
914 if (packet.key == kExceptionKey) {
918 status_zx = child_process_.kill();
919 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
920 }
else if (packet.key == kProcessKey) {
922 GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));
923 GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED);
924 process_terminated =
true;
925 }
else if (packet.key == kSocketKey) {
926 GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));
927 if (packet.signal.observed & ZX_SOCKET_READABLE) {
929 constexpr
size_t kBufferSize = 1024;
931 size_t old_length = captured_stderr_.length();
932 size_t bytes_read = 0;
933 captured_stderr_.resize(old_length + kBufferSize);
934 status_zx = stderr_socket_.read(
935 0, &captured_stderr_.front() + old_length, kBufferSize,
937 captured_stderr_.resize(old_length + bytes_read);
938 }
while (status_zx == ZX_OK);
939 if (status_zx == ZX_ERR_PEER_CLOSED) {
940 socket_closed =
true;
942 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_ERR_SHOULD_WAIT);
943 status_zx = stderr_socket_.wait_async(
944 port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED,
946 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
949 GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_SOCKET_PEER_CLOSED);
950 socket_closed =
true;
953 }
while (!process_terminated && !socket_closed);
955 ReadAndInterpretStatusByte();
957 zx_info_process_t buffer;
958 status_zx = child_process_.get_info(
959 ZX_INFO_PROCESS, &buffer,
sizeof(buffer),
nullptr,
nullptr);
960 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
962 GTEST_DEATH_TEST_CHECK_(buffer.exited);
963 set_status(buffer.return_code);
972 DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
973 const UnitTestImpl*
const impl = GetUnitTestImpl();
974 const InternalRunDeathTestFlag*
const flag =
975 impl->internal_run_death_test_flag();
976 const TestInfo*
const info = impl->current_test_info();
977 const int death_test_index = info->result()->death_test_count();
979 if (flag !=
nullptr) {
982 set_write_fd(kFuchsiaReadPipeFd);
991 kFilterFlag +
"=" + info->test_suite_name() +
993 const std::string internal_flag =
999 args.AddArguments(GetInjectableArgvs());
1000 args.AddArgument(filter_flag.c_str());
1001 args.AddArgument(internal_flag.c_str());
1005 zx_handle_t child_pipe_handle;
1007 status = fdio_pipe_half(&child_pipe_fd, &child_pipe_handle);
1008 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
1009 set_read_fd(child_pipe_fd);
1012 fdio_spawn_action_t spawn_actions[2] = {};
1013 fdio_spawn_action_t* add_handle_action = &spawn_actions[0];
1014 add_handle_action->action = FDIO_SPAWN_ACTION_ADD_HANDLE;
1015 add_handle_action->h.id = PA_HND(PA_FD, kFuchsiaReadPipeFd);
1016 add_handle_action->h.handle = child_pipe_handle;
1019 zx::socket stderr_producer_socket;
1021 zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);
1022 GTEST_DEATH_TEST_CHECK_(status >= 0);
1023 int stderr_producer_fd = -1;
1025 fdio_fd_create(stderr_producer_socket.release(), &stderr_producer_fd);
1026 GTEST_DEATH_TEST_CHECK_(status >= 0);
1029 GTEST_DEATH_TEST_CHECK_(fcntl(stderr_producer_fd, F_SETFL, 0) == 0);
1031 fdio_spawn_action_t* add_stderr_action = &spawn_actions[1];
1032 add_stderr_action->action = FDIO_SPAWN_ACTION_CLONE_FD;
1033 add_stderr_action->fd.local_fd = stderr_producer_fd;
1034 add_stderr_action->fd.target_fd = STDERR_FILENO;
1037 zx_handle_t child_job = ZX_HANDLE_INVALID;
1038 status = zx_job_create(zx_job_default(), 0, & child_job);
1039 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
1040 zx_policy_basic_t policy;
1041 policy.condition = ZX_POL_NEW_ANY;
1042 policy.policy = ZX_POL_ACTION_ALLOW;
1043 status = zx_job_set_policy(
1044 child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, &policy, 1);
1045 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
1050 zx_task_create_exception_channel(
1051 child_job, 0, exception_channel_.reset_and_get_address());
1052 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
1055 status = fdio_spawn_etc(
1056 child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(),
nullptr,
1057 2, spawn_actions, child_process_.reset_and_get_address(),
nullptr);
1058 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
1061 return OVERSEE_TEST;
1064 std::string FuchsiaDeathTest::GetErrorLogs() {
1065 return captured_stderr_;
1068 #else // We are neither on Windows, nor on Fuchsia.
1073 class ForkingDeathTest :
public DeathTestImpl {
1075 ForkingDeathTest(
const char* statement, Matcher<const std::string&> matcher);
1078 int Wait()
override;
1081 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
1089 ForkingDeathTest::ForkingDeathTest(
const char* a_statement,
1090 Matcher<const std::string&> matcher)
1091 : DeathTestImpl(a_statement, std::move(matcher)), child_pid_(-1) {}
1096 int ForkingDeathTest::Wait() {
1100 ReadAndInterpretStatusByte();
1103 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
1104 set_status(status_value);
1105 return status_value;
1110 class NoExecDeathTest :
public ForkingDeathTest {
1112 NoExecDeathTest(
const char* a_statement, Matcher<const std::string&> matcher)
1113 : ForkingDeathTest(a_statement, std::move(matcher)) {}
1114 TestRole AssumeRole()
override;
1119 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
1121 if (thread_count != 1) {
1122 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
1126 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
1128 DeathTest::set_last_death_test_message(
"");
1139 const pid_t child_pid = fork();
1140 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
1141 set_child_pid(child_pid);
1142 if (child_pid == 0) {
1143 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
1144 set_write_fd(pipe_fd[1]);
1151 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
1152 g_in_fast_death_test_child =
true;
1153 return EXECUTE_TEST;
1155 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
1156 set_read_fd(pipe_fd[0]);
1158 return OVERSEE_TEST;
1165 class ExecDeathTest :
public ForkingDeathTest {
1167 ExecDeathTest(
const char* a_statement, Matcher<const std::string&> matcher,
1168 const char* file,
int line)
1169 : ForkingDeathTest(a_statement, std::move(matcher)),
1172 TestRole AssumeRole()
override;
1175 static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {
1176 ::std::vector<std::string> args = GetInjectableArgvs();
1177 # if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
1178 ::std::vector<std::string> extra_args =
1179 GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
1180 args.insert(args.end(), extra_args.begin(), extra_args.end());
1181 # endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
1185 const char*
const file_;
1193 Arguments() { args_.push_back(
nullptr); }
1196 for (std::vector<char*>::iterator
i = args_.begin();
i != args_.end();
1201 void AddArgument(
const char* argument) {
1205 template <
typename Str>
1206 void AddArguments(const ::std::vector<Str>& arguments) {
1207 for (typename ::std::vector<Str>::const_iterator
i = arguments.begin();
1208 i != arguments.end();
1213 char*
const* Argv() {
1218 std::vector<char*> args_;
1223 struct ExecDeathTestArgs {
1229 inline char** GetEnviron() {
1233 return *_NSGetEnviron();
1238 extern "C" char** environ;
1239 inline char** GetEnviron() {
return environ; }
1240 # endif // GTEST_OS_MAC
1246 static int ExecDeathTestChildMain(
void* child_arg) {
1247 ExecDeathTestArgs*
const args =
static_cast<ExecDeathTestArgs*
>(child_arg);
1248 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
1253 const char*
const original_dir =
1254 UnitTest::GetInstance()->original_working_dir();
1256 if (chdir(original_dir) != 0) {
1257 DeathTestAbort(std::string(
"chdir(\"") + original_dir +
"\") failed: " +
1258 GetLastErrnoDescription());
1259 return EXIT_FAILURE;
1267 execve(args->argv[0], args->argv, GetEnviron());
1268 DeathTestAbort(std::string(
"execve(") + args->argv[0] +
", ...) in " +
1269 original_dir +
" failed: " +
1270 GetLastErrnoDescription());
1271 return EXIT_FAILURE;
1273 # endif // !GTEST_OS_QNX
1275 # if GTEST_HAS_CLONE
1285 static void StackLowerThanAddress(
const void* ptr,
1295 static void StackLowerThanAddress(
const void* ptr,
bool* result) {
1297 *result = (&dummy < ptr);
1303 static bool StackGrowsDown() {
1306 StackLowerThanAddress(&dummy, &result);
1309 # endif // GTEST_HAS_CLONE
1318 static pid_t ExecDeathTestSpawnChild(
char*
const* argv,
int close_fd) {
1319 ExecDeathTestArgs args = { argv, close_fd };
1320 pid_t child_pid = -1;
1325 const int cwd_fd = open(
".", O_RDONLY);
1326 GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
1327 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
1331 const char*
const original_dir =
1332 UnitTest::GetInstance()->original_working_dir();
1334 if (chdir(original_dir) != 0) {
1335 DeathTestAbort(std::string(
"chdir(\"") + original_dir +
"\") failed: " +
1336 GetLastErrnoDescription());
1337 return EXIT_FAILURE;
1342 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
1343 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
1344 fd_flags | FD_CLOEXEC));
1345 struct inheritance inherit = {0};
1348 spawn(args.argv[0], 0,
nullptr, &inherit, args.argv, GetEnviron());
1350 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
1351 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
1353 # else // GTEST_OS_QNX
1358 struct sigaction saved_sigprof_action;
1359 struct sigaction ignore_sigprof_action;
1360 memset(&ignore_sigprof_action, 0,
sizeof(ignore_sigprof_action));
1361 sigemptyset(&ignore_sigprof_action.sa_mask);
1362 ignore_sigprof_action.sa_handler = SIG_IGN;
1363 GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
1364 SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
1365 # endif // GTEST_OS_LINUX
1367 # if GTEST_HAS_CLONE
1368 const bool use_fork =
GTEST_FLAG(death_test_use_fork);
1371 static const bool stack_grows_down = StackGrowsDown();
1372 const auto stack_size =
static_cast<size_t>(getpagesize() * 2);
1374 void*
const stack = mmap(
nullptr, stack_size, PROT_READ | PROT_WRITE,
1375 MAP_ANON | MAP_PRIVATE, -1, 0);
1376 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
1384 const size_t kMaxStackAlignment = 64;
1385 void*
const stack_top =
1386 static_cast<char*
>(stack) +
1387 (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
1388 GTEST_DEATH_TEST_CHECK_(
1389 static_cast<size_t>(stack_size) > kMaxStackAlignment &&
1390 reinterpret_cast<uintptr_t>(stack_top) % kMaxStackAlignment == 0);
1392 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
1394 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
1397 const bool use_fork =
true;
1398 # endif // GTEST_HAS_CLONE
1400 if (use_fork && (child_pid = fork()) == 0) {
1401 ExecDeathTestChildMain(&args);
1404 # endif // GTEST_OS_QNX
1406 GTEST_DEATH_TEST_CHECK_SYSCALL_(
1407 sigaction(SIGPROF, &saved_sigprof_action,
nullptr));
1408 # endif // GTEST_OS_LINUX
1410 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
1418 DeathTest::TestRole ExecDeathTest::AssumeRole() {
1419 const UnitTestImpl*
const impl = GetUnitTestImpl();
1420 const InternalRunDeathTestFlag*
const flag =
1421 impl->internal_run_death_test_flag();
1422 const TestInfo*
const info = impl->current_test_info();
1423 const int death_test_index = info->result()->death_test_count();
1425 if (flag !=
nullptr) {
1426 set_write_fd(flag->write_fd());
1427 return EXECUTE_TEST;
1431 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
1434 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
1437 kFilterFlag +
"=" + info->test_suite_name() +
1439 const std::string internal_flag =
1445 args.AddArguments(GetArgvsForDeathTestChildProcess());
1446 args.AddArgument(filter_flag.c_str());
1447 args.AddArgument(internal_flag.c_str());
1449 DeathTest::set_last_death_test_message(
"");
1456 const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
1457 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
1458 set_child_pid(child_pid);
1459 set_read_fd(pipe_fd[0]);
1461 return OVERSEE_TEST;
1464 # endif // !GTEST_OS_WINDOWS
1471 bool DefaultDeathTestFactory::Create(
const char* statement,
1472 Matcher<const std::string&> matcher,
1473 const char* file,
int line,
1475 UnitTestImpl*
const impl = GetUnitTestImpl();
1476 const InternalRunDeathTestFlag*
const flag =
1477 impl->internal_run_death_test_flag();
1478 const int death_test_index = impl->current_test_info()
1479 ->increment_death_test_count();
1481 if (flag !=
nullptr) {
1482 if (death_test_index > flag->index()) {
1483 DeathTest::set_last_death_test_message(
1485 +
") somehow exceeded expected maximum ("
1490 if (!(flag->file() == file && flag->line() == line &&
1491 flag->index() == death_test_index)) {
1497 # if GTEST_OS_WINDOWS
1499 if (
GTEST_FLAG(death_test_style) ==
"threadsafe" ||
1501 *test =
new WindowsDeathTest(statement, std::move(matcher), file, line);
1504 # elif GTEST_OS_FUCHSIA
1506 if (
GTEST_FLAG(death_test_style) ==
"threadsafe" ||
1508 *test =
new FuchsiaDeathTest(statement, std::move(matcher), file, line);
1513 if (
GTEST_FLAG(death_test_style) ==
"threadsafe") {
1514 *test =
new ExecDeathTest(statement, std::move(matcher), file, line);
1515 }
else if (
GTEST_FLAG(death_test_style) ==
"fast") {
1516 *test =
new NoExecDeathTest(statement, std::move(matcher));
1519 # endif // GTEST_OS_WINDOWS
1522 DeathTest::set_last_death_test_message(
1523 "Unknown death test style \"" +
GTEST_FLAG(death_test_style)
1524 +
"\" encountered");
1531 # if GTEST_OS_WINDOWS
1535 static int GetStatusFileDescriptor(
unsigned int parent_process_id,
1536 size_t write_handle_as_size_t,
1537 size_t event_handle_as_size_t) {
1538 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
1540 parent_process_id));
1541 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
1542 DeathTestAbort(
"Unable to open parent process " +
1548 const HANDLE write_handle =
1549 reinterpret_cast<HANDLE
>(write_handle_as_size_t);
1550 HANDLE dup_write_handle;
1555 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
1556 ::GetCurrentProcess(), &dup_write_handle,
1560 DUPLICATE_SAME_ACCESS)) {
1561 DeathTestAbort(
"Unable to duplicate the pipe handle " +
1563 " from the parent process " +
1567 const HANDLE event_handle =
reinterpret_cast<HANDLE
>(event_handle_as_size_t);
1568 HANDLE dup_event_handle;
1570 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
1571 ::GetCurrentProcess(), &dup_event_handle,
1574 DUPLICATE_SAME_ACCESS)) {
1575 DeathTestAbort(
"Unable to duplicate the event handle " +
1577 " from the parent process " +
1581 const int write_fd =
1582 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
1583 if (write_fd == -1) {
1584 DeathTestAbort(
"Unable to convert pipe handle " +
1586 " to a file descriptor");
1591 ::SetEvent(dup_event_handle);
1595 # endif // GTEST_OS_WINDOWS
1600 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
1601 if (
GTEST_FLAG(internal_run_death_test) ==
"")
return nullptr;
1607 ::std::vector< ::std::string> fields;
1611 # if GTEST_OS_WINDOWS
1613 unsigned int parent_process_id = 0;
1614 size_t write_handle_as_size_t = 0;
1615 size_t event_handle_as_size_t = 0;
1617 if (fields.size() != 6
1618 || !ParseNaturalNumber(fields[1], &line)
1619 || !ParseNaturalNumber(fields[2], &index)
1620 || !ParseNaturalNumber(fields[3], &parent_process_id)
1621 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
1622 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
1623 DeathTestAbort(
"Bad --gtest_internal_run_death_test flag: " +
1626 write_fd = GetStatusFileDescriptor(parent_process_id,
1627 write_handle_as_size_t,
1628 event_handle_as_size_t);
1630 # elif GTEST_OS_FUCHSIA
1632 if (fields.size() != 3
1633 || !ParseNaturalNumber(fields[1], &line)
1634 || !ParseNaturalNumber(fields[2], &index)) {
1635 DeathTestAbort(
"Bad --gtest_internal_run_death_test flag: "
1641 if (fields.size() != 4
1642 || !ParseNaturalNumber(fields[1], &line)
1643 || !ParseNaturalNumber(fields[2], &index)
1644 || !ParseNaturalNumber(fields[3], &write_fd)) {
1645 DeathTestAbort(
"Bad --gtest_internal_run_death_test flag: "
1649 # endif // GTEST_OS_WINDOWS
1651 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
1656 #endif // GTEST_HAS_DEATH_TEST
GTEST_API_ std::string GetCapturedStderr()
static const char kDefaultDeathTestStyle[]
const char * StringFromGTestEnv(const char *flag, const char *default_val)
#define GTEST_LOG_(severity)
void SplitString(const ::std::string &str, char delimiter,::std::vector< ::std::string > *dest)
GTEST_API_ size_t GetThreadCount()
const char kInternalRunDeathTestFlag[]
#define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
GTEST_DEFINE_string_(death_test_style, internal::StringFromGTestEnv("death_test_style", 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).")
std::string StreamableToString(const T &streamable)
int Write(int fd, const void *buf, unsigned int count)
#define GTEST_DEFAULT_DEATH_TEST_STYLE
#define GTEST_CHECK_(condition)
int Read(int fd, void *buf, unsigned int count)
bool BoolFromGTestEnv(const char *flag, bool default_val)
GTEST_DEFINE_bool_(death_test_use_fork, 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_API_ void CaptureStderr()
#define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
GTEST_DEFINE_string_(internal_run_death_test,"","Indicates the file, line number, temporal index of ""the single death test to run, and a file descriptor to ""which a success code may be sent, all separated by ""the '|' characters. This flag is specified if and only if the ""current process is a sub-process launched for running a thread-safe ""death test. FOR INTERNAL USE ONLY.")
FILE * FDOpen(int fd, const char *mode)
char * StrDup(const char *src)
const char * StrError(int errnum)
#define GTEST_FLAG_PREFIX_