Debian Codegraph @

src/googletest/src/gtest-death-test.cc

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