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