00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034 #include "gtest/gtest-death-test.h"
00035 #include "gtest/internal/gtest-port.h"
00036
00037 #if GTEST_HAS_DEATH_TEST
00038
00039 # if GTEST_OS_MAC
00040 # include <crt_externs.h>
00041 # endif // GTEST_OS_MAC
00042
00043 # include <errno.h>
00044 # include <fcntl.h>
00045 # include <limits.h>
00046
00047 # if GTEST_OS_LINUX
00048 # include <signal.h>
00049 # endif // GTEST_OS_LINUX
00050
00051 # include <stdarg.h>
00052
00053 # if GTEST_OS_WINDOWS
00054 # include <windows.h>
00055 # else
00056 # include <sys/mman.h>
00057 # include <sys/wait.h>
00058 # endif // GTEST_OS_WINDOWS
00059
00060 # if GTEST_OS_QNX
00061 # include <spawn.h>
00062 # endif // GTEST_OS_QNX
00063
00064 #endif // GTEST_HAS_DEATH_TEST
00065
00066 #include "gtest/gtest-message.h"
00067 #include "gtest/internal/gtest-string.h"
00068
00069
00070
00071
00072
00073
00074 #define GTEST_IMPLEMENTATION_ 1
00075 #include "src/gtest-internal-inl.h"
00076 #undef GTEST_IMPLEMENTATION_
00077
00078 namespace testing {
00079
00080
00081
00082
00083 static const char kDefaultDeathTestStyle[] = "fast";
00084
00085 GTEST_DEFINE_string_(
00086 death_test_style,
00087 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
00088 "Indicates how to run a death test in a forked child process: "
00089 "\"threadsafe\" (child process re-executes the test binary "
00090 "from the beginning, running only the specific death test) or "
00091 "\"fast\" (child process runs the death test immediately "
00092 "after forking).");
00093
00094 GTEST_DEFINE_bool_(
00095 death_test_use_fork,
00096 internal::BoolFromGTestEnv("death_test_use_fork", false),
00097 "Instructs to use fork()/_exit() instead of clone() in death tests. "
00098 "Ignored and always uses fork() on POSIX systems where clone() is not "
00099 "implemented. Useful when running under valgrind or similar tools if "
00100 "those do not support clone(). Valgrind 3.3.1 will just fail if "
00101 "it sees an unsupported combination of clone() flags. "
00102 "It is not recommended to use this flag w/o valgrind though it will "
00103 "work in 99% of the cases. Once valgrind is fixed, this flag will "
00104 "most likely be removed.");
00105
00106 namespace internal {
00107 GTEST_DEFINE_string_(
00108 internal_run_death_test, "",
00109 "Indicates the file, line number, temporal index of "
00110 "the single death test to run, and a file descriptor to "
00111 "which a success code may be sent, all separated by "
00112 "the '|' characters. This flag is specified if and only if the current "
00113 "process is a sub-process launched for running a thread-safe "
00114 "death test. FOR INTERNAL USE ONLY.");
00115 }
00116
00117 #if GTEST_HAS_DEATH_TEST
00118
00119 namespace internal {
00120
00121
00122
00123 static bool g_in_fast_death_test_child = false;
00124
00125
00126
00127
00128
00129
00130 bool InDeathTestChild() {
00131 # if GTEST_OS_WINDOWS
00132
00133
00134
00135 return !GTEST_FLAG(internal_run_death_test).empty();
00136
00137 # else
00138
00139 if (GTEST_FLAG(death_test_style) == "threadsafe")
00140 return !GTEST_FLAG(internal_run_death_test).empty();
00141 else
00142 return g_in_fast_death_test_child;
00143 #endif
00144 }
00145
00146 }
00147
00148
00149 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
00150 }
00151
00152
00153 bool ExitedWithCode::operator()(int exit_status) const {
00154 # if GTEST_OS_WINDOWS
00155
00156 return exit_status == exit_code_;
00157
00158 # else
00159
00160 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
00161
00162 # endif // GTEST_OS_WINDOWS
00163 }
00164
00165 # if !GTEST_OS_WINDOWS
00166
00167 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
00168 }
00169
00170
00171 bool KilledBySignal::operator()(int exit_status) const {
00172 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
00173 }
00174 # endif // !GTEST_OS_WINDOWS
00175
00176 namespace internal {
00177
00178
00179
00180
00181
00182 static std::string ExitSummary(int exit_code) {
00183 Message m;
00184
00185 # if GTEST_OS_WINDOWS
00186
00187 m << "Exited with exit status " << exit_code;
00188
00189 # else
00190
00191 if (WIFEXITED(exit_code)) {
00192 m << "Exited with exit status " << WEXITSTATUS(exit_code);
00193 } else if (WIFSIGNALED(exit_code)) {
00194 m << "Terminated by signal " << WTERMSIG(exit_code);
00195 }
00196 # ifdef WCOREDUMP
00197 if (WCOREDUMP(exit_code)) {
00198 m << " (core dumped)";
00199 }
00200 # endif
00201 # endif // GTEST_OS_WINDOWS
00202
00203 return m.GetString();
00204 }
00205
00206
00207
00208 bool ExitedUnsuccessfully(int exit_status) {
00209 return !ExitedWithCode(0)(exit_status);
00210 }
00211
00212 # if !GTEST_OS_WINDOWS
00213
00214
00215
00216
00217 static std::string DeathTestThreadWarning(size_t thread_count) {
00218 Message msg;
00219 msg << "Death tests use fork(), which is unsafe particularly"
00220 << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
00221 if (thread_count == 0)
00222 msg << "couldn't detect the number of threads.";
00223 else
00224 msg << "detected " << thread_count << " threads.";
00225 return msg.GetString();
00226 }
00227 # endif // !GTEST_OS_WINDOWS
00228
00229
00230 static const char kDeathTestLived = 'L';
00231 static const char kDeathTestReturned = 'R';
00232 static const char kDeathTestThrew = 'T';
00233 static const char kDeathTestInternalError = 'I';
00234
00235
00236
00237
00238
00239
00240
00241
00242
00243
00244 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
00245
00246
00247
00248
00249
00250
00251 void DeathTestAbort(const std::string& message) {
00252
00253
00254
00255 const InternalRunDeathTestFlag* const flag =
00256 GetUnitTestImpl()->internal_run_death_test_flag();
00257 if (flag != NULL) {
00258 FILE* parent = posix::FDOpen(flag->write_fd(), "w");
00259 fputc(kDeathTestInternalError, parent);
00260 fprintf(parent, "%s", message.c_str());
00261 fflush(parent);
00262 _exit(1);
00263 } else {
00264 fprintf(stderr, "%s", message.c_str());
00265 fflush(stderr);
00266 posix::Abort();
00267 }
00268 }
00269
00270
00271
00272 # define GTEST_DEATH_TEST_CHECK_(expression) \
00273 do { \
00274 if (!::testing::internal::IsTrue(expression)) { \
00275 DeathTestAbort( \
00276 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
00277 + ::testing::internal::StreamableToString(__LINE__) + ": " \
00278 + #expression); \
00279 } \
00280 } while (::testing::internal::AlwaysFalse())
00281
00282
00283
00284
00285
00286
00287
00288
00289 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
00290 do { \
00291 int gtest_retval; \
00292 do { \
00293 gtest_retval = (expression); \
00294 } while (gtest_retval == -1 && errno == EINTR); \
00295 if (gtest_retval == -1) { \
00296 DeathTestAbort( \
00297 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
00298 + ::testing::internal::StreamableToString(__LINE__) + ": " \
00299 + #expression + " != -1"); \
00300 } \
00301 } while (::testing::internal::AlwaysFalse())
00302
00303
00304 std::string GetLastErrnoDescription() {
00305 return errno == 0 ? "" : posix::StrError(errno);
00306 }
00307
00308
00309
00310
00311
00312 static void FailFromInternalError(int fd) {
00313 Message error;
00314 char buffer[256];
00315 int num_read;
00316
00317 do {
00318 while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
00319 buffer[num_read] = '\0';
00320 error << buffer;
00321 }
00322 } while (num_read == -1 && errno == EINTR);
00323
00324 if (num_read == 0) {
00325 GTEST_LOG_(FATAL) << error.GetString();
00326 } else {
00327 const int last_error = errno;
00328 GTEST_LOG_(FATAL) << "Error while reading death test internal: "
00329 << GetLastErrnoDescription() << " [" << last_error << "]";
00330 }
00331 }
00332
00333
00334
00335 DeathTest::DeathTest() {
00336 TestInfo* const info = GetUnitTestImpl()->current_test_info();
00337 if (info == NULL) {
00338 DeathTestAbort("Cannot run a death test outside of a TEST or "
00339 "TEST_F construct");
00340 }
00341 }
00342
00343
00344
00345 bool DeathTest::Create(const char* statement, const RE* regex,
00346 const char* file, int line, DeathTest** test) {
00347 return GetUnitTestImpl()->death_test_factory()->Create(
00348 statement, regex, file, line, test);
00349 }
00350
00351 const char* DeathTest::LastMessage() {
00352 return last_death_test_message_.c_str();
00353 }
00354
00355 void DeathTest::set_last_death_test_message(const std::string& message) {
00356 last_death_test_message_ = message;
00357 }
00358
00359 std::string DeathTest::last_death_test_message_;
00360
00361
00362 class DeathTestImpl : public DeathTest {
00363 protected:
00364 DeathTestImpl(const char* a_statement, const RE* a_regex)
00365 : statement_(a_statement),
00366 regex_(a_regex),
00367 spawned_(false),
00368 status_(-1),
00369 outcome_(IN_PROGRESS),
00370 read_fd_(-1),
00371 write_fd_(-1) {}
00372
00373
00374 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
00375
00376 void Abort(AbortReason reason);
00377 virtual bool Passed(bool status_ok);
00378
00379 const char* statement() const { return statement_; }
00380 const RE* regex() const { return regex_; }
00381 bool spawned() const { return spawned_; }
00382 void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
00383 int status() const { return status_; }
00384 void set_status(int a_status) { status_ = a_status; }
00385 DeathTestOutcome outcome() const { return outcome_; }
00386 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
00387 int read_fd() const { return read_fd_; }
00388 void set_read_fd(int fd) { read_fd_ = fd; }
00389 int write_fd() const { return write_fd_; }
00390 void set_write_fd(int fd) { write_fd_ = fd; }
00391
00392
00393
00394
00395
00396 void ReadAndInterpretStatusByte();
00397
00398 private:
00399
00400
00401 const char* const statement_;
00402
00403
00404 const RE* const regex_;
00405
00406 bool spawned_;
00407
00408 int status_;
00409
00410 DeathTestOutcome outcome_;
00411
00412
00413
00414 int read_fd_;
00415
00416
00417
00418 int write_fd_;
00419 };
00420
00421
00422
00423
00424
00425 void DeathTestImpl::ReadAndInterpretStatusByte() {
00426 char flag;
00427 int bytes_read;
00428
00429
00430
00431
00432
00433 do {
00434 bytes_read = posix::Read(read_fd(), &flag, 1);
00435 } while (bytes_read == -1 && errno == EINTR);
00436
00437 if (bytes_read == 0) {
00438 set_outcome(DIED);
00439 } else if (bytes_read == 1) {
00440 switch (flag) {
00441 case kDeathTestReturned:
00442 set_outcome(RETURNED);
00443 break;
00444 case kDeathTestThrew:
00445 set_outcome(THREW);
00446 break;
00447 case kDeathTestLived:
00448 set_outcome(LIVED);
00449 break;
00450 case kDeathTestInternalError:
00451 FailFromInternalError(read_fd());
00452 break;
00453 default:
00454 GTEST_LOG_(FATAL) << "Death test child process reported "
00455 << "unexpected status byte ("
00456 << static_cast<unsigned int>(flag) << ")";
00457 }
00458 } else {
00459 GTEST_LOG_(FATAL) << "Read from death test child process failed: "
00460 << GetLastErrnoDescription();
00461 }
00462 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
00463 set_read_fd(-1);
00464 }
00465
00466
00467
00468
00469
00470 void DeathTestImpl::Abort(AbortReason reason) {
00471
00472
00473
00474 const char status_ch =
00475 reason == TEST_DID_NOT_DIE ? kDeathTestLived :
00476 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
00477
00478 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
00479
00480
00481
00482
00483
00484
00485
00486
00487 _exit(1);
00488 }
00489
00490
00491
00492
00493 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
00494 ::std::string ret;
00495 for (size_t at = 0; ; ) {
00496 const size_t line_end = output.find('\n', at);
00497 ret += "[ DEATH ] ";
00498 if (line_end == ::std::string::npos) {
00499 ret += output.substr(at);
00500 break;
00501 }
00502 ret += output.substr(at, line_end + 1 - at);
00503 at = line_end + 1;
00504 }
00505 return ret;
00506 }
00507
00508
00509
00510
00511
00512
00513
00514
00515
00516
00517
00518
00519
00520
00521
00522
00523
00524
00525
00526
00527
00528
00529
00530 bool DeathTestImpl::Passed(bool status_ok) {
00531 if (!spawned())
00532 return false;
00533
00534 const std::string error_message = GetCapturedStderr();
00535
00536 bool success = false;
00537 Message buffer;
00538
00539 buffer << "Death test: " << statement() << "\n";
00540 switch (outcome()) {
00541 case LIVED:
00542 buffer << " Result: failed to die.\n"
00543 << " Error msg:\n" << FormatDeathTestOutput(error_message);
00544 break;
00545 case THREW:
00546 buffer << " Result: threw an exception.\n"
00547 << " Error msg:\n" << FormatDeathTestOutput(error_message);
00548 break;
00549 case RETURNED:
00550 buffer << " Result: illegal return in test statement.\n"
00551 << " Error msg:\n" << FormatDeathTestOutput(error_message);
00552 break;
00553 case DIED:
00554 if (status_ok) {
00555 const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
00556 if (matched) {
00557 success = true;
00558 } else {
00559 buffer << " Result: died but not with expected error.\n"
00560 << " Expected: " << regex()->pattern() << "\n"
00561 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
00562 }
00563 } else {
00564 buffer << " Result: died but not with expected exit code:\n"
00565 << " " << ExitSummary(status()) << "\n"
00566 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
00567 }
00568 break;
00569 case IN_PROGRESS:
00570 default:
00571 GTEST_LOG_(FATAL)
00572 << "DeathTest::Passed somehow called before conclusion of test";
00573 }
00574
00575 DeathTest::set_last_death_test_message(buffer.GetString());
00576 return success;
00577 }
00578
00579 # if GTEST_OS_WINDOWS
00580
00581
00582
00583
00584
00585
00586
00587
00588
00589
00590
00591
00592
00593
00594
00595
00596
00597
00598
00599
00600
00601
00602
00603
00604
00605
00606
00607
00608 class WindowsDeathTest : public DeathTestImpl {
00609 public:
00610 WindowsDeathTest(const char* a_statement,
00611 const RE* a_regex,
00612 const char* file,
00613 int line)
00614 : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
00615
00616
00617 virtual int Wait();
00618 virtual TestRole AssumeRole();
00619
00620 private:
00621
00622 const char* const file_;
00623
00624 const int line_;
00625
00626 AutoHandle write_handle_;
00627
00628 AutoHandle child_handle_;
00629
00630
00631
00632
00633 AutoHandle event_handle_;
00634 };
00635
00636
00637
00638
00639 int WindowsDeathTest::Wait() {
00640 if (!spawned())
00641 return 0;
00642
00643
00644
00645 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
00646 switch (::WaitForMultipleObjects(2,
00647 wait_handles,
00648 FALSE,
00649 INFINITE)) {
00650 case WAIT_OBJECT_0:
00651 case WAIT_OBJECT_0 + 1:
00652 break;
00653 default:
00654 GTEST_DEATH_TEST_CHECK_(false);
00655 }
00656
00657
00658
00659 write_handle_.Reset();
00660 event_handle_.Reset();
00661
00662 ReadAndInterpretStatusByte();
00663
00664
00665
00666
00667
00668 GTEST_DEATH_TEST_CHECK_(
00669 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
00670 INFINITE));
00671 DWORD status_code;
00672 GTEST_DEATH_TEST_CHECK_(
00673 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
00674 child_handle_.Reset();
00675 set_status(static_cast<int>(status_code));
00676 return status();
00677 }
00678
00679
00680
00681
00682
00683
00684 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
00685 const UnitTestImpl* const impl = GetUnitTestImpl();
00686 const InternalRunDeathTestFlag* const flag =
00687 impl->internal_run_death_test_flag();
00688 const TestInfo* const info = impl->current_test_info();
00689 const int death_test_index = info->result()->death_test_count();
00690
00691 if (flag != NULL) {
00692
00693
00694 set_write_fd(flag->write_fd());
00695 return EXECUTE_TEST;
00696 }
00697
00698
00699
00700 SECURITY_ATTRIBUTES handles_are_inheritable = {
00701 sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
00702 HANDLE read_handle, write_handle;
00703 GTEST_DEATH_TEST_CHECK_(
00704 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
00705 0)
00706 != FALSE);
00707 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
00708 O_RDONLY));
00709 write_handle_.Reset(write_handle);
00710 event_handle_.Reset(::CreateEvent(
00711 &handles_are_inheritable,
00712 TRUE,
00713 FALSE,
00714 NULL));
00715 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
00716 const std::string filter_flag =
00717 std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
00718 info->test_case_name() + "." + info->name();
00719 const std::string internal_flag =
00720 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
00721 "=" + file_ + "|" + StreamableToString(line_) + "|" +
00722 StreamableToString(death_test_index) + "|" +
00723 StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
00724
00725
00726
00727 "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
00728 "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
00729
00730 char executable_path[_MAX_PATH + 1];
00731 GTEST_DEATH_TEST_CHECK_(
00732 _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
00733 executable_path,
00734 _MAX_PATH));
00735
00736 std::string command_line =
00737 std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
00738 internal_flag + "\"";
00739
00740 DeathTest::set_last_death_test_message("");
00741
00742 CaptureStderr();
00743
00744 FlushInfoLog();
00745
00746
00747 STARTUPINFOA startup_info;
00748 memset(&startup_info, 0, sizeof(STARTUPINFO));
00749 startup_info.dwFlags = STARTF_USESTDHANDLES;
00750 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
00751 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
00752 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
00753
00754 PROCESS_INFORMATION process_info;
00755 GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
00756 executable_path,
00757 const_cast<char*>(command_line.c_str()),
00758 NULL,
00759 NULL,
00760 TRUE,
00761 0x0,
00762 NULL,
00763 UnitTest::GetInstance()->original_working_dir(),
00764 &startup_info,
00765 &process_info) != FALSE);
00766 child_handle_.Reset(process_info.hProcess);
00767 ::CloseHandle(process_info.hThread);
00768 set_spawned(true);
00769 return OVERSEE_TEST;
00770 }
00771 # else // We are not on Windows.
00772
00773
00774
00775
00776 class ForkingDeathTest : public DeathTestImpl {
00777 public:
00778 ForkingDeathTest(const char* statement, const RE* regex);
00779
00780
00781 virtual int Wait();
00782
00783 protected:
00784 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
00785
00786 private:
00787
00788 pid_t child_pid_;
00789 };
00790
00791
00792 ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
00793 : DeathTestImpl(a_statement, a_regex),
00794 child_pid_(-1) {}
00795
00796
00797
00798
00799 int ForkingDeathTest::Wait() {
00800 if (!spawned())
00801 return 0;
00802
00803 ReadAndInterpretStatusByte();
00804
00805 int status_value;
00806 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
00807 set_status(status_value);
00808 return status_value;
00809 }
00810
00811
00812
00813 class NoExecDeathTest : public ForkingDeathTest {
00814 public:
00815 NoExecDeathTest(const char* a_statement, const RE* a_regex) :
00816 ForkingDeathTest(a_statement, a_regex) { }
00817 virtual TestRole AssumeRole();
00818 };
00819
00820
00821
00822 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
00823 const size_t thread_count = GetThreadCount();
00824 if (thread_count != 1) {
00825 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
00826 }
00827
00828 int pipe_fd[2];
00829 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
00830
00831 DeathTest::set_last_death_test_message("");
00832 CaptureStderr();
00833
00834
00835
00836
00837
00838
00839
00840 FlushInfoLog();
00841
00842 const pid_t child_pid = fork();
00843 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
00844 set_child_pid(child_pid);
00845 if (child_pid == 0) {
00846 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
00847 set_write_fd(pipe_fd[1]);
00848
00849
00850
00851 LogToStderr();
00852
00853
00854 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
00855 g_in_fast_death_test_child = true;
00856 return EXECUTE_TEST;
00857 } else {
00858 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
00859 set_read_fd(pipe_fd[0]);
00860 set_spawned(true);
00861 return OVERSEE_TEST;
00862 }
00863 }
00864
00865
00866
00867
00868 class ExecDeathTest : public ForkingDeathTest {
00869 public:
00870 ExecDeathTest(const char* a_statement, const RE* a_regex,
00871 const char* file, int line) :
00872 ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
00873 virtual TestRole AssumeRole();
00874 private:
00875 static ::std::vector<testing::internal::string>
00876 GetArgvsForDeathTestChildProcess() {
00877 ::std::vector<testing::internal::string> args = GetInjectableArgvs();
00878 return args;
00879 }
00880
00881 const char* const file_;
00882
00883 const int line_;
00884 };
00885
00886
00887 class Arguments {
00888 public:
00889 Arguments() {
00890 args_.push_back(NULL);
00891 }
00892
00893 ~Arguments() {
00894 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
00895 ++i) {
00896 free(*i);
00897 }
00898 }
00899 void AddArgument(const char* argument) {
00900 args_.insert(args_.end() - 1, posix::StrDup(argument));
00901 }
00902
00903 template <typename Str>
00904 void AddArguments(const ::std::vector<Str>& arguments) {
00905 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
00906 i != arguments.end();
00907 ++i) {
00908 args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
00909 }
00910 }
00911 char* const* Argv() {
00912 return &args_[0];
00913 }
00914
00915 private:
00916 std::vector<char*> args_;
00917 };
00918
00919
00920
00921 struct ExecDeathTestArgs {
00922 char* const* argv;
00923 int close_fd;
00924 };
00925
00926 # if GTEST_OS_MAC
00927 inline char** GetEnviron() {
00928
00929
00930
00931 return *_NSGetEnviron();
00932 }
00933 # else
00934
00935
00936 extern "C" char** environ;
00937 inline char** GetEnviron() { return environ; }
00938 # endif // GTEST_OS_MAC
00939
00940 # if !GTEST_OS_QNX
00941
00942
00943
00944 static int ExecDeathTestChildMain(void* child_arg) {
00945 ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
00946 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
00947
00948
00949
00950
00951 const char* const original_dir =
00952 UnitTest::GetInstance()->original_working_dir();
00953
00954 if (chdir(original_dir) != 0) {
00955 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
00956 GetLastErrnoDescription());
00957 return EXIT_FAILURE;
00958 }
00959
00960
00961
00962
00963
00964
00965 execve(args->argv[0], args->argv, GetEnviron());
00966 DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
00967 original_dir + " failed: " +
00968 GetLastErrnoDescription());
00969 return EXIT_FAILURE;
00970 }
00971 # endif // !GTEST_OS_QNX
00972
00973
00974
00975
00976
00977
00978
00979
00980
00981
00982 void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;
00983 void StackLowerThanAddress(const void* ptr, bool* result) {
00984 int dummy;
00985 *result = (&dummy < ptr);
00986 }
00987
00988
00989 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
00990 bool StackGrowsDown() {
00991 int dummy;
00992 bool result;
00993 StackLowerThanAddress(&dummy, &result);
00994 return result;
00995 }
00996
00997
00998
00999
01000
01001
01002
01003
01004 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
01005 ExecDeathTestArgs args = { argv, close_fd };
01006 pid_t child_pid = -1;
01007
01008 # if GTEST_OS_QNX
01009
01010
01011 const int cwd_fd = open(".", O_RDONLY);
01012 GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
01013 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
01014
01015
01016
01017 const char* const original_dir =
01018 UnitTest::GetInstance()->original_working_dir();
01019
01020 if (chdir(original_dir) != 0) {
01021 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
01022 GetLastErrnoDescription());
01023 return EXIT_FAILURE;
01024 }
01025
01026 int fd_flags;
01027
01028 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
01029 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
01030 fd_flags | FD_CLOEXEC));
01031 struct inheritance inherit = {0};
01032
01033 child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
01034
01035 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
01036 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
01037
01038 # else // GTEST_OS_QNX
01039 # if GTEST_OS_LINUX
01040
01041
01042
01043 struct sigaction saved_sigprof_action;
01044 struct sigaction ignore_sigprof_action;
01045 memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
01046 sigemptyset(&ignore_sigprof_action.sa_mask);
01047 ignore_sigprof_action.sa_handler = SIG_IGN;
01048 GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
01049 SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
01050 # endif // GTEST_OS_LINUX
01051
01052 # if GTEST_HAS_CLONE
01053 const bool use_fork = GTEST_FLAG(death_test_use_fork);
01054
01055 if (!use_fork) {
01056 static const bool stack_grows_down = StackGrowsDown();
01057 const size_t stack_size = getpagesize();
01058
01059 void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
01060 MAP_ANON | MAP_PRIVATE, -1, 0);
01061 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
01062
01063
01064
01065
01066
01067
01068
01069 const size_t kMaxStackAlignment = 64;
01070 void* const stack_top =
01071 static_cast<char*>(stack) +
01072 (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
01073 GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
01074 reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
01075
01076 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
01077
01078 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
01079 }
01080 # else
01081 const bool use_fork = true;
01082 # endif // GTEST_HAS_CLONE
01083
01084 if (use_fork && (child_pid = fork()) == 0) {
01085 ExecDeathTestChildMain(&args);
01086 _exit(0);
01087 }
01088 # endif // GTEST_OS_QNX
01089 # if GTEST_OS_LINUX
01090 GTEST_DEATH_TEST_CHECK_SYSCALL_(
01091 sigaction(SIGPROF, &saved_sigprof_action, NULL));
01092 # endif // GTEST_OS_LINUX
01093
01094 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
01095 return child_pid;
01096 }
01097
01098
01099
01100
01101
01102 DeathTest::TestRole ExecDeathTest::AssumeRole() {
01103 const UnitTestImpl* const impl = GetUnitTestImpl();
01104 const InternalRunDeathTestFlag* const flag =
01105 impl->internal_run_death_test_flag();
01106 const TestInfo* const info = impl->current_test_info();
01107 const int death_test_index = info->result()->death_test_count();
01108
01109 if (flag != NULL) {
01110 set_write_fd(flag->write_fd());
01111 return EXECUTE_TEST;
01112 }
01113
01114 int pipe_fd[2];
01115 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
01116
01117
01118 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
01119
01120 const std::string filter_flag =
01121 std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
01122 + info->test_case_name() + "." + info->name();
01123 const std::string internal_flag =
01124 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
01125 + file_ + "|" + StreamableToString(line_) + "|"
01126 + StreamableToString(death_test_index) + "|"
01127 + StreamableToString(pipe_fd[1]);
01128 Arguments args;
01129 args.AddArguments(GetArgvsForDeathTestChildProcess());
01130 args.AddArgument(filter_flag.c_str());
01131 args.AddArgument(internal_flag.c_str());
01132
01133 DeathTest::set_last_death_test_message("");
01134
01135 CaptureStderr();
01136
01137
01138 FlushInfoLog();
01139
01140 const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
01141 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
01142 set_child_pid(child_pid);
01143 set_read_fd(pipe_fd[0]);
01144 set_spawned(true);
01145 return OVERSEE_TEST;
01146 }
01147
01148 # endif // !GTEST_OS_WINDOWS
01149
01150
01151
01152
01153
01154
01155 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
01156 const char* file, int line,
01157 DeathTest** test) {
01158 UnitTestImpl* const impl = GetUnitTestImpl();
01159 const InternalRunDeathTestFlag* const flag =
01160 impl->internal_run_death_test_flag();
01161 const int death_test_index = impl->current_test_info()
01162 ->increment_death_test_count();
01163
01164 if (flag != NULL) {
01165 if (death_test_index > flag->index()) {
01166 DeathTest::set_last_death_test_message(
01167 "Death test count (" + StreamableToString(death_test_index)
01168 + ") somehow exceeded expected maximum ("
01169 + StreamableToString(flag->index()) + ")");
01170 return false;
01171 }
01172
01173 if (!(flag->file() == file && flag->line() == line &&
01174 flag->index() == death_test_index)) {
01175 *test = NULL;
01176 return true;
01177 }
01178 }
01179
01180 # if GTEST_OS_WINDOWS
01181
01182 if (GTEST_FLAG(death_test_style) == "threadsafe" ||
01183 GTEST_FLAG(death_test_style) == "fast") {
01184 *test = new WindowsDeathTest(statement, regex, file, line);
01185 }
01186
01187 # else
01188
01189 if (GTEST_FLAG(death_test_style) == "threadsafe") {
01190 *test = new ExecDeathTest(statement, regex, file, line);
01191 } else if (GTEST_FLAG(death_test_style) == "fast") {
01192 *test = new NoExecDeathTest(statement, regex);
01193 }
01194
01195 # endif // GTEST_OS_WINDOWS
01196
01197 else {
01198 DeathTest::set_last_death_test_message(
01199 "Unknown death test style \"" + GTEST_FLAG(death_test_style)
01200 + "\" encountered");
01201 return false;
01202 }
01203
01204 return true;
01205 }
01206
01207
01208
01209
01210 static void SplitString(const ::std::string& str, char delimiter,
01211 ::std::vector< ::std::string>* dest) {
01212 ::std::vector< ::std::string> parsed;
01213 ::std::string::size_type pos = 0;
01214 while (::testing::internal::AlwaysTrue()) {
01215 const ::std::string::size_type colon = str.find(delimiter, pos);
01216 if (colon == ::std::string::npos) {
01217 parsed.push_back(str.substr(pos));
01218 break;
01219 } else {
01220 parsed.push_back(str.substr(pos, colon - pos));
01221 pos = colon + 1;
01222 }
01223 }
01224 dest->swap(parsed);
01225 }
01226
01227 # if GTEST_OS_WINDOWS
01228
01229
01230
01231 int GetStatusFileDescriptor(unsigned int parent_process_id,
01232 size_t write_handle_as_size_t,
01233 size_t event_handle_as_size_t) {
01234 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
01235 FALSE,
01236 parent_process_id));
01237 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
01238 DeathTestAbort("Unable to open parent process " +
01239 StreamableToString(parent_process_id));
01240 }
01241
01242
01243
01244 GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
01245
01246 const HANDLE write_handle =
01247 reinterpret_cast<HANDLE>(write_handle_as_size_t);
01248 HANDLE dup_write_handle;
01249
01250
01251
01252
01253 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
01254 ::GetCurrentProcess(), &dup_write_handle,
01255 0x0,
01256
01257 FALSE,
01258 DUPLICATE_SAME_ACCESS)) {
01259 DeathTestAbort("Unable to duplicate the pipe handle " +
01260 StreamableToString(write_handle_as_size_t) +
01261 " from the parent process " +
01262 StreamableToString(parent_process_id));
01263 }
01264
01265 const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
01266 HANDLE dup_event_handle;
01267
01268 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
01269 ::GetCurrentProcess(), &dup_event_handle,
01270 0x0,
01271 FALSE,
01272 DUPLICATE_SAME_ACCESS)) {
01273 DeathTestAbort("Unable to duplicate the event handle " +
01274 StreamableToString(event_handle_as_size_t) +
01275 " from the parent process " +
01276 StreamableToString(parent_process_id));
01277 }
01278
01279 const int write_fd =
01280 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
01281 if (write_fd == -1) {
01282 DeathTestAbort("Unable to convert pipe handle " +
01283 StreamableToString(write_handle_as_size_t) +
01284 " to a file descriptor");
01285 }
01286
01287
01288
01289 ::SetEvent(dup_event_handle);
01290
01291 return write_fd;
01292 }
01293 # endif // GTEST_OS_WINDOWS
01294
01295
01296
01297
01298 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
01299 if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
01300
01301
01302
01303 int line = -1;
01304 int index = -1;
01305 ::std::vector< ::std::string> fields;
01306 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
01307 int write_fd = -1;
01308
01309 # if GTEST_OS_WINDOWS
01310
01311 unsigned int parent_process_id = 0;
01312 size_t write_handle_as_size_t = 0;
01313 size_t event_handle_as_size_t = 0;
01314
01315 if (fields.size() != 6
01316 || !ParseNaturalNumber(fields[1], &line)
01317 || !ParseNaturalNumber(fields[2], &index)
01318 || !ParseNaturalNumber(fields[3], &parent_process_id)
01319 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
01320 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
01321 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
01322 GTEST_FLAG(internal_run_death_test));
01323 }
01324 write_fd = GetStatusFileDescriptor(parent_process_id,
01325 write_handle_as_size_t,
01326 event_handle_as_size_t);
01327 # else
01328
01329 if (fields.size() != 4
01330 || !ParseNaturalNumber(fields[1], &line)
01331 || !ParseNaturalNumber(fields[2], &index)
01332 || !ParseNaturalNumber(fields[3], &write_fd)) {
01333 DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
01334 + GTEST_FLAG(internal_run_death_test));
01335 }
01336
01337 # endif // GTEST_OS_WINDOWS
01338
01339 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
01340 }
01341
01342 }
01343
01344 #endif // GTEST_HAS_DEATH_TEST
01345
01346 }