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