]>
Commit | Line | Data |
---|---|---|
223e47cc LB |
1 | // Copyright 2005, Google Inc. |
2 | // All rights reserved. | |
3 | // | |
4 | // Redistribution and use in source and binary forms, with or without | |
5 | // modification, are permitted provided that the following conditions are | |
6 | // met: | |
7 | // | |
8 | // * Redistributions of source code must retain the above copyright | |
9 | // notice, this list of conditions and the following disclaimer. | |
10 | // * Redistributions in binary form must reproduce the above | |
11 | // copyright notice, this list of conditions and the following disclaimer | |
12 | // in the documentation and/or other materials provided with the | |
13 | // distribution. | |
14 | // * Neither the name of Google Inc. nor the names of its | |
15 | // contributors may be used to endorse or promote products derived from | |
16 | // this software without specific prior written permission. | |
17 | // | |
18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
29 | // | |
30 | // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev) | |
31 | // | |
32 | // This file implements death tests. | |
33 | ||
34 | #include "gtest/gtest-death-test.h" | |
35 | #include "gtest/internal/gtest-port.h" | |
36 | ||
37 | #if GTEST_HAS_DEATH_TEST | |
38 | ||
39 | # if GTEST_OS_MAC | |
40 | # include <crt_externs.h> | |
41 | # endif // GTEST_OS_MAC | |
42 | ||
43 | # include <errno.h> | |
44 | # include <fcntl.h> | |
45 | # include <limits.h> | |
46 | # include <stdarg.h> | |
47 | ||
48 | # 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 | |
54 | ||
55 | #endif // GTEST_HAS_DEATH_TEST | |
56 | ||
57 | #include "gtest/gtest-message.h" | |
58 | #include "gtest/internal/gtest-string.h" | |
59 | ||
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. | |
65 | #define GTEST_IMPLEMENTATION_ 1 | |
1a4d82fc | 66 | #include "src/gtest-internal-inl.h" |
223e47cc LB |
67 | #undef GTEST_IMPLEMENTATION_ |
68 | ||
69 | namespace testing { | |
70 | ||
71 | // Constants. | |
72 | ||
73 | // The default death test style. | |
74 | static const char kDefaultDeathTestStyle[] = "fast"; | |
75 | ||
76 | GTEST_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 | ||
85 | GTEST_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 | ||
97 | namespace internal { | |
98 | GTEST_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 | ||
108 | #if GTEST_HAS_DEATH_TEST | |
109 | ||
110 | // ExitedWithCode constructor. | |
111 | ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) { | |
112 | } | |
113 | ||
114 | // ExitedWithCode function-call operator. | |
115 | bool ExitedWithCode::operator()(int exit_status) const { | |
116 | # if GTEST_OS_WINDOWS | |
117 | ||
118 | return exit_status == exit_code_; | |
119 | ||
120 | # else | |
121 | ||
122 | return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_; | |
123 | ||
124 | # endif // GTEST_OS_WINDOWS | |
125 | } | |
126 | ||
127 | # if !GTEST_OS_WINDOWS | |
128 | // KilledBySignal constructor. | |
129 | KilledBySignal::KilledBySignal(int signum) : signum_(signum) { | |
130 | } | |
131 | ||
132 | // KilledBySignal function-call operator. | |
133 | bool KilledBySignal::operator()(int exit_status) const { | |
134 | return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_; | |
135 | } | |
136 | # endif // !GTEST_OS_WINDOWS | |
137 | ||
138 | namespace 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). | |
144 | static String ExitSummary(int exit_code) { | |
145 | Message m; | |
146 | ||
147 | # if GTEST_OS_WINDOWS | |
148 | ||
149 | m << "Exited with exit status " << exit_code; | |
150 | ||
151 | # else | |
152 | ||
153 | 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 | } | |
158 | # ifdef WCOREDUMP | |
159 | if (WCOREDUMP(exit_code)) { | |
160 | m << " (core dumped)"; | |
161 | } | |
162 | # endif | |
163 | # endif // GTEST_OS_WINDOWS | |
164 | ||
165 | 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. | |
170 | bool ExitedUnsuccessfully(int exit_status) { | |
171 | return !ExitedWithCode(0)(exit_status); | |
172 | } | |
173 | ||
174 | # if !GTEST_OS_WINDOWS | |
175 | // 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. | |
179 | static String DeathTestThreadWarning(size_t thread_count) { | |
180 | Message msg; | |
181 | msg << "Death tests use fork(), which is unsafe particularly" | |
182 | << " in a threaded context. For this test, " << GTEST_NAME_ << " "; | |
183 | 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 | } | |
189 | # endif // !GTEST_OS_WINDOWS | |
190 | ||
191 | // Flag characters for reporting a death test that did not die. | |
192 | static const char kDeathTestLived = 'L'; | |
193 | static const char kDeathTestReturned = 'R'; | |
194 | static const char kDeathTestThrew = 'T'; | |
195 | static const char kDeathTestInternalError = 'I'; | |
196 | ||
197 | // 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. | |
206 | enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW }; | |
207 | ||
208 | // Routine for aborting the program which is safe to call from an | |
209 | // exec-style death test child process, in which case the error | |
210 | // 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. | |
213 | void 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. | |
217 | const InternalRunDeathTestFlag* const flag = | |
218 | GetUnitTestImpl()->internal_run_death_test_flag(); | |
219 | if (flag != NULL) { | |
220 | FILE* parent = posix::FDOpen(flag->write_fd(), "w"); | |
221 | fputc(kDeathTestInternalError, parent); | |
222 | fprintf(parent, "%s", message.c_str()); | |
223 | fflush(parent); | |
224 | _exit(1); | |
225 | } else { | |
226 | fprintf(stderr, "%s", message.c_str()); | |
227 | fflush(stderr); | |
228 | posix::Abort(); | |
229 | } | |
230 | } | |
231 | ||
232 | // A replacement for CHECK that calls DeathTestAbort if the assertion | |
233 | // fails. | |
234 | # define GTEST_DEATH_TEST_CHECK_(expression) \ | |
235 | do { \ | |
236 | if (!::testing::internal::IsTrue(expression)) { \ | |
237 | DeathTestAbort(::testing::internal::String::Format( \ | |
238 | "CHECK failed: File %s, line %d: %s", \ | |
239 | __FILE__, __LINE__, #expression)); \ | |
240 | } \ | |
241 | } while (::testing::internal::AlwaysFalse()) | |
242 | ||
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. | |
250 | # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ | |
251 | do { \ | |
252 | int gtest_retval; \ | |
253 | do { \ | |
254 | gtest_retval = (expression); \ | |
255 | } while (gtest_retval == -1 && errno == EINTR); \ | |
256 | if (gtest_retval == -1) { \ | |
257 | DeathTestAbort(::testing::internal::String::Format( \ | |
258 | "CHECK failed: File %s, line %d: %s != -1", \ | |
259 | __FILE__, __LINE__, #expression)); \ | |
260 | } \ | |
261 | } while (::testing::internal::AlwaysFalse()) | |
262 | ||
263 | // Returns the message describing the last system error in errno. | |
264 | String GetLastErrnoDescription() { | |
265 | return String(errno == 0 ? "" : posix::StrError(errno)); | |
266 | } | |
267 | ||
268 | // 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. | |
272 | static 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 | } | |
292 | ||
293 | // Death test constructor. Increments the running death test count | |
294 | // for the current test. | |
295 | DeathTest::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 | ||
1a4d82fc JJ |
303 | // Pin the vtable to this file. |
304 | DeathTest::~DeathTest() {} | |
305 | ||
223e47cc LB |
306 | // Creates and returns a death test by dispatching to the current |
307 | // death test factory. | |
308 | bool DeathTest::Create(const char* statement, const RE* regex, | |
309 | const char* file, int line, DeathTest** test) { | |
310 | return GetUnitTestImpl()->death_test_factory()->Create( | |
311 | statement, regex, file, line, test); | |
312 | } | |
313 | ||
314 | const char* DeathTest::LastMessage() { | |
315 | return last_death_test_message_.c_str(); | |
316 | } | |
317 | ||
318 | void DeathTest::set_last_death_test_message(const String& message) { | |
319 | last_death_test_message_ = message; | |
320 | } | |
321 | ||
322 | String DeathTest::last_death_test_message_; | |
323 | ||
324 | // Provides cross platform implementation for some death functionality. | |
325 | class DeathTestImpl : public DeathTest { | |
326 | protected: | |
327 | DeathTestImpl(const char* a_statement, const RE* a_regex) | |
328 | : statement_(a_statement), | |
329 | regex_(a_regex), | |
330 | spawned_(false), | |
331 | status_(-1), | |
332 | outcome_(IN_PROGRESS), | |
333 | read_fd_(-1), | |
334 | write_fd_(-1) {} | |
335 | ||
336 | // read_fd_ is expected to be closed and cleared by a derived class. | |
337 | ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); } | |
338 | ||
339 | void Abort(AbortReason reason); | |
340 | virtual bool Passed(bool status_ok); | |
341 | ||
342 | const char* statement() const { return statement_; } | |
343 | const RE* regex() const { return regex_; } | |
344 | bool spawned() const { return spawned_; } | |
345 | void set_spawned(bool is_spawned) { spawned_ = is_spawned; } | |
346 | int status() const { return status_; } | |
347 | void set_status(int a_status) { status_ = a_status; } | |
348 | DeathTestOutcome outcome() const { return outcome_; } | |
349 | void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; } | |
350 | int read_fd() const { return read_fd_; } | |
351 | void set_read_fd(int fd) { read_fd_ = fd; } | |
352 | int write_fd() const { return write_fd_; } | |
353 | void set_write_fd(int fd) { write_fd_ = fd; } | |
354 | ||
355 | // Called in the parent process only. Reads the result code of the death | |
356 | // test child process via a pipe, interprets it to set the outcome_ | |
357 | // member, and closes read_fd_. Outputs diagnostics and terminates in | |
358 | // case of unexpected codes. | |
359 | void ReadAndInterpretStatusByte(); | |
360 | ||
361 | private: | |
362 | // The textual content of the code this object is testing. This class | |
363 | // doesn't own this string and should not attempt to delete it. | |
364 | const char* const statement_; | |
365 | // The regular expression which test output must match. DeathTestImpl | |
366 | // doesn't own this object and should not attempt to delete it. | |
367 | const RE* const regex_; | |
368 | // True if the death test child process has been successfully spawned. | |
369 | bool spawned_; | |
370 | // The exit status of the child process. | |
371 | int status_; | |
372 | // How the death test concluded. | |
373 | DeathTestOutcome outcome_; | |
374 | // Descriptor to the read end of the pipe to the child process. It is | |
375 | // always -1 in the child process. The child keeps its write end of the | |
376 | // pipe in write_fd_. | |
377 | int read_fd_; | |
378 | // Descriptor to the child's write end of the pipe to the parent process. | |
379 | // It is always -1 in the parent process. The parent keeps its end of the | |
380 | // pipe in read_fd_. | |
381 | int write_fd_; | |
382 | }; | |
383 | ||
384 | // Called in the parent process only. Reads the result code of the death | |
385 | // test child process via a pipe, interprets it to set the outcome_ | |
386 | // member, and closes read_fd_. Outputs diagnostics and terminates in | |
387 | // case of unexpected codes. | |
388 | void DeathTestImpl::ReadAndInterpretStatusByte() { | |
389 | char flag; | |
390 | int bytes_read; | |
391 | ||
392 | // The read() here blocks until data is available (signifying the | |
393 | // failure of the death test) or until the pipe is closed (signifying | |
394 | // its success), so it's okay to call this in the parent before | |
395 | // the child process has exited. | |
396 | do { | |
397 | bytes_read = posix::Read(read_fd(), &flag, 1); | |
398 | } while (bytes_read == -1 && errno == EINTR); | |
399 | ||
400 | if (bytes_read == 0) { | |
401 | set_outcome(DIED); | |
402 | } else if (bytes_read == 1) { | |
403 | switch (flag) { | |
404 | case kDeathTestReturned: | |
405 | set_outcome(RETURNED); | |
406 | break; | |
407 | case kDeathTestThrew: | |
408 | set_outcome(THREW); | |
409 | break; | |
410 | case kDeathTestLived: | |
411 | set_outcome(LIVED); | |
412 | break; | |
413 | case kDeathTestInternalError: | |
414 | FailFromInternalError(read_fd()); // Does not return. | |
415 | break; | |
416 | default: | |
417 | GTEST_LOG_(FATAL) << "Death test child process reported " | |
418 | << "unexpected status byte (" | |
419 | << static_cast<unsigned int>(flag) << ")"; | |
420 | } | |
421 | } else { | |
422 | GTEST_LOG_(FATAL) << "Read from death test child process failed: " | |
423 | << GetLastErrnoDescription(); | |
424 | } | |
425 | GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd())); | |
426 | set_read_fd(-1); | |
427 | } | |
428 | ||
429 | // Signals that the death test code which should have exited, didn't. | |
430 | // Should be called only in a death test child process. | |
431 | // Writes a status byte to the child's status file descriptor, then | |
432 | // calls _exit(1). | |
433 | void DeathTestImpl::Abort(AbortReason reason) { | |
434 | // The parent process considers the death test to be a failure if | |
435 | // it finds any data in our pipe. So, here we write a single flag byte | |
436 | // to the pipe, then exit. | |
437 | const char status_ch = | |
438 | reason == TEST_DID_NOT_DIE ? kDeathTestLived : | |
439 | reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned; | |
440 | ||
441 | GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1)); | |
442 | // We are leaking the descriptor here because on some platforms (i.e., | |
443 | // when built as Windows DLL), destructors of global objects will still | |
444 | // run after calling _exit(). On such systems, write_fd_ will be | |
445 | // indirectly closed from the destructor of UnitTestImpl, causing double | |
446 | // close if it is also closed here. On debug configurations, double close | |
447 | // may assert. As there are no in-process buffers to flush here, we are | |
448 | // relying on the OS to close the descriptor after the process terminates | |
449 | // when the destructors are not run. | |
450 | _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash) | |
451 | } | |
452 | ||
453 | // Returns an indented copy of stderr output for a death test. | |
454 | // This makes distinguishing death test output lines from regular log lines | |
455 | // much easier. | |
456 | static ::std::string FormatDeathTestOutput(const ::std::string& output) { | |
457 | ::std::string ret; | |
458 | for (size_t at = 0; ; ) { | |
459 | const size_t line_end = output.find('\n', at); | |
460 | ret += "[ DEATH ] "; | |
461 | if (line_end == ::std::string::npos) { | |
462 | ret += output.substr(at); | |
463 | break; | |
464 | } | |
465 | ret += output.substr(at, line_end + 1 - at); | |
466 | at = line_end + 1; | |
467 | } | |
468 | return ret; | |
469 | } | |
470 | ||
471 | // Assesses the success or failure of a death test, using both private | |
472 | // members which have previously been set, and one argument: | |
473 | // | |
474 | // Private data members: | |
475 | // outcome: An enumeration describing how the death test | |
476 | // concluded: DIED, LIVED, THREW, or RETURNED. The death test | |
477 | // fails in the latter three cases. | |
478 | // status: The exit status of the child process. On *nix, it is in the | |
479 | // in the format specified by wait(2). On Windows, this is the | |
480 | // value supplied to the ExitProcess() API or a numeric code | |
481 | // of the exception that terminated the program. | |
482 | // regex: A regular expression object to be applied to | |
483 | // the test's captured standard error output; the death test | |
484 | // fails if it does not match. | |
485 | // | |
486 | // Argument: | |
487 | // status_ok: true if exit_status is acceptable in the context of | |
488 | // this particular death test, which fails if it is false | |
489 | // | |
490 | // Returns true iff all of the above conditions are met. Otherwise, the | |
491 | // first failing condition, in the order given above, is the one that is | |
492 | // reported. Also sets the last death test message string. | |
493 | bool DeathTestImpl::Passed(bool status_ok) { | |
494 | if (!spawned()) | |
495 | return false; | |
496 | ||
497 | const String error_message = GetCapturedStderr(); | |
498 | ||
499 | bool success = false; | |
500 | Message buffer; | |
501 | ||
502 | buffer << "Death test: " << statement() << "\n"; | |
503 | switch (outcome()) { | |
504 | case LIVED: | |
505 | buffer << " Result: failed to die.\n" | |
506 | << " Error msg:\n" << FormatDeathTestOutput(error_message); | |
507 | break; | |
508 | case THREW: | |
509 | buffer << " Result: threw an exception.\n" | |
510 | << " Error msg:\n" << FormatDeathTestOutput(error_message); | |
511 | break; | |
512 | case RETURNED: | |
513 | buffer << " Result: illegal return in test statement.\n" | |
514 | << " Error msg:\n" << FormatDeathTestOutput(error_message); | |
515 | break; | |
516 | case DIED: | |
517 | if (status_ok) { | |
518 | const bool matched = RE::PartialMatch(error_message.c_str(), *regex()); | |
519 | if (matched) { | |
520 | success = true; | |
521 | } else { | |
522 | buffer << " Result: died but not with expected error.\n" | |
523 | << " Expected: " << regex()->pattern() << "\n" | |
524 | << "Actual msg:\n" << FormatDeathTestOutput(error_message); | |
525 | } | |
526 | } else { | |
527 | buffer << " Result: died but not with expected exit code:\n" | |
528 | << " " << ExitSummary(status()) << "\n" | |
529 | << "Actual msg:\n" << FormatDeathTestOutput(error_message); | |
530 | } | |
531 | break; | |
532 | case IN_PROGRESS: | |
533 | GTEST_LOG_(FATAL) | |
534 | << "DeathTest::Passed somehow called before conclusion of test"; | |
535 | } | |
536 | ||
537 | DeathTest::set_last_death_test_message(buffer.GetString()); | |
538 | return success; | |
539 | } | |
540 | ||
541 | # if GTEST_OS_WINDOWS | |
542 | // WindowsDeathTest implements death tests on Windows. Due to the | |
543 | // specifics of starting new processes on Windows, death tests there are | |
544 | // always threadsafe, and Google Test considers the | |
545 | // --gtest_death_test_style=fast setting to be equivalent to | |
546 | // --gtest_death_test_style=threadsafe there. | |
547 | // | |
548 | // A few implementation notes: Like the Linux version, the Windows | |
549 | // implementation uses pipes for child-to-parent communication. But due to | |
550 | // the specifics of pipes on Windows, some extra steps are required: | |
551 | // | |
552 | // 1. The parent creates a communication pipe and stores handles to both | |
553 | // ends of it. | |
554 | // 2. The parent starts the child and provides it with the information | |
555 | // necessary to acquire the handle to the write end of the pipe. | |
556 | // 3. The child acquires the write end of the pipe and signals the parent | |
557 | // using a Windows event. | |
558 | // 4. Now the parent can release the write end of the pipe on its side. If | |
559 | // this is done before step 3, the object's reference count goes down to | |
560 | // 0 and it is destroyed, preventing the child from acquiring it. The | |
561 | // parent now has to release it, or read operations on the read end of | |
562 | // the pipe will not return when the child terminates. | |
563 | // 5. The parent reads child's output through the pipe (outcome code and | |
564 | // any possible error messages) from the pipe, and its stderr and then | |
565 | // determines whether to fail the test. | |
566 | // | |
567 | // Note: to distinguish Win32 API calls from the local method and function | |
568 | // calls, the former are explicitly resolved in the global namespace. | |
569 | // | |
570 | class WindowsDeathTest : public DeathTestImpl { | |
571 | public: | |
572 | WindowsDeathTest(const char* a_statement, | |
573 | const RE* a_regex, | |
574 | const char* file, | |
575 | int line) | |
576 | : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {} | |
577 | ||
578 | // All of these virtual functions are inherited from DeathTest. | |
579 | virtual int Wait(); | |
580 | virtual TestRole AssumeRole(); | |
581 | ||
582 | private: | |
583 | // The name of the file in which the death test is located. | |
584 | const char* const file_; | |
585 | // The line number on which the death test is located. | |
586 | const int line_; | |
587 | // Handle to the write end of the pipe to the child process. | |
588 | AutoHandle write_handle_; | |
589 | // Child process handle. | |
590 | AutoHandle child_handle_; | |
591 | // Event the child process uses to signal the parent that it has | |
592 | // acquired the handle to the write end of the pipe. After seeing this | |
593 | // event the parent can release its own handles to make sure its | |
594 | // ReadFile() calls return when the child terminates. | |
595 | AutoHandle event_handle_; | |
596 | }; | |
597 | ||
598 | // Waits for the child in a death test to exit, returning its exit | |
599 | // status, or 0 if no child process exists. As a side effect, sets the | |
600 | // outcome data member. | |
601 | int WindowsDeathTest::Wait() { | |
602 | if (!spawned()) | |
603 | return 0; | |
604 | ||
605 | // Wait until the child either signals that it has acquired the write end | |
606 | // of the pipe or it dies. | |
607 | const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() }; | |
608 | switch (::WaitForMultipleObjects(2, | |
609 | wait_handles, | |
610 | FALSE, // Waits for any of the handles. | |
611 | INFINITE)) { | |
612 | case WAIT_OBJECT_0: | |
613 | case WAIT_OBJECT_0 + 1: | |
614 | break; | |
615 | default: | |
616 | GTEST_DEATH_TEST_CHECK_(false); // Should not get here. | |
617 | } | |
618 | ||
619 | // The child has acquired the write end of the pipe or exited. | |
620 | // We release the handle on our side and continue. | |
621 | write_handle_.Reset(); | |
622 | event_handle_.Reset(); | |
623 | ||
624 | ReadAndInterpretStatusByte(); | |
625 | ||
626 | // Waits for the child process to exit if it haven't already. This | |
627 | // returns immediately if the child has already exited, regardless of | |
628 | // whether previous calls to WaitForMultipleObjects synchronized on this | |
629 | // handle or not. | |
630 | GTEST_DEATH_TEST_CHECK_( | |
631 | WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(), | |
632 | INFINITE)); | |
633 | DWORD status_code; | |
634 | GTEST_DEATH_TEST_CHECK_( | |
635 | ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE); | |
636 | child_handle_.Reset(); | |
637 | set_status(static_cast<int>(status_code)); | |
638 | return status(); | |
639 | } | |
640 | ||
641 | // The AssumeRole process for a Windows death test. It creates a child | |
642 | // process with the same executable as the current process to run the | |
643 | // death test. The child process is given the --gtest_filter and | |
644 | // --gtest_internal_run_death_test flags such that it knows to run the | |
645 | // current death test only. | |
646 | DeathTest::TestRole WindowsDeathTest::AssumeRole() { | |
647 | const UnitTestImpl* const impl = GetUnitTestImpl(); | |
648 | const InternalRunDeathTestFlag* const flag = | |
649 | impl->internal_run_death_test_flag(); | |
650 | const TestInfo* const info = impl->current_test_info(); | |
651 | const int death_test_index = info->result()->death_test_count(); | |
652 | ||
653 | if (flag != NULL) { | |
654 | // ParseInternalRunDeathTestFlag() has performed all the necessary | |
655 | // processing. | |
656 | set_write_fd(flag->write_fd()); | |
657 | return EXECUTE_TEST; | |
658 | } | |
659 | ||
660 | // WindowsDeathTest uses an anonymous pipe to communicate results of | |
661 | // a death test. | |
662 | SECURITY_ATTRIBUTES handles_are_inheritable = { | |
663 | sizeof(SECURITY_ATTRIBUTES), NULL, TRUE }; | |
664 | HANDLE read_handle, write_handle; | |
665 | GTEST_DEATH_TEST_CHECK_( | |
666 | ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable, | |
667 | 0) // Default buffer size. | |
668 | != FALSE); | |
669 | set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle), | |
670 | O_RDONLY)); | |
671 | write_handle_.Reset(write_handle); | |
672 | event_handle_.Reset(::CreateEvent( | |
673 | &handles_are_inheritable, | |
674 | TRUE, // The event will automatically reset to non-signaled state. | |
675 | FALSE, // The initial state is non-signalled. | |
676 | NULL)); // The even is unnamed. | |
677 | GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL); | |
678 | const String filter_flag = String::Format("--%s%s=%s.%s", | |
679 | GTEST_FLAG_PREFIX_, kFilterFlag, | |
680 | info->test_case_name(), | |
681 | info->name()); | |
682 | const String internal_flag = String::Format( | |
683 | "--%s%s=%s|%d|%d|%u|%Iu|%Iu", | |
684 | GTEST_FLAG_PREFIX_, | |
685 | kInternalRunDeathTestFlag, | |
686 | file_, line_, | |
687 | death_test_index, | |
688 | static_cast<unsigned int>(::GetCurrentProcessId()), | |
689 | // size_t has the same with as pointers on both 32-bit and 64-bit | |
690 | // Windows platforms. | |
691 | // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. | |
692 | reinterpret_cast<size_t>(write_handle), | |
693 | reinterpret_cast<size_t>(event_handle_.Get())); | |
694 | ||
695 | char executable_path[_MAX_PATH + 1]; // NOLINT | |
696 | GTEST_DEATH_TEST_CHECK_( | |
697 | _MAX_PATH + 1 != ::GetModuleFileNameA(NULL, | |
698 | executable_path, | |
699 | _MAX_PATH)); | |
700 | ||
701 | String command_line = String::Format("%s %s \"%s\"", | |
702 | ::GetCommandLineA(), | |
703 | filter_flag.c_str(), | |
704 | internal_flag.c_str()); | |
705 | ||
706 | DeathTest::set_last_death_test_message(""); | |
707 | ||
708 | CaptureStderr(); | |
709 | // Flush the log buffers since the log streams are shared with the child. | |
710 | FlushInfoLog(); | |
711 | ||
712 | // The child process will share the standard handles with the parent. | |
713 | STARTUPINFOA startup_info; | |
714 | memset(&startup_info, 0, sizeof(STARTUPINFO)); | |
715 | startup_info.dwFlags = STARTF_USESTDHANDLES; | |
716 | startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE); | |
717 | startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE); | |
718 | startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE); | |
719 | ||
720 | PROCESS_INFORMATION process_info; | |
721 | GTEST_DEATH_TEST_CHECK_(::CreateProcessA( | |
722 | executable_path, | |
723 | const_cast<char*>(command_line.c_str()), | |
724 | NULL, // Retuned process handle is not inheritable. | |
725 | NULL, // Retuned thread handle is not inheritable. | |
726 | TRUE, // Child inherits all inheritable handles (for write_handle_). | |
727 | 0x0, // Default creation flags. | |
728 | NULL, // Inherit the parent's environment. | |
729 | UnitTest::GetInstance()->original_working_dir(), | |
730 | &startup_info, | |
731 | &process_info) != FALSE); | |
732 | child_handle_.Reset(process_info.hProcess); | |
733 | ::CloseHandle(process_info.hThread); | |
734 | set_spawned(true); | |
735 | return OVERSEE_TEST; | |
736 | } | |
737 | # else // We are not on Windows. | |
738 | ||
739 | // ForkingDeathTest provides implementations for most of the abstract | |
740 | // methods of the DeathTest interface. Only the AssumeRole method is | |
741 | // left undefined. | |
742 | class ForkingDeathTest : public DeathTestImpl { | |
743 | public: | |
744 | ForkingDeathTest(const char* statement, const RE* regex); | |
745 | ||
746 | // All of these virtual functions are inherited from DeathTest. | |
747 | virtual int Wait(); | |
748 | ||
749 | protected: | |
750 | void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; } | |
751 | ||
752 | private: | |
753 | // PID of child process during death test; 0 in the child process itself. | |
754 | pid_t child_pid_; | |
755 | }; | |
756 | ||
757 | // Constructs a ForkingDeathTest. | |
758 | ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex) | |
759 | : DeathTestImpl(a_statement, a_regex), | |
760 | child_pid_(-1) {} | |
761 | ||
762 | // Waits for the child in a death test to exit, returning its exit | |
763 | // status, or 0 if no child process exists. As a side effect, sets the | |
764 | // outcome data member. | |
765 | int ForkingDeathTest::Wait() { | |
766 | if (!spawned()) | |
767 | return 0; | |
768 | ||
769 | ReadAndInterpretStatusByte(); | |
770 | ||
771 | int status_value; | |
772 | GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0)); | |
773 | set_status(status_value); | |
774 | return status_value; | |
775 | } | |
776 | ||
777 | // A concrete death test class that forks, then immediately runs the test | |
778 | // in the child process. | |
779 | class NoExecDeathTest : public ForkingDeathTest { | |
780 | public: | |
781 | NoExecDeathTest(const char* a_statement, const RE* a_regex) : | |
782 | ForkingDeathTest(a_statement, a_regex) { } | |
783 | virtual TestRole AssumeRole(); | |
784 | }; | |
785 | ||
786 | // The AssumeRole process for a fork-and-run death test. It implements a | |
787 | // straightforward fork, with a simple pipe to transmit the status byte. | |
788 | DeathTest::TestRole NoExecDeathTest::AssumeRole() { | |
789 | const size_t thread_count = GetThreadCount(); | |
790 | if (thread_count != 1) { | |
791 | GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count); | |
792 | } | |
793 | ||
794 | int pipe_fd[2]; | |
795 | GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); | |
796 | ||
797 | DeathTest::set_last_death_test_message(""); | |
798 | CaptureStderr(); | |
799 | // When we fork the process below, the log file buffers are copied, but the | |
800 | // file descriptors are shared. We flush all log files here so that closing | |
801 | // the file descriptors in the child process doesn't throw off the | |
802 | // synchronization between descriptors and buffers in the parent process. | |
803 | // This is as close to the fork as possible to avoid a race condition in case | |
804 | // there are multiple threads running before the death test, and another | |
805 | // thread writes to the log file. | |
806 | FlushInfoLog(); | |
807 | ||
808 | const pid_t child_pid = fork(); | |
809 | GTEST_DEATH_TEST_CHECK_(child_pid != -1); | |
810 | set_child_pid(child_pid); | |
811 | if (child_pid == 0) { | |
812 | GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0])); | |
813 | set_write_fd(pipe_fd[1]); | |
814 | // Redirects all logging to stderr in the child process to prevent | |
815 | // concurrent writes to the log files. We capture stderr in the parent | |
816 | // process and append the child process' output to a log. | |
817 | LogToStderr(); | |
818 | // Event forwarding to the listeners of event listener API mush be shut | |
819 | // down in death test subprocesses. | |
820 | GetUnitTestImpl()->listeners()->SuppressEventForwarding(); | |
821 | return EXECUTE_TEST; | |
822 | } else { | |
823 | GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); | |
824 | set_read_fd(pipe_fd[0]); | |
825 | set_spawned(true); | |
826 | return OVERSEE_TEST; | |
827 | } | |
828 | } | |
829 | ||
830 | // A concrete death test class that forks and re-executes the main | |
831 | // program from the beginning, with command-line flags set that cause | |
832 | // only this specific death test to be run. | |
833 | class ExecDeathTest : public ForkingDeathTest { | |
834 | public: | |
835 | ExecDeathTest(const char* a_statement, const RE* a_regex, | |
836 | const char* file, int line) : | |
837 | ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { } | |
838 | virtual TestRole AssumeRole(); | |
839 | private: | |
840 | // The name of the file in which the death test is located. | |
841 | const char* const file_; | |
842 | // The line number on which the death test is located. | |
843 | const int line_; | |
844 | }; | |
845 | ||
846 | // Utility class for accumulating command-line arguments. | |
847 | class Arguments { | |
848 | public: | |
849 | Arguments() { | |
850 | args_.push_back(NULL); | |
851 | } | |
852 | ||
853 | ~Arguments() { | |
854 | for (std::vector<char*>::iterator i = args_.begin(); i != args_.end(); | |
855 | ++i) { | |
856 | free(*i); | |
857 | } | |
858 | } | |
859 | void AddArgument(const char* argument) { | |
860 | args_.insert(args_.end() - 1, posix::StrDup(argument)); | |
861 | } | |
862 | ||
863 | template <typename Str> | |
864 | void AddArguments(const ::std::vector<Str>& arguments) { | |
865 | for (typename ::std::vector<Str>::const_iterator i = arguments.begin(); | |
866 | i != arguments.end(); | |
867 | ++i) { | |
868 | args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); | |
869 | } | |
870 | } | |
871 | char* const* Argv() { | |
872 | return &args_[0]; | |
873 | } | |
874 | private: | |
875 | std::vector<char*> args_; | |
876 | }; | |
877 | ||
878 | // A struct that encompasses the arguments to the child process of a | |
879 | // threadsafe-style death test process. | |
880 | struct ExecDeathTestArgs { | |
881 | char* const* argv; // Command-line arguments for the child's call to exec | |
882 | int close_fd; // File descriptor to close; the read end of a pipe | |
883 | }; | |
884 | ||
885 | # if GTEST_OS_MAC | |
886 | inline char** GetEnviron() { | |
887 | // When Google Test is built as a framework on MacOS X, the environ variable | |
888 | // is unavailable. Apple's documentation (man environ) recommends using | |
889 | // _NSGetEnviron() instead. | |
890 | return *_NSGetEnviron(); | |
891 | } | |
892 | # else | |
893 | // Some POSIX platforms expect you to declare environ. extern "C" makes | |
894 | // it reside in the global namespace. | |
895 | extern "C" char** environ; | |
896 | inline char** GetEnviron() { return environ; } | |
897 | # endif // GTEST_OS_MAC | |
898 | ||
899 | // The main function for a threadsafe-style death test child process. | |
900 | // This function is called in a clone()-ed process and thus must avoid | |
901 | // any potentially unsafe operations like malloc or libc functions. | |
902 | static int ExecDeathTestChildMain(void* child_arg) { | |
903 | ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg); | |
904 | GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd)); | |
905 | ||
906 | // We need to execute the test program in the same environment where | |
907 | // it was originally invoked. Therefore we change to the original | |
908 | // working directory first. | |
909 | const char* const original_dir = | |
910 | UnitTest::GetInstance()->original_working_dir(); | |
911 | // We can safely call chdir() as it's a direct system call. | |
912 | if (chdir(original_dir) != 0) { | |
913 | DeathTestAbort(String::Format("chdir(\"%s\") failed: %s", | |
914 | original_dir, | |
915 | GetLastErrnoDescription().c_str())); | |
916 | return EXIT_FAILURE; | |
917 | } | |
918 | ||
919 | // We can safely call execve() as it's a direct system call. We | |
920 | // cannot use execvp() as it's a libc function and thus potentially | |
921 | // unsafe. Since execve() doesn't search the PATH, the user must | |
922 | // invoke the test program via a valid path that contains at least | |
923 | // one path separator. | |
924 | execve(args->argv[0], args->argv, GetEnviron()); | |
925 | DeathTestAbort(String::Format("execve(%s, ...) in %s failed: %s", | |
926 | args->argv[0], | |
927 | original_dir, | |
928 | GetLastErrnoDescription().c_str())); | |
929 | return EXIT_FAILURE; | |
930 | } | |
931 | ||
932 | // Two utility routines that together determine the direction the stack | |
933 | // grows. | |
934 | // This could be accomplished more elegantly by a single recursive | |
935 | // function, but we want to guard against the unlikely possibility of | |
936 | // a smart compiler optimizing the recursion away. | |
937 | // | |
938 | // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining | |
939 | // StackLowerThanAddress into StackGrowsDown, which then doesn't give | |
940 | // correct answer. | |
941 | bool StackLowerThanAddress(const void* ptr) GTEST_NO_INLINE_; | |
942 | bool StackLowerThanAddress(const void* ptr) { | |
943 | int dummy; | |
944 | return &dummy < ptr; | |
945 | } | |
946 | ||
947 | bool StackGrowsDown() { | |
948 | int dummy; | |
949 | return StackLowerThanAddress(&dummy); | |
950 | } | |
951 | ||
952 | // A threadsafe implementation of fork(2) for threadsafe-style death tests | |
953 | // that uses clone(2). It dies with an error message if anything goes | |
954 | // wrong. | |
955 | static pid_t ExecDeathTestFork(char* const* argv, int close_fd) { | |
956 | ExecDeathTestArgs args = { argv, close_fd }; | |
957 | pid_t child_pid = -1; | |
958 | ||
959 | # if GTEST_HAS_CLONE | |
960 | const bool use_fork = GTEST_FLAG(death_test_use_fork); | |
961 | ||
962 | if (!use_fork) { | |
963 | static const bool stack_grows_down = StackGrowsDown(); | |
964 | const size_t stack_size = getpagesize(); | |
965 | // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead. | |
966 | void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE, | |
967 | MAP_ANON | MAP_PRIVATE, -1, 0); | |
968 | GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED); | |
969 | void* const stack_top = | |
970 | static_cast<char*>(stack) + (stack_grows_down ? stack_size : 0); | |
971 | ||
972 | child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args); | |
973 | ||
974 | GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1); | |
975 | } | |
976 | # else | |
977 | const bool use_fork = true; | |
978 | # endif // GTEST_HAS_CLONE | |
979 | ||
980 | if (use_fork && (child_pid = fork()) == 0) { | |
981 | ExecDeathTestChildMain(&args); | |
982 | _exit(0); | |
983 | } | |
984 | ||
985 | GTEST_DEATH_TEST_CHECK_(child_pid != -1); | |
986 | return child_pid; | |
987 | } | |
988 | ||
989 | // The AssumeRole process for a fork-and-exec death test. It re-executes the | |
990 | // main program from the beginning, setting the --gtest_filter | |
991 | // and --gtest_internal_run_death_test flags to cause only the current | |
992 | // death test to be re-run. | |
993 | DeathTest::TestRole ExecDeathTest::AssumeRole() { | |
994 | const UnitTestImpl* const impl = GetUnitTestImpl(); | |
995 | const InternalRunDeathTestFlag* const flag = | |
996 | impl->internal_run_death_test_flag(); | |
997 | const TestInfo* const info = impl->current_test_info(); | |
998 | const int death_test_index = info->result()->death_test_count(); | |
999 | ||
1000 | if (flag != NULL) { | |
1001 | set_write_fd(flag->write_fd()); | |
1002 | return EXECUTE_TEST; | |
1003 | } | |
1004 | ||
1005 | int pipe_fd[2]; | |
1006 | GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); | |
1007 | // Clear the close-on-exec flag on the write end of the pipe, lest | |
1008 | // it be closed when the child process does an exec: | |
1009 | GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1); | |
1010 | ||
1011 | const String filter_flag = | |
1012 | String::Format("--%s%s=%s.%s", | |
1013 | GTEST_FLAG_PREFIX_, kFilterFlag, | |
1014 | info->test_case_name(), info->name()); | |
1015 | const String internal_flag = | |
1016 | String::Format("--%s%s=%s|%d|%d|%d", | |
1017 | GTEST_FLAG_PREFIX_, kInternalRunDeathTestFlag, | |
1018 | file_, line_, death_test_index, pipe_fd[1]); | |
1019 | Arguments args; | |
1020 | args.AddArguments(GetArgvs()); | |
1021 | args.AddArgument(filter_flag.c_str()); | |
1022 | args.AddArgument(internal_flag.c_str()); | |
1023 | ||
1024 | DeathTest::set_last_death_test_message(""); | |
1025 | ||
1026 | CaptureStderr(); | |
1027 | // See the comment in NoExecDeathTest::AssumeRole for why the next line | |
1028 | // is necessary. | |
1029 | FlushInfoLog(); | |
1030 | ||
1031 | const pid_t child_pid = ExecDeathTestFork(args.Argv(), pipe_fd[0]); | |
1032 | GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); | |
1033 | set_child_pid(child_pid); | |
1034 | set_read_fd(pipe_fd[0]); | |
1035 | set_spawned(true); | |
1036 | return OVERSEE_TEST; | |
1037 | } | |
1038 | ||
1039 | # endif // !GTEST_OS_WINDOWS | |
1040 | ||
1041 | // Creates a concrete DeathTest-derived class that depends on the | |
1042 | // --gtest_death_test_style flag, and sets the pointer pointed to | |
1043 | // by the "test" argument to its address. If the test should be | |
1044 | // skipped, sets that pointer to NULL. Returns true, unless the | |
1045 | // flag is set to an invalid value. | |
1046 | bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex, | |
1047 | const char* file, int line, | |
1048 | DeathTest** test) { | |
1049 | UnitTestImpl* const impl = GetUnitTestImpl(); | |
1050 | const InternalRunDeathTestFlag* const flag = | |
1051 | impl->internal_run_death_test_flag(); | |
1052 | const int death_test_index = impl->current_test_info() | |
1053 | ->increment_death_test_count(); | |
1054 | ||
1055 | if (flag != NULL) { | |
1056 | if (death_test_index > flag->index()) { | |
1057 | DeathTest::set_last_death_test_message(String::Format( | |
1058 | "Death test count (%d) somehow exceeded expected maximum (%d)", | |
1059 | death_test_index, flag->index())); | |
1060 | return false; | |
1061 | } | |
1062 | ||
1063 | if (!(flag->file() == file && flag->line() == line && | |
1064 | flag->index() == death_test_index)) { | |
1065 | *test = NULL; | |
1066 | return true; | |
1067 | } | |
1068 | } | |
1069 | ||
1070 | # if GTEST_OS_WINDOWS | |
1071 | ||
1072 | if (GTEST_FLAG(death_test_style) == "threadsafe" || | |
1073 | GTEST_FLAG(death_test_style) == "fast") { | |
1074 | *test = new WindowsDeathTest(statement, regex, file, line); | |
1075 | } | |
1076 | ||
1077 | # else | |
1078 | ||
1079 | if (GTEST_FLAG(death_test_style) == "threadsafe") { | |
1080 | *test = new ExecDeathTest(statement, regex, file, line); | |
1081 | } else if (GTEST_FLAG(death_test_style) == "fast") { | |
1082 | *test = new NoExecDeathTest(statement, regex); | |
1083 | } | |
1084 | ||
1085 | # endif // GTEST_OS_WINDOWS | |
1086 | ||
1087 | else { // NOLINT - this is more readable than unbalanced brackets inside #if. | |
1088 | DeathTest::set_last_death_test_message(String::Format( | |
1089 | "Unknown death test style \"%s\" encountered", | |
1090 | GTEST_FLAG(death_test_style).c_str())); | |
1091 | return false; | |
1092 | } | |
1093 | ||
1094 | return true; | |
1095 | } | |
1096 | ||
1a4d82fc JJ |
1097 | // Pin the vtable to this file. |
1098 | DeathTestFactory::~DeathTestFactory() {} | |
1099 | ||
223e47cc LB |
1100 | // Splits a given string on a given delimiter, populating a given |
1101 | // vector with the fields. GTEST_HAS_DEATH_TEST implies that we have | |
1102 | // ::std::string, so we can use it here. | |
1103 | static void SplitString(const ::std::string& str, char delimiter, | |
1104 | ::std::vector< ::std::string>* dest) { | |
1105 | ::std::vector< ::std::string> parsed; | |
1106 | ::std::string::size_type pos = 0; | |
1107 | while (::testing::internal::AlwaysTrue()) { | |
1108 | const ::std::string::size_type colon = str.find(delimiter, pos); | |
1109 | if (colon == ::std::string::npos) { | |
1110 | parsed.push_back(str.substr(pos)); | |
1111 | break; | |
1112 | } else { | |
1113 | parsed.push_back(str.substr(pos, colon - pos)); | |
1114 | pos = colon + 1; | |
1115 | } | |
1116 | } | |
1117 | dest->swap(parsed); | |
1118 | } | |
1119 | ||
1120 | # if GTEST_OS_WINDOWS | |
1121 | // Recreates the pipe and event handles from the provided parameters, | |
1122 | // signals the event, and returns a file descriptor wrapped around the pipe | |
1123 | // handle. This function is called in the child process only. | |
1124 | int GetStatusFileDescriptor(unsigned int parent_process_id, | |
1125 | size_t write_handle_as_size_t, | |
1126 | size_t event_handle_as_size_t) { | |
1127 | AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE, | |
1128 | FALSE, // Non-inheritable. | |
1129 | parent_process_id)); | |
1130 | if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) { | |
1131 | DeathTestAbort(String::Format("Unable to open parent process %u", | |
1132 | parent_process_id)); | |
1133 | } | |
1134 | ||
1135 | // TODO(vladl@google.com): Replace the following check with a | |
1136 | // compile-time assertion when available. | |
1137 | GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t)); | |
1138 | ||
1139 | const HANDLE write_handle = | |
1140 | reinterpret_cast<HANDLE>(write_handle_as_size_t); | |
1141 | HANDLE dup_write_handle; | |
1142 | ||
1143 | // The newly initialized handle is accessible only in in the parent | |
1144 | // process. To obtain one accessible within the child, we need to use | |
1145 | // DuplicateHandle. | |
1146 | if (!::DuplicateHandle(parent_process_handle.Get(), write_handle, | |
1147 | ::GetCurrentProcess(), &dup_write_handle, | |
1148 | 0x0, // Requested privileges ignored since | |
1149 | // DUPLICATE_SAME_ACCESS is used. | |
1150 | FALSE, // Request non-inheritable handler. | |
1151 | DUPLICATE_SAME_ACCESS)) { | |
1152 | DeathTestAbort(String::Format( | |
1153 | "Unable to duplicate the pipe handle %Iu from the parent process %u", | |
1154 | write_handle_as_size_t, parent_process_id)); | |
1155 | } | |
1156 | ||
1157 | const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t); | |
1158 | HANDLE dup_event_handle; | |
1159 | ||
1160 | if (!::DuplicateHandle(parent_process_handle.Get(), event_handle, | |
1161 | ::GetCurrentProcess(), &dup_event_handle, | |
1162 | 0x0, | |
1163 | FALSE, | |
1164 | DUPLICATE_SAME_ACCESS)) { | |
1165 | DeathTestAbort(String::Format( | |
1166 | "Unable to duplicate the event handle %Iu from the parent process %u", | |
1167 | event_handle_as_size_t, parent_process_id)); | |
1168 | } | |
1169 | ||
1170 | const int write_fd = | |
1171 | ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND); | |
1172 | if (write_fd == -1) { | |
1173 | DeathTestAbort(String::Format( | |
1174 | "Unable to convert pipe handle %Iu to a file descriptor", | |
1175 | write_handle_as_size_t)); | |
1176 | } | |
1177 | ||
1178 | // Signals the parent that the write end of the pipe has been acquired | |
1179 | // so the parent can release its own write end. | |
1180 | ::SetEvent(dup_event_handle); | |
1181 | ||
1182 | return write_fd; | |
1183 | } | |
1184 | # endif // GTEST_OS_WINDOWS | |
1185 | ||
1186 | // Returns a newly created InternalRunDeathTestFlag object with fields | |
1187 | // initialized from the GTEST_FLAG(internal_run_death_test) flag if | |
1188 | // the flag is specified; otherwise returns NULL. | |
1189 | InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { | |
1190 | if (GTEST_FLAG(internal_run_death_test) == "") return NULL; | |
1191 | ||
1192 | // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we | |
1193 | // can use it here. | |
1194 | int line = -1; | |
1195 | int index = -1; | |
1196 | ::std::vector< ::std::string> fields; | |
1197 | SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields); | |
1198 | int write_fd = -1; | |
1199 | ||
1200 | # if GTEST_OS_WINDOWS | |
1201 | ||
1202 | unsigned int parent_process_id = 0; | |
1203 | size_t write_handle_as_size_t = 0; | |
1204 | size_t event_handle_as_size_t = 0; | |
1205 | ||
1206 | if (fields.size() != 6 | |
1207 | || !ParseNaturalNumber(fields[1], &line) | |
1208 | || !ParseNaturalNumber(fields[2], &index) | |
1209 | || !ParseNaturalNumber(fields[3], &parent_process_id) | |
1210 | || !ParseNaturalNumber(fields[4], &write_handle_as_size_t) | |
1211 | || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { | |
1212 | DeathTestAbort(String::Format( | |
1213 | "Bad --gtest_internal_run_death_test flag: %s", | |
1214 | GTEST_FLAG(internal_run_death_test).c_str())); | |
1215 | } | |
1216 | write_fd = GetStatusFileDescriptor(parent_process_id, | |
1217 | write_handle_as_size_t, | |
1218 | event_handle_as_size_t); | |
1219 | # else | |
1220 | ||
1221 | if (fields.size() != 4 | |
1222 | || !ParseNaturalNumber(fields[1], &line) | |
1223 | || !ParseNaturalNumber(fields[2], &index) | |
1224 | || !ParseNaturalNumber(fields[3], &write_fd)) { | |
1225 | DeathTestAbort(String::Format( | |
1226 | "Bad --gtest_internal_run_death_test flag: %s", | |
1227 | GTEST_FLAG(internal_run_death_test).c_str())); | |
1228 | } | |
1229 | ||
1230 | # endif // GTEST_OS_WINDOWS | |
1231 | ||
1232 | return new InternalRunDeathTestFlag(fields[0], line, index, write_fd); | |
1233 | } | |
1234 | ||
1235 | } // namespace internal | |
1236 | ||
1237 | #endif // GTEST_HAS_DEATH_TEST | |
1238 | ||
1239 | } // namespace testing |