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