gtest-death-test.cc 57 KB

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