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