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