The source code and dockerfile for the GSW2024 AI Lab.
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.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

1644 lines
61 KiB

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