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>
102 "Indicates how to run a death test in a forked child process: "
103 "\"threadsafe\" (child process re-executes the test binary "
104 "from the beginning, running only the specific death test) or "
105 "\"fast\" (child process runs the death test immediately "
111 "Instructs to use fork()/_exit() instead of clone() in death tests. "
112 "Ignored and always uses fork() on POSIX systems where clone() is not "
113 "implemented. Useful when running under valgrind or similar tools if "
114 "those do not support clone(). Valgrind 3.3.1 will just fail if "
115 "it sees an unsupported combination of clone() flags. "
116 "It is not recommended to use this flag w/o valgrind though it will "
117 "work in 99% of the cases. Once valgrind is fixed, this flag will "
118 "most likely be removed.");
122 internal_run_death_test,
"",
123 "Indicates the file, line number, temporal index of "
124 "the single death test to run, and a file descriptor to "
125 "which a success code may be sent, all separated by "
126 "the '|' characters. This flag is specified if and only if the "
127 "current process is a sub-process launched for running a thread-safe "
128 "death test. FOR INTERNAL USE ONLY.");
131#if GTEST_HAS_DEATH_TEST
137# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
138static bool g_in_fast_death_test_child =
false;
146bool InDeathTestChild() {
147# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
151 return !
GTEST_FLAG(internal_run_death_test).empty();
155 if (
GTEST_FLAG(death_test_style) ==
"threadsafe")
156 return !
GTEST_FLAG(internal_run_death_test).empty();
158 return g_in_fast_death_test_child;
165ExitedWithCode::ExitedWithCode(
int exit_code) : exit_code_(exit_code) {
169bool ExitedWithCode::operator()(
int exit_status)
const {
170# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
172 return exit_status == exit_code_;
176 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
181# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
183KilledBySignal::KilledBySignal(
int signum) : signum_(signum) {
187bool KilledBySignal::operator()(
int exit_status)
const {
188# if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
191 if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
196 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
206static std::string ExitSummary(
int exit_code) {
209# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
211 m <<
"Exited with exit status " << exit_code;
215 if (WIFEXITED(exit_code)) {
216 m <<
"Exited with exit status " << WEXITSTATUS(exit_code);
217 }
else if (WIFSIGNALED(exit_code)) {
218 m <<
"Terminated by signal " << WTERMSIG(exit_code);
221 if (WCOREDUMP(exit_code)) {
222 m <<
" (core dumped)";
227 return m.GetString();
232bool ExitedUnsuccessfully(
int exit_status) {
233 return !ExitedWithCode(0)(exit_status);
236# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
241static std::string DeathTestThreadWarning(
size_t thread_count) {
243 msg <<
"Death tests use fork(), which is unsafe particularly"
244 <<
" in a threaded context. For this test, " <<
GTEST_NAME_ <<
" ";
245 if (thread_count == 0) {
246 msg <<
"couldn't detect the number of threads.";
248 msg <<
"detected " << thread_count <<
" threads.";
251 "https://github.com/google/googletest/blob/master/docs/"
252 "advanced.md#death-tests-and-threads"
253 <<
" for more explanation and suggested solutions, especially if"
254 <<
" this is the last message you see before your test times out.";
255 return msg.GetString();
260static const char kDeathTestLived =
'L';
261static const char kDeathTestReturned =
'R';
262static const char kDeathTestThrew =
'T';
263static const char kDeathTestInternalError =
'I';
268static const int kFuchsiaReadPipeFd = 3;
279enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
286static void DeathTestAbort(
const std::string&
message) {
290 const InternalRunDeathTestFlag*
const flag =
291 GetUnitTestImpl()->internal_run_death_test_flag();
292 if (flag !=
nullptr) {
294 fputc(kDeathTestInternalError, parent);
295 fprintf(parent,
"%s",
message.c_str());
299 fprintf(stderr,
"%s",
message.c_str());
307# define GTEST_DEATH_TEST_CHECK_(expression) \
309 if (!::testing::internal::IsTrue(expression)) { \
311 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
312 + ::testing::internal::StreamableToString(__LINE__) + ": " \
315 } while (::testing::internal::AlwaysFalse())
324# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
328 gtest_retval = (expression); \
329 } while (gtest_retval == -1 && errno == EINTR); \
330 if (gtest_retval == -1) { \
332 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
333 + ::testing::internal::StreamableToString(__LINE__) + ": " \
334 + #expression + " != -1"); \
336 } while (::testing::internal::AlwaysFalse())
339std::string GetLastErrnoDescription() {
347static void FailFromInternalError(
int fd) {
353 while ((num_read =
posix::Read(fd, buffer, 255)) > 0) {
354 buffer[num_read] =
'\0';
357 }
while (num_read == -1 && errno == EINTR);
362 const int last_error = errno;
364 << GetLastErrnoDescription() <<
" [" << last_error <<
"]";
370DeathTest::DeathTest() {
371 TestInfo*
const info = GetUnitTestImpl()->current_test_info();
372 if (info ==
nullptr) {
373 DeathTestAbort(
"Cannot run a death test outside of a TEST or "
380bool DeathTest::Create(
const char* statement,
381 Matcher<const std::string&> matcher,
const char*
file,
382 int line, DeathTest** test) {
383 return GetUnitTestImpl()->death_test_factory()->Create(
384 statement, std::move(matcher),
file, line, test);
387const char* DeathTest::LastMessage() {
388 return last_death_test_message_.c_str();
391void DeathTest::set_last_death_test_message(
const std::string&
message) {
392 last_death_test_message_ =
message;
395std::string DeathTest::last_death_test_message_;
398class DeathTestImpl :
public DeathTest {
400 DeathTestImpl(
const char* a_statement, Matcher<const std::string&> matcher)
401 : statement_(a_statement),
402 matcher_(
std::move(matcher)),
405 outcome_(IN_PROGRESS),
410 ~DeathTestImpl()
override { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
412 void Abort(AbortReason reason)
override;
413 bool Passed(
bool status_ok)
override;
415 const char* statement()
const {
return statement_; }
416 bool spawned()
const {
return spawned_; }
417 void set_spawned(
bool is_spawned) { spawned_ = is_spawned; }
418 int status()
const {
return status_; }
419 void set_status(
int a_status) { status_ = a_status; }
420 DeathTestOutcome outcome()
const {
return outcome_; }
421 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
422 int read_fd()
const {
return read_fd_; }
423 void set_read_fd(
int fd) { read_fd_ = fd; }
424 int write_fd()
const {
return write_fd_; }
425 void set_write_fd(
int fd) { write_fd_ = fd; }
431 void ReadAndInterpretStatusByte();
434 virtual std::string GetErrorLogs();
439 const char*
const statement_;
441 Matcher<const std::string&> matcher_;
447 DeathTestOutcome outcome_;
462void DeathTestImpl::ReadAndInterpretStatusByte() {
472 }
while (bytes_read == -1 && errno == EINTR);
474 if (bytes_read == 0) {
476 }
else if (bytes_read == 1) {
478 case kDeathTestReturned:
479 set_outcome(RETURNED);
481 case kDeathTestThrew:
484 case kDeathTestLived:
487 case kDeathTestInternalError:
488 FailFromInternalError(read_fd());
492 <<
"unexpected status byte ("
493 <<
static_cast<unsigned int>(flag) <<
")";
497 << GetLastErrnoDescription();
499 GTEST_DEATH_TEST_CHECK_SYSCALL_(
posix::Close(read_fd()));
503std::string DeathTestImpl::GetErrorLogs() {
515 const char status_ch =
516 reason == TEST_DID_NOT_DIE ? kDeathTestLived :
517 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : 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) {
543 ret +=
output.substr(at, line_end + 1 - at);
570bool DeathTestImpl::Passed(
bool status_ok) {
574 const std::string error_message = GetErrorLogs();
576 bool success =
false;
579 buffer <<
"Death test: " << statement() <<
"\n";
582 buffer <<
" Result: failed to die.\n"
583 <<
" Error msg:\n" << FormatDeathTestOutput(error_message);
586 buffer <<
" Result: threw an exception.\n"
587 <<
" Error msg:\n" << FormatDeathTestOutput(error_message);
590 buffer <<
" Result: illegal return in test statement.\n"
591 <<
" Error msg:\n" << FormatDeathTestOutput(error_message);
595 if (matcher_.Matches(error_message)) {
598 std::ostringstream stream;
599 matcher_.DescribeTo(&stream);
600 buffer <<
" Result: died but not with expected error.\n"
601 <<
" Expected: " << stream.str() <<
"\n"
603 << FormatDeathTestOutput(error_message);
606 buffer <<
" Result: died but not with expected exit code:\n"
607 <<
" " << ExitSummary(status()) <<
"\n"
608 <<
"Actual msg:\n" << FormatDeathTestOutput(error_message);
614 <<
"DeathTest::Passed somehow called before conclusion of test";
617 DeathTest::set_last_death_test_message(buffer.GetString());
650class WindowsDeathTest :
public DeathTestImpl {
652 WindowsDeathTest(
const char* a_statement, Matcher<const std::string&> matcher,
653 const char*
file,
int line)
654 : DeathTestImpl(a_statement,
std::move(matcher)),
660 virtual TestRole AssumeRole();
664 const char*
const file_;
668 AutoHandle write_handle_;
670 AutoHandle child_handle_;
675 AutoHandle event_handle_;
681int WindowsDeathTest::Wait() {
687 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
688 switch (::WaitForMultipleObjects(2,
693 case WAIT_OBJECT_0 + 1:
696 GTEST_DEATH_TEST_CHECK_(
false);
701 write_handle_.Reset();
702 event_handle_.Reset();
704 ReadAndInterpretStatusByte();
710 GTEST_DEATH_TEST_CHECK_(
711 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
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_(
746 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
749 set_read_fd(::_open_osfhandle(
reinterpret_cast<intptr_t
>(read_handle),
751 write_handle_.Reset(write_handle);
752 event_handle_.Reset(::CreateEvent(
753 &handles_are_inheritable,
757 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() !=
nullptr);
759 kFilterFlag +
"=" + info->test_suite_name() +
761 const std::string internal_flag =
772 char executable_path[_MAX_PATH + 1];
773 GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(
nullptr,
777 std::string command_line =
778 std::string(::GetCommandLineA()) +
" " + filter_flag +
" \"" +
779 internal_flag +
"\"";
781 DeathTest::set_last_death_test_message(
"");
788 STARTUPINFOA startup_info;
789 memset(&startup_info, 0,
sizeof(STARTUPINFO));
790 startup_info.dwFlags = STARTF_USESTDHANDLES;
791 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
792 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
793 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
795 PROCESS_INFORMATION process_info;
796 GTEST_DEATH_TEST_CHECK_(
798 executable_path,
const_cast<char*
>(command_line.c_str()),
805 &process_info) !=
FALSE);
806 child_handle_.Reset(process_info.hProcess);
807 ::CloseHandle(process_info.hThread);
812# elif GTEST_OS_FUCHSIA
814class FuchsiaDeathTest :
public DeathTestImpl {
816 FuchsiaDeathTest(
const char* a_statement, Matcher<const std::string&> matcher,
817 const char*
file,
int line)
818 : DeathTestImpl(a_statement,
std::move(matcher)),
824 TestRole AssumeRole()
override;
825 std::string GetErrorLogs()
override;
829 const char*
const file_;
833 std::string captured_stderr_;
835 zx::process child_process_;
836 zx::channel exception_channel_;
837 zx::socket stderr_socket_;
843 Arguments() { args_.push_back(
nullptr); }
846 for (std::vector<char*>::iterator
i = args_.begin();
i != args_.end();
851 void AddArgument(
const char* argument) {
855 template <
typename Str>
856 void AddArguments(const ::std::vector<Str>& arguments) {
857 for (typename ::std::vector<Str>::const_iterator
i = arguments.begin();
858 i != arguments.end();
863 char*
const* Argv() {
868 return static_cast<int>(args_.size()) - 1;
872 std::vector<char*> args_;
878int FuchsiaDeathTest::Wait() {
879 const int kProcessKey = 0;
880 const int kSocketKey = 1;
881 const int kExceptionKey = 2;
887 zx_status_t status_zx;
889 status_zx = zx::port::create(0, &port);
890 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
893 status_zx = child_process_.wait_async(
894 port, kProcessKey, ZX_PROCESS_TERMINATED, 0);
895 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
898 status_zx = stderr_socket_.wait_async(
899 port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0);
900 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
903 status_zx = exception_channel_.wait_async(
904 port, kExceptionKey, ZX_CHANNEL_READABLE, 0);
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, 0);
945 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
948 GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_SOCKET_PEER_CLOSED);
949 socket_closed =
true;
952 }
while (!process_terminated && !socket_closed);
954 ReadAndInterpretStatusByte();
956 zx_info_process_t buffer;
957 status_zx = child_process_.get_info(ZX_INFO_PROCESS, &buffer,
sizeof(buffer),
959 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
961 GTEST_DEATH_TEST_CHECK_(buffer.flags & ZX_INFO_PROCESS_FLAG_EXITED);
962 set_status(
static_cast<int>(buffer.return_code));
971DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
972 const UnitTestImpl*
const impl = GetUnitTestImpl();
973 const InternalRunDeathTestFlag*
const flag =
974 impl->internal_run_death_test_flag();
975 const TestInfo*
const info = impl->current_test_info();
976 const int death_test_index = info->result()->death_test_count();
978 if (flag !=
nullptr) {
981 set_write_fd(kFuchsiaReadPipeFd);
990 kFilterFlag +
"=" + info->test_suite_name() +
992 const std::string internal_flag =
998 args.AddArguments(GetInjectableArgvs());
999 args.AddArgument(filter_flag.c_str());
1000 args.AddArgument(internal_flag.c_str());
1004 zx_handle_t child_pipe_handle;
1006 status = fdio_pipe_half(&child_pipe_fd, &child_pipe_handle);
1007 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
1008 set_read_fd(child_pipe_fd);
1011 fdio_spawn_action_t spawn_actions[2] = {};
1012 fdio_spawn_action_t* add_handle_action = &spawn_actions[0];
1013 add_handle_action->action = FDIO_SPAWN_ACTION_ADD_HANDLE;
1014 add_handle_action->h.id = PA_HND(PA_FD, kFuchsiaReadPipeFd);
1015 add_handle_action->h.handle = child_pipe_handle;
1018 zx::socket stderr_producer_socket;
1020 zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);
1021 GTEST_DEATH_TEST_CHECK_(status >= 0);
1022 int stderr_producer_fd = -1;
1024 fdio_fd_create(stderr_producer_socket.release(), &stderr_producer_fd);
1025 GTEST_DEATH_TEST_CHECK_(status >= 0);
1028 GTEST_DEATH_TEST_CHECK_(fcntl(stderr_producer_fd, F_SETFL, 0) == 0);
1030 fdio_spawn_action_t* add_stderr_action = &spawn_actions[1];
1031 add_stderr_action->action = FDIO_SPAWN_ACTION_CLONE_FD;
1032 add_stderr_action->fd.local_fd = stderr_producer_fd;
1033 add_stderr_action->fd.target_fd = STDERR_FILENO;
1036 zx_handle_t child_job = ZX_HANDLE_INVALID;
1037 status = zx_job_create(zx_job_default(), 0, & child_job);
1038 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
1039 zx_policy_basic_t policy;
1040 policy.condition = ZX_POL_NEW_ANY;
1041 policy.policy = ZX_POL_ACTION_ALLOW;
1042 status = zx_job_set_policy(
1043 child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, &policy, 1);
1044 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
1049 zx_task_create_exception_channel(
1050 child_job, 0, exception_channel_.reset_and_get_address());
1051 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
1054 status = fdio_spawn_etc(
1055 child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(),
nullptr,
1056 2, spawn_actions, child_process_.reset_and_get_address(),
nullptr);
1057 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
1060 return OVERSEE_TEST;
1063std::string FuchsiaDeathTest::GetErrorLogs() {
1064 return captured_stderr_;
1072class ForkingDeathTest :
public DeathTestImpl {
1074 ForkingDeathTest(
const char* statement, Matcher<const std::string&> matcher);
1077 int Wait()
override;
1080 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
1088ForkingDeathTest::ForkingDeathTest(
const char* a_statement,
1089 Matcher<const std::string&> matcher)
1090 : DeathTestImpl(a_statement,
std::move(matcher)), child_pid_(-1) {}
1095int ForkingDeathTest::Wait() {
1099 ReadAndInterpretStatusByte();
1102 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
1103 set_status(status_value);
1104 return status_value;
1109class NoExecDeathTest :
public ForkingDeathTest {
1111 NoExecDeathTest(
const char* a_statement, Matcher<const std::string&> matcher)
1112 : ForkingDeathTest(a_statement,
std::move(matcher)) {}
1113 TestRole AssumeRole()
override;
1118DeathTest::TestRole NoExecDeathTest::AssumeRole() {
1120 if (thread_count != 1) {
1125 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
1127 DeathTest::set_last_death_test_message(
"");
1138 const pid_t child_pid = fork();
1139 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
1140 set_child_pid(child_pid);
1141 if (child_pid == 0) {
1142 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
1143 set_write_fd(pipe_fd[1]);
1150 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
1151 g_in_fast_death_test_child =
true;
1152 return EXECUTE_TEST;
1154 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
1155 set_read_fd(pipe_fd[0]);
1157 return OVERSEE_TEST;
1164class ExecDeathTest :
public ForkingDeathTest {
1166 ExecDeathTest(
const char* a_statement, Matcher<const std::string&> matcher,
1167 const char*
file,
int line)
1168 : ForkingDeathTest(a_statement,
std::move(matcher)),
1171 TestRole AssumeRole()
override;
1174 static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {
1175 ::std::vector<std::string> args = GetInjectableArgvs();
1176# if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
1177 ::std::vector<std::string> extra_args =
1178 GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
1179 args.insert(args.end(), extra_args.begin(), extra_args.end());
1184 const char*
const file_;
1192 Arguments() { args_.push_back(
nullptr); }
1195 for (std::vector<char*>::iterator
i = args_.begin();
i != args_.end();
1200 void AddArgument(
const char* argument) {
1204 template <
typename Str>
1205 void AddArguments(const ::std::vector<Str>& arguments) {
1206 for (typename ::std::vector<Str>::const_iterator
i = arguments.begin();
1207 i != arguments.end();
1212 char*
const* Argv() {
1217 std::vector<char*> args_;
1222struct ExecDeathTestArgs {
1233static int ExecDeathTestChildMain(
void* child_arg) {
1234 ExecDeathTestArgs*
const args =
static_cast<ExecDeathTestArgs*
>(child_arg);
1235 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
1240 const char*
const original_dir =
1243 if (chdir(original_dir) != 0) {
1244 DeathTestAbort(std::string(
"chdir(\"") + original_dir +
"\") failed: " +
1245 GetLastErrnoDescription());
1246 return EXIT_FAILURE;
1254 execv(args->argv[0], args->argv);
1255 DeathTestAbort(std::string(
"execv(") + args->argv[0] +
", ...) in " +
1256 original_dir +
" failed: " +
1257 GetLastErrnoDescription());
1258 return EXIT_FAILURE;
1272static void StackLowerThanAddress(
const void* ptr,
1282static void StackLowerThanAddress(
const void* ptr,
bool* result) {
1284 *result = std::less<const void*>()(&dummy, ptr);
1290static bool StackGrowsDown() {
1293 StackLowerThanAddress(&dummy, &result);
1305static pid_t ExecDeathTestSpawnChild(
char*
const* argv,
int close_fd) {
1306 ExecDeathTestArgs args = { argv, close_fd };
1307 pid_t child_pid = -1;
1312 const int cwd_fd = open(
".", O_RDONLY);
1313 GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
1314 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
1318 const char*
const original_dir =
1321 if (chdir(original_dir) != 0) {
1322 DeathTestAbort(std::string(
"chdir(\"") + original_dir +
"\") failed: " +
1323 GetLastErrnoDescription());
1324 return EXIT_FAILURE;
1329 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
1330 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
1331 fd_flags | FD_CLOEXEC));
1332 struct inheritance inherit = {0};
1334 child_pid = spawn(args.argv[0], 0,
nullptr, &inherit, args.argv,
environ);
1336 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
1337 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
1344 struct sigaction saved_sigprof_action;
1345 struct sigaction ignore_sigprof_action;
1346 memset(&ignore_sigprof_action, 0,
sizeof(ignore_sigprof_action));
1347 sigemptyset(&ignore_sigprof_action.sa_mask);
1348 ignore_sigprof_action.sa_handler = SIG_IGN;
1349 GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
1350 SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
1354 const bool use_fork =
GTEST_FLAG(death_test_use_fork);
1357 static const bool stack_grows_down = StackGrowsDown();
1358 const auto stack_size =
static_cast<size_t>(getpagesize() * 2);
1360 void*
const stack = mmap(
nullptr, stack_size, PROT_READ | PROT_WRITE,
1361 MAP_ANON | MAP_PRIVATE, -1, 0);
1362 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
1370 const size_t kMaxStackAlignment = 64;
1371 void*
const stack_top =
1372 static_cast<char*
>(stack) +
1373 (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
1374 GTEST_DEATH_TEST_CHECK_(
1375 static_cast<size_t>(stack_size) > kMaxStackAlignment &&
1376 reinterpret_cast<uintptr_t
>(stack_top) % kMaxStackAlignment == 0);
1378 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
1380 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
1383 const bool use_fork =
true;
1386 if (use_fork && (child_pid = fork()) == 0) {
1387 ExecDeathTestChildMain(&args);
1392 GTEST_DEATH_TEST_CHECK_SYSCALL_(
1393 sigaction(SIGPROF, &saved_sigprof_action,
nullptr));
1396 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
1404DeathTest::TestRole ExecDeathTest::AssumeRole() {
1405 const UnitTestImpl*
const impl = GetUnitTestImpl();
1406 const InternalRunDeathTestFlag*
const flag =
1407 impl->internal_run_death_test_flag();
1408 const TestInfo*
const info = impl->current_test_info();
1409 const int death_test_index = info->result()->death_test_count();
1411 if (flag !=
nullptr) {
1412 set_write_fd(flag->write_fd());
1413 return EXECUTE_TEST;
1417 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
1420 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
1423 kFilterFlag +
"=" + info->test_suite_name() +
1425 const std::string internal_flag =
1431 args.AddArguments(GetArgvsForDeathTestChildProcess());
1432 args.AddArgument(filter_flag.c_str());
1433 args.AddArgument(internal_flag.c_str());
1435 DeathTest::set_last_death_test_message(
"");
1442 const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
1443 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
1444 set_child_pid(child_pid);
1445 set_read_fd(pipe_fd[0]);
1447 return OVERSEE_TEST;
1457bool DefaultDeathTestFactory::Create(
const char* statement,
1458 Matcher<const std::string&> matcher,
1459 const char*
file,
int line,
1461 UnitTestImpl*
const impl = GetUnitTestImpl();
1462 const InternalRunDeathTestFlag*
const flag =
1463 impl->internal_run_death_test_flag();
1464 const int death_test_index = impl->current_test_info()
1465 ->increment_death_test_count();
1467 if (flag !=
nullptr) {
1468 if (death_test_index > flag->index()) {
1469 DeathTest::set_last_death_test_message(
1471 +
") somehow exceeded expected maximum ("
1476 if (!(flag->file() ==
file && flag->line() == line &&
1477 flag->index() == death_test_index)) {
1483# if GTEST_OS_WINDOWS
1485 if (
GTEST_FLAG(death_test_style) ==
"threadsafe" ||
1487 *test =
new WindowsDeathTest(statement, std::move(matcher),
file, line);
1490# elif GTEST_OS_FUCHSIA
1492 if (
GTEST_FLAG(death_test_style) ==
"threadsafe" ||
1494 *test =
new FuchsiaDeathTest(statement, std::move(matcher),
file, line);
1499 if (
GTEST_FLAG(death_test_style) ==
"threadsafe") {
1500 *test =
new ExecDeathTest(statement, std::move(matcher),
file, line);
1501 }
else if (
GTEST_FLAG(death_test_style) ==
"fast") {
1502 *test =
new NoExecDeathTest(statement, std::move(matcher));
1508 DeathTest::set_last_death_test_message(
1509 "Unknown death test style \"" +
GTEST_FLAG(death_test_style)
1510 +
"\" encountered");
1517# if GTEST_OS_WINDOWS
1521static int GetStatusFileDescriptor(
unsigned int parent_process_id,
1522 size_t write_handle_as_size_t,
1523 size_t event_handle_as_size_t) {
1524 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
1526 parent_process_id));
1527 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
1528 DeathTestAbort(
"Unable to open parent process " +
1534 const HANDLE write_handle =
1535 reinterpret_cast<HANDLE
>(write_handle_as_size_t);
1536 HANDLE dup_write_handle;
1541 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
1542 ::GetCurrentProcess(), &dup_write_handle,
1546 DUPLICATE_SAME_ACCESS)) {
1547 DeathTestAbort(
"Unable to duplicate the pipe handle " +
1549 " from the parent process " +
1553 const HANDLE event_handle =
reinterpret_cast<HANDLE
>(event_handle_as_size_t);
1554 HANDLE dup_event_handle;
1556 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
1557 ::GetCurrentProcess(), &dup_event_handle,
1560 DUPLICATE_SAME_ACCESS)) {
1561 DeathTestAbort(
"Unable to duplicate the event handle " +
1563 " from the parent process " +
1567 const int write_fd =
1568 ::_open_osfhandle(
reinterpret_cast<intptr_t
>(dup_write_handle), O_APPEND);
1569 if (write_fd == -1) {
1570 DeathTestAbort(
"Unable to convert pipe handle " +
1572 " to a file descriptor");
1577 ::SetEvent(dup_event_handle);
1586InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
1587 if (
GTEST_FLAG(internal_run_death_test) ==
"")
return nullptr;
1593 ::std::vector< ::std::string> fields;
1597# if GTEST_OS_WINDOWS
1599 unsigned int parent_process_id = 0;
1600 size_t write_handle_as_size_t = 0;
1601 size_t event_handle_as_size_t = 0;
1603 if (fields.size() != 6
1604 || !ParseNaturalNumber(fields[1], &line)
1605 || !ParseNaturalNumber(fields[2], &index)
1606 || !ParseNaturalNumber(fields[3], &parent_process_id)
1607 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
1608 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
1609 DeathTestAbort(
"Bad --gtest_internal_run_death_test flag: " +
1612 write_fd = GetStatusFileDescriptor(parent_process_id,
1613 write_handle_as_size_t,
1614 event_handle_as_size_t);
1616# elif GTEST_OS_FUCHSIA
1618 if (fields.size() != 3
1619 || !ParseNaturalNumber(fields[1], &line)
1620 || !ParseNaturalNumber(fields[2], &index)) {
1621 DeathTestAbort(
"Bad --gtest_internal_run_death_test flag: "
1627 if (fields.size() != 4
1628 || !ParseNaturalNumber(fields[1], &line)
1629 || !ParseNaturalNumber(fields[2], &index)
1630 || !ParseNaturalNumber(fields[3], &write_fd)) {
1631 DeathTestAbort(
"Bad --gtest_internal_run_death_test flag: "
1637 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
#define GTEST_FLAG_PREFIX_
#define GTEST_DEFAULT_DEATH_TEST_STYLE
#define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
#define GTEST_LOG_(severity)
#define GTEST_CHECK_(condition)
#define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
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_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).")
GTEST_API_ std::string GetCapturedStderr()
GTEST_API_ size_t GetThreadCount()
bool BoolFromGTestEnv(const char *flag, bool default_val)
const char * StringFromGTestEnv(const char *flag, const char *default_val)
const char kInternalRunDeathTestFlag[]
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.")
void SplitString(const ::std::string &str, char delimiter, ::std::vector< ::std::string > *dest)
GTEST_API_ void CaptureStderr()
std::string StreamableToString(const T &streamable)
int Read(int fd, void *buf, unsigned int count)
char * StrDup(const char *src)
const char * StrError(int errnum)
FILE * FDOpen(int fd, const char *mode)
int Write(int fd, const void *buf, unsigned int count)
static UnitTest * GetInstance()
const char * original_working_dir() const