gtest-death-test.cc 61 KB

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