/Unittests/googletest/src/gtest-death-test.cc

http://unladen-swallow.googlecode.com/ · C++ · 1174 lines · 747 code · 131 blank · 296 comment · 129 complexity · 3590ad89e01bfb8d15605ffe2250652a MD5 · raw file

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