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 // The Google C++ Testing and Mocking Framework (Google Test)
31 //
32 // This header file defines internal utilities needed for implementing
33 // death tests.  They are subject to change without notice.
34 // GOOGLETEST_CM0001 DO NOT DELETE
35 
36 // IWYU pragma: private, include "gtest/gtest.h"
37 // IWYU pragma: friend gtest/.*
38 // IWYU pragma: friend gmock/.*
39 
40 #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
41 #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
42 
43 #include "gtest/gtest-matchers.h"
44 #include "gtest/internal/gtest-internal.h"
45 
46 #include <stdio.h>
47 #include <memory>
48 
49 namespace testing {
50 namespace internal {
51 
52 GTEST_DECLARE_string_(internal_run_death_test);
53 
54 // Names of the flags (needed for parsing Google Test flags).
55 const char kDeathTestStyleFlag[] = "death_test_style";
56 const char kDeathTestUseFork[] = "death_test_use_fork";
57 const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
58 
59 #if GTEST_HAS_DEATH_TEST
60 
61 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
62 /* class A needs to have dll-interface to be used by clients of class B */)
63 
64 // DeathTest is a class that hides much of the complexity of the
65 // GTEST_DEATH_TEST_ macro.  It is abstract; its static Create method
66 // returns a concrete class that depends on the prevailing death test
67 // style, as defined by the --gtest_death_test_style and/or
68 // --gtest_internal_run_death_test flags.
69 
70 // In describing the results of death tests, these terms are used with
71 // the corresponding definitions:
72 //
73 // exit status:  The integer exit information in the format specified
74 //               by wait(2)
75 // exit code:    The integer code passed to exit(3), _exit(2), or
76 //               returned from main()
77 class GTEST_API_ DeathTest {
78  public:
79   // Create returns false if there was an error determining the
80   // appropriate action to take for the current death test; for example,
81   // if the gtest_death_test_style flag is set to an invalid value.
82   // The LastMessage method will return a more detailed message in that
83   // case.  Otherwise, the DeathTest pointer pointed to by the "test"
84   // argument is set.  If the death test should be skipped, the pointer
85   // is set to NULL; otherwise, it is set to the address of a new concrete
86   // DeathTest object that controls the execution of the current test.
87   static bool Create(const char* statement, Matcher<const std::string&> matcher,
88                      const char* file, int line, DeathTest** test);
89   DeathTest();
~DeathTest()90   virtual ~DeathTest() { }
91 
92   // A helper class that aborts a death test when it's deleted.
93   class ReturnSentinel {
94    public:
ReturnSentinel(DeathTest * test)95     explicit ReturnSentinel(DeathTest* test) : test_(test) { }
~ReturnSentinel()96     ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }
97    private:
98     DeathTest* const test_;
99     GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel);
100   } GTEST_ATTRIBUTE_UNUSED_;
101 
102   // An enumeration of possible roles that may be taken when a death
103   // test is encountered.  EXECUTE means that the death test logic should
104   // be executed immediately.  OVERSEE means that the program should prepare
105   // the appropriate environment for a child process to execute the death
106   // test, then wait for it to complete.
107   enum TestRole { OVERSEE_TEST, EXECUTE_TEST };
108 
109   // An enumeration of the three reasons that a test might be aborted.
110   enum AbortReason {
111     TEST_ENCOUNTERED_RETURN_STATEMENT,
112     TEST_THREW_EXCEPTION,
113     TEST_DID_NOT_DIE
114   };
115 
116   // Assumes one of the above roles.
117   virtual TestRole AssumeRole() = 0;
118 
119   // Waits for the death test to finish and returns its status.
120   virtual int Wait() = 0;
121 
122   // Returns true if the death test passed; that is, the test process
123   // exited during the test, its exit status matches a user-supplied
124   // predicate, and its stderr output matches a user-supplied regular
125   // expression.
126   // The user-supplied predicate may be a macro expression rather
127   // than a function pointer or functor, or else Wait and Passed could
128   // be combined.
129   virtual bool Passed(bool exit_status_ok) = 0;
130 
131   // Signals that the death test did not die as expected.
132   virtual void Abort(AbortReason reason) = 0;
133 
134   // Returns a human-readable outcome message regarding the outcome of
135   // the last death test.
136   static const char* LastMessage();
137 
138   static void set_last_death_test_message(const std::string& message);
139 
140  private:
141   // A string containing a description of the outcome of the last death test.
142   static std::string last_death_test_message_;
143 
144   GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest);
145 };
146 
GTEST_DISABLE_MSC_WARNINGS_POP_()147 GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251
148 
149 // Factory interface for death tests.  May be mocked out for testing.
150 class DeathTestFactory {
151  public:
152   virtual ~DeathTestFactory() { }
153   virtual bool Create(const char* statement,
154                       Matcher<const std::string&> matcher, const char* file,
155                       int line, DeathTest** test) = 0;
156 };
157 
158 // A concrete DeathTestFactory implementation for normal use.
159 class DefaultDeathTestFactory : public DeathTestFactory {
160  public:
161   bool Create(const char* statement, Matcher<const std::string&> matcher,
162               const char* file, int line, DeathTest** test) override;
163 };
164 
165 // Returns true if exit_status describes a process that was terminated
166 // by a signal, or exited normally with a nonzero exit code.
167 GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
168 
169 // A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads
170 // and interpreted as a regex (rather than an Eq matcher) for legacy
171 // compatibility.
MakeDeathTestMatcher(::testing::internal::RE regex)172 inline Matcher<const ::std::string&> MakeDeathTestMatcher(
173     ::testing::internal::RE regex) {
174   return ContainsRegex(regex.pattern());
175 }
MakeDeathTestMatcher(const char * regex)176 inline Matcher<const ::std::string&> MakeDeathTestMatcher(const char* regex) {
177   return ContainsRegex(regex);
178 }
MakeDeathTestMatcher(const::std::string & regex)179 inline Matcher<const ::std::string&> MakeDeathTestMatcher(
180     const ::std::string& regex) {
181   return ContainsRegex(regex);
182 }
183 
184 // If a Matcher<const ::std::string&> is passed to EXPECT_DEATH (etc.), it's
185 // used directly.
MakeDeathTestMatcher(Matcher<const::std::string &> matcher)186 inline Matcher<const ::std::string&> MakeDeathTestMatcher(
187     Matcher<const ::std::string&> matcher) {
188   return matcher;
189 }
190 
191 // Traps C++ exceptions escaping statement and reports them as test
192 // failures. Note that trapping SEH exceptions is not implemented here.
193 # if GTEST_HAS_EXCEPTIONS
194 #  define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
195   try { \
196     GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
197   } catch (const ::std::exception& gtest_exception) { \
198     fprintf(\
199         stderr, \
200         "\n%s: Caught std::exception-derived exception escaping the " \
201         "death test statement. Exception message: %s\n", \
202         ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \
203         gtest_exception.what()); \
204     fflush(stderr); \
205     death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
206   } catch (...) { \
207     death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
208   }
209 
210 # else
211 #  define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
212   GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
213 
214 # endif
215 
216 // This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,
217 // ASSERT_EXIT*, and EXPECT_EXIT*.
218 #define GTEST_DEATH_TEST_(statement, predicate, regex_or_matcher, fail)        \
219   GTEST_AMBIGUOUS_ELSE_BLOCKER_                                                \
220   if (::testing::internal::AlwaysTrue()) {                                     \
221     ::testing::internal::DeathTest* gtest_dt;                                  \
222     if (!::testing::internal::DeathTest::Create(                               \
223             #statement,                                                        \
224             ::testing::internal::MakeDeathTestMatcher(regex_or_matcher),       \
225             __FILE__, __LINE__, &gtest_dt)) {                                  \
226       goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__);                        \
227     }                                                                          \
228     if (gtest_dt != nullptr) {                                                 \
229       std::unique_ptr< ::testing::internal::DeathTest> gtest_dt_ptr(gtest_dt); \
230       switch (gtest_dt->AssumeRole()) {                                        \
231         case ::testing::internal::DeathTest::OVERSEE_TEST:                     \
232           if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) {                \
233             goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__);                  \
234           }                                                                    \
235           break;                                                               \
236         case ::testing::internal::DeathTest::EXECUTE_TEST: {                   \
237           ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel(       \
238               gtest_dt);                                                       \
239           GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt);            \
240           gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE);   \
241           break;                                                               \
242         }                                                                      \
243       }                                                                        \
244     }                                                                          \
245   } else                                                                       \
246     GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__)                                \
247         : fail(::testing::internal::DeathTest::LastMessage())
248 // The symbol "fail" here expands to something into which a message
249 // can be streamed.
250 
251 // This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in
252 // NDEBUG mode. In this case we need the statements to be executed and the macro
253 // must accept a streamed message even though the message is never printed.
254 // The regex object is not evaluated, but it is used to prevent "unused"
255 // warnings and to avoid an expression that doesn't compile in debug mode.
256 #define GTEST_EXECUTE_STATEMENT_(statement, regex_or_matcher)    \
257   GTEST_AMBIGUOUS_ELSE_BLOCKER_                                  \
258   if (::testing::internal::AlwaysTrue()) {                       \
259     GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement);   \
260   } else if (!::testing::internal::AlwaysTrue()) {               \
261     ::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \
262   } else                                                         \
263     ::testing::Message()
264 
265 // A class representing the parsed contents of the
266 // --gtest_internal_run_death_test flag, as it existed when
267 // RUN_ALL_TESTS was called.
268 class InternalRunDeathTestFlag {
269  public:
InternalRunDeathTestFlag(const std::string & a_file,int a_line,int an_index,int a_write_fd)270   InternalRunDeathTestFlag(const std::string& a_file,
271                            int a_line,
272                            int an_index,
273                            int a_write_fd)
274       : file_(a_file), line_(a_line), index_(an_index),
275         write_fd_(a_write_fd) {}
276 
~InternalRunDeathTestFlag()277   ~InternalRunDeathTestFlag() {
278     if (write_fd_ >= 0)
279       posix::Close(write_fd_);
280   }
281 
file()282   const std::string& file() const { return file_; }
line()283   int line() const { return line_; }
index()284   int index() const { return index_; }
write_fd()285   int write_fd() const { return write_fd_; }
286 
287  private:
288   std::string file_;
289   int line_;
290   int index_;
291   int write_fd_;
292 
293   GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag);
294 };
295 
296 // Returns a newly created InternalRunDeathTestFlag object with fields
297 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
298 // the flag is specified; otherwise returns NULL.
299 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();
300 
301 #endif  // GTEST_HAS_DEATH_TEST
302 
303 }  // namespace internal
304 }  // namespace testing
305 
306 #endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
307