blob: 65893851e2d3c4bd1e60367da72c1a28f49ee5ee [file] [log] [blame]
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001// 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//
Benjamin Kramere4b9c932010-06-02 22:01:25 +000030// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
Misha Brukman7ae6ff42008-12-31 17:34:06 +000031//
32// This file implements death tests.
33
Jay Foadb33f8e32011-07-27 09:25:14 +000034#include "gtest/gtest-death-test.h"
35#include "gtest/internal/gtest-port.h"
Misha Brukman7ae6ff42008-12-31 17:34:06 +000036
Benjamin Kramere4b9c932010-06-02 22:01:25 +000037#if GTEST_HAS_DEATH_TEST
38
Jay Foadb33f8e32011-07-27 09:25:14 +000039# if GTEST_OS_MAC
40# include <crt_externs.h>
41# endif // GTEST_OS_MAC
Benjamin Kramere4b9c932010-06-02 22:01:25 +000042
Jay Foadb33f8e32011-07-27 09:25:14 +000043# include <errno.h>
44# include <fcntl.h>
45# include <limits.h>
46# include <stdarg.h>
Benjamin Kramere4b9c932010-06-02 22:01:25 +000047
Jay Foadb33f8e32011-07-27 09:25:14 +000048# if GTEST_OS_WINDOWS
49# include <windows.h>
50# else
51# include <sys/mman.h>
52# include <sys/wait.h>
53# endif // GTEST_OS_WINDOWS
Benjamin Kramere4b9c932010-06-02 22:01:25 +000054
Misha Brukman7ae6ff42008-12-31 17:34:06 +000055#endif // GTEST_HAS_DEATH_TEST
56
Jay Foadb33f8e32011-07-27 09:25:14 +000057#include "gtest/gtest-message.h"
58#include "gtest/internal/gtest-string.h"
Misha Brukman7ae6ff42008-12-31 17:34:06 +000059
60// Indicates that this translation unit is part of Google Test's
61// implementation. It must come before gtest-internal-inl.h is
62// included, or there will be a compiler error. This trick is to
63// prevent a user from accidentally including gtest-internal-inl.h in
64// his code.
Benjamin Kramere4b9c932010-06-02 22:01:25 +000065#define GTEST_IMPLEMENTATION_ 1
Misha Brukmane5f94712009-01-01 02:05:43 +000066#include "gtest/internal/gtest-internal-inl.h"
Benjamin Kramere4b9c932010-06-02 22:01:25 +000067#undef GTEST_IMPLEMENTATION_
Misha Brukman7ae6ff42008-12-31 17:34:06 +000068
69namespace testing {
70
71// Constants.
72
73// The default death test style.
74static const char kDefaultDeathTestStyle[] = "fast";
75
76GTEST_DEFINE_string_(
77 death_test_style,
78 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
79 "Indicates how to run a death test in a forked child process: "
80 "\"threadsafe\" (child process re-executes the test binary "
81 "from the beginning, running only the specific death test) or "
82 "\"fast\" (child process runs the death test immediately "
83 "after forking).");
84
Benjamin Kramere4b9c932010-06-02 22:01:25 +000085GTEST_DEFINE_bool_(
86 death_test_use_fork,
87 internal::BoolFromGTestEnv("death_test_use_fork", false),
88 "Instructs to use fork()/_exit() instead of clone() in death tests. "
89 "Ignored and always uses fork() on POSIX systems where clone() is not "
90 "implemented. Useful when running under valgrind or similar tools if "
91 "those do not support clone(). Valgrind 3.3.1 will just fail if "
92 "it sees an unsupported combination of clone() flags. "
93 "It is not recommended to use this flag w/o valgrind though it will "
94 "work in 99% of the cases. Once valgrind is fixed, this flag will "
95 "most likely be removed.");
96
Misha Brukman7ae6ff42008-12-31 17:34:06 +000097namespace internal {
98GTEST_DEFINE_string_(
99 internal_run_death_test, "",
100 "Indicates the file, line number, temporal index of "
101 "the single death test to run, and a file descriptor to "
102 "which a success code may be sent, all separated by "
103 "colons. This flag is specified if and only if the current "
104 "process is a sub-process launched for running a thread-safe "
105 "death test. FOR INTERNAL USE ONLY.");
106} // namespace internal
107
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000108#if GTEST_HAS_DEATH_TEST
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000109
110// ExitedWithCode constructor.
111ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
112}
113
114// ExitedWithCode function-call operator.
115bool ExitedWithCode::operator()(int exit_status) const {
Jay Foadb33f8e32011-07-27 09:25:14 +0000116# if GTEST_OS_WINDOWS
117
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000118 return exit_status == exit_code_;
Jay Foadb33f8e32011-07-27 09:25:14 +0000119
120# else
121
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000122 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
Jay Foadb33f8e32011-07-27 09:25:14 +0000123
124# endif // GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000125}
126
Jay Foadb33f8e32011-07-27 09:25:14 +0000127# if !GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000128// KilledBySignal constructor.
129KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
130}
131
132// KilledBySignal function-call operator.
133bool KilledBySignal::operator()(int exit_status) const {
134 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
135}
Jay Foadb33f8e32011-07-27 09:25:14 +0000136# endif // !GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000137
138namespace internal {
139
140// Utilities needed for death tests.
141
142// Generates a textual description of a given exit code, in the format
143// specified by wait(2).
144static String ExitSummary(int exit_code) {
145 Message m;
Jay Foadb33f8e32011-07-27 09:25:14 +0000146
147# if GTEST_OS_WINDOWS
148
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000149 m << "Exited with exit status " << exit_code;
Jay Foadb33f8e32011-07-27 09:25:14 +0000150
151# else
152
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000153 if (WIFEXITED(exit_code)) {
154 m << "Exited with exit status " << WEXITSTATUS(exit_code);
155 } else if (WIFSIGNALED(exit_code)) {
156 m << "Terminated by signal " << WTERMSIG(exit_code);
157 }
Jay Foadb33f8e32011-07-27 09:25:14 +0000158# ifdef WCOREDUMP
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000159 if (WCOREDUMP(exit_code)) {
160 m << " (core dumped)";
161 }
Jay Foadb33f8e32011-07-27 09:25:14 +0000162# endif
163# endif // GTEST_OS_WINDOWS
164
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000165 return m.GetString();
166}
167
168// Returns true if exit_status describes a process that was terminated
169// by a signal, or exited normally with a nonzero exit code.
170bool ExitedUnsuccessfully(int exit_status) {
171 return !ExitedWithCode(0)(exit_status);
172}
173
Jay Foadb33f8e32011-07-27 09:25:14 +0000174# if !GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000175// Generates a textual failure message when a death test finds more than
176// one thread running, or cannot determine the number of threads, prior
177// to executing the given statement. It is the responsibility of the
178// caller not to pass a thread_count of 1.
179static String DeathTestThreadWarning(size_t thread_count) {
180 Message msg;
181 msg << "Death tests use fork(), which is unsafe particularly"
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000182 << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000183 if (thread_count == 0)
184 msg << "couldn't detect the number of threads.";
185 else
186 msg << "detected " << thread_count << " threads.";
187 return msg.GetString();
188}
Jay Foadb33f8e32011-07-27 09:25:14 +0000189# endif // !GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000190
191// Flag characters for reporting a death test that did not die.
192static const char kDeathTestLived = 'L';
193static const char kDeathTestReturned = 'R';
Jay Foadb33f8e32011-07-27 09:25:14 +0000194static const char kDeathTestThrew = 'T';
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000195static const char kDeathTestInternalError = 'I';
196
Jay Foadb33f8e32011-07-27 09:25:14 +0000197// An enumeration describing all of the possible ways that a death test can
198// conclude. DIED means that the process died while executing the test
199// code; LIVED means that process lived beyond the end of the test code;
200// RETURNED means that the test statement attempted to execute a return
201// statement, which is not allowed; THREW means that the test statement
202// returned control by throwing an exception. IN_PROGRESS means the test
203// has not yet concluded.
204// TODO(vladl@google.com): Unify names and possibly values for
205// AbortReason, DeathTestOutcome, and flag characters above.
206enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000207
208// Routine for aborting the program which is safe to call from an
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000209// exec-style death test child process, in which case the error
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000210// message is propagated back to the parent process. Otherwise, the
211// message is simply printed to stderr. In either case, the program
212// then exits with status 1.
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000213void DeathTestAbort(const String& message) {
214 // On a POSIX system, this function may be called from a threadsafe-style
215 // death test child process, which operates on a very small stack. Use
216 // the heap for any additional non-minuscule memory requirements.
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000217 const InternalRunDeathTestFlag* const flag =
218 GetUnitTestImpl()->internal_run_death_test_flag();
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000219 if (flag != NULL) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000220 FILE* parent = posix::FDOpen(flag->write_fd(), "w");
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000221 fputc(kDeathTestInternalError, parent);
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000222 fprintf(parent, "%s", message.c_str());
223 fflush(parent);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000224 _exit(1);
225 } else {
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000226 fprintf(stderr, "%s", message.c_str());
227 fflush(stderr);
Jay Foadb33f8e32011-07-27 09:25:14 +0000228 posix::Abort();
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000229 }
230}
231
232// A replacement for CHECK that calls DeathTestAbort if the assertion
233// fails.
Jay Foadb33f8e32011-07-27 09:25:14 +0000234# define GTEST_DEATH_TEST_CHECK_(expression) \
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000235 do { \
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000236 if (!::testing::internal::IsTrue(expression)) { \
237 DeathTestAbort(::testing::internal::String::Format( \
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000238 "CHECK failed: File %s, line %d: %s", \
239 __FILE__, __LINE__, #expression)); \
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000240 } \
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000241 } while (::testing::internal::AlwaysFalse())
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000242
243// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
244// evaluating any system call that fulfills two conditions: it must return
245// -1 on failure, and set errno to EINTR when it is interrupted and
246// should be tried again. The macro expands to a loop that repeatedly
247// evaluates the expression as long as it evaluates to -1 and sets
248// errno to EINTR. If the expression evaluates to -1 but errno is
249// something other than EINTR, DeathTestAbort is called.
Jay Foadb33f8e32011-07-27 09:25:14 +0000250# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000251 do { \
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000252 int gtest_retval; \
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000253 do { \
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000254 gtest_retval = (expression); \
255 } while (gtest_retval == -1 && errno == EINTR); \
256 if (gtest_retval == -1) { \
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000257 DeathTestAbort(::testing::internal::String::Format( \
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000258 "CHECK failed: File %s, line %d: %s != -1", \
259 __FILE__, __LINE__, #expression)); \
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000260 } \
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000261 } while (::testing::internal::AlwaysFalse())
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000262
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000263// Returns the message describing the last system error in errno.
264String GetLastErrnoDescription() {
265 return String(errno == 0 ? "" : posix::StrError(errno));
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000266}
267
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000268// This is called from a death test parent process to read a failure
269// message from the death test child process and log it with the FATAL
270// severity. On Windows, the message is read from a pipe handle. On other
271// platforms, it is read from a file descriptor.
272static void FailFromInternalError(int fd) {
273 Message error;
274 char buffer[256];
275 int num_read;
276
277 do {
278 while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
279 buffer[num_read] = '\0';
280 error << buffer;
281 }
282 } while (num_read == -1 && errno == EINTR);
283
284 if (num_read == 0) {
285 GTEST_LOG_(FATAL) << error.GetString();
286 } else {
287 const int last_error = errno;
288 GTEST_LOG_(FATAL) << "Error while reading death test internal: "
289 << GetLastErrnoDescription() << " [" << last_error << "]";
290 }
291}
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000292
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000293// Death test constructor. Increments the running death test count
294// for the current test.
295DeathTest::DeathTest() {
296 TestInfo* const info = GetUnitTestImpl()->current_test_info();
297 if (info == NULL) {
298 DeathTestAbort("Cannot run a death test outside of a TEST or "
299 "TEST_F construct");
300 }
301}
302
303// Creates and returns a death test by dispatching to the current
304// death test factory.
305bool DeathTest::Create(const char* statement, const RE* regex,
306 const char* file, int line, DeathTest** test) {
307 return GetUnitTestImpl()->death_test_factory()->Create(
308 statement, regex, file, line, test);
309}
310
311const char* DeathTest::LastMessage() {
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000312 return last_death_test_message_.c_str();
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000313}
314
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000315void DeathTest::set_last_death_test_message(const String& message) {
316 last_death_test_message_ = message;
317}
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000318
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000319String DeathTest::last_death_test_message_;
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000320
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000321// Provides cross platform implementation for some death functionality.
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000322class DeathTestImpl : public DeathTest {
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000323 protected:
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000324 DeathTestImpl(const char* a_statement, const RE* a_regex)
325 : statement_(a_statement),
326 regex_(a_regex),
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000327 spawned_(false),
328 status_(-1),
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000329 outcome_(IN_PROGRESS),
330 read_fd_(-1),
331 write_fd_(-1) {}
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000332
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000333 // read_fd_ is expected to be closed and cleared by a derived class.
334 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
335
336 void Abort(AbortReason reason);
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000337 virtual bool Passed(bool status_ok);
338
339 const char* statement() const { return statement_; }
340 const RE* regex() const { return regex_; }
341 bool spawned() const { return spawned_; }
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000342 void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000343 int status() const { return status_; }
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000344 void set_status(int a_status) { status_ = a_status; }
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000345 DeathTestOutcome outcome() const { return outcome_; }
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000346 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000347 int read_fd() const { return read_fd_; }
348 void set_read_fd(int fd) { read_fd_ = fd; }
349 int write_fd() const { return write_fd_; }
350 void set_write_fd(int fd) { write_fd_ = fd; }
351
352 // Called in the parent process only. Reads the result code of the death
353 // test child process via a pipe, interprets it to set the outcome_
354 // member, and closes read_fd_. Outputs diagnostics and terminates in
355 // case of unexpected codes.
356 void ReadAndInterpretStatusByte();
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000357
358 private:
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000359 // The textual content of the code this object is testing. This class
360 // doesn't own this string and should not attempt to delete it.
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000361 const char* const statement_;
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000362 // The regular expression which test output must match. DeathTestImpl
363 // doesn't own this object and should not attempt to delete it.
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000364 const RE* const regex_;
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000365 // True if the death test child process has been successfully spawned.
366 bool spawned_;
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000367 // The exit status of the child process.
368 int status_;
369 // How the death test concluded.
370 DeathTestOutcome outcome_;
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000371 // Descriptor to the read end of the pipe to the child process. It is
372 // always -1 in the child process. The child keeps its write end of the
373 // pipe in write_fd_.
374 int read_fd_;
375 // Descriptor to the child's write end of the pipe to the parent process.
376 // It is always -1 in the parent process. The parent keeps its end of the
377 // pipe in read_fd_.
378 int write_fd_;
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000379};
380
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000381// Called in the parent process only. Reads the result code of the death
382// test child process via a pipe, interprets it to set the outcome_
383// member, and closes read_fd_. Outputs diagnostics and terminates in
384// case of unexpected codes.
385void DeathTestImpl::ReadAndInterpretStatusByte() {
386 char flag;
387 int bytes_read;
388
389 // The read() here blocks until data is available (signifying the
390 // failure of the death test) or until the pipe is closed (signifying
391 // its success), so it's okay to call this in the parent before
392 // the child process has exited.
393 do {
394 bytes_read = posix::Read(read_fd(), &flag, 1);
395 } while (bytes_read == -1 && errno == EINTR);
396
397 if (bytes_read == 0) {
398 set_outcome(DIED);
399 } else if (bytes_read == 1) {
400 switch (flag) {
401 case kDeathTestReturned:
402 set_outcome(RETURNED);
403 break;
Jay Foadb33f8e32011-07-27 09:25:14 +0000404 case kDeathTestThrew:
405 set_outcome(THREW);
406 break;
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000407 case kDeathTestLived:
408 set_outcome(LIVED);
409 break;
410 case kDeathTestInternalError:
411 FailFromInternalError(read_fd()); // Does not return.
412 break;
413 default:
414 GTEST_LOG_(FATAL) << "Death test child process reported "
415 << "unexpected status byte ("
416 << static_cast<unsigned int>(flag) << ")";
417 }
418 } else {
419 GTEST_LOG_(FATAL) << "Read from death test child process failed: "
420 << GetLastErrnoDescription();
421 }
422 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
423 set_read_fd(-1);
424}
425
426// Signals that the death test code which should have exited, didn't.
427// Should be called only in a death test child process.
428// Writes a status byte to the child's status file descriptor, then
429// calls _exit(1).
430void DeathTestImpl::Abort(AbortReason reason) {
431 // The parent process considers the death test to be a failure if
432 // it finds any data in our pipe. So, here we write a single flag byte
433 // to the pipe, then exit.
434 const char status_ch =
Jay Foadb33f8e32011-07-27 09:25:14 +0000435 reason == TEST_DID_NOT_DIE ? kDeathTestLived :
436 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
437
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000438 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
Jay Foadb33f8e32011-07-27 09:25:14 +0000439 // We are leaking the descriptor here because on some platforms (i.e.,
440 // when built as Windows DLL), destructors of global objects will still
441 // run after calling _exit(). On such systems, write_fd_ will be
442 // indirectly closed from the destructor of UnitTestImpl, causing double
443 // close if it is also closed here. On debug configurations, double close
444 // may assert. As there are no in-process buffers to flush here, we are
445 // relying on the OS to close the descriptor after the process terminates
446 // when the destructors are not run.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000447 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
448}
449
Jay Foadb33f8e32011-07-27 09:25:14 +0000450// Returns an indented copy of stderr output for a death test.
451// This makes distinguishing death test output lines from regular log lines
452// much easier.
453static ::std::string FormatDeathTestOutput(const ::std::string& output) {
454 ::std::string ret;
455 for (size_t at = 0; ; ) {
456 const size_t line_end = output.find('\n', at);
457 ret += "[ DEATH ] ";
458 if (line_end == ::std::string::npos) {
459 ret += output.substr(at);
460 break;
461 }
462 ret += output.substr(at, line_end + 1 - at);
463 at = line_end + 1;
464 }
465 return ret;
466}
467
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000468// Assesses the success or failure of a death test, using both private
469// members which have previously been set, and one argument:
470//
471// Private data members:
472// outcome: An enumeration describing how the death test
Jay Foadb33f8e32011-07-27 09:25:14 +0000473// concluded: DIED, LIVED, THREW, or RETURNED. The death test
474// fails in the latter three cases.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000475// status: The exit status of the child process. On *nix, it is in the
476// in the format specified by wait(2). On Windows, this is the
477// value supplied to the ExitProcess() API or a numeric code
478// of the exception that terminated the program.
479// regex: A regular expression object to be applied to
480// the test's captured standard error output; the death test
481// fails if it does not match.
482//
483// Argument:
484// status_ok: true if exit_status is acceptable in the context of
485// this particular death test, which fails if it is false
486//
487// Returns true iff all of the above conditions are met. Otherwise, the
488// first failing condition, in the order given above, is the one that is
489// reported. Also sets the last death test message string.
490bool DeathTestImpl::Passed(bool status_ok) {
491 if (!spawned())
492 return false;
493
494 const String error_message = GetCapturedStderr();
495
496 bool success = false;
497 Message buffer;
498
499 buffer << "Death test: " << statement() << "\n";
500 switch (outcome()) {
501 case LIVED:
502 buffer << " Result: failed to die.\n"
Jay Foadb33f8e32011-07-27 09:25:14 +0000503 << " Error msg:\n" << FormatDeathTestOutput(error_message);
504 break;
505 case THREW:
506 buffer << " Result: threw an exception.\n"
507 << " Error msg:\n" << FormatDeathTestOutput(error_message);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000508 break;
509 case RETURNED:
510 buffer << " Result: illegal return in test statement.\n"
Jay Foadb33f8e32011-07-27 09:25:14 +0000511 << " Error msg:\n" << FormatDeathTestOutput(error_message);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000512 break;
513 case DIED:
514 if (status_ok) {
515 const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
516 if (matched) {
517 success = true;
518 } else {
519 buffer << " Result: died but not with expected error.\n"
520 << " Expected: " << regex()->pattern() << "\n"
Jay Foadb33f8e32011-07-27 09:25:14 +0000521 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000522 }
523 } else {
524 buffer << " Result: died but not with expected exit code:\n"
Jay Foadb33f8e32011-07-27 09:25:14 +0000525 << " " << ExitSummary(status()) << "\n"
526 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000527 }
528 break;
529 case IN_PROGRESS:
530 default:
531 GTEST_LOG_(FATAL)
532 << "DeathTest::Passed somehow called before conclusion of test";
533 }
534
535 DeathTest::set_last_death_test_message(buffer.GetString());
536 return success;
537}
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000538
Jay Foadb33f8e32011-07-27 09:25:14 +0000539# if GTEST_OS_WINDOWS
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000540// WindowsDeathTest implements death tests on Windows. Due to the
541// specifics of starting new processes on Windows, death tests there are
542// always threadsafe, and Google Test considers the
543// --gtest_death_test_style=fast setting to be equivalent to
544// --gtest_death_test_style=threadsafe there.
545//
546// A few implementation notes: Like the Linux version, the Windows
547// implementation uses pipes for child-to-parent communication. But due to
548// the specifics of pipes on Windows, some extra steps are required:
549//
550// 1. The parent creates a communication pipe and stores handles to both
551// ends of it.
552// 2. The parent starts the child and provides it with the information
553// necessary to acquire the handle to the write end of the pipe.
554// 3. The child acquires the write end of the pipe and signals the parent
555// using a Windows event.
556// 4. Now the parent can release the write end of the pipe on its side. If
557// this is done before step 3, the object's reference count goes down to
558// 0 and it is destroyed, preventing the child from acquiring it. The
559// parent now has to release it, or read operations on the read end of
560// the pipe will not return when the child terminates.
561// 5. The parent reads child's output through the pipe (outcome code and
562// any possible error messages) from the pipe, and its stderr and then
563// determines whether to fail the test.
564//
565// Note: to distinguish Win32 API calls from the local method and function
566// calls, the former are explicitly resolved in the global namespace.
567//
568class WindowsDeathTest : public DeathTestImpl {
569 public:
Jay Foadb33f8e32011-07-27 09:25:14 +0000570 WindowsDeathTest(const char* a_statement,
571 const RE* a_regex,
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000572 const char* file,
573 int line)
Jay Foadb33f8e32011-07-27 09:25:14 +0000574 : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000575
576 // All of these virtual functions are inherited from DeathTest.
577 virtual int Wait();
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000578 virtual TestRole AssumeRole();
579
580 private:
581 // The name of the file in which the death test is located.
582 const char* const file_;
583 // The line number on which the death test is located.
584 const int line_;
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000585 // Handle to the write end of the pipe to the child process.
586 AutoHandle write_handle_;
587 // Child process handle.
588 AutoHandle child_handle_;
589 // Event the child process uses to signal the parent that it has
590 // acquired the handle to the write end of the pipe. After seeing this
591 // event the parent can release its own handles to make sure its
592 // ReadFile() calls return when the child terminates.
593 AutoHandle event_handle_;
594};
595
596// Waits for the child in a death test to exit, returning its exit
597// status, or 0 if no child process exists. As a side effect, sets the
598// outcome data member.
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000599int WindowsDeathTest::Wait() {
600 if (!spawned())
601 return 0;
602
603 // Wait until the child either signals that it has acquired the write end
604 // of the pipe or it dies.
605 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
606 switch (::WaitForMultipleObjects(2,
607 wait_handles,
608 FALSE, // Waits for any of the handles.
609 INFINITE)) {
610 case WAIT_OBJECT_0:
611 case WAIT_OBJECT_0 + 1:
612 break;
613 default:
614 GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
615 }
616
617 // The child has acquired the write end of the pipe or exited.
618 // We release the handle on our side and continue.
619 write_handle_.Reset();
620 event_handle_.Reset();
621
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000622 ReadAndInterpretStatusByte();
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000623
624 // Waits for the child process to exit if it haven't already. This
625 // returns immediately if the child has already exited, regardless of
626 // whether previous calls to WaitForMultipleObjects synchronized on this
627 // handle or not.
628 GTEST_DEATH_TEST_CHECK_(
629 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
630 INFINITE));
Jay Foadb33f8e32011-07-27 09:25:14 +0000631 DWORD status_code;
632 GTEST_DEATH_TEST_CHECK_(
633 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000634 child_handle_.Reset();
Jay Foadb33f8e32011-07-27 09:25:14 +0000635 set_status(static_cast<int>(status_code));
636 return status();
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000637}
638
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000639// The AssumeRole process for a Windows death test. It creates a child
640// process with the same executable as the current process to run the
641// death test. The child process is given the --gtest_filter and
642// --gtest_internal_run_death_test flags such that it knows to run the
643// current death test only.
644DeathTest::TestRole WindowsDeathTest::AssumeRole() {
645 const UnitTestImpl* const impl = GetUnitTestImpl();
646 const InternalRunDeathTestFlag* const flag =
647 impl->internal_run_death_test_flag();
648 const TestInfo* const info = impl->current_test_info();
649 const int death_test_index = info->result()->death_test_count();
650
651 if (flag != NULL) {
652 // ParseInternalRunDeathTestFlag() has performed all the necessary
653 // processing.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000654 set_write_fd(flag->write_fd());
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000655 return EXECUTE_TEST;
656 }
657
658 // WindowsDeathTest uses an anonymous pipe to communicate results of
659 // a death test.
660 SECURITY_ATTRIBUTES handles_are_inheritable = {
661 sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
662 HANDLE read_handle, write_handle;
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000663 GTEST_DEATH_TEST_CHECK_(
664 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
665 0) // Default buffer size.
666 != FALSE);
667 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
668 O_RDONLY));
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000669 write_handle_.Reset(write_handle);
670 event_handle_.Reset(::CreateEvent(
671 &handles_are_inheritable,
672 TRUE, // The event will automatically reset to non-signaled state.
673 FALSE, // The initial state is non-signalled.
674 NULL)); // The even is unnamed.
675 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
676 const String filter_flag = String::Format("--%s%s=%s.%s",
677 GTEST_FLAG_PREFIX_, kFilterFlag,
678 info->test_case_name(),
679 info->name());
680 const String internal_flag = String::Format(
681 "--%s%s=%s|%d|%d|%u|%Iu|%Iu",
682 GTEST_FLAG_PREFIX_,
683 kInternalRunDeathTestFlag,
684 file_, line_,
685 death_test_index,
686 static_cast<unsigned int>(::GetCurrentProcessId()),
687 // size_t has the same with as pointers on both 32-bit and 64-bit
688 // Windows platforms.
689 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
690 reinterpret_cast<size_t>(write_handle),
691 reinterpret_cast<size_t>(event_handle_.Get()));
692
693 char executable_path[_MAX_PATH + 1]; // NOLINT
694 GTEST_DEATH_TEST_CHECK_(
695 _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
696 executable_path,
697 _MAX_PATH));
698
699 String command_line = String::Format("%s %s \"%s\"",
700 ::GetCommandLineA(),
701 filter_flag.c_str(),
702 internal_flag.c_str());
703
704 DeathTest::set_last_death_test_message("");
705
706 CaptureStderr();
707 // Flush the log buffers since the log streams are shared with the child.
708 FlushInfoLog();
709
710 // The child process will share the standard handles with the parent.
711 STARTUPINFOA startup_info;
712 memset(&startup_info, 0, sizeof(STARTUPINFO));
713 startup_info.dwFlags = STARTF_USESTDHANDLES;
714 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
715 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
716 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
717
718 PROCESS_INFORMATION process_info;
719 GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
720 executable_path,
721 const_cast<char*>(command_line.c_str()),
722 NULL, // Retuned process handle is not inheritable.
723 NULL, // Retuned thread handle is not inheritable.
724 TRUE, // Child inherits all inheritable handles (for write_handle_).
725 0x0, // Default creation flags.
726 NULL, // Inherit the parent's environment.
727 UnitTest::GetInstance()->original_working_dir(),
728 &startup_info,
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000729 &process_info) != FALSE);
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000730 child_handle_.Reset(process_info.hProcess);
731 ::CloseHandle(process_info.hThread);
732 set_spawned(true);
733 return OVERSEE_TEST;
734}
Jay Foadb33f8e32011-07-27 09:25:14 +0000735# else // We are not on Windows.
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000736
737// ForkingDeathTest provides implementations for most of the abstract
738// methods of the DeathTest interface. Only the AssumeRole method is
739// left undefined.
740class ForkingDeathTest : public DeathTestImpl {
741 public:
742 ForkingDeathTest(const char* statement, const RE* regex);
743
744 // All of these virtual functions are inherited from DeathTest.
745 virtual int Wait();
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000746
747 protected:
748 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000749
750 private:
751 // PID of child process during death test; 0 in the child process itself.
752 pid_t child_pid_;
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000753};
754
755// Constructs a ForkingDeathTest.
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000756ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
757 : DeathTestImpl(a_statement, a_regex),
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000758 child_pid_(-1) {}
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000759
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000760// Waits for the child in a death test to exit, returning its exit
761// status, or 0 if no child process exists. As a side effect, sets the
762// outcome data member.
763int ForkingDeathTest::Wait() {
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000764 if (!spawned())
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000765 return 0;
766
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000767 ReadAndInterpretStatusByte();
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000768
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000769 int status_value;
770 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
771 set_status(status_value);
772 return status_value;
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000773}
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000774
775// A concrete death test class that forks, then immediately runs the test
776// in the child process.
777class NoExecDeathTest : public ForkingDeathTest {
778 public:
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000779 NoExecDeathTest(const char* a_statement, const RE* a_regex) :
780 ForkingDeathTest(a_statement, a_regex) { }
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000781 virtual TestRole AssumeRole();
782};
783
784// The AssumeRole process for a fork-and-run death test. It implements a
785// straightforward fork, with a simple pipe to transmit the status byte.
786DeathTest::TestRole NoExecDeathTest::AssumeRole() {
787 const size_t thread_count = GetThreadCount();
788 if (thread_count != 1) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000789 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000790 }
791
792 int pipe_fd[2];
793 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
794
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000795 DeathTest::set_last_death_test_message("");
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000796 CaptureStderr();
797 // When we fork the process below, the log file buffers are copied, but the
798 // file descriptors are shared. We flush all log files here so that closing
799 // the file descriptors in the child process doesn't throw off the
800 // synchronization between descriptors and buffers in the parent process.
801 // This is as close to the fork as possible to avoid a race condition in case
802 // there are multiple threads running before the death test, and another
803 // thread writes to the log file.
804 FlushInfoLog();
805
806 const pid_t child_pid = fork();
807 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
808 set_child_pid(child_pid);
809 if (child_pid == 0) {
810 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
811 set_write_fd(pipe_fd[1]);
812 // Redirects all logging to stderr in the child process to prevent
813 // concurrent writes to the log files. We capture stderr in the parent
814 // process and append the child process' output to a log.
815 LogToStderr();
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000816 // Event forwarding to the listeners of event listener API mush be shut
817 // down in death test subprocesses.
818 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000819 return EXECUTE_TEST;
820 } else {
821 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
822 set_read_fd(pipe_fd[0]);
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000823 set_spawned(true);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000824 return OVERSEE_TEST;
825 }
826}
827
828// A concrete death test class that forks and re-executes the main
829// program from the beginning, with command-line flags set that cause
830// only this specific death test to be run.
831class ExecDeathTest : public ForkingDeathTest {
832 public:
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000833 ExecDeathTest(const char* a_statement, const RE* a_regex,
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000834 const char* file, int line) :
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000835 ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000836 virtual TestRole AssumeRole();
837 private:
838 // The name of the file in which the death test is located.
839 const char* const file_;
840 // The line number on which the death test is located.
841 const int line_;
842};
843
844// Utility class for accumulating command-line arguments.
845class Arguments {
846 public:
847 Arguments() {
848 args_.push_back(NULL);
849 }
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000850
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000851 ~Arguments() {
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000852 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000853 ++i) {
854 free(*i);
855 }
856 }
857 void AddArgument(const char* argument) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000858 args_.insert(args_.end() - 1, posix::StrDup(argument));
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000859 }
860
861 template <typename Str>
862 void AddArguments(const ::std::vector<Str>& arguments) {
863 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
864 i != arguments.end();
865 ++i) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000866 args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000867 }
868 }
869 char* const* Argv() {
870 return &args_[0];
871 }
872 private:
873 std::vector<char*> args_;
874};
875
876// A struct that encompasses the arguments to the child process of a
877// threadsafe-style death test process.
878struct ExecDeathTestArgs {
879 char* const* argv; // Command-line arguments for the child's call to exec
880 int close_fd; // File descriptor to close; the read end of a pipe
881};
882
Jay Foadb33f8e32011-07-27 09:25:14 +0000883# if GTEST_OS_MAC
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000884inline char** GetEnviron() {
885 // When Google Test is built as a framework on MacOS X, the environ variable
886 // is unavailable. Apple's documentation (man environ) recommends using
887 // _NSGetEnviron() instead.
888 return *_NSGetEnviron();
889}
Jay Foadb33f8e32011-07-27 09:25:14 +0000890# else
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000891// Some POSIX platforms expect you to declare environ. extern "C" makes
892// it reside in the global namespace.
893extern "C" char** environ;
894inline char** GetEnviron() { return environ; }
Jay Foadb33f8e32011-07-27 09:25:14 +0000895# endif // GTEST_OS_MAC
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000896
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000897// The main function for a threadsafe-style death test child process.
898// This function is called in a clone()-ed process and thus must avoid
899// any potentially unsafe operations like malloc or libc functions.
900static int ExecDeathTestChildMain(void* child_arg) {
901 ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
902 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
903
904 // We need to execute the test program in the same environment where
905 // it was originally invoked. Therefore we change to the original
906 // working directory first.
907 const char* const original_dir =
908 UnitTest::GetInstance()->original_working_dir();
909 // We can safely call chdir() as it's a direct system call.
910 if (chdir(original_dir) != 0) {
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000911 DeathTestAbort(String::Format("chdir(\"%s\") failed: %s",
912 original_dir,
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000913 GetLastErrnoDescription().c_str()));
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000914 return EXIT_FAILURE;
915 }
916
917 // We can safely call execve() as it's a direct system call. We
918 // cannot use execvp() as it's a libc function and thus potentially
919 // unsafe. Since execve() doesn't search the PATH, the user must
920 // invoke the test program via a valid path that contains at least
921 // one path separator.
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000922 execve(args->argv[0], args->argv, GetEnviron());
923 DeathTestAbort(String::Format("execve(%s, ...) in %s failed: %s",
924 args->argv[0],
925 original_dir,
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000926 GetLastErrnoDescription().c_str()));
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000927 return EXIT_FAILURE;
928}
929
930// Two utility routines that together determine the direction the stack
931// grows.
932// This could be accomplished more elegantly by a single recursive
933// function, but we want to guard against the unlikely possibility of
934// a smart compiler optimizing the recursion away.
Jay Foadb33f8e32011-07-27 09:25:14 +0000935//
936// GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
937// StackLowerThanAddress into StackGrowsDown, which then doesn't give
938// correct answer.
939bool StackLowerThanAddress(const void* ptr) GTEST_NO_INLINE_;
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000940bool StackLowerThanAddress(const void* ptr) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000941 int dummy;
942 return &dummy < ptr;
943}
944
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000945bool StackGrowsDown() {
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000946 int dummy;
947 return StackLowerThanAddress(&dummy);
948}
949
950// A threadsafe implementation of fork(2) for threadsafe-style death tests
951// that uses clone(2). It dies with an error message if anything goes
952// wrong.
953static pid_t ExecDeathTestFork(char* const* argv, int close_fd) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000954 ExecDeathTestArgs args = { argv, close_fd };
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000955 pid_t child_pid = -1;
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000956
Jay Foadb33f8e32011-07-27 09:25:14 +0000957# if GTEST_HAS_CLONE
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000958 const bool use_fork = GTEST_FLAG(death_test_use_fork);
959
960 if (!use_fork) {
961 static const bool stack_grows_down = StackGrowsDown();
962 const size_t stack_size = getpagesize();
963 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
964 void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
965 MAP_ANON | MAP_PRIVATE, -1, 0);
966 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
967 void* const stack_top =
968 static_cast<char*>(stack) + (stack_grows_down ? stack_size : 0);
969
970 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
971
972 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
973 }
Jay Foadb33f8e32011-07-27 09:25:14 +0000974# else
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000975 const bool use_fork = true;
Jay Foadb33f8e32011-07-27 09:25:14 +0000976# endif // GTEST_HAS_CLONE
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000977
978 if (use_fork && (child_pid = fork()) == 0) {
979 ExecDeathTestChildMain(&args);
980 _exit(0);
981 }
982
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000983 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000984 return child_pid;
985}
986
987// The AssumeRole process for a fork-and-exec death test. It re-executes the
988// main program from the beginning, setting the --gtest_filter
989// and --gtest_internal_run_death_test flags to cause only the current
990// death test to be re-run.
991DeathTest::TestRole ExecDeathTest::AssumeRole() {
992 const UnitTestImpl* const impl = GetUnitTestImpl();
993 const InternalRunDeathTestFlag* const flag =
994 impl->internal_run_death_test_flag();
995 const TestInfo* const info = impl->current_test_info();
996 const int death_test_index = info->result()->death_test_count();
997
998 if (flag != NULL) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000999 set_write_fd(flag->write_fd());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001000 return EXECUTE_TEST;
1001 }
1002
1003 int pipe_fd[2];
1004 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
1005 // Clear the close-on-exec flag on the write end of the pipe, lest
1006 // it be closed when the child process does an exec:
1007 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
1008
1009 const String filter_flag =
1010 String::Format("--%s%s=%s.%s",
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001011 GTEST_FLAG_PREFIX_, kFilterFlag,
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001012 info->test_case_name(), info->name());
1013 const String internal_flag =
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001014 String::Format("--%s%s=%s|%d|%d|%d",
1015 GTEST_FLAG_PREFIX_, kInternalRunDeathTestFlag,
1016 file_, line_, death_test_index, pipe_fd[1]);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001017 Arguments args;
1018 args.AddArguments(GetArgvs());
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001019 args.AddArgument(filter_flag.c_str());
1020 args.AddArgument(internal_flag.c_str());
1021
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001022 DeathTest::set_last_death_test_message("");
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001023
1024 CaptureStderr();
1025 // See the comment in NoExecDeathTest::AssumeRole for why the next line
1026 // is necessary.
1027 FlushInfoLog();
1028
1029 const pid_t child_pid = ExecDeathTestFork(args.Argv(), pipe_fd[0]);
1030 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
1031 set_child_pid(child_pid);
1032 set_read_fd(pipe_fd[0]);
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001033 set_spawned(true);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001034 return OVERSEE_TEST;
1035}
1036
Jay Foadb33f8e32011-07-27 09:25:14 +00001037# endif // !GTEST_OS_WINDOWS
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001038
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001039// Creates a concrete DeathTest-derived class that depends on the
1040// --gtest_death_test_style flag, and sets the pointer pointed to
1041// by the "test" argument to its address. If the test should be
1042// skipped, sets that pointer to NULL. Returns true, unless the
1043// flag is set to an invalid value.
1044bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
1045 const char* file, int line,
1046 DeathTest** test) {
1047 UnitTestImpl* const impl = GetUnitTestImpl();
1048 const InternalRunDeathTestFlag* const flag =
1049 impl->internal_run_death_test_flag();
1050 const int death_test_index = impl->current_test_info()
1051 ->increment_death_test_count();
1052
1053 if (flag != NULL) {
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001054 if (death_test_index > flag->index()) {
1055 DeathTest::set_last_death_test_message(String::Format(
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001056 "Death test count (%d) somehow exceeded expected maximum (%d)",
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001057 death_test_index, flag->index()));
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001058 return false;
1059 }
1060
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001061 if (!(flag->file() == file && flag->line() == line &&
1062 flag->index() == death_test_index)) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001063 *test = NULL;
1064 return true;
1065 }
1066 }
1067
Jay Foadb33f8e32011-07-27 09:25:14 +00001068# if GTEST_OS_WINDOWS
1069
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001070 if (GTEST_FLAG(death_test_style) == "threadsafe" ||
1071 GTEST_FLAG(death_test_style) == "fast") {
1072 *test = new WindowsDeathTest(statement, regex, file, line);
1073 }
Jay Foadb33f8e32011-07-27 09:25:14 +00001074
1075# else
1076
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001077 if (GTEST_FLAG(death_test_style) == "threadsafe") {
1078 *test = new ExecDeathTest(statement, regex, file, line);
1079 } else if (GTEST_FLAG(death_test_style) == "fast") {
1080 *test = new NoExecDeathTest(statement, regex);
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001081 }
Jay Foadb33f8e32011-07-27 09:25:14 +00001082
1083# endif // GTEST_OS_WINDOWS
1084
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001085 else { // NOLINT - this is more readable than unbalanced brackets inside #if.
1086 DeathTest::set_last_death_test_message(String::Format(
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001087 "Unknown death test style \"%s\" encountered",
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001088 GTEST_FLAG(death_test_style).c_str()));
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001089 return false;
1090 }
1091
1092 return true;
1093}
1094
1095// Splits a given string on a given delimiter, populating a given
1096// vector with the fields. GTEST_HAS_DEATH_TEST implies that we have
1097// ::std::string, so we can use it here.
1098static void SplitString(const ::std::string& str, char delimiter,
1099 ::std::vector< ::std::string>* dest) {
1100 ::std::vector< ::std::string> parsed;
1101 ::std::string::size_type pos = 0;
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001102 while (::testing::internal::AlwaysTrue()) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001103 const ::std::string::size_type colon = str.find(delimiter, pos);
1104 if (colon == ::std::string::npos) {
1105 parsed.push_back(str.substr(pos));
1106 break;
1107 } else {
1108 parsed.push_back(str.substr(pos, colon - pos));
1109 pos = colon + 1;
1110 }
1111 }
1112 dest->swap(parsed);
1113}
1114
Jay Foadb33f8e32011-07-27 09:25:14 +00001115# if GTEST_OS_WINDOWS
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001116// Recreates the pipe and event handles from the provided parameters,
1117// signals the event, and returns a file descriptor wrapped around the pipe
1118// handle. This function is called in the child process only.
1119int GetStatusFileDescriptor(unsigned int parent_process_id,
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001120 size_t write_handle_as_size_t,
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001121 size_t event_handle_as_size_t) {
1122 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
1123 FALSE, // Non-inheritable.
1124 parent_process_id));
1125 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
1126 DeathTestAbort(String::Format("Unable to open parent process %u",
1127 parent_process_id));
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001128 }
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001129
1130 // TODO(vladl@google.com): Replace the following check with a
1131 // compile-time assertion when available.
1132 GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
1133
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001134 const HANDLE write_handle =
1135 reinterpret_cast<HANDLE>(write_handle_as_size_t);
1136 HANDLE dup_write_handle;
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001137
1138 // The newly initialized handle is accessible only in in the parent
1139 // process. To obtain one accessible within the child, we need to use
1140 // DuplicateHandle.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001141 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
1142 ::GetCurrentProcess(), &dup_write_handle,
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001143 0x0, // Requested privileges ignored since
1144 // DUPLICATE_SAME_ACCESS is used.
1145 FALSE, // Request non-inheritable handler.
1146 DUPLICATE_SAME_ACCESS)) {
1147 DeathTestAbort(String::Format(
1148 "Unable to duplicate the pipe handle %Iu from the parent process %u",
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001149 write_handle_as_size_t, parent_process_id));
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001150 }
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001151
1152 const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
1153 HANDLE dup_event_handle;
1154
1155 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
1156 ::GetCurrentProcess(), &dup_event_handle,
1157 0x0,
1158 FALSE,
1159 DUPLICATE_SAME_ACCESS)) {
1160 DeathTestAbort(String::Format(
1161 "Unable to duplicate the event handle %Iu from the parent process %u",
1162 event_handle_as_size_t, parent_process_id));
1163 }
1164
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001165 const int write_fd =
1166 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
1167 if (write_fd == -1) {
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001168 DeathTestAbort(String::Format(
1169 "Unable to convert pipe handle %Iu to a file descriptor",
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001170 write_handle_as_size_t));
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001171 }
1172
1173 // Signals the parent that the write end of the pipe has been acquired
1174 // so the parent can release its own write end.
1175 ::SetEvent(dup_event_handle);
1176
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001177 return write_fd;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001178}
Jay Foadb33f8e32011-07-27 09:25:14 +00001179# endif // GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001180
1181// Returns a newly created InternalRunDeathTestFlag object with fields
1182// initialized from the GTEST_FLAG(internal_run_death_test) flag if
1183// the flag is specified; otherwise returns NULL.
1184InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
1185 if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
1186
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001187 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
1188 // can use it here.
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001189 int line = -1;
1190 int index = -1;
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001191 ::std::vector< ::std::string> fields;
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001192 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001193 int write_fd = -1;
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001194
Jay Foadb33f8e32011-07-27 09:25:14 +00001195# if GTEST_OS_WINDOWS
1196
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001197 unsigned int parent_process_id = 0;
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001198 size_t write_handle_as_size_t = 0;
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001199 size_t event_handle_as_size_t = 0;
1200
1201 if (fields.size() != 6
1202 || !ParseNaturalNumber(fields[1], &line)
1203 || !ParseNaturalNumber(fields[2], &index)
1204 || !ParseNaturalNumber(fields[3], &parent_process_id)
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001205 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001206 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
1207 DeathTestAbort(String::Format(
1208 "Bad --gtest_internal_run_death_test flag: %s",
1209 GTEST_FLAG(internal_run_death_test).c_str()));
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001210 }
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001211 write_fd = GetStatusFileDescriptor(parent_process_id,
1212 write_handle_as_size_t,
1213 event_handle_as_size_t);
Jay Foadb33f8e32011-07-27 09:25:14 +00001214# else
1215
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001216 if (fields.size() != 4
1217 || !ParseNaturalNumber(fields[1], &line)
1218 || !ParseNaturalNumber(fields[2], &index)
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001219 || !ParseNaturalNumber(fields[3], &write_fd)) {
Benjamin Kramere4b9c932010-06-02 22:01:25 +00001220 DeathTestAbort(String::Format(
1221 "Bad --gtest_internal_run_death_test flag: %s",
1222 GTEST_FLAG(internal_run_death_test).c_str()));
1223 }
Jay Foadb33f8e32011-07-27 09:25:14 +00001224
1225# endif // GTEST_OS_WINDOWS
1226
Benjamin Kramer190f8ee2010-06-02 22:02:11 +00001227 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001228}
1229
1230} // namespace internal
1231
1232#endif // GTEST_HAS_DEATH_TEST
1233
1234} // namespace testing