1 // Copyright 2005, Google Inc. 2 // All rights reserved. 3 // 4 // Redistribution and use in source and binary forms, with or without 5 // modification, are permitted provided that the following conditions are 6 // met: 7 // 8 // * Redistributions of source code must retain the above copyright 9 // notice, this list of conditions and the following disclaimer. 10 // * Redistributions in binary form must reproduce the above 11 // copyright notice, this list of conditions and the following disclaimer 12 // in the documentation and/or other materials provided with the 13 // distribution. 14 // * Neither the name of Google Inc. nor the names of its 15 // contributors may be used to endorse or promote products derived from 16 // this software without specific prior written permission. 17 // 18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 // 30 // Author: wan (at) google.com (Zhanyong Wan), vladl (at) google.com (Vlad Losev) 31 // 32 // This file implements death tests. 33 34 #include "gtest/gtest-death-test.h" 35 #include "gtest/internal/gtest-port.h" 36 #include "gtest/internal/custom/gtest.h" 37 38 #if GTEST_HAS_DEATH_TEST 39 40 # if GTEST_OS_MAC 41 # include <crt_externs.h> 42 # endif // GTEST_OS_MAC 43 44 # include <errno.h> 45 # include <fcntl.h> 46 # include <limits.h> 47 48 # if GTEST_OS_LINUX 49 # include <signal.h> 50 # endif // GTEST_OS_LINUX 51 52 # include <stdarg.h> 53 54 # if GTEST_OS_WINDOWS 55 # include <windows.h> 56 # else 57 # include <sys/mman.h> 58 # include <sys/wait.h> 59 # endif // GTEST_OS_WINDOWS 60 61 # if GTEST_OS_QNX 62 # include <spawn.h> 63 # endif // GTEST_OS_QNX 64 65 #endif // GTEST_HAS_DEATH_TEST 66 67 #include "gtest/gtest-message.h" 68 #include "gtest/internal/gtest-string.h" 69 70 // Indicates that this translation unit is part of Google Test's 71 // implementation. It must come before gtest-internal-inl.h is 72 // included, or there will be a compiler error. This trick exists to 73 // prevent the accidental inclusion of gtest-internal-inl.h in the 74 // user's code. 75 #define GTEST_IMPLEMENTATION_ 1 76 #include "src/gtest-internal-inl.h" 77 #undef GTEST_IMPLEMENTATION_ 78 79 namespace testing { 80 81 // Constants. 82 83 // The default death test style. 84 static const char kDefaultDeathTestStyle[] = "fast"; 85 86 GTEST_DEFINE_string_( 87 death_test_style, 88 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle), 89 "Indicates how to run a death test in a forked child process: " 90 "\"threadsafe\" (child process re-executes the test binary " 91 "from the beginning, running only the specific death test) or " 92 "\"fast\" (child process runs the death test immediately " 93 "after forking)."); 94 95 GTEST_DEFINE_bool_( 96 death_test_use_fork, 97 internal::BoolFromGTestEnv("death_test_use_fork", false), 98 "Instructs to use fork()/_exit() instead of clone() in death tests. " 99 "Ignored and always uses fork() on POSIX systems where clone() is not " 100 "implemented. Useful when running under valgrind or similar tools if " 101 "those do not support clone(). Valgrind 3.3.1 will just fail if " 102 "it sees an unsupported combination of clone() flags. " 103 "It is not recommended to use this flag w/o valgrind though it will " 104 "work in 99% of the cases. Once valgrind is fixed, this flag will " 105 "most likely be removed."); 106 107 namespace internal { 108 GTEST_DEFINE_string_( 109 internal_run_death_test, "", 110 "Indicates the file, line number, temporal index of " 111 "the single death test to run, and a file descriptor to " 112 "which a success code may be sent, all separated by " 113 "the '|' characters. This flag is specified if and only if the current " 114 "process is a sub-process launched for running a thread-safe " 115 "death test. FOR INTERNAL USE ONLY."); 116 } // namespace internal 117 118 #if GTEST_HAS_DEATH_TEST 119 120 namespace internal { 121 122 // Valid only for fast death tests. Indicates the code is running in the 123 // child process of a fast style death test. 124 # if !GTEST_OS_WINDOWS 125 static bool g_in_fast_death_test_child = false; 126 # endif 127 128 // Returns a Boolean value indicating whether the caller is currently 129 // executing in the context of the death test child process. Tools such as 130 // Valgrind heap checkers may need this to modify their behavior in death 131 // tests. IMPORTANT: This is an internal utility. Using it may break the 132 // implementation of death tests. User code MUST NOT use it. 133 bool InDeathTestChild() { 134 # if GTEST_OS_WINDOWS 135 136 // On Windows, death tests are thread-safe regardless of the value of the 137 // death_test_style flag. 138 return !GTEST_FLAG(internal_run_death_test).empty(); 139 140 # else 141 142 if (GTEST_FLAG(death_test_style) == "threadsafe") 143 return !GTEST_FLAG(internal_run_death_test).empty(); 144 else 145 return g_in_fast_death_test_child; 146 #endif 147 } 148 149 } // namespace internal 150 151 // ExitedWithCode constructor. 152 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) { 153 } 154 155 // ExitedWithCode function-call operator. 156 bool ExitedWithCode::operator()(int exit_status) const { 157 # if GTEST_OS_WINDOWS 158 159 return exit_status == exit_code_; 160 161 # else 162 163 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_; 164 165 # endif // GTEST_OS_WINDOWS 166 } 167 168 # if !GTEST_OS_WINDOWS 169 // KilledBySignal constructor. 170 KilledBySignal::KilledBySignal(int signum) : signum_(signum) { 171 } 172 173 // KilledBySignal function-call operator. 174 bool KilledBySignal::operator()(int exit_status) const { 175 # if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) 176 { 177 bool result; 178 if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) { 179 return result; 180 } 181 } 182 # endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) 183 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_; 184 } 185 # endif // !GTEST_OS_WINDOWS 186 187 namespace internal { 188 189 // Utilities needed for death tests. 190 191 // Generates a textual description of a given exit code, in the format 192 // specified by wait(2). 193 static std::string ExitSummary(int exit_code) { 194 Message m; 195 196 # if GTEST_OS_WINDOWS 197 198 m << "Exited with exit status " << exit_code; 199 200 # else 201 202 if (WIFEXITED(exit_code)) { 203 m << "Exited with exit status " << WEXITSTATUS(exit_code); 204 } else if (WIFSIGNALED(exit_code)) { 205 m << "Terminated by signal " << WTERMSIG(exit_code); 206 } 207 # ifdef WCOREDUMP 208 if (WCOREDUMP(exit_code)) { 209 m << " (core dumped)"; 210 } 211 # endif 212 # endif // GTEST_OS_WINDOWS 213 214 return m.GetString(); 215 } 216 217 // Returns true if exit_status describes a process that was terminated 218 // by a signal, or exited normally with a nonzero exit code. 219 bool ExitedUnsuccessfully(int exit_status) { 220 return !ExitedWithCode(0)(exit_status); 221 } 222 223 # if !GTEST_OS_WINDOWS 224 // Generates a textual failure message when a death test finds more than 225 // one thread running, or cannot determine the number of threads, prior 226 // to executing the given statement. It is the responsibility of the 227 // caller not to pass a thread_count of 1. 228 static std::string DeathTestThreadWarning(size_t thread_count) { 229 Message msg; 230 msg << "Death tests use fork(), which is unsafe particularly" 231 << " in a threaded context. For this test, " << GTEST_NAME_ << " "; 232 if (thread_count == 0) 233 msg << "couldn't detect the number of threads."; 234 else 235 msg << "detected " << thread_count << " threads."; 236 return msg.GetString(); 237 } 238 # endif // !GTEST_OS_WINDOWS 239 240 // Flag characters for reporting a death test that did not die. 241 static const char kDeathTestLived = 'L'; 242 static const char kDeathTestReturned = 'R'; 243 static const char kDeathTestThrew = 'T'; 244 static const char kDeathTestInternalError = 'I'; 245 246 // An enumeration describing all of the possible ways that a death test can 247 // conclude. DIED means that the process died while executing the test 248 // code; LIVED means that process lived beyond the end of the test code; 249 // RETURNED means that the test statement attempted to execute a return 250 // statement, which is not allowed; THREW means that the test statement 251 // returned control by throwing an exception. IN_PROGRESS means the test 252 // has not yet concluded. 253 // TODO(vladl (at) google.com): Unify names and possibly values for 254 // AbortReason, DeathTestOutcome, and flag characters above. 255 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW }; 256 257 // Routine for aborting the program which is safe to call from an 258 // exec-style death test child process, in which case the error 259 // message is propagated back to the parent process. Otherwise, the 260 // message is simply printed to stderr. In either case, the program 261 // then exits with status 1. 262 void DeathTestAbort(const std::string& message) { 263 // On a POSIX system, this function may be called from a threadsafe-style 264 // death test child process, which operates on a very small stack. Use 265 // the heap for any additional non-minuscule memory requirements. 266 const InternalRunDeathTestFlag* const flag = 267 GetUnitTestImpl()->internal_run_death_test_flag(); 268 if (flag != NULL) { 269 FILE* parent = posix::FDOpen(flag->write_fd(), "w"); 270 fputc(kDeathTestInternalError, parent); 271 fprintf(parent, "%s", message.c_str()); 272 fflush(parent); 273 _exit(1); 274 } else { 275 fprintf(stderr, "%s", message.c_str()); 276 fflush(stderr); 277 posix::Abort(); 278 } 279 } 280 281 // A replacement for CHECK that calls DeathTestAbort if the assertion 282 // fails. 283 # define GTEST_DEATH_TEST_CHECK_(expression) \ 284 do { \ 285 if (!::testing::internal::IsTrue(expression)) { \ 286 DeathTestAbort( \ 287 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ 288 + ::testing::internal::StreamableToString(__LINE__) + ": " \ 289 + #expression); \ 290 } \ 291 } while (::testing::internal::AlwaysFalse()) 292 293 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for 294 // evaluating any system call that fulfills two conditions: it must return 295 // -1 on failure, and set errno to EINTR when it is interrupted and 296 // should be tried again. The macro expands to a loop that repeatedly 297 // evaluates the expression as long as it evaluates to -1 and sets 298 // errno to EINTR. If the expression evaluates to -1 but errno is 299 // something other than EINTR, DeathTestAbort is called. 300 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ 301 do { \ 302 int gtest_retval; \ 303 do { \ 304 gtest_retval = (expression); \ 305 } while (gtest_retval == -1 && errno == EINTR); \ 306 if (gtest_retval == -1) { \ 307 DeathTestAbort( \ 308 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ 309 + ::testing::internal::StreamableToString(__LINE__) + ": " \ 310 + #expression + " != -1"); \ 311 } \ 312 } while (::testing::internal::AlwaysFalse()) 313 314 // Returns the message describing the last system error in errno. 315 std::string GetLastErrnoDescription() { 316 return errno == 0 ? "" : posix::StrError(errno); 317 } 318 319 // This is called from a death test parent process to read a failure 320 // message from the death test child process and log it with the FATAL 321 // severity. On Windows, the message is read from a pipe handle. On other 322 // platforms, it is read from a file descriptor. 323 static void FailFromInternalError(int fd) { 324 Message error; 325 char buffer[256]; 326 int num_read; 327 328 do { 329 while ((num_read = posix::Read(fd, buffer, 255)) > 0) { 330 buffer[num_read] = '\0'; 331 error << buffer; 332 } 333 } while (num_read == -1 && errno == EINTR); 334 335 if (num_read == 0) { 336 GTEST_LOG_(FATAL) << error.GetString(); 337 } else { 338 const int last_error = errno; 339 GTEST_LOG_(FATAL) << "Error while reading death test internal: " 340 << GetLastErrnoDescription() << " [" << last_error << "]"; 341 } 342 } 343 344 // Death test constructor. Increments the running death test count 345 // for the current test. 346 DeathTest::DeathTest() { 347 TestInfo* const info = GetUnitTestImpl()->current_test_info(); 348 if (info == NULL) { 349 DeathTestAbort("Cannot run a death test outside of a TEST or " 350 "TEST_F construct"); 351 } 352 } 353 354 // Creates and returns a death test by dispatching to the current 355 // death test factory. 356 bool DeathTest::Create(const char* statement, const RE* regex, 357 const char* file, int line, DeathTest** test) { 358 return GetUnitTestImpl()->death_test_factory()->Create( 359 statement, regex, file, line, test); 360 } 361 362 const char* DeathTest::LastMessage() { 363 return last_death_test_message_.c_str(); 364 } 365 366 void DeathTest::set_last_death_test_message(const std::string& message) { 367 last_death_test_message_ = message; 368 } 369 370 std::string DeathTest::last_death_test_message_; 371 372 // Provides cross platform implementation for some death functionality. 373 class DeathTestImpl : public DeathTest { 374 protected: 375 DeathTestImpl(const char* a_statement, const RE* a_regex) 376 : statement_(a_statement), 377 regex_(a_regex), 378 spawned_(false), 379 status_(-1), 380 outcome_(IN_PROGRESS), 381 read_fd_(-1), 382 write_fd_(-1) {} 383 384 // read_fd_ is expected to be closed and cleared by a derived class. 385 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); } 386 387 void Abort(AbortReason reason); 388 virtual bool Passed(bool status_ok); 389 390 const char* statement() const { return statement_; } 391 const RE* regex() const { return regex_; } 392 bool spawned() const { return spawned_; } 393 void set_spawned(bool is_spawned) { spawned_ = is_spawned; } 394 int status() const { return status_; } 395 void set_status(int a_status) { status_ = a_status; } 396 DeathTestOutcome outcome() const { return outcome_; } 397 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; } 398 int read_fd() const { return read_fd_; } 399 void set_read_fd(int fd) { read_fd_ = fd; } 400 int write_fd() const { return write_fd_; } 401 void set_write_fd(int fd) { write_fd_ = fd; } 402 403 // Called in the parent process only. Reads the result code of the death 404 // test child process via a pipe, interprets it to set the outcome_ 405 // member, and closes read_fd_. Outputs diagnostics and terminates in 406 // case of unexpected codes. 407 void ReadAndInterpretStatusByte(); 408 409 private: 410 // The textual content of the code this object is testing. This class 411 // doesn't own this string and should not attempt to delete it. 412 const char* const statement_; 413 // The regular expression which test output must match. DeathTestImpl 414 // doesn't own this object and should not attempt to delete it. 415 const RE* const regex_; 416 // True if the death test child process has been successfully spawned. 417 bool spawned_; 418 // The exit status of the child process. 419 int status_; 420 // How the death test concluded. 421 DeathTestOutcome outcome_; 422 // Descriptor to the read end of the pipe to the child process. It is 423 // always -1 in the child process. The child keeps its write end of the 424 // pipe in write_fd_. 425 int read_fd_; 426 // Descriptor to the child's write end of the pipe to the parent process. 427 // It is always -1 in the parent process. The parent keeps its end of the 428 // pipe in read_fd_. 429 int write_fd_; 430 }; 431 432 // Called in the parent process only. Reads the result code of the death 433 // test child process via a pipe, interprets it to set the outcome_ 434 // member, and closes read_fd_. Outputs diagnostics and terminates in 435 // case of unexpected codes. 436 void DeathTestImpl::ReadAndInterpretStatusByte() { 437 char flag; 438 int bytes_read; 439 440 // The read() here blocks until data is available (signifying the 441 // failure of the death test) or until the pipe is closed (signifying 442 // its success), so it's okay to call this in the parent before 443 // the child process has exited. 444 do { 445 bytes_read = posix::Read(read_fd(), &flag, 1); 446 } while (bytes_read == -1 && errno == EINTR); 447 448 if (bytes_read == 0) { 449 set_outcome(DIED); 450 } else if (bytes_read == 1) { 451 switch (flag) { 452 case kDeathTestReturned: 453 set_outcome(RETURNED); 454 break; 455 case kDeathTestThrew: 456 set_outcome(THREW); 457 break; 458 case kDeathTestLived: 459 set_outcome(LIVED); 460 break; 461 case kDeathTestInternalError: 462 FailFromInternalError(read_fd()); // Does not return. 463 break; 464 default: 465 GTEST_LOG_(FATAL) << "Death test child process reported " 466 << "unexpected status byte (" 467 << static_cast<unsigned int>(flag) << ")"; 468 } 469 } else { 470 GTEST_LOG_(FATAL) << "Read from death test child process failed: " 471 << GetLastErrnoDescription(); 472 } 473 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd())); 474 set_read_fd(-1); 475 } 476 477 // Signals that the death test code which should have exited, didn't. 478 // Should be called only in a death test child process. 479 // Writes a status byte to the child's status file descriptor, then 480 // calls _exit(1). 481 void DeathTestImpl::Abort(AbortReason reason) { 482 // The parent process considers the death test to be a failure if 483 // it finds any data in our pipe. So, here we write a single flag byte 484 // to the pipe, then exit. 485 const char status_ch = 486 reason == TEST_DID_NOT_DIE ? kDeathTestLived : 487 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned; 488 489 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1)); 490 // We are leaking the descriptor here because on some platforms (i.e., 491 // when built as Windows DLL), destructors of global objects will still 492 // run after calling _exit(). On such systems, write_fd_ will be 493 // indirectly closed from the destructor of UnitTestImpl, causing double 494 // close if it is also closed here. On debug configurations, double close 495 // may assert. As there are no in-process buffers to flush here, we are 496 // relying on the OS to close the descriptor after the process terminates 497 // when the destructors are not run. 498 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash) 499 } 500 501 // Returns an indented copy of stderr output for a death test. 502 // This makes distinguishing death test output lines from regular log lines 503 // much easier. 504 static ::std::string FormatDeathTestOutput(const ::std::string& output) { 505 ::std::string ret; 506 for (size_t at = 0; ; ) { 507 const size_t line_end = output.find('\n', at); 508 ret += "[ DEATH ] "; 509 if (line_end == ::std::string::npos) { 510 ret += output.substr(at); 511 break; 512 } 513 ret += output.substr(at, line_end + 1 - at); 514 at = line_end + 1; 515 } 516 return ret; 517 } 518 519 // Assesses the success or failure of a death test, using both private 520 // members which have previously been set, and one argument: 521 // 522 // Private data members: 523 // outcome: An enumeration describing how the death test 524 // concluded: DIED, LIVED, THREW, or RETURNED. The death test 525 // fails in the latter three cases. 526 // status: The exit status of the child process. On *nix, it is in the 527 // in the format specified by wait(2). On Windows, this is the 528 // value supplied to the ExitProcess() API or a numeric code 529 // of the exception that terminated the program. 530 // regex: A regular expression object to be applied to 531 // the test's captured standard error output; the death test 532 // fails if it does not match. 533 // 534 // Argument: 535 // status_ok: true if exit_status is acceptable in the context of 536 // this particular death test, which fails if it is false 537 // 538 // Returns true iff all of the above conditions are met. Otherwise, the 539 // first failing condition, in the order given above, is the one that is 540 // reported. Also sets the last death test message string. 541 bool DeathTestImpl::Passed(bool status_ok) { 542 if (!spawned()) 543 return false; 544 545 const std::string error_message = GetCapturedStderr(); 546 547 bool success = false; 548 Message buffer; 549 550 buffer << "Death test: " << statement() << "\n"; 551 switch (outcome()) { 552 case LIVED: 553 buffer << " Result: failed to die.\n" 554 << " Error msg:\n" << FormatDeathTestOutput(error_message); 555 break; 556 case THREW: 557 buffer << " Result: threw an exception.\n" 558 << " Error msg:\n" << FormatDeathTestOutput(error_message); 559 break; 560 case RETURNED: 561 buffer << " Result: illegal return in test statement.\n" 562 << " Error msg:\n" << FormatDeathTestOutput(error_message); 563 break; 564 case DIED: 565 if (status_ok) { 566 const bool matched = RE::PartialMatch(error_message.c_str(), *regex()); 567 if (matched) { 568 success = true; 569 } else { 570 buffer << " Result: died but not with expected error.\n" 571 << " Expected: " << regex()->pattern() << "\n" 572 << "Actual msg:\n" << FormatDeathTestOutput(error_message); 573 } 574 } else { 575 buffer << " Result: died but not with expected exit code:\n" 576 << " " << ExitSummary(status()) << "\n" 577 << "Actual msg:\n" << FormatDeathTestOutput(error_message); 578 } 579 break; 580 case IN_PROGRESS: 581 default: 582 GTEST_LOG_(FATAL) 583 << "DeathTest::Passed somehow called before conclusion of test"; 584 } 585 586 DeathTest::set_last_death_test_message(buffer.GetString()); 587 return success; 588 } 589 590 # if GTEST_OS_WINDOWS 591 // WindowsDeathTest implements death tests on Windows. Due to the 592 // specifics of starting new processes on Windows, death tests there are 593 // always threadsafe, and Google Test considers the 594 // --gtest_death_test_style=fast setting to be equivalent to 595 // --gtest_death_test_style=threadsafe there. 596 // 597 // A few implementation notes: Like the Linux version, the Windows 598 // implementation uses pipes for child-to-parent communication. But due to 599 // the specifics of pipes on Windows, some extra steps are required: 600 // 601 // 1. The parent creates a communication pipe and stores handles to both 602 // ends of it. 603 // 2. The parent starts the child and provides it with the information 604 // necessary to acquire the handle to the write end of the pipe. 605 // 3. The child acquires the write end of the pipe and signals the parent 606 // using a Windows event. 607 // 4. Now the parent can release the write end of the pipe on its side. If 608 // this is done before step 3, the object's reference count goes down to 609 // 0 and it is destroyed, preventing the child from acquiring it. The 610 // parent now has to release it, or read operations on the read end of 611 // the pipe will not return when the child terminates. 612 // 5. The parent reads child's output through the pipe (outcome code and 613 // any possible error messages) from the pipe, and its stderr and then 614 // determines whether to fail the test. 615 // 616 // Note: to distinguish Win32 API calls from the local method and function 617 // calls, the former are explicitly resolved in the global namespace. 618 // 619 class WindowsDeathTest : public DeathTestImpl { 620 public: 621 WindowsDeathTest(const char* a_statement, 622 const RE* a_regex, 623 const char* file, 624 int line) 625 : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {} 626 627 // All of these virtual functions are inherited from DeathTest. 628 virtual int Wait(); 629 virtual TestRole AssumeRole(); 630 631 private: 632 // The name of the file in which the death test is located. 633 const char* const file_; 634 // The line number on which the death test is located. 635 const int line_; 636 // Handle to the write end of the pipe to the child process. 637 AutoHandle write_handle_; 638 // Child process handle. 639 AutoHandle child_handle_; 640 // Event the child process uses to signal the parent that it has 641 // acquired the handle to the write end of the pipe. After seeing this 642 // event the parent can release its own handles to make sure its 643 // ReadFile() calls return when the child terminates. 644 AutoHandle event_handle_; 645 }; 646 647 // Waits for the child in a death test to exit, returning its exit 648 // status, or 0 if no child process exists. As a side effect, sets the 649 // outcome data member. 650 int WindowsDeathTest::Wait() { 651 if (!spawned()) 652 return 0; 653 654 // Wait until the child either signals that it has acquired the write end 655 // of the pipe or it dies. 656 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() }; 657 switch (::WaitForMultipleObjects(2, 658 wait_handles, 659 FALSE, // Waits for any of the handles. 660 INFINITE)) { 661 case WAIT_OBJECT_0: 662 case WAIT_OBJECT_0 + 1: 663 break; 664 default: 665 GTEST_DEATH_TEST_CHECK_(false); // Should not get here. 666 } 667 668 // The child has acquired the write end of the pipe or exited. 669 // We release the handle on our side and continue. 670 write_handle_.Reset(); 671 event_handle_.Reset(); 672 673 ReadAndInterpretStatusByte(); 674 675 // Waits for the child process to exit if it haven't already. This 676 // returns immediately if the child has already exited, regardless of 677 // whether previous calls to WaitForMultipleObjects synchronized on this 678 // handle or not. 679 GTEST_DEATH_TEST_CHECK_( 680 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(), 681 INFINITE)); 682 DWORD status_code; 683 GTEST_DEATH_TEST_CHECK_( 684 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE); 685 child_handle_.Reset(); 686 set_status(static_cast<int>(status_code)); 687 return status(); 688 } 689 690 // The AssumeRole process for a Windows death test. It creates a child 691 // process with the same executable as the current process to run the 692 // death test. The child process is given the --gtest_filter and 693 // --gtest_internal_run_death_test flags such that it knows to run the 694 // current death test only. 695 DeathTest::TestRole WindowsDeathTest::AssumeRole() { 696 const UnitTestImpl* const impl = GetUnitTestImpl(); 697 const InternalRunDeathTestFlag* const flag = 698 impl->internal_run_death_test_flag(); 699 const TestInfo* const info = impl->current_test_info(); 700 const int death_test_index = info->result()->death_test_count(); 701 702 if (flag != NULL) { 703 // ParseInternalRunDeathTestFlag() has performed all the necessary 704 // processing. 705 set_write_fd(flag->write_fd()); 706 return EXECUTE_TEST; 707 } 708 709 // WindowsDeathTest uses an anonymous pipe to communicate results of 710 // a death test. 711 SECURITY_ATTRIBUTES handles_are_inheritable = { 712 sizeof(SECURITY_ATTRIBUTES), NULL, TRUE }; 713 HANDLE read_handle, write_handle; 714 GTEST_DEATH_TEST_CHECK_( 715 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable, 716 0) // Default buffer size. 717 != FALSE); 718 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle), 719 O_RDONLY)); 720 write_handle_.Reset(write_handle); 721 event_handle_.Reset(::CreateEvent( 722 &handles_are_inheritable, 723 TRUE, // The event will automatically reset to non-signaled state. 724 FALSE, // The initial state is non-signalled. 725 NULL)); // The even is unnamed. 726 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL); 727 const std::string filter_flag = 728 std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" + 729 info->test_case_name() + "." + info->name(); 730 const std::string internal_flag = 731 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + 732 "=" + file_ + "|" + StreamableToString(line_) + "|" + 733 StreamableToString(death_test_index) + "|" + 734 StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) + 735 // size_t has the same width as pointers on both 32-bit and 64-bit 736 // Windows platforms. 737 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. 738 "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) + 739 "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get())); 740 741 char executable_path[_MAX_PATH + 1]; // NOLINT 742 GTEST_DEATH_TEST_CHECK_( 743 _MAX_PATH + 1 != ::GetModuleFileNameA(NULL, 744 executable_path, 745 _MAX_PATH)); 746 747 std::string command_line = 748 std::string(::GetCommandLineA()) + " " + filter_flag + " \"" + 749 internal_flag + "\""; 750 751 DeathTest::set_last_death_test_message(""); 752 753 CaptureStderr(); 754 // Flush the log buffers since the log streams are shared with the child. 755 FlushInfoLog(); 756 757 // The child process will share the standard handles with the parent. 758 STARTUPINFOA startup_info; 759 memset(&startup_info, 0, sizeof(STARTUPINFO)); 760 startup_info.dwFlags = STARTF_USESTDHANDLES; 761 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE); 762 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE); 763 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE); 764 765 PROCESS_INFORMATION process_info; 766 GTEST_DEATH_TEST_CHECK_(::CreateProcessA( 767 executable_path, 768 const_cast<char*>(command_line.c_str()), 769 NULL, // Retuned process handle is not inheritable. 770 NULL, // Retuned thread handle is not inheritable. 771 TRUE, // Child inherits all inheritable handles (for write_handle_). 772 0x0, // Default creation flags. 773 NULL, // Inherit the parent's environment. 774 UnitTest::GetInstance()->original_working_dir(), 775 &startup_info, 776 &process_info) != FALSE); 777 child_handle_.Reset(process_info.hProcess); 778 ::CloseHandle(process_info.hThread); 779 set_spawned(true); 780 return OVERSEE_TEST; 781 } 782 # else // We are not on Windows. 783 784 // ForkingDeathTest provides implementations for most of the abstract 785 // methods of the DeathTest interface. Only the AssumeRole method is 786 // left undefined. 787 class ForkingDeathTest : public DeathTestImpl { 788 public: 789 ForkingDeathTest(const char* statement, const RE* regex); 790 791 // All of these virtual functions are inherited from DeathTest. 792 virtual int Wait(); 793 794 protected: 795 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; } 796 797 private: 798 // PID of child process during death test; 0 in the child process itself. 799 pid_t child_pid_; 800 }; 801 802 // Constructs a ForkingDeathTest. 803 ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex) 804 : DeathTestImpl(a_statement, a_regex), 805 child_pid_(-1) {} 806 807 // Waits for the child in a death test to exit, returning its exit 808 // status, or 0 if no child process exists. As a side effect, sets the 809 // outcome data member. 810 int ForkingDeathTest::Wait() { 811 if (!spawned()) 812 return 0; 813 814 ReadAndInterpretStatusByte(); 815 816 int status_value; 817 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0)); 818 set_status(status_value); 819 return status_value; 820 } 821 822 // A concrete death test class that forks, then immediately runs the test 823 // in the child process. 824 class NoExecDeathTest : public ForkingDeathTest { 825 public: 826 NoExecDeathTest(const char* a_statement, const RE* a_regex) : 827 ForkingDeathTest(a_statement, a_regex) { } 828 virtual TestRole AssumeRole(); 829 }; 830 831 // The AssumeRole process for a fork-and-run death test. It implements a 832 // straightforward fork, with a simple pipe to transmit the status byte. 833 DeathTest::TestRole NoExecDeathTest::AssumeRole() { 834 const size_t thread_count = GetThreadCount(); 835 if (thread_count != 1) { 836 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count); 837 } 838 839 int pipe_fd[2]; 840 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); 841 842 DeathTest::set_last_death_test_message(""); 843 CaptureStderr(); 844 // When we fork the process below, the log file buffers are copied, but the 845 // file descriptors are shared. We flush all log files here so that closing 846 // the file descriptors in the child process doesn't throw off the 847 // synchronization between descriptors and buffers in the parent process. 848 // This is as close to the fork as possible to avoid a race condition in case 849 // there are multiple threads running before the death test, and another 850 // thread writes to the log file. 851 FlushInfoLog(); 852 853 const pid_t child_pid = fork(); 854 GTEST_DEATH_TEST_CHECK_(child_pid != -1); 855 set_child_pid(child_pid); 856 if (child_pid == 0) { 857 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0])); 858 set_write_fd(pipe_fd[1]); 859 // Redirects all logging to stderr in the child process to prevent 860 // concurrent writes to the log files. We capture stderr in the parent 861 // process and append the child process' output to a log. 862 LogToStderr(); 863 // Event forwarding to the listeners of event listener API mush be shut 864 // down in death test subprocesses. 865 GetUnitTestImpl()->listeners()->SuppressEventForwarding(); 866 g_in_fast_death_test_child = true; 867 return EXECUTE_TEST; 868 } else { 869 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); 870 set_read_fd(pipe_fd[0]); 871 set_spawned(true); 872 return OVERSEE_TEST; 873 } 874 } 875 876 // A concrete death test class that forks and re-executes the main 877 // program from the beginning, with command-line flags set that cause 878 // only this specific death test to be run. 879 class ExecDeathTest : public ForkingDeathTest { 880 public: 881 ExecDeathTest(const char* a_statement, const RE* a_regex, 882 const char* file, int line) : 883 ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { } 884 virtual TestRole AssumeRole(); 885 private: 886 static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() { 887 ::std::vector<std::string> args = GetInjectableArgvs(); 888 # if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) 889 ::std::vector<std::string> extra_args = 890 GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_(); 891 args.insert(args.end(), extra_args.begin(), extra_args.end()); 892 # endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) 893 return args; 894 } 895 // The name of the file in which the death test is located. 896 const char* const file_; 897 // The line number on which the death test is located. 898 const int line_; 899 }; 900 901 // Utility class for accumulating command-line arguments. 902 class Arguments { 903 public: 904 Arguments() { 905 args_.push_back(NULL); 906 } 907 908 ~Arguments() { 909 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end(); 910 ++i) { 911 free(*i); 912 } 913 } 914 void AddArgument(const char* argument) { 915 args_.insert(args_.end() - 1, posix::StrDup(argument)); 916 } 917 918 template <typename Str> 919 void AddArguments(const ::std::vector<Str>& arguments) { 920 for (typename ::std::vector<Str>::const_iterator i = arguments.begin(); 921 i != arguments.end(); 922 ++i) { 923 args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); 924 } 925 } 926 char* const* Argv() { 927 return &args_[0]; 928 } 929 930 private: 931 std::vector<char*> args_; 932 }; 933 934 // A struct that encompasses the arguments to the child process of a 935 // threadsafe-style death test process. 936 struct ExecDeathTestArgs { 937 char* const* argv; // Command-line arguments for the child's call to exec 938 int close_fd; // File descriptor to close; the read end of a pipe 939 }; 940 941 # if GTEST_OS_MAC 942 inline char** GetEnviron() { 943 // When Google Test is built as a framework on MacOS X, the environ variable 944 // is unavailable. Apple's documentation (man environ) recommends using 945 // _NSGetEnviron() instead. 946 return *_NSGetEnviron(); 947 } 948 # else 949 // Some POSIX platforms expect you to declare environ. extern "C" makes 950 // it reside in the global namespace. 951 extern "C" char** environ; 952 inline char** GetEnviron() { return environ; } 953 # endif // GTEST_OS_MAC 954 955 # if !GTEST_OS_QNX 956 // The main function for a threadsafe-style death test child process. 957 // This function is called in a clone()-ed process and thus must avoid 958 // any potentially unsafe operations like malloc or libc functions. 959 static int ExecDeathTestChildMain(void* child_arg) { 960 ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg); 961 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd)); 962 963 // We need to execute the test program in the same environment where 964 // it was originally invoked. Therefore we change to the original 965 // working directory first. 966 const char* const original_dir = 967 UnitTest::GetInstance()->original_working_dir(); 968 // We can safely call chdir() as it's a direct system call. 969 if (chdir(original_dir) != 0) { 970 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + 971 GetLastErrnoDescription()); 972 return EXIT_FAILURE; 973 } 974 975 // We can safely call execve() as it's a direct system call. We 976 // cannot use execvp() as it's a libc function and thus potentially 977 // unsafe. Since execve() doesn't search the PATH, the user must 978 // invoke the test program via a valid path that contains at least 979 // one path separator. 980 execve(args->argv[0], args->argv, GetEnviron()); 981 DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " + 982 original_dir + " failed: " + 983 GetLastErrnoDescription()); 984 return EXIT_FAILURE; 985 } 986 # endif // !GTEST_OS_QNX 987 988 // Two utility routines that together determine the direction the stack 989 // grows. 990 // This could be accomplished more elegantly by a single recursive 991 // function, but we want to guard against the unlikely possibility of 992 // a smart compiler optimizing the recursion away. 993 // 994 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining 995 // StackLowerThanAddress into StackGrowsDown, which then doesn't give 996 // correct answer. 997 void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_; 998 void StackLowerThanAddress(const void* ptr, bool* result) { 999 int dummy; 1000 *result = (&dummy < ptr); 1001 } 1002 1003 // Make sure AddressSanitizer does not tamper with the stack here. 1004 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ 1005 bool StackGrowsDown() { 1006 int dummy; 1007 bool result; 1008 StackLowerThanAddress(&dummy, &result); 1009 return result; 1010 } 1011 1012 // Spawns a child process with the same executable as the current process in 1013 // a thread-safe manner and instructs it to run the death test. The 1014 // implementation uses fork(2) + exec. On systems where clone(2) is 1015 // available, it is used instead, being slightly more thread-safe. On QNX, 1016 // fork supports only single-threaded environments, so this function uses 1017 // spawn(2) there instead. The function dies with an error message if 1018 // anything goes wrong. 1019 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { 1020 ExecDeathTestArgs args = { argv, close_fd }; 1021 pid_t child_pid = -1; 1022 1023 # if GTEST_OS_QNX 1024 // Obtains the current directory and sets it to be closed in the child 1025 // process. 1026 const int cwd_fd = open(".", O_RDONLY); 1027 GTEST_DEATH_TEST_CHECK_(cwd_fd != -1); 1028 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC)); 1029 // We need to execute the test program in the same environment where 1030 // it was originally invoked. Therefore we change to the original 1031 // working directory first. 1032 const char* const original_dir = 1033 UnitTest::GetInstance()->original_working_dir(); 1034 // We can safely call chdir() as it's a direct system call. 1035 if (chdir(original_dir) != 0) { 1036 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + 1037 GetLastErrnoDescription()); 1038 return EXIT_FAILURE; 1039 } 1040 1041 int fd_flags; 1042 // Set close_fd to be closed after spawn. 1043 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD)); 1044 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD, 1045 fd_flags | FD_CLOEXEC)); 1046 struct inheritance inherit = {0}; 1047 // spawn is a system call. 1048 child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron()); 1049 // Restores the current working directory. 1050 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1); 1051 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd)); 1052 1053 # else // GTEST_OS_QNX 1054 # if GTEST_OS_LINUX 1055 // When a SIGPROF signal is received while fork() or clone() are executing, 1056 // the process may hang. To avoid this, we ignore SIGPROF here and re-enable 1057 // it after the call to fork()/clone() is complete. 1058 struct sigaction saved_sigprof_action; 1059 struct sigaction ignore_sigprof_action; 1060 memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action)); 1061 sigemptyset(&ignore_sigprof_action.sa_mask); 1062 ignore_sigprof_action.sa_handler = SIG_IGN; 1063 GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction( 1064 SIGPROF, &ignore_sigprof_action, &saved_sigprof_action)); 1065 # endif // GTEST_OS_LINUX 1066 1067 # if GTEST_HAS_CLONE 1068 const bool use_fork = GTEST_FLAG(death_test_use_fork); 1069 1070 if (!use_fork) { 1071 static const bool stack_grows_down = StackGrowsDown(); 1072 const size_t stack_size = getpagesize(); 1073 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead. 1074 void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE, 1075 MAP_ANON | MAP_PRIVATE, -1, 0); 1076 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED); 1077 1078 // Maximum stack alignment in bytes: For a downward-growing stack, this 1079 // amount is subtracted from size of the stack space to get an address 1080 // that is within the stack space and is aligned on all systems we care 1081 // about. As far as I know there is no ABI with stack alignment greater 1082 // than 64. We assume stack and stack_size already have alignment of 1083 // kMaxStackAlignment. 1084 const size_t kMaxStackAlignment = 64; 1085 void* const stack_top = 1086 static_cast<char*>(stack) + 1087 (stack_grows_down ? stack_size - kMaxStackAlignment : 0); 1088 GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment && 1089 reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0); 1090 1091 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args); 1092 1093 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1); 1094 } 1095 # else 1096 const bool use_fork = true; 1097 # endif // GTEST_HAS_CLONE 1098 1099 if (use_fork && (child_pid = fork()) == 0) { 1100 ExecDeathTestChildMain(&args); 1101 _exit(0); 1102 } 1103 # endif // GTEST_OS_QNX 1104 # if GTEST_OS_LINUX 1105 GTEST_DEATH_TEST_CHECK_SYSCALL_( 1106 sigaction(SIGPROF, &saved_sigprof_action, NULL)); 1107 # endif // GTEST_OS_LINUX 1108 1109 GTEST_DEATH_TEST_CHECK_(child_pid != -1); 1110 return child_pid; 1111 } 1112 1113 // The AssumeRole process for a fork-and-exec death test. It re-executes the 1114 // main program from the beginning, setting the --gtest_filter 1115 // and --gtest_internal_run_death_test flags to cause only the current 1116 // death test to be re-run. 1117 DeathTest::TestRole ExecDeathTest::AssumeRole() { 1118 const UnitTestImpl* const impl = GetUnitTestImpl(); 1119 const InternalRunDeathTestFlag* const flag = 1120 impl->internal_run_death_test_flag(); 1121 const TestInfo* const info = impl->current_test_info(); 1122 const int death_test_index = info->result()->death_test_count(); 1123 1124 if (flag != NULL) { 1125 set_write_fd(flag->write_fd()); 1126 return EXECUTE_TEST; 1127 } 1128 1129 int pipe_fd[2]; 1130 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); 1131 // Clear the close-on-exec flag on the write end of the pipe, lest 1132 // it be closed when the child process does an exec: 1133 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1); 1134 1135 const std::string filter_flag = 1136 std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" 1137 + info->test_case_name() + "." + info->name(); 1138 const std::string internal_flag = 1139 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" 1140 + file_ + "|" + StreamableToString(line_) + "|" 1141 + StreamableToString(death_test_index) + "|" 1142 + StreamableToString(pipe_fd[1]); 1143 Arguments args; 1144 args.AddArguments(GetArgvsForDeathTestChildProcess()); 1145 args.AddArgument(filter_flag.c_str()); 1146 args.AddArgument(internal_flag.c_str()); 1147 1148 DeathTest::set_last_death_test_message(""); 1149 1150 CaptureStderr(); 1151 // See the comment in NoExecDeathTest::AssumeRole for why the next line 1152 // is necessary. 1153 FlushInfoLog(); 1154 1155 const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]); 1156 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); 1157 set_child_pid(child_pid); 1158 set_read_fd(pipe_fd[0]); 1159 set_spawned(true); 1160 return OVERSEE_TEST; 1161 } 1162 1163 # endif // !GTEST_OS_WINDOWS 1164 1165 // Creates a concrete DeathTest-derived class that depends on the 1166 // --gtest_death_test_style flag, and sets the pointer pointed to 1167 // by the "test" argument to its address. If the test should be 1168 // skipped, sets that pointer to NULL. Returns true, unless the 1169 // flag is set to an invalid value. 1170 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex, 1171 const char* file, int line, 1172 DeathTest** test) { 1173 UnitTestImpl* const impl = GetUnitTestImpl(); 1174 const InternalRunDeathTestFlag* const flag = 1175 impl->internal_run_death_test_flag(); 1176 const int death_test_index = impl->current_test_info() 1177 ->increment_death_test_count(); 1178 1179 if (flag != NULL) { 1180 if (death_test_index > flag->index()) { 1181 DeathTest::set_last_death_test_message( 1182 "Death test count (" + StreamableToString(death_test_index) 1183 + ") somehow exceeded expected maximum (" 1184 + StreamableToString(flag->index()) + ")"); 1185 return false; 1186 } 1187 1188 if (!(flag->file() == file && flag->line() == line && 1189 flag->index() == death_test_index)) { 1190 *test = NULL; 1191 return true; 1192 } 1193 } 1194 1195 # if GTEST_OS_WINDOWS 1196 1197 if (GTEST_FLAG(death_test_style) == "threadsafe" || 1198 GTEST_FLAG(death_test_style) == "fast") { 1199 *test = new WindowsDeathTest(statement, regex, file, line); 1200 } 1201 1202 # else 1203 1204 if (GTEST_FLAG(death_test_style) == "threadsafe") { 1205 *test = new ExecDeathTest(statement, regex, file, line); 1206 } else if (GTEST_FLAG(death_test_style) == "fast") { 1207 *test = new NoExecDeathTest(statement, regex); 1208 } 1209 1210 # endif // GTEST_OS_WINDOWS 1211 1212 else { // NOLINT - this is more readable than unbalanced brackets inside #if. 1213 DeathTest::set_last_death_test_message( 1214 "Unknown death test style \"" + GTEST_FLAG(death_test_style) 1215 + "\" encountered"); 1216 return false; 1217 } 1218 1219 return true; 1220 } 1221 1222 # if GTEST_OS_WINDOWS 1223 // Recreates the pipe and event handles from the provided parameters, 1224 // signals the event, and returns a file descriptor wrapped around the pipe 1225 // handle. This function is called in the child process only. 1226 int GetStatusFileDescriptor(unsigned int parent_process_id, 1227 size_t write_handle_as_size_t, 1228 size_t event_handle_as_size_t) { 1229 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE, 1230 FALSE, // Non-inheritable. 1231 parent_process_id)); 1232 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) { 1233 DeathTestAbort("Unable to open parent process " + 1234 StreamableToString(parent_process_id)); 1235 } 1236 1237 // TODO(vladl (at) google.com): Replace the following check with a 1238 // compile-time assertion when available. 1239 GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t)); 1240 1241 const HANDLE write_handle = 1242 reinterpret_cast<HANDLE>(write_handle_as_size_t); 1243 HANDLE dup_write_handle; 1244 1245 // The newly initialized handle is accessible only in the parent 1246 // process. To obtain one accessible within the child, we need to use 1247 // DuplicateHandle. 1248 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle, 1249 ::GetCurrentProcess(), &dup_write_handle, 1250 0x0, // Requested privileges ignored since 1251 // DUPLICATE_SAME_ACCESS is used. 1252 FALSE, // Request non-inheritable handler. 1253 DUPLICATE_SAME_ACCESS)) { 1254 DeathTestAbort("Unable to duplicate the pipe handle " + 1255 StreamableToString(write_handle_as_size_t) + 1256 " from the parent process " + 1257 StreamableToString(parent_process_id)); 1258 } 1259 1260 const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t); 1261 HANDLE dup_event_handle; 1262 1263 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle, 1264 ::GetCurrentProcess(), &dup_event_handle, 1265 0x0, 1266 FALSE, 1267 DUPLICATE_SAME_ACCESS)) { 1268 DeathTestAbort("Unable to duplicate the event handle " + 1269 StreamableToString(event_handle_as_size_t) + 1270 " from the parent process " + 1271 StreamableToString(parent_process_id)); 1272 } 1273 1274 const int write_fd = 1275 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND); 1276 if (write_fd == -1) { 1277 DeathTestAbort("Unable to convert pipe handle " + 1278 StreamableToString(write_handle_as_size_t) + 1279 " to a file descriptor"); 1280 } 1281 1282 // Signals the parent that the write end of the pipe has been acquired 1283 // so the parent can release its own write end. 1284 ::SetEvent(dup_event_handle); 1285 1286 return write_fd; 1287 } 1288 # endif // GTEST_OS_WINDOWS 1289 1290 // Returns a newly created InternalRunDeathTestFlag object with fields 1291 // initialized from the GTEST_FLAG(internal_run_death_test) flag if 1292 // the flag is specified; otherwise returns NULL. 1293 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { 1294 if (GTEST_FLAG(internal_run_death_test) == "") return NULL; 1295 1296 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we 1297 // can use it here. 1298 int line = -1; 1299 int index = -1; 1300 ::std::vector< ::std::string> fields; 1301 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields); 1302 int write_fd = -1; 1303 1304 # if GTEST_OS_WINDOWS 1305 1306 unsigned int parent_process_id = 0; 1307 size_t write_handle_as_size_t = 0; 1308 size_t event_handle_as_size_t = 0; 1309 1310 if (fields.size() != 6 1311 || !ParseNaturalNumber(fields[1], &line) 1312 || !ParseNaturalNumber(fields[2], &index) 1313 || !ParseNaturalNumber(fields[3], &parent_process_id) 1314 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t) 1315 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { 1316 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + 1317 GTEST_FLAG(internal_run_death_test)); 1318 } 1319 write_fd = GetStatusFileDescriptor(parent_process_id, 1320 write_handle_as_size_t, 1321 event_handle_as_size_t); 1322 # else 1323 1324 if (fields.size() != 4 1325 || !ParseNaturalNumber(fields[1], &line) 1326 || !ParseNaturalNumber(fields[2], &index) 1327 || !ParseNaturalNumber(fields[3], &write_fd)) { 1328 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " 1329 + GTEST_FLAG(internal_run_death_test)); 1330 } 1331 1332 # endif // GTEST_OS_WINDOWS 1333 1334 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd); 1335 } 1336 1337 } // namespace internal 1338 1339 #endif // GTEST_HAS_DEATH_TEST 1340 1341 } // namespace testing 1342