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 bool StackGrowsDown() {
00989 int dummy;
00990 bool result;
00991 StackLowerThanAddress(&dummy, &result);
00992 return result;
00993 }
00994
00995
00996
00997
00998
00999
01000
01001
01002 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
01003 ExecDeathTestArgs args = { argv, close_fd };
01004 pid_t child_pid = -1;
01005
01006 # if GTEST_OS_QNX
01007
01008
01009 const int cwd_fd = open(".", O_RDONLY);
01010 GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
01011 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
01012
01013
01014
01015 const char* const original_dir =
01016 UnitTest::GetInstance()->original_working_dir();
01017
01018 if (chdir(original_dir) != 0) {
01019 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
01020 GetLastErrnoDescription());
01021 return EXIT_FAILURE;
01022 }
01023
01024 int fd_flags;
01025
01026 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
01027 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
01028 fd_flags | FD_CLOEXEC));
01029 struct inheritance inherit = {0};
01030
01031 child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
01032
01033 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
01034 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
01035
01036 # else // GTEST_OS_QNX
01037 # if GTEST_OS_LINUX
01038
01039
01040
01041 struct sigaction saved_sigprof_action;
01042 struct sigaction ignore_sigprof_action;
01043 memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
01044 sigemptyset(&ignore_sigprof_action.sa_mask);
01045 ignore_sigprof_action.sa_handler = SIG_IGN;
01046 GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
01047 SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
01048 # endif // GTEST_OS_LINUX
01049
01050 # if GTEST_HAS_CLONE
01051 const bool use_fork = GTEST_FLAG(death_test_use_fork);
01052
01053 if (!use_fork) {
01054 static const bool stack_grows_down = StackGrowsDown();
01055 const size_t stack_size = getpagesize();
01056
01057 void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
01058 MAP_ANON | MAP_PRIVATE, -1, 0);
01059 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
01060
01061
01062
01063
01064
01065
01066
01067 const size_t kMaxStackAlignment = 64;
01068 void* const stack_top =
01069 static_cast<char*>(stack) +
01070 (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
01071 GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
01072 reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
01073
01074 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
01075
01076 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
01077 }
01078 # else
01079 const bool use_fork = true;
01080 # endif // GTEST_HAS_CLONE
01081
01082 if (use_fork && (child_pid = fork()) == 0) {
01083 ExecDeathTestChildMain(&args);
01084 _exit(0);
01085 }
01086 # endif // GTEST_OS_QNX
01087 # if GTEST_OS_LINUX
01088 GTEST_DEATH_TEST_CHECK_SYSCALL_(
01089 sigaction(SIGPROF, &saved_sigprof_action, NULL));
01090 # endif // GTEST_OS_LINUX
01091
01092 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
01093 return child_pid;
01094 }
01095
01096
01097
01098
01099
01100 DeathTest::TestRole ExecDeathTest::AssumeRole() {
01101 const UnitTestImpl* const impl = GetUnitTestImpl();
01102 const InternalRunDeathTestFlag* const flag =
01103 impl->internal_run_death_test_flag();
01104 const TestInfo* const info = impl->current_test_info();
01105 const int death_test_index = info->result()->death_test_count();
01106
01107 if (flag != NULL) {
01108 set_write_fd(flag->write_fd());
01109 return EXECUTE_TEST;
01110 }
01111
01112 int pipe_fd[2];
01113 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
01114
01115
01116 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
01117
01118 const std::string filter_flag =
01119 std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
01120 + info->test_case_name() + "." + info->name();
01121 const std::string internal_flag =
01122 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
01123 + file_ + "|" + StreamableToString(line_) + "|"
01124 + StreamableToString(death_test_index) + "|"
01125 + StreamableToString(pipe_fd[1]);
01126 Arguments args;
01127 args.AddArguments(GetArgvsForDeathTestChildProcess());
01128 args.AddArgument(filter_flag.c_str());
01129 args.AddArgument(internal_flag.c_str());
01130
01131 DeathTest::set_last_death_test_message("");
01132
01133 CaptureStderr();
01134
01135
01136 FlushInfoLog();
01137
01138 const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
01139 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
01140 set_child_pid(child_pid);
01141 set_read_fd(pipe_fd[0]);
01142 set_spawned(true);
01143 return OVERSEE_TEST;
01144 }
01145
01146 # endif // !GTEST_OS_WINDOWS
01147
01148
01149
01150
01151
01152
01153 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
01154 const char* file, int line,
01155 DeathTest** test) {
01156 UnitTestImpl* const impl = GetUnitTestImpl();
01157 const InternalRunDeathTestFlag* const flag =
01158 impl->internal_run_death_test_flag();
01159 const int death_test_index = impl->current_test_info()
01160 ->increment_death_test_count();
01161
01162 if (flag != NULL) {
01163 if (death_test_index > flag->index()) {
01164 DeathTest::set_last_death_test_message(
01165 "Death test count (" + StreamableToString(death_test_index)
01166 + ") somehow exceeded expected maximum ("
01167 + StreamableToString(flag->index()) + ")");
01168 return false;
01169 }
01170
01171 if (!(flag->file() == file && flag->line() == line &&
01172 flag->index() == death_test_index)) {
01173 *test = NULL;
01174 return true;
01175 }
01176 }
01177
01178 # if GTEST_OS_WINDOWS
01179
01180 if (GTEST_FLAG(death_test_style) == "threadsafe" ||
01181 GTEST_FLAG(death_test_style) == "fast") {
01182 *test = new WindowsDeathTest(statement, regex, file, line);
01183 }
01184
01185 # else
01186
01187 if (GTEST_FLAG(death_test_style) == "threadsafe") {
01188 *test = new ExecDeathTest(statement, regex, file, line);
01189 } else if (GTEST_FLAG(death_test_style) == "fast") {
01190 *test = new NoExecDeathTest(statement, regex);
01191 }
01192
01193 # endif // GTEST_OS_WINDOWS
01194
01195 else {
01196 DeathTest::set_last_death_test_message(
01197 "Unknown death test style \"" + GTEST_FLAG(death_test_style)
01198 + "\" encountered");
01199 return false;
01200 }
01201
01202 return true;
01203 }
01204
01205
01206
01207
01208 static void SplitString(const ::std::string& str, char delimiter,
01209 ::std::vector< ::std::string>* dest) {
01210 ::std::vector< ::std::string> parsed;
01211 ::std::string::size_type pos = 0;
01212 while (::testing::internal::AlwaysTrue()) {
01213 const ::std::string::size_type colon = str.find(delimiter, pos);
01214 if (colon == ::std::string::npos) {
01215 parsed.push_back(str.substr(pos));
01216 break;
01217 } else {
01218 parsed.push_back(str.substr(pos, colon - pos));
01219 pos = colon + 1;
01220 }
01221 }
01222 dest->swap(parsed);
01223 }
01224
01225 # if GTEST_OS_WINDOWS
01226
01227
01228
01229 int GetStatusFileDescriptor(unsigned int parent_process_id,
01230 size_t write_handle_as_size_t,
01231 size_t event_handle_as_size_t) {
01232 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
01233 FALSE,
01234 parent_process_id));
01235 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
01236 DeathTestAbort("Unable to open parent process " +
01237 StreamableToString(parent_process_id));
01238 }
01239
01240
01241
01242 GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
01243
01244 const HANDLE write_handle =
01245 reinterpret_cast<HANDLE>(write_handle_as_size_t);
01246 HANDLE dup_write_handle;
01247
01248
01249
01250
01251 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
01252 ::GetCurrentProcess(), &dup_write_handle,
01253 0x0,
01254
01255 FALSE,
01256 DUPLICATE_SAME_ACCESS)) {
01257 DeathTestAbort("Unable to duplicate the pipe handle " +
01258 StreamableToString(write_handle_as_size_t) +
01259 " from the parent process " +
01260 StreamableToString(parent_process_id));
01261 }
01262
01263 const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
01264 HANDLE dup_event_handle;
01265
01266 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
01267 ::GetCurrentProcess(), &dup_event_handle,
01268 0x0,
01269 FALSE,
01270 DUPLICATE_SAME_ACCESS)) {
01271 DeathTestAbort("Unable to duplicate the event handle " +
01272 StreamableToString(event_handle_as_size_t) +
01273 " from the parent process " +
01274 StreamableToString(parent_process_id));
01275 }
01276
01277 const int write_fd =
01278 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
01279 if (write_fd == -1) {
01280 DeathTestAbort("Unable to convert pipe handle " +
01281 StreamableToString(write_handle_as_size_t) +
01282 " to a file descriptor");
01283 }
01284
01285
01286
01287 ::SetEvent(dup_event_handle);
01288
01289 return write_fd;
01290 }
01291 # endif // GTEST_OS_WINDOWS
01292
01293
01294
01295
01296 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
01297 if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
01298
01299
01300
01301 int line = -1;
01302 int index = -1;
01303 ::std::vector< ::std::string> fields;
01304 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
01305 int write_fd = -1;
01306
01307 # if GTEST_OS_WINDOWS
01308
01309 unsigned int parent_process_id = 0;
01310 size_t write_handle_as_size_t = 0;
01311 size_t event_handle_as_size_t = 0;
01312
01313 if (fields.size() != 6
01314 || !ParseNaturalNumber(fields[1], &line)
01315 || !ParseNaturalNumber(fields[2], &index)
01316 || !ParseNaturalNumber(fields[3], &parent_process_id)
01317 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
01318 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
01319 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
01320 GTEST_FLAG(internal_run_death_test));
01321 }
01322 write_fd = GetStatusFileDescriptor(parent_process_id,
01323 write_handle_as_size_t,
01324 event_handle_as_size_t);
01325 # else
01326
01327 if (fields.size() != 4
01328 || !ParseNaturalNumber(fields[1], &line)
01329 || !ParseNaturalNumber(fields[2], &index)
01330 || !ParseNaturalNumber(fields[3], &write_fd)) {
01331 DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
01332 + GTEST_FLAG(internal_run_death_test));
01333 }
01334
01335 # endif // GTEST_OS_WINDOWS
01336
01337 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
01338 }
01339
01340 }
01341
01342 #endif // GTEST_HAS_DEATH_TEST
01343
01344 }