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