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