gtest-death-test.cc 62 KB

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