You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234 lines
45 KiB

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